{"_id":"@blitzjb/claude-code-sdk","_rev":"5-9e8c0025f1944833a6b60734bbfa0b75","name":"@blitzjb/claude-code-sdk","dist-tags":{"latest":"0.3.0"},"versions":{"0.1.0":{"name":"@blitzjb/claude-code-sdk","version":"0.1.0","keywords":["claude","ai","typescript","sdk","streaming","conversational"],"author":"","license":"MIT","_id":"@blitzjb/claude-code-sdk@0.1.0","maintainers":[{"name":"blitzjb","email":"blitz04.dev@gmail.com"}],"dist":{"shasum":"a64bc88f4222c5601637d049d78f2a72c1358c14","tarball":"https://registry.npmjs.org/@blitzjb/claude-code-sdk/-/claude-code-sdk-0.1.0.tgz","fileCount":38,"integrity":"sha512-Fx8EUlcQ5FdhADWdZpOFNvAcb7VHnVLz0j+OLwCy2Jp/HboaAq5rdTG24WziNcVdnCuCGfpKsxCuDgwOZgEGEA==","signatures":[{"sig":"MEUCIB/x/07Eu6+fpLYZ9vz1brYbrD8QoSZnAqn0dmfz4mkCAiEAn9fW5DXNnFpmdT/vnq2xuhwga/6wAloLCCY574m4yu4=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":68766},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=16.0.0"},"scripts":{"dev":"tsc --watch","lint":"eslint src/**/*.ts","test":"jest","build":"tsc","format":"prettier --write src/**/*.ts","prepublishOnly":"npm run build"},"_npmUser":{"name":"blitzjb","email":"blitz04.dev@gmail.com"},"_npmVersion":"10.9.2","description":"A conversational TypeScript SDK for Claude CLI with streaming support","directories":{},"_nodeVersion":"23.6.0","dependencies":{"node-pty":"^1.0.0"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.0.0","eslint":"^8.0.0","prettier":"^3.0.0","typescript":"^5.0.0","@types/node":"^20.0.0","@typescript-eslint/parser":"^6.0.0","@typescript-eslint/eslint-plugin":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claude-code-sdk_0.1.0_1756096551580_0.37127797333719625","host":"s3://npm-registry-packages-npm-production"}},"0.1.1":{"name":"@blitzjb/claude-code-sdk","version":"0.1.1","keywords":["claude","ai","typescript","sdk","streaming","conversational"],"author":"","license":"MIT","_id":"@blitzjb/claude-code-sdk@0.1.1","maintainers":[{"name":"blitzjb","email":"blitz04.dev@gmail.com"}],"dist":{"shasum":"443e4a1c1a5fdf8550fd0818a5208533e9afb302","tarball":"https://registry.npmjs.org/@blitzjb/claude-code-sdk/-/claude-code-sdk-0.1.1.tgz","fileCount":38,"integrity":"sha512-C1tbIk4kvXVlfV+8xktIjsy5J0RsQh2ArYy7i0IOsr8iRKNuYBAwkvZWR9COcwl4HDDMipPFaMHKYn2n9iubvA==","signatures":[{"sig":"MEQCIEkx93NxAHaJ+sGA02N+N6qpX+8+IpoQY/DHGADh/ZYVAiAixvAqyt+SOV6p45ZM0fSY8rI9i1bmaH3K7h73vjtPTA==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":68799},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=16.0.0"},"scripts":{"dev":"tsc --watch","lint":"eslint src/**/*.ts","test":"jest","build":"tsc","format":"prettier --write src/**/*.ts","prepublishOnly":"npm run build"},"_npmUser":{"name":"blitzjb","email":"blitz04.dev@gmail.com"},"_npmVersion":"10.9.2","description":"A conversational TypeScript SDK for Claude CLI with streaming support","directories":{},"_nodeVersion":"23.6.0","dependencies":{"node-pty":"^1.0.0"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.0.0","eslint":"^8.0.0","prettier":"^3.0.0","typescript":"^5.0.0","@types/node":"^20.0.0","@typescript-eslint/parser":"^6.0.0","@typescript-eslint/eslint-plugin":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claude-code-sdk_0.1.1_1756125739973_0.40889781948895987","host":"s3://npm-registry-packages-npm-production"}},"0.2.0":{"name":"@blitzjb/claude-code-sdk","version":"0.2.0","keywords":["claude","ai","typescript","sdk","streaming","conversational"],"author":"","license":"MIT","_id":"@blitzjb/claude-code-sdk@0.2.0","maintainers":[{"name":"blitzjb","email":"blitz04.dev@gmail.com"}],"dist":{"shasum":"52a70a4e8db33f08886516cfa827e2e2c76ccba6","tarball":"https://registry.npmjs.org/@blitzjb/claude-code-sdk/-/claude-code-sdk-0.2.0.tgz","fileCount":42,"integrity":"sha512-zhuXKmcUz68dCCp8txTi8nC5xMJQR1jC3lxegKbH+hqvb93nd7FoAfkBke9rMFgku3/uw4tp8563fpjl2dG5EA==","signatures":[{"sig":"MEYCIQD8LOY6SBxwVkdE5fOWTMHFl8+ce4zfcR+G8DplEwavgwIhAJtQS+UbPXD4m1l4vBM8vx82hGCRh6+FPN5eJyM9fCpu","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":89409},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=16.0.0"},"scripts":{"dev":"tsc --watch","lint":"eslint src/**/*.ts","test":"jest","build":"tsc","format":"prettier --write src/**/*.ts","prepublishOnly":"npm run build"},"_npmUser":{"name":"blitzjb","email":"blitz04.dev@gmail.com"},"_npmVersion":"10.9.2","description":"A conversational TypeScript SDK for Claude CLI with streaming support","directories":{},"_nodeVersion":"23.6.0","dependencies":{"node-pty":"^1.0.0"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.0.0","eslint":"^8.0.0","prettier":"^3.0.0","typescript":"^5.0.0","@types/node":"^20.0.0","@typescript-eslint/parser":"^6.0.0","@typescript-eslint/eslint-plugin":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claude-code-sdk_0.2.0_1756149692732_0.542299080175056","host":"s3://npm-registry-packages-npm-production"}},"0.2.1":{"name":"@blitzjb/claude-code-sdk","version":"0.2.1","keywords":["claude","ai","typescript","sdk","streaming","conversational"],"author":"","license":"MIT","_id":"@blitzjb/claude-code-sdk@0.2.1","maintainers":[{"name":"blitzjb","email":"blitz04.dev@gmail.com"}],"dist":{"shasum":"7746af2c316512f6b2aa1a8efe5c501404b3132c","tarball":"https://registry.npmjs.org/@blitzjb/claude-code-sdk/-/claude-code-sdk-0.2.1.tgz","fileCount":42,"integrity":"sha512-bzhO7Q7j3KI905CMRReZAhbu2aX4WyjvwQcBdI2eU+FIfqjZZo89ceSkSLboI9HeAsdGMynhXSekT6y6GwZN7w==","signatures":[{"sig":"MEYCIQCTEtRwmgsQY49XfFovnDLJsfQ0EjN3kMuWpB7B0XtMRwIhANXZl/yuFzGYbS7DdeY2IUnUfrtSK9Z7F5QMXdrrCojv","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":76419},"main":"dist/index.js","types":"dist/index.d.ts","engines":{"node":">=16.0.0"},"scripts":{"dev":"tsc --watch","lint":"eslint src/**/*.ts","test":"jest","build":"tsc","format":"prettier --write src/**/*.ts","prepublishOnly":"npm run build"},"_npmUser":{"name":"blitzjb","email":"blitz04.dev@gmail.com"},"_npmVersion":"10.9.2","description":"A conversational TypeScript SDK for Claude CLI with streaming support","directories":{},"_nodeVersion":"23.6.0","dependencies":{"node-pty":"^1.0.0"},"_hasShrinkwrap":false,"devDependencies":{"jest":"^29.0.0","eslint":"^8.0.0","prettier":"^3.0.0","typescript":"^5.0.0","@types/node":"^20.0.0","@typescript-eslint/parser":"^6.0.0","@typescript-eslint/eslint-plugin":"^6.0.0"},"_npmOperationalInternal":{"tmp":"tmp/claude-code-sdk_0.2.1_1756150168675_0.7791698577826005","host":"s3://npm-registry-packages-npm-production"}},"0.3.0":{"name":"@blitzjb/claude-code-sdk","version":"0.3.0","description":"A conversational TypeScript SDK for Claude CLI with streaming support","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","dev":"tsc --watch","test":"jest","lint":"eslint src/**/*.ts","format":"prettier --write src/**/*.ts","prepublishOnly":"npm run build"},"keywords":["claude","ai","typescript","sdk","streaming","conversational"],"author":"","license":"MIT","devDependencies":{"@types/node":"^20.0.0","@typescript-eslint/eslint-plugin":"^6.0.0","@typescript-eslint/parser":"^6.0.0","eslint":"^8.0.0","jest":"^29.0.0","prettier":"^3.0.0","typescript":"^5.0.0"},"dependencies":{"node-pty":"^1.0.0"},"engines":{"node":">=16.0.0"},"_id":"@blitzjb/claude-code-sdk@0.3.0","_nodeVersion":"23.6.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-WSc99r5p0PP+QQPYVLjT6Ha44k7fpqbo8hnbUZ8sE1PcYZF7MIE5Kwe2/qG+DRSmQ6UVnciHOrjFeseETjstaw==","shasum":"136cd5fccb36708aa20b3cfe191f195e8d8d5848","tarball":"https://registry.npmjs.org/@blitzjb/claude-code-sdk/-/claude-code-sdk-0.3.0.tgz","fileCount":42,"unpackedSize":87346,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCK89GPBgF9Dm4KFirzntWU+FLTotFuC3xiCScAhP6nYgIgGwHh0/VuW+J0ZYmKN1f78WZ96ptQe0IWY61SdnhSAIY="}]},"_npmUser":{"name":"blitzjb","email":"blitz04.dev@gmail.com"},"directories":{},"maintainers":[{"name":"blitzjb","email":"blitz04.dev@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/claude-code-sdk_0.3.0_1756191253627_0.8742670187525607"},"_hasShrinkwrap":false}},"time":{"created":"2025-08-25T04:35:51.480Z","modified":"2025-08-26T06:54:13.975Z","0.1.0":"2025-08-25T04:35:51.752Z","0.1.1":"2025-08-25T12:42:20.140Z","0.2.0":"2025-08-25T19:21:32.941Z","0.2.1":"2025-08-25T19:29:28.855Z","0.3.0":"2025-08-26T06:54:13.804Z"},"license":"MIT","keywords":["claude","ai","typescript","sdk","streaming","conversational"],"description":"A conversational TypeScript SDK for Claude CLI with streaming support","maintainers":[{"name":"blitzjb","email":"blitz04.dev@gmail.com"}],"readme":"# Claude Code SDK\n\nA conversational TypeScript SDK for Claude CLI with session management, robust error handling, and **full subagent support**.\n\n## 🚨 Important Note for Newer Claude CLI Versions\n\nDue to known issues with programmatic execution of Claude CLI (particularly versions with stream-json hanging), this SDK focuses on **session management and history loading** rather than direct CLI execution. \n\n**The SDK excels at:**\n- ✅ Loading and parsing existing Claude CLI session history\n- ✅ Type-safe conversation management  \n- ✅ Session resumption with full context\n- ✅ Unified message handling across all interaction types\n- ✅ **Full subagent detection and tracking**\n- ✅ **Hierarchical message parsing with parent-child relationships**\n- ✅ **Complete project and session discovery**\n- ✅ **Directory enumeration for all Claude projects**\n\n**For new conversations:**\n- The SDK provides the exact command to run manually\n- Session history is automatically loaded once Claude CLI creates the session file\n- Full conversation context is maintained for subsequent operations\n\n## Features\n\n- 🗣️ **Conversational API**: Natural `.say()` and `.ask()` methods\n- 💾 **History Integration**: Uses Claude's built-in session storage\n- 🔒 **Type Safety**: Full TypeScript support with discriminated unions\n- 🛡️ **Robust Error Handling**: Graceful parsing with unknown message recovery\n- ⚡ **Session Management**: Automatic loading and resumption\n- 🎯 **Zero Dependencies**: Lightweight (only node-pty for terminal compatibility)\n\n## Installation\n\n```bash\nnpm install @blitzjb/claude-code-sdk\n```\n\n## Quick Start\n\n### Basic Session Management\n\n```typescript\nimport { Claude } from '@blitzjb/claude-code-sdk';\n\n// Start a conversation (provides manual command to run)\nconst conversation = await Claude.start();\n\n// The SDK will provide the command to run:\n// claude -p \"your prompt\" --output-format json --dangerously-skip-permissions\n\n// After running the command manually, resume the session\nconst resumedChat = await Claude.resume(conversation.sessionId);\nconst history = resumedChat.getHistory();\nconsole.log(`Loaded ${history.length} messages`);\n```\n\n### Working with Existing Sessions\n\n```typescript\n// Resume an existing session ID\nconst chat = await Claude.resume('existing-session-id');\nawait chat.load();\n\nconst history = chat.getHistory();\nconsole.log(`Session has ${history.length} messages`);\n\n// Get specific message types\nconst userMessages = history.filter(msg => msg.type === 'user');\nconst assistantMessages = history.filter(msg => msg.type === 'assistant');\n\n// Access conversation content\nhistory.forEach((msg, index) => {\n  console.log(`${index + 1}. [${msg.timestamp.toLocaleTimeString()}] ${msg.type}: ${\n    typeof msg.content === 'string' ? msg.content.substring(0, 50) + '...' : 'Tool use'\n  }`);\n});\n```\n\n### Type-Safe Message Handling\n\n```typescript\nconst conversation = await Claude.resume('session-id');\nawait conversation.load();\n\nconst messages = conversation.getHistory();\n\nmessages.forEach(msg => {\n  switch(msg.type) {\n    case 'user':\n      console.log(`User: ${msg.content}`);\n      break;\n    case 'assistant':\n      if (typeof msg.content === 'string') {\n        console.log(`Claude: ${msg.content}`);\n      } else {\n        console.log(`Tool: ${msg.content.name}`);\n      }\n      break;\n    case 'tool_result':\n      console.log(`Result: ${msg.content}`);\n      break;\n    case 'system':\n      console.log(`System: ${msg.subtype}`);\n      break;\n  }\n});\n```\n\n## API Reference\n\n### Claude Class\n\n```typescript\n// Start a new conversation (returns instructions for manual execution)\nconst chat = await Claude.start({ debug: true });\n\n// Resume existing conversation\nconst chat = await Claude.resume('session-id');\n\n// Check if session exists\nconst exists = await Claude.sessionExists('session-id');\n\n// Get session summary\nconst summary = await Claude.getSessionSummary('session-id');\n```\n\n### Conversation Class\n\n```typescript\n// Load conversation history\nawait conversation.load();\n\n// Get conversation history\nconst messages = conversation.getHistory();\nconst count = conversation.getMessageCount();\nconst lastMsg = conversation.getLastMessage();\n\n// Get messages by type\nconst userMessages = conversation.getMessagesByType('user');\n```\n\n## Subagent Support\n\nThe SDK automatically detects and parses subagent interactions from Claude CLI sessions. Subagent messages are included as part of the regular conversation history with additional metadata.\n\n### Simple History Loading\n\n```typescript\nimport { Claude } from '@blitzjb/claude-code-sdk';\n\n// Load all history from a session (includes subagent interactions)\nconst history = await Claude.loadHistory('session-id');\n\n// Filter subagent-related messages\nconst subagentMessages = history.filter(msg => (msg as any).parentToolUseId);\nconsole.log(`Found ${subagentMessages.length} subagent messages`);\n\n// Find Task tool calls (subagent initiations)\nconst taskCalls = history.filter(msg => \n  msg.type === 'assistant' && \n  typeof msg.content === 'object' && \n  msg.content?.name === 'Task'\n);\n\nconsole.log(`Found ${taskCalls.length} subagent tasks`);\n```\n\n### Working with Subagent Data\n\n```typescript\n// Load conversation with subagent data\nconst conversation = await Claude.resume('session-id');\nconst messages = conversation.getHistory();\n\n// Process each message\nmessages.forEach((msg, index) => {\n  console.log(`Message ${index}: ${msg.type}`);\n  \n  // Check if this message is part of a subagent\n  if ((msg as any).parentToolUseId) {\n    console.log(`  Part of subagent: ${(msg as any).parentToolUseId}`);\n  }\n  \n  // Check if this is a subagent task initiation\n  if ((msg as any).isSubagentTask) {\n    console.log(`  Subagent type: ${(msg as any).subagentType}`);\n  }\n});\n```\n\n### Subagent Types\n\nSupports any custom subagent type as a string:\n\n```typescript\ntype SubagentType = string; // 'general-purpose', 'custom-agent', etc.\n```\n\n### Example: Manual Command\n\n```typescript\n// Run this to generate subagent interactions:\n// claude -p \"Please use the general-purpose agent to analyze this code\" --output-format stream-json --verbose\n\n// Then load the session:\nconst sessionId = 'your-session-id-from-cli';\nconst history = await Claude.loadHistory(sessionId);\n\n// Subagent interactions are automatically parsed and included\nconsole.log(`Total messages: ${history.length}`);\n```\n\n## Project and Session Discovery\n\nThe SDK provides comprehensive methods to discover and enumerate all Claude projects and sessions.\n\n### List All Projects\n\n```typescript\n// Get all project directories in ~/.claude/projects/\nconst projects = await Claude.listProjects();\nconsole.log(`Found ${projects.length} projects:`);\n\nprojects.forEach(project => {\n  const realPath = Claude.getProjectNameFromPath(project);\n  console.log(`${project} → ${realPath}`);\n});\n```\n\n### List Sessions in a Project\n\n```typescript\n// Get all sessions within a specific project\nconst sessions = await Claude.listSessionsInProject('project-name');\nconsole.log(`Found ${sessions.length} sessions in project`);\n\nsessions.forEach(sessionId => {\n  console.log(`Session: ${sessionId}`);\n});\n```\n\n### Get All Sessions Globally\n\n```typescript\n// Get all sessions across all projects\nconst allSessions = await Claude.getAllSessions();\nconsole.log(`Total sessions: ${allSessions.length}`);\n\nallSessions.forEach(({project, sessionId}) => {\n  const realPath = Claude.getProjectNameFromPath(project);\n  console.log(`${realPath}: ${sessionId}`);\n});\n```\n\n### Utility Methods\n\n```typescript\n// Check if a project exists\nconst exists = await Claude.projectExists('project-name');\n\n// Convert encoded project path to real path\nconst realPath = Claude.getProjectNameFromPath('-Users-user-Projects-myapp');\nconsole.log(realPath); // Users/user/Projects/myapp\n\n// Load history from a specific project and session\nconst sessionFile = ClaudePaths.getSessionFileFromProject(sessionId, projectName);\n```\n\n### Complete Discovery Example\n\n```typescript\nimport { Claude } from '@blitzjb/claude-code-sdk';\n\nasync function discoverAllSessions() {\n  // Get all projects\n  const projects = await Claude.listProjects();\n  console.log(`📁 Found ${projects.length} projects`);\n  \n  // Get all sessions globally\n  const allSessions = await Claude.getAllSessions();\n  console.log(`💬 Found ${allSessions.length} total sessions`);\n  \n  // Group sessions by project\n  const sessionsByProject = allSessions.reduce((acc, {project, sessionId}) => {\n    if (!acc[project]) acc[project] = [];\n    acc[project].push(sessionId);\n    return acc;\n  }, {} as Record<string, string[]>);\n  \n  // Display summary\n  for (const [project, sessions] of Object.entries(sessionsByProject)) {\n    const realPath = Claude.getProjectNameFromPath(project);\n    console.log(`\\n${realPath}:`);\n    console.log(`  ${sessions.length} sessions`);\n    \n    // Load a sample session\n    if (sessions.length > 0) {\n      const history = await Claude.loadHistory(sessions[0]);\n      console.log(`  Sample session has ${history.length} messages`);\n    }\n  }\n}\n```\n\n## Message Types\n\nAll messages use a unified type system:\n\n```typescript\ntype Message = \n  | UserMessage      // { type: 'user', content: string }\n  | AssistantMessage // { type: 'assistant', content: string | ToolUse }\n  | ToolMessage      // { type: 'tool_result', toolUseId, content }\n  | SystemMessage    // { type: 'system', subtype, data }\n  | UnknownMessage;  // { type: 'unknown', raw, parseError }\n```\n\n## Workflow\n\n### 1. Starting a New Conversation\n\n```typescript\nconst conversation = await Claude.start();\nconsole.log(`Session ID: ${conversation.sessionId}`);\n\n// SDK provides the command to run manually:\n// claude -p \"your prompt\" --output-format json --dangerously-skip-permissions\n```\n\n### 2. Working with Session History\n\n```typescript\n// After running Claude CLI manually, resume the session\nconst chat = await Claude.resume('session-id-from-step-1');\nawait chat.load();\n\nconst history = chat.getHistory();\nconsole.log(`Loaded ${history.length} messages from Claude CLI session`);\n```\n\n### 3. Continuing Conversations\n\n```typescript\n// For continued conversations, the SDK provides the resume command:\n// claude -p \"follow up question\" --resume session-id --output-format json --dangerously-skip-permissions\n\n// Then load the updated session:\nawait chat.load(); // Reloads with new messages\nconst updatedHistory = chat.getHistory();\n```\n\n## Why This Approach?\n\n1. **Claude CLI Reliability Issues**: Programmatic execution of Claude CLI has known hanging issues with stream-json format\n2. **Session Persistence**: Manual execution ensures sessions are properly saved to Claude's storage\n3. **Full Feature Access**: Manual execution provides access to all Claude CLI features (tools, etc.)\n4. **Type Safety**: SDK provides full TypeScript safety for session management\n5. **Best of Both Worlds**: Combines Claude CLI's full capabilities with SDK convenience\n\n## Session Storage\n\nThe SDK reads from Claude CLI's built-in storage:\n- Location: `~/.claude/projects/`\n- Format: JSONL files with UUID names\n- Content: Complete conversation history with tools, timestamps, and metadata\n\n## Configuration\n\n```typescript\n// Debug mode for detailed logging\nconst conversation = await Claude.start({ debug: true });\n\n// Work with specific session ID\nconst conversation = await Claude.start({ sessionId: 'your-uuid' });\n\n// Validate session ID format\nif (Claude.validateSessionId(sessionId)) {\n  // Valid UUID format\n}\n```\n\n## Requirements\n\n- Node.js 16+\n- Claude CLI installed and configured\n- TypeScript 5+ (for development)\n\n## Contributing\n\n1. Clone the repository\n2. Run `npm install`\n3. Run `npm run build` to compile TypeScript\n4. Test with existing Claude CLI sessions\n\n## License\n\nMIT\n\n## Support\n\nFor issues related to:\n- **Claude CLI execution**: Check [Claude Code GitHub Issues](https://github.com/anthropics/claude-code/issues)\n- **SDK functionality**: Open an issue in this repository\n\nThe SDK provides a robust, type-safe interface for working with Claude CLI sessions while respecting the CLI's execution limitations.","readmeFilename":"README.md"}