[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6G6CY4TG07T1APPV781HAQM":3,"skill-same:01M6G6CY4TG07T1APPV781HAQM":157},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":48,"repositoryHtmlUrl":49,"repositoryHomepageUrl":6,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":51,"install":52,"resources":64},"01M6G6CY4TG07T1APPV781HAQM","claude-agent-sdk",null,"Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors.\n\nUse when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup.","kbarbel640-del\u002Fskills","kbarbel640-del","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F255315490?v=4","01M6CJPPQGCCESXMG3K7BBGQ5J","01M6CJPPX2PB2BCZERFVM2C2B3",1,"MIT","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"sdk","agent sdk","claude agent sdk","schema validation","MCP","event-driven","structured output","systems","autonomous ai agents","build","sre","use","coding","json","system","subagent","cleanup","config","workflows","security","2026-11-10 10:12:30",false,"---\nname: claude-agent-sdk\ndescription: |\n  Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors.\n\n  Use when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup.\nuser-invocable: true\n---\n\n# Claude Agent SDK - Structured Outputs & Error Prevention Guide\n\n**Package**: @anthropic-ai\u002Fclaude-agent-sdk@0.2.12\n**Breaking Changes**: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required\n\n---\n\n## What's New in v0.1.45+ (Nov 2025)\n\n**Major Features:**\n\n### 1. Structured Outputs (v0.1.45, Nov 14, 2025)\n- **JSON schema validation** - Guarantees responses match exact schemas\n- **`outputFormat` parameter** - Define output structure with JSON schema or Zod\n- **Access validated results** - Via `message.structured_output`\n- **Beta header required**: `structured-outputs-2025-11-13`\n- **Type safety** - Full TypeScript inference with Zod schemas\n\n**Example:**\n```typescript\nimport { query } from \"@anthropic-ai\u002Fclaude-agent-sdk\";\nimport { z } from \"zod\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\nconst schema = z.object({\n  summary: z.string(),\n  sentiment: z.enum(['positive', 'neutral', 'negative']),\n  confidence: z.number().min(0).max(1)\n});\n\nconst response = query({\n  prompt: \"Analyze this code review feedback\",\n  options: {\n    model: \"claude-sonnet-4-5\",\n    outputFormat: {\n      type: \"json_schema\",\n      json_schema: {\n        name: \"AnalysisResult\",\n        strict: true,\n        schema: zodToJsonSchema(schema)\n      }\n    }\n  }\n});\n\nfor await (const message of response) {\n  if (message.type === 'result' && message.structured_output) {\n    \u002F\u002F Guaranteed to match schema\n    const validated = schema.parse(message.structured_output);\n    console.log(`Sentiment: ${validated.sentiment}`);\n  }\n}\n```\n\n**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.\n\n### 2. Plugins System (v0.1.27)\n- **`plugins` array** - Load local plugin paths\n- **Custom plugin support** - Extend agent capabilities\n\n### 3. Hooks System (v0.1.0+)\n\n**All 12 Hook Events:**\n\n| Hook | When Fired | Use Case |\n|------|------------|----------|\n| `PreToolUse` | Before tool execution | Validate, modify, or block tool calls |\n| `PostToolUse` | After tool execution | Log results, trigger side effects |\n| `Notification` | Agent notifications | Display status updates |\n| `UserPromptSubmit` | User prompt received | Pre-process or validate input |\n| `SubagentStart` | Subagent spawned | Track delegation, log context |\n| `SubagentStop` | Subagent completed | Aggregate results, cleanup |\n| `PreCompact` | Before context compaction | Save state before truncation |\n| `PermissionRequest` | Permission needed | Custom approval workflows |\n| `Stop` | Agent stopping | Cleanup, final logging |\n| `SessionStart` | Session begins | Initialize state |\n| `SessionEnd` | Session ends | Persist state, cleanup |\n| `Error` | Error occurred | Custom error handling |\n\n**Hook Configuration:**\n```typescript\nconst response = query({\n  prompt: \"...\",\n  options: {\n    hooks: {\n      PreToolUse: async (input) => {\n        console.log(`Tool: ${input.toolName}`);\n        return { allow: true };  \u002F\u002F or { allow: false, message: \"...\" }\n      },\n      PostToolUse: async (input) => {\n        await logToolUsage(input.toolName, input.result);\n      }\n    }\n  }\n});\n```\n\n### 4. Additional Options\n- **`fallbackModel`** - Automatic model fallback on failures\n- **`maxThinkingTokens`** - Control extended thinking budget\n- **`strictMcpConfig`** - Strict MCP configuration validation\n- **`continue`** - Resume with new prompt (differs from `resume`)\n- **`permissionMode: 'plan'`** - New permission mode for planning workflows\n\n? **Docs**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fstructured-outputs\n\n---\n\n## The Complete Claude Agent SDK Reference\n\n## Table of Contents\n\n1. [Core Query API](#core-query-api)\n2. [Tool Integration](#tool-integration-built-in--custom)\n3. [MCP Servers](#mcp-servers-model-context-protocol)\n4. [Subagent Orchestration](#subagent-orchestration)\n5. [Session Management](#session-management)\n6. [Permission Control](#permission-control)\n7. [Sandbox Settings](#sandbox-settings-security-critical)\n8. [File Checkpointing](#file-checkpointing)\n9. [Filesystem Settings](#filesystem-settings)\n10. [Query Object Methods](#query-object-methods)\n11. [Message Types & Streaming](#message-types--streaming)\n12. [Error Handling](#error-handling)\n13. [Known Issues](#known-issues-prevention)\n\n---\n\n## Core Query API\n\n**Key signature:**\n```typescript\nquery(prompt: string | AsyncIterable\u003CSDKUserMessage>, options?: Options)\n  -> AsyncGenerator\u003CSDKMessage>\n```\n\n**Critical Options:**\n- `outputFormat` - Structured JSON schema validation (v0.1.45+)\n- `settingSources` - Filesystem settings loading ('user'|'project'|'local')\n- `canUseTool` - Custom permission logic callback\n- `agents` - Programmatic subagent definitions\n- `mcpServers` - MCP server configuration\n- `permissionMode` - 'default'|'acceptEdits'|'bypassPermissions'|'plan'\n- `betas` - Enable beta features (e.g., 1M context window)\n- `sandbox` - Sandbox settings for secure execution\n- `enableFileCheckpointing` - Enable file state snapshots\n- `systemPrompt` - System prompt (string or preset object)\n\n### Extended Context (1M Tokens)\n\nEnable 1 million token context window:\n\n```typescript\nconst response = query({\n  prompt: \"Analyze this large codebase\",\n  options: {\n    betas: ['context-1m-2025-08-07'],  \u002F\u002F Enable 1M context\n    model: \"claude-sonnet-4-5\"\n  }\n});\n```\n\n### System Prompt Configuration\n\nTwo forms of systemPrompt:\n\n```typescript\n\u002F\u002F 1. Simple string\nsystemPrompt: \"You are a helpful coding assistant.\"\n\n\u002F\u002F 2. Preset with optional append (preserves Claude Code defaults)\nsystemPrompt: {\n  type: 'preset',\n  preset: 'claude_code',\n  append: \"\\n\\nAdditional context: Focus on security.\"\n}\n```\n\n**Use preset form** when you want Claude Code's default behaviors plus custom additions.\n\n---\n\n## Tool Integration (Built-in + Custom)\n\n**Tool Control:**\n- `allowedTools` - Whitelist (takes precedence)\n- `disallowedTools` - Blacklist\n- `canUseTool` - Custom permission callback (see Permission Control section)\n\n**Built-in Tools:** Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion\n\n### AskUserQuestion Tool (v0.1.71+)\n\nEnable user interaction during agent execution:\n\n```typescript\nconst response = query({\n  prompt: \"Review and refactor the codebase\",\n  options: {\n    allowedTools: [\"Read\", \"Write\", \"Edit\", \"AskUserQuestion\"]\n  }\n});\n\n\u002F\u002F Agent can now ask clarifying questions\n\u002F\u002F Questions appear in message stream as tool_call with name \"AskUserQuestion\"\n```\n\n**Use cases:**\n- Clarify ambiguous requirements mid-task\n- Get user approval before destructive operations\n- Present options and get selection\n\n### Tools Configuration (v0.1.57+)\n\n**Three forms of tool configuration:**\n\n```typescript\n\u002F\u002F 1. Exact allowlist (string array)\ntools: [\"Read\", \"Write\", \"Grep\"]\n\n\u002F\u002F 2. Disable all tools (empty array)\ntools: []\n\n\u002F\u002F 3. Preset with defaults (object form)\ntools: { type: 'preset', preset: 'claude_code' }\n```\n\n**Note:** `allowedTools` and `disallowedTools` still work but `tools` provides more flexibility.\n\n---\n\n## MCP Servers (Model Context Protocol)\n\n**Server Types:**\n- **In-process** - `createSdkMcpServer()` with `tool()` definitions\n- **External** - stdio, HTTP, SSE transport\n\n**Tool Definition:**\n```typescript\ntool(name: string, description: string, zodSchema, handler)\n```\n\n**Handler Return:**\n```typescript\n{ content: [{ type: \"text\", text: \"...\" }], isError?: boolean }\n```\n\n### External MCP Servers (stdio)\n\n```typescript\nconst response = query({\n  prompt: \"List files and analyze Git history\",\n  options: {\n    mcpServers: {\n      \u002F\u002F Filesystem server\n      \"filesystem\": {\n        command: \"npx\",\n        args: [\"@modelcontextprotocol\u002Fserver-filesystem\"],\n        env: {\n          ALLOWED_PATHS: \"\u002FUsers\u002Fdeveloper\u002Fprojects:\u002Ftmp\"\n        }\n      },\n      \u002F\u002F Git operations server\n      \"git\": {\n        command: \"npx\",\n        args: [\"@modelcontextprotocol\u002Fserver-git\"],\n        env: {\n          GIT_REPO_PATH: \"\u002FUsers\u002Fdeveloper\u002Fprojects\u002Fmy-repo\"\n        }\n      }\n    },\n    allowedTools: [\n      \"mcp__filesystem__list_files\",\n      \"mcp__filesystem__read_file\",\n      \"mcp__git__log\",\n      \"mcp__git__diff\"\n    ]\n  }\n});\n```\n\n### External MCP Servers (HTTP\u002FSSE)\n\n```typescript\nconst response = query({\n  prompt: \"Analyze data from remote service\",\n  options: {\n    mcpServers: {\n      \"remote-service\": {\n        url: \"https:\u002F\u002Fapi.example.com\u002Fmcp\",\n        headers: {\n          \"Authorization\": \"Bearer your-token-here\",\n          \"Content-Type\": \"application\u002Fjson\"\n        }\n      }\n    },\n    allowedTools: [\"mcp__remote-service__analyze\"]\n  }\n});\n```\n\n### MCP Tool Naming Convention\n\n**Format**: `mcp__\u003Cserver-name>__\u003Ctool-name>`\n\n**CRITICAL:**\n- Server name and tool name MUST match configuration\n- Use double underscores (`__`) as separators\n- Include in `allowedTools` array\n\n**Examples:** `mcp__weather-service__get_weather`, `mcp__filesystem__read_file`\n\n---\n\n## Subagent Orchestration\n\n### AgentDefinition Type\n\n```typescript\ntype AgentDefinition = {\n  description: string;        \u002F\u002F When to use this agent\n  prompt: string;             \u002F\u002F System prompt for agent\n  tools?: string[];           \u002F\u002F Allowed tools (optional)\n  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';  \u002F\u002F Model (optional)\n  skills?: string[];          \u002F\u002F Skills to load (v0.2.10+)\n  maxTurns?: number;          \u002F\u002F Maximum turns before stopping (v0.2.10+)\n}\n```\n\n**Field Details:**\n\n- **description**: When to use agent (used by main agent for delegation)\n- **prompt**: System prompt (defines role, inherits main context)\n- **tools**: Allowed tools (if omitted, inherits from main agent)\n- **model**: Model override (`haiku`\u002F`sonnet`\u002F`opus`\u002F`inherit`)\n- **skills**: Skills to load for agent (v0.2.10+)\n- **maxTurns**: Limit agent to N turns before returning control (v0.2.10+)\n\n**Usage:**\n```typescript\nagents: {\n  \"security-checker\": {\n    description: \"Security audits and vulnerability scanning\",\n    prompt: \"You check security. Scan for secrets, verify OWASP compliance.\",\n    tools: [\"Read\", \"Grep\", \"Bash\"],\n    model: \"sonnet\",\n    skills: [\"security-best-practices\"],  \u002F\u002F Load specific skills\n    maxTurns: 10  \u002F\u002F Limit to 10 turns\n  }\n}\n```\n\n### ⚠️ Subagent Cleanup Warning\n\n**Known Issue**: Subagents don't stop when parent agent stops ([Issue #132](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F132))\n\nWhen a parent agent is stopped (via cancellation or error), spawned subagents continue running as orphaned processes. This can lead to:\n- Resource leaks\n- Continued tool execution after parent stopped\n- RAM out-of-memory in recursive scenarios ([Claude Code Issue #4850](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Fissues\u002F4850))\n\n**Workaround**: Implement cleanup in Stop hooks:\n\n```typescript\nconst response = query({\n  prompt: \"Deploy to production\",\n  options: {\n    agents: {\n      \"deployer\": {\n        description: \"Handle deployments\",\n        prompt: \"Deploy the application\",\n        tools: [\"Bash\"]\n      }\n    },\n    hooks: {\n      Stop: async (input) => {\n        \u002F\u002F Manual cleanup of spawned processes\n        console.log(\"Parent stopped - cleaning up subagents\");\n        \u002F\u002F Implement process tracking and termination\n      }\n    }\n  }\n});\n```\n\n**Enhancement Tracking**: [Issue #142](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F142) proposes auto-termination\n\n---\n\n## Session Management\n\n**Options:**\n- `resume: sessionId` - Continue previous session\n- `forkSession: true` - Create new branch from session\n- `continue: prompt` - Resume with new prompt (differs from `resume`)\n\n**Session Forking Pattern (Unique Capability):**\n\n```typescript\n\u002F\u002F Explore alternative without modifying original\nconst forked = query({\n  prompt: \"Try GraphQL instead of REST\",\n  options: {\n    resume: sessionId,\n    forkSession: true  \u002F\u002F Creates new branch, original session unchanged\n  }\n});\n```\n\n**Capture Session ID:**\n```typescript\nfor await (const message of response) {\n  if (message.type === 'system' && message.subtype === 'init') {\n    sessionId = message.session_id;  \u002F\u002F Save for later resume\u002Ffork\n  }\n}\n```\n\n### V2 Session APIs (Preview - v0.1.54+)\n\n**Simpler multi-turn conversation pattern:**\n\n```typescript\nimport {\n  unstable_v2_createSession,\n  unstable_v2_resumeSession,\n  unstable_v2_prompt\n} from \"@anthropic-ai\u002Fclaude-agent-sdk\";\n\n\u002F\u002F Create a new session\nconst session = await unstable_v2_createSession({\n  model: \"claude-sonnet-4-5\",\n  workingDirectory: process.cwd(),\n  allowedTools: [\"Read\", \"Grep\", \"Glob\"]\n});\n\n\u002F\u002F Send prompts and stream responses\nconst stream = unstable_v2_prompt(session, \"Analyze the codebase structure\");\nfor await (const message of stream) {\n  console.log(message);\n}\n\n\u002F\u002F Continue conversation in same session\nconst stream2 = unstable_v2_prompt(session, \"Now suggest improvements\");\nfor await (const message of stream2) {\n  console.log(message);\n}\n\n\u002F\u002F Resume a previous session\nconst resumedSession = await unstable_v2_resumeSession(session.sessionId);\n```\n\n**Note:** V2 APIs are in preview (`unstable_` prefix). The `.receive()` method was renamed to `.stream()` in v0.1.72.\n\n---\n\n## Permission Control\n\n**Permission Modes:**\n```typescript\ntype PermissionMode = \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n```\n\n- `default` - Standard permission checks\n- `acceptEdits` - Auto-approve file edits\n- `bypassPermissions` - Skip ALL checks (use in CI\u002FCD only)\n- `plan` - Planning mode (v0.1.45+)\n\n### Custom Permission Logic\n\n```typescript\nconst response = query({\n  prompt: \"Deploy application to production\",\n  options: {\n    permissionMode: \"default\",\n    canUseTool: async (toolName, input) => {\n      \u002F\u002F Allow read-only operations\n      if (['Read', 'Grep', 'Glob'].includes(toolName)) {\n        return { behavior: \"allow\" };\n      }\n\n      \u002F\u002F Deny destructive bash commands\n      if (toolName === 'Bash') {\n        const dangerous = ['rm -rf', 'dd if=', 'mkfs', '> \u002Fdev\u002F'];\n        if (dangerous.some(pattern => input.command.includes(pattern))) {\n          return {\n            behavior: \"deny\",\n            message: \"Destructive command blocked for safety\"\n          };\n        }\n      }\n\n      \u002F\u002F Require confirmation for deployments\n      if (input.command?.includes('deploy') || input.command?.includes('kubectl apply')) {\n        return {\n          behavior: \"ask\",\n          message: \"Confirm deployment to production?\"\n        };\n      }\n\n      \u002F\u002F Allow by default\n      return { behavior: \"allow\" };\n    }\n  }\n});\n```\n\n### canUseTool Callback\n\n```typescript\ntype CanUseToolCallback = (\n  toolName: string,\n  input: any\n) => Promise\u003CPermissionDecision>;\n\ntype PermissionDecision =\n  | { behavior: \"allow\" }\n  | { behavior: \"deny\"; message?: string }\n  | { behavior: \"ask\"; message?: string };\n```\n\n**Examples:**\n\n```typescript\n\u002F\u002F Block all file writes\ncanUseTool: async (toolName, input) => {\n  if (toolName === 'Write' || toolName === 'Edit') {\n    return { behavior: \"deny\", message: \"No file modifications allowed\" };\n  }\n  return { behavior: \"allow\" };\n}\n\n\u002F\u002F Require confirmation for specific files\ncanUseTool: async (toolName, input) => {\n  const sensitivePaths = ['\u002Fetc\u002F', '\u002Froot\u002F', '.env', 'credentials.json'];\n  if ((toolName === 'Write' || toolName === 'Edit') &&\n      sensitivePaths.some(path => input.file_path?.includes(path))) {\n    return {\n      behavior: \"ask\",\n      message: `Modify sensitive file ${input.file_path}?`\n    };\n  }\n  return { behavior: \"allow\" };\n}\n\n\u002F\u002F Log all tool usage\ncanUseTool: async (toolName, input) => {\n  console.log(`Tool requested: ${toolName}`, input);\n  await logToDatabase(toolName, input);\n  return { behavior: \"allow\" };\n}\n```\n\n---\n\n## Sandbox Settings (Security-Critical)\n\n**Enable sandboxed execution for Bash commands:**\n\n```typescript\nconst response = query({\n  prompt: \"Run system diagnostics\",\n  options: {\n    sandbox: {\n      enabled: true,\n      autoAllowBashIfSandboxed: true,  \u002F\u002F Auto-approve bash in sandbox\n      excludedCommands: [\"rm\", \"dd\", \"mkfs\"],  \u002F\u002F Never auto-approve these\n      allowUnsandboxedCommands: false  \u002F\u002F Deny unsandboxable commands\n    }\n  }\n});\n```\n\n### SandboxSettings Type\n\n```typescript\ntype SandboxSettings = {\n  enabled: boolean;\n  autoAllowBashIfSandboxed?: boolean;  \u002F\u002F Default: false\n  excludedCommands?: string[];\n  allowUnsandboxedCommands?: boolean;  \u002F\u002F Default: false\n  network?: NetworkSandboxSettings;\n  ignoreViolations?: SandboxIgnoreViolations;\n};\n\ntype NetworkSandboxSettings = {\n  enabled: boolean;\n  proxyUrl?: string;  \u002F\u002F HTTP proxy for network requests\n};\n```\n\n**Key Options:**\n- `enabled` - Activate sandbox isolation\n- `autoAllowBashIfSandboxed` - Skip permission prompts for safe bash commands\n- `excludedCommands` - Commands that always require permission\n- `allowUnsandboxedCommands` - Allow commands that can't be sandboxed (risky)\n- `network.proxyUrl` - Route network through proxy for monitoring\n\n**Best Practice:** Always use sandbox in production agents handling untrusted input.\n\n---\n\n## File Checkpointing\n\n**Enable file state snapshots for rollback capability:**\n\n```typescript\nconst response = query({\n  prompt: \"Refactor the authentication module\",\n  options: {\n    enableFileCheckpointing: true  \u002F\u002F Enable file snapshots\n  }\n});\n\n\u002F\u002F Later: rewind file changes to a specific point\nfor await (const message of response) {\n  if (message.type === 'user' && message.uuid) {\n    \u002F\u002F Can rewind to this point later\n    const userMessageUuid = message.uuid;\n\n    \u002F\u002F To rewind (call on Query object)\n    await response.rewindFiles(userMessageUuid);\n  }\n}\n```\n\n**Use cases:**\n- Undo failed refactoring attempts\n- A\u002FB test code changes\n- Safe exploration of alternatives\n\n---\n\n## Filesystem Settings\n\n**Setting Sources:**\n```typescript\ntype SettingSource = 'user' | 'project' | 'local';\n```\n\n- `user` - `~\u002F.claude\u002Fsettings.json` (global)\n- `project` - `.claude\u002Fsettings.json` (team-shared)\n- `local` - `.claude\u002Fsettings.local.json` (gitignored overrides)\n\n**Default:** NO settings loaded (`settingSources: []`)\n\n### Settings Priority\n\nWhen multiple sources loaded, settings merge in this order (highest priority first):\n\n1. **Programmatic options** (passed to `query()`) - Always win\n2. **Local settings** (`.claude\u002Fsettings.local.json`)\n3. **Project settings** (`.claude\u002Fsettings.json`)\n4. **User settings** (`~\u002F.claude\u002Fsettings.json`)\n\n**Example:**\n\n```typescript\n\u002F\u002F .claude\u002Fsettings.json\n{\n  \"allowedTools\": [\"Read\", \"Write\", \"Edit\"]\n}\n\n\u002F\u002F .claude\u002Fsettings.local.json\n{\n  \"allowedTools\": [\"Read\"]  \u002F\u002F Overrides project settings\n}\n\n\u002F\u002F Programmatic\nconst response = query({\n  options: {\n    settingSources: [\"project\", \"local\"],\n    allowedTools: [\"Read\", \"Grep\"]  \u002F\u002F ← This wins\n  }\n});\n\n\u002F\u002F Actual allowedTools: [\"Read\", \"Grep\"]\n```\n\n**Best Practice:** Use `settingSources: [\"project\"]` in CI\u002FCD for consistent behavior.\n\n---\n\n## Query Object Methods\n\nThe `query()` function returns a `Query` object with these methods:\n\n```typescript\nconst q = query({ prompt: \"...\" });\n\n\u002F\u002F Async iteration (primary usage)\nfor await (const message of q) { ... }\n\n\u002F\u002F Runtime model control\nawait q.setModel(\"claude-opus-4-5\");           \u002F\u002F Change model mid-session\nawait q.setMaxThinkingTokens(4096);            \u002F\u002F Set thinking budget\n\n\u002F\u002F Introspection\nconst models = await q.supportedModels();     \u002F\u002F List available models\nconst commands = await q.supportedCommands(); \u002F\u002F List available commands\nconst account = await q.accountInfo();        \u002F\u002F Get account details\n\n\u002F\u002F MCP status\nconst status = await q.mcpServerStatus();     \u002F\u002F Check MCP server status\n\u002F\u002F Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }\n\n\u002F\u002F File operations (requires enableFileCheckpointing)\nawait q.rewindFiles(userMessageUuid);         \u002F\u002F Rewind to checkpoint\n```\n\n**Use cases:**\n- Dynamic model switching based on task complexity\n- Monitoring MCP server health\n- Adjusting thinking budget for reasoning tasks\n\n---\n\n## Message Types & Streaming\n\n**Message Types:**\n- `system` - Session init\u002Fcompletion (includes `session_id`)\n- `assistant` - Agent responses\n- `tool_call` - Tool execution requests\n- `tool_result` - Tool execution results\n- `error` - Error messages\n- `result` - Final result (includes `structured_output` for v0.1.45+)\n\n**Streaming Pattern:**\n```typescript\nfor await (const message of response) {\n  if (message.type === 'system' && message.subtype === 'init') {\n    sessionId = message.session_id;  \u002F\u002F Capture for resume\u002Ffork\n  }\n  if (message.type === 'result' && message.structured_output) {\n    \u002F\u002F Structured output available (v0.1.45+)\n    const validated = schema.parse(message.structured_output);\n  }\n}\n```\n\n---\n\n## Error Handling\n\n**Error Codes:**\n\n| Error Code | Cause | Solution |\n|------------|-------|----------|\n| `CLI_NOT_FOUND` | Claude Code not installed | Install: `npm install -g @anthropic-ai\u002Fclaude-code` |\n| `AUTHENTICATION_FAILED` | Invalid API key | Check ANTHROPIC_API_KEY env var |\n| `RATE_LIMIT_EXCEEDED` | Too many requests | Implement retry with backoff |\n| `CONTEXT_LENGTH_EXCEEDED` | Prompt too long | Use session compaction, reduce context |\n| `PERMISSION_DENIED` | Tool blocked | Check permissionMode, canUseTool |\n| `TOOL_EXECUTION_FAILED` | Tool error | Check tool implementation |\n| `SESSION_NOT_FOUND` | Invalid session ID | Verify session ID |\n| `MCP_SERVER_FAILED` | Server error | Check server configuration |\n\n---\n\n## Known Issues Prevention\n\nThis skill prevents **14** documented issues:\n\n### Issue #1: CLI Not Found Error\n**Error**: `\"Claude Code CLI not installed\"`\n**Source**: SDK requires Claude Code CLI\n**Why It Happens**: CLI not installed globally\n**Prevention**: Install before using SDK: `npm install -g @anthropic-ai\u002Fclaude-code`\n\n### Issue #2: Authentication Failed\n**Error**: `\"Invalid API key\"`\n**Source**: Missing or incorrect ANTHROPIC_API_KEY\n**Why It Happens**: Environment variable not set\n**Prevention**: Always set `export ANTHROPIC_API_KEY=\"sk-ant-...\"`\n\n### Issue #3: Permission Denied Errors\n**Error**: Tool execution blocked\n**Source**: `permissionMode` restrictions\n**Why It Happens**: Tool not allowed by permissions\n**Prevention**: Use `allowedTools` or custom `canUseTool` callback\n\n### Issue #4: Context Length Exceeded (Session-Breaking)\n**Error**: `\"Prompt too long\"`\n**Source**: Input exceeds model context window ([Issue #138](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F138))\n**Why It Happens**: Large codebase, long conversations\n\n**⚠️ Critical Behavior**: Once a session hits context limit:\n1. All subsequent requests to that session return \"Prompt too long\"\n2. `\u002Fcompact` command fails with same error\n3. **Session is permanently broken and must be abandoned**\n\n**Prevention Strategies**:\n\n```typescript\n\u002F\u002F 1. Proactive session forking (create checkpoints before hitting limit)\nconst checkpoint = query({\n  prompt: \"Checkpoint current state\",\n  options: {\n    resume: sessionId,\n    forkSession: true  \u002F\u002F Create branch before hitting limit\n  }\n});\n\n\u002F\u002F 2. Monitor time and rotate sessions proactively\nconst MAX_SESSION_TIME = 80 * 60 * 1000;  \u002F\u002F 80 minutes (before 90-min crash)\nlet sessionStartTime = Date.now();\n\nfunction shouldRotateSession() {\n  return Date.now() - sessionStartTime > MAX_SESSION_TIME;\n}\n\n\u002F\u002F 3. Start new sessions before hitting context limits\nif (shouldRotateSession()) {\n  const summary = await getSummary(currentSession);\n  const newSession = query({\n    prompt: `Continue with context: ${summary}`\n  });\n  sessionStartTime = Date.now();\n}\n```\n\n**Note**: SDK auto-compacts, but if limit is reached, session becomes unrecoverable\n\n### Issue #5: Tool Execution Timeout\n**Error**: Tool doesn't respond\n**Source**: Long-running tool execution\n**Why It Happens**: Tool takes too long (>5 minutes default)\n**Prevention**: Implement timeout handling in tool implementations\n\n### Issue #6: Session Not Found\n**Error**: `\"Invalid session ID\"`\n**Source**: Session expired or invalid\n**Why It Happens**: Session ID incorrect or too old\n**Prevention**: Capture `session_id` from `system` init message\n\n### Issue #7: MCP Server Connection Failed\n**Error**: Server not responding\n**Source**: Server not running or misconfigured\n**Why It Happens**: Command\u002FURL incorrect, server crashed\n**Prevention**: Test MCP server independently, verify command\u002FURL\n\n### Issue #8: Subagent Definition Errors\n**Error**: Invalid AgentDefinition\n**Source**: Missing required fields\n**Why It Happens**: `description` or `prompt` missing\n**Prevention**: Always include `description` and `prompt` fields\n\n### Issue #9: Settings File Not Found\n**Error**: `\"Cannot read settings\"`\n**Source**: Settings file doesn't exist\n**Why It Happens**: `settingSources` includes non-existent file\n**Prevention**: Check file exists before including in sources\n\n### Issue #10: Tool Name Collision\n**Error**: Duplicate tool name\n**Source**: Multiple tools with same name\n**Why It Happens**: Two MCP servers define same tool name\n**Prevention**: Use unique tool names, prefix with server name\n\n### Issue #11: Zod Schema Validation Error\n**Error**: Invalid tool input\n**Source**: Input doesn't match Zod schema\n**Why It Happens**: Agent provided wrong data type\n**Prevention**: Use descriptive Zod schemas with `.describe()`\n\n### Issue #12: Filesystem Permission Denied\n**Error**: Cannot access path\n**Source**: Restricted filesystem access\n**Why It Happens**: Path outside `workingDirectory` or no permissions\n**Prevention**: Set correct `workingDirectory`, check file permissions\n\n### Issue #13: MCP Server Config Missing `type` Field\n**Error**: `\"Claude Code process exited with code 1\"` (cryptic, no context)\n**Source**: [GitHub Issue #131](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F131)\n**Why It Happens**: URL-based MCP servers require explicit `type: \"http\"` or `type: \"sse\"` field\n**Prevention**: Always specify transport type for URL-based MCP servers\n\n```typescript\n\u002F\u002F ❌ Wrong - missing type field (causes cryptic exit code 1)\nmcpServers: {\n  \"my-server\": {\n    url: \"https:\u002F\u002Fapi.example.com\u002Fmcp\"\n  }\n}\n\n\u002F\u002F ✅ Correct - type field required for URL-based servers\nmcpServers: {\n  \"my-server\": {\n    url: \"https:\u002F\u002Fapi.example.com\u002Fmcp\",\n    type: \"http\"  \u002F\u002F or \"sse\" for Server-Sent Events\n  }\n}\n```\n\n**Diagnostic Clue**: If you see \"process exited with code 1\" with no other context, check your MCP server configuration for missing `type` fields.\n\n### Issue #14: MCP Tool Result with Unicode Line Separators\n**Error**: JSON parse error, agent hangs\n**Source**: [GitHub Issue #137](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F137)\n**Why It Happens**: Unicode U+2028 (line separator) and U+2029 (paragraph separator) are valid in JSON but break JavaScript parsing\n**Prevention**: Escape these characters in MCP tool results\n\n```typescript\n\u002F\u002F MCP tool handler - sanitize external data\ntool(\"fetch_content\", \"Fetch text content\", {}, async (args) => {\n  const content = await fetchExternalData();\n\n  \u002F\u002F ✅ Sanitize Unicode line\u002Fparagraph separators\n  const sanitized = content\n    .replace(\u002F\\u2028\u002Fg, '\\\\u2028')\n    .replace(\u002F\\u2029\u002Fg, '\\\\u2029');\n\n  return {\n    content: [{ type: \"text\", text: sanitized }]\n  };\n});\n```\n\n**When This Matters**: External data sources (APIs, web scraping, user input) that may contain these characters\n\n**Related**: [MCP Python SDK Issue #1356](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fissues\u002F1356)\n\n---\n\n## Official Documentation\n\n- **Agent SDK Overview**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fapi\u002Fagent-sdk\u002Foverview\n- **TypeScript API**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fapi\u002Fagent-sdk\u002Ftypescript\n- **Structured Outputs**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fstructured-outputs\n- **GitHub (TypeScript)**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\n- **CHANGELOG**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fblob\u002Fmain\u002FCHANGELOG.md\n\n---\n\n**Token Efficiency**:\n- **Without skill**: ~15,000 tokens (MCP setup, permission patterns, session APIs, sandbox config, hooks, structured outputs, error handling)\n- **With skill**: ~4,500 tokens (comprehensive v0.2.12 coverage + error prevention + advanced patterns)\n- **Savings**: ~70% (~10,500 tokens)\n\n**Errors prevented**: 14 documented issues with exact solutions (including 2 community-sourced gotchas)\n**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, subagent cleanup patterns\n\n---\n\n**Last verified**: 2026-01-20 | **Skill version**: 3.1.0 | **Changes**: Added Issue #13 (MCP type field), Issue #14 (Unicode U+2028\u002FU+2029), expanded Issue #4 (session-breaking), added subagent cleanup warning with Stop hook pattern\n","# Claude Agent SDK - Structured Outputs & Error Prevention Guide\n\n**Package**: @anthropic-ai\u002Fclaude-agent-sdk@0.2.12\n**Breaking Changes**: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required\n\n---\n\n## What's New in v0.1.45+ (Nov 2025)\n\n**Major Features:**\n\n### 1. Structured Outputs (v0.1.45, Nov 14, 2025)\n- **JSON schema validation** - Guarantees responses match exact schemas\n- **`outputFormat` parameter** - Define output structure with JSON schema or Zod\n- **Access validated results** - Via `message.structured_output`\n- **Beta header required**: `structured-outputs-2025-11-13`\n- **Type safety** - Full TypeScript inference with Zod schemas\n\n**Example:**\n```typescript\nimport { query } from \"@anthropic-ai\u002Fclaude-agent-sdk\";\nimport { z } from \"zod\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\nconst schema = z.object({\n  summary: z.string(),\n  sentiment: z.enum(['positive', 'neutral', 'negative']),\n  confidence: z.number().min(0).max(1)\n});\n\nconst response = query({\n  prompt: \"Analyze this code review feedback\",\n  options: {\n    model: \"claude-sonnet-4-5\",\n    outputFormat: {\n      type: \"json_schema\",\n      json_schema: {\n        name: \"AnalysisResult\",\n        strict: true,\n        schema: zodToJsonSchema(schema)\n      }\n    }\n  }\n});\n\nfor await (const message of response) {\n  if (message.type === 'result' && message.structured_output) {\n    \u002F\u002F Guaranteed to match schema\n    const validated = schema.parse(message.structured_output);\n    console.log(`Sentiment: ${validated.sentiment}`);\n  }\n}\n```\n\n**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.\n\n### 2. Plugins System (v0.1.27)\n- **`plugins` array** - Load local plugin paths\n- **Custom plugin support** - Extend agent capabilities\n\n### 3. Hooks System (v0.1.0+)\n\n**All 12 Hook Events:**\n\n| Hook | When Fired | Use Case |\n|------|------------|----------|\n| `PreToolUse` | Before tool execution | Validate, modify, or block tool calls |\n| `PostToolUse` | After tool execution | Log results, trigger side effects |\n| `Notification` | Agent notifications | Display status updates |\n| `UserPromptSubmit` | User prompt received | Pre-process or validate input |\n| `SubagentStart` | Subagent spawned | Track delegation, log context |\n| `SubagentStop` | Subagent completed | Aggregate results, cleanup |\n| `PreCompact` | Before context compaction | Save state before truncation |\n| `PermissionRequest` | Permission needed | Custom approval workflows |\n| `Stop` | Agent stopping | Cleanup, final logging |\n| `SessionStart` | Session begins | Initialize state |\n| `SessionEnd` | Session ends | Persist state, cleanup |\n| `Error` | Error occurred | Custom error handling |\n\n**Hook Configuration:**\n```typescript\nconst response = query({\n  prompt: \"...\",\n  options: {\n    hooks: {\n      PreToolUse: async (input) => {\n        console.log(`Tool: ${input.toolName}`);\n        return { allow: true };  \u002F\u002F or { allow: false, message: \"...\" }\n      },\n      PostToolUse: async (input) => {\n        await logToolUsage(input.toolName, input.result);\n      }\n    }\n  }\n});\n```\n\n### 4. Additional Options\n- **`fallbackModel`** - Automatic model fallback on failures\n- **`maxThinkingTokens`** - Control extended thinking budget\n- **`strictMcpConfig`** - Strict MCP configuration validation\n- **`continue`** - Resume with new prompt (differs from `resume`)\n- **`permissionMode: 'plan'`** - New permission mode for planning workflows\n\n? **Docs**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fstructured-outputs\n\n---\n\n## The Complete Claude Agent SDK Reference\n\n## Table of Contents\n\n1. [Core Query API](#core-query-api)\n2. [Tool Integration](#tool-integration-built-in--custom)\n3. [MCP Servers](#mcp-servers-model-context-protocol)\n4. [Subagent Orchestration](#subagent-orchestration)\n5. [Session Management](#session-management)\n6. [Permission Control](#permission-control)\n7. [Sandbox Settings](#sandbox-settings-security-critical)\n8. [File Checkpointing](#file-checkpointing)\n9. [Filesystem Settings](#filesystem-settings)\n10. [Query Object Methods](#query-object-methods)\n11. [Message Types & Streaming](#message-types--streaming)\n12. [Error Handling](#error-handling)\n13. [Known Issues](#known-issues-prevention)\n\n---\n\n## Core Query API\n\n**Key signature:**\n```typescript\nquery(prompt: string | AsyncIterable\u003CSDKUserMessage>, options?: Options)\n  -> AsyncGenerator\u003CSDKMessage>\n```\n\n**Critical Options:**\n- `outputFormat` - Structured JSON schema validation (v0.1.45+)\n- `settingSources` - Filesystem settings loading ('user'|'project'|'local')\n- `canUseTool` - Custom permission logic callback\n- `agents` - Programmatic subagent definitions\n- `mcpServers` - MCP server configuration\n- `permissionMode` - 'default'|'acceptEdits'|'bypassPermissions'|'plan'\n- `betas` - Enable beta features (e.g., 1M context window)\n- `sandbox` - Sandbox settings for secure execution\n- `enableFileCheckpointing` - Enable file state snapshots\n- `systemPrompt` - System prompt (string or preset object)\n\n### Extended Context (1M Tokens)\n\nEnable 1 million token context window:\n\n```typescript\nconst response = query({\n  prompt: \"Analyze this large codebase\",\n  options: {\n    betas: ['context-1m-2025-08-07'],  \u002F\u002F Enable 1M context\n    model: \"claude-sonnet-4-5\"\n  }\n});\n```\n\n### System Prompt Configuration\n\nTwo forms of systemPrompt:\n\n```typescript\n\u002F\u002F 1. Simple string\nsystemPrompt: \"You are a helpful coding assistant.\"\n\n\u002F\u002F 2. Preset with optional append (preserves Claude Code defaults)\nsystemPrompt: {\n  type: 'preset',\n  preset: 'claude_code',\n  append: \"\\n\\nAdditional context: Focus on security.\"\n}\n```\n\n**Use preset form** when you want Claude Code's default behaviors plus custom additions.\n\n---\n\n## Tool Integration (Built-in + Custom)\n\n**Tool Control:**\n- `allowedTools` - Whitelist (takes precedence)\n- `disallowedTools` - Blacklist\n- `canUseTool` - Custom permission callback (see Permission Control section)\n\n**Built-in Tools:** Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion\n\n### AskUserQuestion Tool (v0.1.71+)\n\nEnable user interaction during agent execution:\n\n```typescript\nconst response = query({\n  prompt: \"Review and refactor the codebase\",\n  options: {\n    allowedTools: [\"Read\", \"Write\", \"Edit\", \"AskUserQuestion\"]\n  }\n});\n\n\u002F\u002F Agent can now ask clarifying questions\n\u002F\u002F Questions appear in message stream as tool_call with name \"AskUserQuestion\"\n```\n\n**Use cases:**\n- Clarify ambiguous requirements mid-task\n- Get user approval before destructive operations\n- Present options and get selection\n\n### Tools Configuration (v0.1.57+)\n\n**Three forms of tool configuration:**\n\n```typescript\n\u002F\u002F 1. Exact allowlist (string array)\ntools: [\"Read\", \"Write\", \"Grep\"]\n\n\u002F\u002F 2. Disable all tools (empty array)\ntools: []\n\n\u002F\u002F 3. Preset with defaults (object form)\ntools: { type: 'preset', preset: 'claude_code' }\n```\n\n**Note:** `allowedTools` and `disallowedTools` still work but `tools` provides more flexibility.\n\n---\n\n## MCP Servers (Model Context Protocol)\n\n**Server Types:**\n- **In-process** - `createSdkMcpServer()` with `tool()` definitions\n- **External** - stdio, HTTP, SSE transport\n\n**Tool Definition:**\n```typescript\ntool(name: string, description: string, zodSchema, handler)\n```\n\n**Handler Return:**\n```typescript\n{ content: [{ type: \"text\", text: \"...\" }], isError?: boolean }\n```\n\n### External MCP Servers (stdio)\n\n```typescript\nconst response = query({\n  prompt: \"List files and analyze Git history\",\n  options: {\n    mcpServers: {\n      \u002F\u002F Filesystem server\n      \"filesystem\": {\n        command: \"npx\",\n        args: [\"@modelcontextprotocol\u002Fserver-filesystem\"],\n        env: {\n          ALLOWED_PATHS: \"\u002FUsers\u002Fdeveloper\u002Fprojects:\u002Ftmp\"\n        }\n      },\n      \u002F\u002F Git operations server\n      \"git\": {\n        command: \"npx\",\n        args: [\"@modelcontextprotocol\u002Fserver-git\"],\n        env: {\n          GIT_REPO_PATH: \"\u002FUsers\u002Fdeveloper\u002Fprojects\u002Fmy-repo\"\n        }\n      }\n    },\n    allowedTools: [\n      \"mcp__filesystem__list_files\",\n      \"mcp__filesystem__read_file\",\n      \"mcp__git__log\",\n      \"mcp__git__diff\"\n    ]\n  }\n});\n```\n\n### External MCP Servers (HTTP\u002FSSE)\n\n```typescript\nconst response = query({\n  prompt: \"Analyze data from remote service\",\n  options: {\n    mcpServers: {\n      \"remote-service\": {\n        url: \"https:\u002F\u002Fapi.example.com\u002Fmcp\",\n        headers: {\n          \"Authorization\": \"Bearer your-token-here\",\n          \"Content-Type\": \"application\u002Fjson\"\n        }\n      }\n    },\n    allowedTools: [\"mcp__remote-service__analyze\"]\n  }\n});\n```\n\n### MCP Tool Naming Convention\n\n**Format**: `mcp__\u003Cserver-name>__\u003Ctool-name>`\n\n**CRITICAL:**\n- Server name and tool name MUST match configuration\n- Use double underscores (`__`) as separators\n- Include in `allowedTools` array\n\n**Examples:** `mcp__weather-service__get_weather`, `mcp__filesystem__read_file`\n\n---\n\n## Subagent Orchestration\n\n### AgentDefinition Type\n\n```typescript\ntype AgentDefinition = {\n  description: string;        \u002F\u002F When to use this agent\n  prompt: string;             \u002F\u002F System prompt for agent\n  tools?: string[];           \u002F\u002F Allowed tools (optional)\n  model?: 'sonnet' | 'opus' | 'haiku' | 'inherit';  \u002F\u002F Model (optional)\n  skills?: string[];          \u002F\u002F Skills to load (v0.2.10+)\n  maxTurns?: number;          \u002F\u002F Maximum turns before stopping (v0.2.10+)\n}\n```\n\n**Field Details:**\n\n- **description**: When to use agent (used by main agent for delegation)\n- **prompt**: System prompt (defines role, inherits main context)\n- **tools**: Allowed tools (if omitted, inherits from main agent)\n- **model**: Model override (`haiku`\u002F`sonnet`\u002F`opus`\u002F`inherit`)\n- **skills**: Skills to load for agent (v0.2.10+)\n- **maxTurns**: Limit agent to N turns before returning control (v0.2.10+)\n\n**Usage:**\n```typescript\nagents: {\n  \"security-checker\": {\n    description: \"Security audits and vulnerability scanning\",\n    prompt: \"You check security. Scan for secrets, verify OWASP compliance.\",\n    tools: [\"Read\", \"Grep\", \"Bash\"],\n    model: \"sonnet\",\n    skills: [\"security-best-practices\"],  \u002F\u002F Load specific skills\n    maxTurns: 10  \u002F\u002F Limit to 10 turns\n  }\n}\n```\n\n### ⚠️ Subagent Cleanup Warning\n\n**Known Issue**: Subagents don't stop when parent agent stops ([Issue #132](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F132))\n\nWhen a parent agent is stopped (via cancellation or error), spawned subagents continue running as orphaned processes. This can lead to:\n- Resource leaks\n- Continued tool execution after parent stopped\n- RAM out-of-memory in recursive scenarios ([Claude Code Issue #4850](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Fissues\u002F4850))\n\n**Workaround**: Implement cleanup in Stop hooks:\n\n```typescript\nconst response = query({\n  prompt: \"Deploy to production\",\n  options: {\n    agents: {\n      \"deployer\": {\n        description: \"Handle deployments\",\n        prompt: \"Deploy the application\",\n        tools: [\"Bash\"]\n      }\n    },\n    hooks: {\n      Stop: async (input) => {\n        \u002F\u002F Manual cleanup of spawned processes\n        console.log(\"Parent stopped - cleaning up subagents\");\n        \u002F\u002F Implement process tracking and termination\n      }\n    }\n  }\n});\n```\n\n**Enhancement Tracking**: [Issue #142](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F142) proposes auto-termination\n\n---\n\n## Session Management\n\n**Options:**\n- `resume: sessionId` - Continue previous session\n- `forkSession: true` - Create new branch from session\n- `continue: prompt` - Resume with new prompt (differs from `resume`)\n\n**Session Forking Pattern (Unique Capability):**\n\n```typescript\n\u002F\u002F Explore alternative without modifying original\nconst forked = query({\n  prompt: \"Try GraphQL instead of REST\",\n  options: {\n    resume: sessionId,\n    forkSession: true  \u002F\u002F Creates new branch, original session unchanged\n  }\n});\n```\n\n**Capture Session ID:**\n```typescript\nfor await (const message of response) {\n  if (message.type === 'system' && message.subtype === 'init') {\n    sessionId = message.session_id;  \u002F\u002F Save for later resume\u002Ffork\n  }\n}\n```\n\n### V2 Session APIs (Preview - v0.1.54+)\n\n**Simpler multi-turn conversation pattern:**\n\n```typescript\nimport {\n  unstable_v2_createSession,\n  unstable_v2_resumeSession,\n  unstable_v2_prompt\n} from \"@anthropic-ai\u002Fclaude-agent-sdk\";\n\n\u002F\u002F Create a new session\nconst session = await unstable_v2_createSession({\n  model: \"claude-sonnet-4-5\",\n  workingDirectory: process.cwd(),\n  allowedTools: [\"Read\", \"Grep\", \"Glob\"]\n});\n\n\u002F\u002F Send prompts and stream responses\nconst stream = unstable_v2_prompt(session, \"Analyze the codebase structure\");\nfor await (const message of stream) {\n  console.log(message);\n}\n\n\u002F\u002F Continue conversation in same session\nconst stream2 = unstable_v2_prompt(session, \"Now suggest improvements\");\nfor await (const message of stream2) {\n  console.log(message);\n}\n\n\u002F\u002F Resume a previous session\nconst resumedSession = await unstable_v2_resumeSession(session.sessionId);\n```\n\n**Note:** V2 APIs are in preview (`unstable_` prefix). The `.receive()` method was renamed to `.stream()` in v0.1.72.\n\n---\n\n## Permission Control\n\n**Permission Modes:**\n```typescript\ntype PermissionMode = \"default\" | \"acceptEdits\" | \"bypassPermissions\" | \"plan\";\n```\n\n- `default` - Standard permission checks\n- `acceptEdits` - Auto-approve file edits\n- `bypassPermissions` - Skip ALL checks (use in CI\u002FCD only)\n- `plan` - Planning mode (v0.1.45+)\n\n### Custom Permission Logic\n\n```typescript\nconst response = query({\n  prompt: \"Deploy application to production\",\n  options: {\n    permissionMode: \"default\",\n    canUseTool: async (toolName, input) => {\n      \u002F\u002F Allow read-only operations\n      if (['Read', 'Grep', 'Glob'].includes(toolName)) {\n        return { behavior: \"allow\" };\n      }\n\n      \u002F\u002F Deny destructive bash commands\n      if (toolName === 'Bash') {\n        const dangerous = ['rm -rf', 'dd if=', 'mkfs', '> \u002Fdev\u002F'];\n        if (dangerous.some(pattern => input.command.includes(pattern))) {\n          return {\n            behavior: \"deny\",\n            message: \"Destructive command blocked for safety\"\n          };\n        }\n      }\n\n      \u002F\u002F Require confirmation for deployments\n      if (input.command?.includes('deploy') || input.command?.includes('kubectl apply')) {\n        return {\n          behavior: \"ask\",\n          message: \"Confirm deployment to production?\"\n        };\n      }\n\n      \u002F\u002F Allow by default\n      return { behavior: \"allow\" };\n    }\n  }\n});\n```\n\n### canUseTool Callback\n\n```typescript\ntype CanUseToolCallback = (\n  toolName: string,\n  input: any\n) => Promise\u003CPermissionDecision>;\n\ntype PermissionDecision =\n  | { behavior: \"allow\" }\n  | { behavior: \"deny\"; message?: string }\n  | { behavior: \"ask\"; message?: string };\n```\n\n**Examples:**\n\n```typescript\n\u002F\u002F Block all file writes\ncanUseTool: async (toolName, input) => {\n  if (toolName === 'Write' || toolName === 'Edit') {\n    return { behavior: \"deny\", message: \"No file modifications allowed\" };\n  }\n  return { behavior: \"allow\" };\n}\n\n\u002F\u002F Require confirmation for specific files\ncanUseTool: async (toolName, input) => {\n  const sensitivePaths = ['\u002Fetc\u002F', '\u002Froot\u002F', '.env', 'credentials.json'];\n  if ((toolName === 'Write' || toolName === 'Edit') &&\n      sensitivePaths.some(path => input.file_path?.includes(path))) {\n    return {\n      behavior: \"ask\",\n      message: `Modify sensitive file ${input.file_path}?`\n    };\n  }\n  return { behavior: \"allow\" };\n}\n\n\u002F\u002F Log all tool usage\ncanUseTool: async (toolName, input) => {\n  console.log(`Tool requested: ${toolName}`, input);\n  await logToDatabase(toolName, input);\n  return { behavior: \"allow\" };\n}\n```\n\n---\n\n## Sandbox Settings (Security-Critical)\n\n**Enable sandboxed execution for Bash commands:**\n\n```typescript\nconst response = query({\n  prompt: \"Run system diagnostics\",\n  options: {\n    sandbox: {\n      enabled: true,\n      autoAllowBashIfSandboxed: true,  \u002F\u002F Auto-approve bash in sandbox\n      excludedCommands: [\"rm\", \"dd\", \"mkfs\"],  \u002F\u002F Never auto-approve these\n      allowUnsandboxedCommands: false  \u002F\u002F Deny unsandboxable commands\n    }\n  }\n});\n```\n\n### SandboxSettings Type\n\n```typescript\ntype SandboxSettings = {\n  enabled: boolean;\n  autoAllowBashIfSandboxed?: boolean;  \u002F\u002F Default: false\n  excludedCommands?: string[];\n  allowUnsandboxedCommands?: boolean;  \u002F\u002F Default: false\n  network?: NetworkSandboxSettings;\n  ignoreViolations?: SandboxIgnoreViolations;\n};\n\ntype NetworkSandboxSettings = {\n  enabled: boolean;\n  proxyUrl?: string;  \u002F\u002F HTTP proxy for network requests\n};\n```\n\n**Key Options:**\n- `enabled` - Activate sandbox isolation\n- `autoAllowBashIfSandboxed` - Skip permission prompts for safe bash commands\n- `excludedCommands` - Commands that always require permission\n- `allowUnsandboxedCommands` - Allow commands that can't be sandboxed (risky)\n- `network.proxyUrl` - Route network through proxy for monitoring\n\n**Best Practice:** Always use sandbox in production agents handling untrusted input.\n\n---\n\n## File Checkpointing\n\n**Enable file state snapshots for rollback capability:**\n\n```typescript\nconst response = query({\n  prompt: \"Refactor the authentication module\",\n  options: {\n    enableFileCheckpointing: true  \u002F\u002F Enable file snapshots\n  }\n});\n\n\u002F\u002F Later: rewind file changes to a specific point\nfor await (const message of response) {\n  if (message.type === 'user' && message.uuid) {\n    \u002F\u002F Can rewind to this point later\n    const userMessageUuid = message.uuid;\n\n    \u002F\u002F To rewind (call on Query object)\n    await response.rewindFiles(userMessageUuid);\n  }\n}\n```\n\n**Use cases:**\n- Undo failed refactoring attempts\n- A\u002FB test code changes\n- Safe exploration of alternatives\n\n---\n\n## Filesystem Settings\n\n**Setting Sources:**\n```typescript\ntype SettingSource = 'user' | 'project' | 'local';\n```\n\n- `user` - `~\u002F.claude\u002Fsettings.json` (global)\n- `project` - `.claude\u002Fsettings.json` (team-shared)\n- `local` - `.claude\u002Fsettings.local.json` (gitignored overrides)\n\n**Default:** NO settings loaded (`settingSources: []`)\n\n### Settings Priority\n\nWhen multiple sources loaded, settings merge in this order (highest priority first):\n\n1. **Programmatic options** (passed to `query()`) - Always win\n2. **Local settings** (`.claude\u002Fsettings.local.json`)\n3. **Project settings** (`.claude\u002Fsettings.json`)\n4. **User settings** (`~\u002F.claude\u002Fsettings.json`)\n\n**Example:**\n\n```typescript\n\u002F\u002F .claude\u002Fsettings.json\n{\n  \"allowedTools\": [\"Read\", \"Write\", \"Edit\"]\n}\n\n\u002F\u002F .claude\u002Fsettings.local.json\n{\n  \"allowedTools\": [\"Read\"]  \u002F\u002F Overrides project settings\n}\n\n\u002F\u002F Programmatic\nconst response = query({\n  options: {\n    settingSources: [\"project\", \"local\"],\n    allowedTools: [\"Read\", \"Grep\"]  \u002F\u002F ← This wins\n  }\n});\n\n\u002F\u002F Actual allowedTools: [\"Read\", \"Grep\"]\n```\n\n**Best Practice:** Use `settingSources: [\"project\"]` in CI\u002FCD for consistent behavior.\n\n---\n\n## Query Object Methods\n\nThe `query()` function returns a `Query` object with these methods:\n\n```typescript\nconst q = query({ prompt: \"...\" });\n\n\u002F\u002F Async iteration (primary usage)\nfor await (const message of q) { ... }\n\n\u002F\u002F Runtime model control\nawait q.setModel(\"claude-opus-4-5\");           \u002F\u002F Change model mid-session\nawait q.setMaxThinkingTokens(4096);            \u002F\u002F Set thinking budget\n\n\u002F\u002F Introspection\nconst models = await q.supportedModels();     \u002F\u002F List available models\nconst commands = await q.supportedCommands(); \u002F\u002F List available commands\nconst account = await q.accountInfo();        \u002F\u002F Get account details\n\n\u002F\u002F MCP status\nconst status = await q.mcpServerStatus();     \u002F\u002F Check MCP server status\n\u002F\u002F Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }\n\n\u002F\u002F File operations (requires enableFileCheckpointing)\nawait q.rewindFiles(userMessageUuid);         \u002F\u002F Rewind to checkpoint\n```\n\n**Use cases:**\n- Dynamic model switching based on task complexity\n- Monitoring MCP server health\n- Adjusting thinking budget for reasoning tasks\n\n---\n\n## Message Types & Streaming\n\n**Message Types:**\n- `system` - Session init\u002Fcompletion (includes `session_id`)\n- `assistant` - Agent responses\n- `tool_call` - Tool execution requests\n- `tool_result` - Tool execution results\n- `error` - Error messages\n- `result` - Final result (includes `structured_output` for v0.1.45+)\n\n**Streaming Pattern:**\n```typescript\nfor await (const message of response) {\n  if (message.type === 'system' && message.subtype === 'init') {\n    sessionId = message.session_id;  \u002F\u002F Capture for resume\u002Ffork\n  }\n  if (message.type === 'result' && message.structured_output) {\n    \u002F\u002F Structured output available (v0.1.45+)\n    const validated = schema.parse(message.structured_output);\n  }\n}\n```\n\n---\n\n## Error Handling\n\n**Error Codes:**\n\n| Error Code | Cause | Solution |\n|------------|-------|----------|\n| `CLI_NOT_FOUND` | Claude Code not installed | Install: `npm install -g @anthropic-ai\u002Fclaude-code` |\n| `AUTHENTICATION_FAILED` | Invalid API key | Check ANTHROPIC_API_KEY env var |\n| `RATE_LIMIT_EXCEEDED` | Too many requests | Implement retry with backoff |\n| `CONTEXT_LENGTH_EXCEEDED` | Prompt too long | Use session compaction, reduce context |\n| `PERMISSION_DENIED` | Tool blocked | Check permissionMode, canUseTool |\n| `TOOL_EXECUTION_FAILED` | Tool error | Check tool implementation |\n| `SESSION_NOT_FOUND` | Invalid session ID | Verify session ID |\n| `MCP_SERVER_FAILED` | Server error | Check server configuration |\n\n---\n\n## Known Issues Prevention\n\nThis skill prevents **14** documented issues:\n\n### Issue #1: CLI Not Found Error\n**Error**: `\"Claude Code CLI not installed\"`\n**Source**: SDK requires Claude Code CLI\n**Why It Happens**: CLI not installed globally\n**Prevention**: Install before using SDK: `npm install -g @anthropic-ai\u002Fclaude-code`\n\n### Issue #2: Authentication Failed\n**Error**: `\"Invalid API key\"`\n**Source**: Missing or incorrect ANTHROPIC_API_KEY\n**Why It Happens**: Environment variable not set\n**Prevention**: Always set `export ANTHROPIC_API_KEY=\"sk-ant-...\"`\n\n### Issue #3: Permission Denied Errors\n**Error**: Tool execution blocked\n**Source**: `permissionMode` restrictions\n**Why It Happens**: Tool not allowed by permissions\n**Prevention**: Use `allowedTools` or custom `canUseTool` callback\n\n### Issue #4: Context Length Exceeded (Session-Breaking)\n**Error**: `\"Prompt too long\"`\n**Source**: Input exceeds model context window ([Issue #138](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F138))\n**Why It Happens**: Large codebase, long conversations\n\n**⚠️ Critical Behavior**: Once a session hits context limit:\n1. All subsequent requests to that session return \"Prompt too long\"\n2. `\u002Fcompact` command fails with same error\n3. **Session is permanently broken and must be abandoned**\n\n**Prevention Strategies**:\n\n```typescript\n\u002F\u002F 1. Proactive session forking (create checkpoints before hitting limit)\nconst checkpoint = query({\n  prompt: \"Checkpoint current state\",\n  options: {\n    resume: sessionId,\n    forkSession: true  \u002F\u002F Create branch before hitting limit\n  }\n});\n\n\u002F\u002F 2. Monitor time and rotate sessions proactively\nconst MAX_SESSION_TIME = 80 * 60 * 1000;  \u002F\u002F 80 minutes (before 90-min crash)\nlet sessionStartTime = Date.now();\n\nfunction shouldRotateSession() {\n  return Date.now() - sessionStartTime > MAX_SESSION_TIME;\n}\n\n\u002F\u002F 3. Start new sessions before hitting context limits\nif (shouldRotateSession()) {\n  const summary = await getSummary(currentSession);\n  const newSession = query({\n    prompt: `Continue with context: ${summary}`\n  });\n  sessionStartTime = Date.now();\n}\n```\n\n**Note**: SDK auto-compacts, but if limit is reached, session becomes unrecoverable\n\n### Issue #5: Tool Execution Timeout\n**Error**: Tool doesn't respond\n**Source**: Long-running tool execution\n**Why It Happens**: Tool takes too long (>5 minutes default)\n**Prevention**: Implement timeout handling in tool implementations\n\n### Issue #6: Session Not Found\n**Error**: `\"Invalid session ID\"`\n**Source**: Session expired or invalid\n**Why It Happens**: Session ID incorrect or too old\n**Prevention**: Capture `session_id` from `system` init message\n\n### Issue #7: MCP Server Connection Failed\n**Error**: Server not responding\n**Source**: Server not running or misconfigured\n**Why It Happens**: Command\u002FURL incorrect, server crashed\n**Prevention**: Test MCP server independently, verify command\u002FURL\n\n### Issue #8: Subagent Definition Errors\n**Error**: Invalid AgentDefinition\n**Source**: Missing required fields\n**Why It Happens**: `description` or `prompt` missing\n**Prevention**: Always include `description` and `prompt` fields\n\n### Issue #9: Settings File Not Found\n**Error**: `\"Cannot read settings\"`\n**Source**: Settings file doesn't exist\n**Why It Happens**: `settingSources` includes non-existent file\n**Prevention**: Check file exists before including in sources\n\n### Issue #10: Tool Name Collision\n**Error**: Duplicate tool name\n**Source**: Multiple tools with same name\n**Why It Happens**: Two MCP servers define same tool name\n**Prevention**: Use unique tool names, prefix with server name\n\n### Issue #11: Zod Schema Validation Error\n**Error**: Invalid tool input\n**Source**: Input doesn't match Zod schema\n**Why It Happens**: Agent provided wrong data type\n**Prevention**: Use descriptive Zod schemas with `.describe()`\n\n### Issue #12: Filesystem Permission Denied\n**Error**: Cannot access path\n**Source**: Restricted filesystem access\n**Why It Happens**: Path outside `workingDirectory` or no permissions\n**Prevention**: Set correct `workingDirectory`, check file permissions\n\n### Issue #13: MCP Server Config Missing `type` Field\n**Error**: `\"Claude Code process exited with code 1\"` (cryptic, no context)\n**Source**: [GitHub Issue #131](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F131)\n**Why It Happens**: URL-based MCP servers require explicit `type: \"http\"` or `type: \"sse\"` field\n**Prevention**: Always specify transport type for URL-based MCP servers\n\n```typescript\n\u002F\u002F ❌ Wrong - missing type field (causes cryptic exit code 1)\nmcpServers: {\n  \"my-server\": {\n    url: \"https:\u002F\u002Fapi.example.com\u002Fmcp\"\n  }\n}\n\n\u002F\u002F ✅ Correct - type field required for URL-based servers\nmcpServers: {\n  \"my-server\": {\n    url: \"https:\u002F\u002Fapi.example.com\u002Fmcp\",\n    type: \"http\"  \u002F\u002F or \"sse\" for Server-Sent Events\n  }\n}\n```\n\n**Diagnostic Clue**: If you see \"process exited with code 1\" with no other context, check your MCP server configuration for missing `type` fields.\n\n### Issue #14: MCP Tool Result with Unicode Line Separators\n**Error**: JSON parse error, agent hangs\n**Source**: [GitHub Issue #137](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fissues\u002F137)\n**Why It Happens**: Unicode U+2028 (line separator) and U+2029 (paragraph separator) are valid in JSON but break JavaScript parsing\n**Prevention**: Escape these characters in MCP tool results\n\n```typescript\n\u002F\u002F MCP tool handler - sanitize external data\ntool(\"fetch_content\", \"Fetch text content\", {}, async (args) => {\n  const content = await fetchExternalData();\n\n  \u002F\u002F ✅ Sanitize Unicode line\u002Fparagraph separators\n  const sanitized = content\n    .replace(\u002F\\u2028\u002Fg, '\\\\u2028')\n    .replace(\u002F\\u2029\u002Fg, '\\\\u2029');\n\n  return {\n    content: [{ type: \"text\", text: sanitized }]\n  };\n});\n```\n\n**When This Matters**: External data sources (APIs, web scraping, user input) that may contain these characters\n\n**Related**: [MCP Python SDK Issue #1356](https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fpython-sdk\u002Fissues\u002F1356)\n\n---\n\n## Official Documentation\n\n- **Agent SDK Overview**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fapi\u002Fagent-sdk\u002Foverview\n- **TypeScript API**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fapi\u002Fagent-sdk\u002Ftypescript\n- **Structured Outputs**: https:\u002F\u002Fplatform.claude.com\u002Fdocs\u002Fen\u002Fagent-sdk\u002Fstructured-outputs\n- **GitHub (TypeScript)**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\n- **CHANGELOG**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-agent-sdk-typescript\u002Fblob\u002Fmain\u002FCHANGELOG.md\n\n---\n\n**Token Efficiency**:\n- **Without skill**: ~15,000 tokens (MCP setup, permission patterns, session APIs, sandbox config, hooks, structured outputs, error handling)\n- **With skill**: ~4,500 tokens (comprehensive v0.2.12 coverage + error prevention + advanced patterns)\n- **Savings**: ~70% (~10,500 tokens)\n\n**Errors prevented**: 14 documented issues with exact solutions (including 2 community-sourced gotchas)\n**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, subagent cleanup patterns\n\n---\n\n**Last verified**: 2026-01-20 | **Skill version**: 3.1.0 | **Changes**: Added Issue #13 (MCP type field), Issue #14 (Unicode U+2028\u002FU+2029), expanded Issue #4 (session-breaking), added subagent cleanup warning with Stop hook pattern\n",{"name":5,"description":43,"user-invocable":44},"Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors.\n\nUse when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup.\n",true,"main","e7e336ac628c3e3bd771aff1aaa469c93778f94a","skills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk",0,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del","2026-08-23 22:39:37",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":44},[54,57,60],{"tool":55,"command":56},"npx","npx skills add kbarbel640-del\u002Fskills --skill claude-agent-sdk",{"tool":58,"command":59},"bunx","bunx skills add kbarbel640-del\u002Fskills --skill claude-agent-sdk",{"tool":61,"command":62},"pnpm","pnpm dlx skills add kbarbel640-del\u002Fskills --skill claude-agent-sdk","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002FSKILL.md",[65,71,75,79,83,87,91,95,99,103,107,113,117,121,125,129,133,137,141,145,149,153],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"_meta.json","REFERENCE","参考文档",296,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002F_meta.json",{"path":72,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":73,"sourceHtmlUrl":74},".claude-plugin\u002Fplugin.json",651,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002F.claude-plugin\u002Fplugin.json",{"path":76,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":77,"sourceHtmlUrl":78},"README.md",13029,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002FREADME.md",{"path":80,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fmcp-servers-guide.md",7320,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Freferences\u002Fmcp-servers-guide.md",{"path":84,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fpermissions-guide.md",8368,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Freferences\u002Fpermissions-guide.md",{"path":88,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Fquery-api-reference.md",8627,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Freferences\u002Fquery-api-reference.md",{"path":92,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Fsession-management.md",9083,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Freferences\u002Fsession-management.md",{"path":96,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":97,"sourceHtmlUrl":98},"references\u002Fsubagents-patterns.md",9008,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Freferences\u002Fsubagents-patterns.md",{"path":100,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Ftop-errors.md",10037,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Freferences\u002Ftop-errors.md",{"path":104,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":105,"sourceHtmlUrl":106},"rules\u002Fclaude-agent-sdk.md",2283,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Frules\u002Fclaude-agent-sdk.md",{"path":108,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":111,"sourceHtmlUrl":112},"scripts\u002Fcheck-versions.sh","SCRIPT","脚本",1261,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Fscripts\u002Fcheck-versions.sh",{"path":114,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":115,"sourceHtmlUrl":116},"templates\u002Fbasic-query.ts",1302,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fbasic-query.ts",{"path":118,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":119,"sourceHtmlUrl":120},"templates\u002Fcustom-mcp-server.ts",4315,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fcustom-mcp-server.ts",{"path":122,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":123,"sourceHtmlUrl":124},"templates\u002Ferror-handling.ts",7976,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Ferror-handling.ts",{"path":126,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":127,"sourceHtmlUrl":128},"templates\u002Ffilesystem-settings.ts",5669,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Ffilesystem-settings.ts",{"path":130,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":131,"sourceHtmlUrl":132},"templates\u002Fmulti-agent-workflow.ts",8957,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fmulti-agent-workflow.ts",{"path":134,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":135,"sourceHtmlUrl":136},"templates\u002Fpackage.json",957,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fpackage.json",{"path":138,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":139,"sourceHtmlUrl":140},"templates\u002Fpermission-control.ts",5786,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fpermission-control.ts",{"path":142,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":143,"sourceHtmlUrl":144},"templates\u002Fquery-with-tools.ts",1569,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fquery-with-tools.ts",{"path":146,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":147,"sourceHtmlUrl":148},"templates\u002Fsession-management.ts",4217,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fsession-management.ts",{"path":150,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":151,"sourceHtmlUrl":152},"templates\u002Fsubagents-orchestration.ts",4419,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Fsubagents-orchestration.ts",{"path":154,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":155,"sourceHtmlUrl":156},"templates\u002Ftsconfig.json",536,"https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fveeramanikandanr48\u002Fclaude-agent-sdk\u002Ftemplates\u002Ftsconfig.json",[158,183,206,224,229,249],{"skillNo":159,"name":160,"nameZh":6,"description":161,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":162,"categories":163,"keywords":164,"publishedAt":38},"01M6G8J55967D6281ACMKAKTEQ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[165,166,167,168,169,170,171,172,173,174,175,176,32,177,178,179,180,181,182],"crowd prompting","prompting","api","with","tokens","domain","world","prompts","operations","instructions","text","tool","improve","productivity","marketplace","https","content","ai agents",{"skillNo":184,"name":185,"nameZh":6,"description":186,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":187,"categories":188,"keywords":189,"publishedAt":38},"01M6G8J0PKPAYVET6BWE8W4C26","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[190,167,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,172,29],"dilemm ai","arena","analyze","browser","openclaw agent","create","automation","browser automation","bot","openclaw","design","strategy","headless","compete","submit","matchmaking",{"skillNo":207,"name":208,"nameZh":6,"description":209,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":210,"categories":211,"keywords":212,"publishedAt":38},"01M6G8HWAF3K9SW7NP3Z83CPJ6","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, and submit comments. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, or submitting paper reviews via API at http:\u002F\u002F150.158.152.82:8000.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Fweak-accept\u002FSKILL.md",[],[213,214,215,216,217,218,219,168,220,204,29,221,167,222,223],"arxiv paper reviews","reviews","arxiv","paper","crawler","papers","comments","fetch","read","http","via",{"skillNo":225,"name":208,"nameZh":6,"description":209,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":226,"categories":227,"keywords":228,"publishedAt":38},"01M6G8HQJ7N7WMY6YV7D7SSJ16","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[216,215,214,213,223,218,219,168,217,204,29,220,221,167,222],{"skillNo":230,"name":231,"nameZh":6,"description":232,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":233,"categories":234,"keywords":235,"publishedAt":38},"01M6G8HM95Y64JNVFC2HN4E2BG","git-summary","Get a quick summary of the current Git repository including status, recent commits, branches, and contributors.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fzweack\u002Fgit-summary\u002FSKILL.md",[],[236,237,238,239,240,241,242,243,244,245,246,247,248],"git","summary","git summary","commits","repository","win32","status","linux","contributors","true","quick","get","branches",{"skillNo":250,"name":251,"nameZh":6,"description":252,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":253,"categories":254,"keywords":255,"publishedAt":38},"01M6G8HGEGF05CNEJCGVYFSC4R","agent-constitution","Interact with AgentConstitution governance contracts on Base Sepolia. Check compliance, read rules, log actions, query governance state.","https:\u002F\u002Fgithub.com\u002Fkbarbel640-del\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fztsalexey\u002Fagent-constitution\u002FSKILL.md",[],[256,257,258,259,168,260,261,45,262,221,263,264,265,266,267,180,268,269,270],"agent constitution","constitution","contracts","tree","query","base","log","check","Rules","projects","compliance","actions","state","governance","github"]