ai-pro-sdk 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ # AI SDK v4 Documentation (Historical)
2
+
3
+ > **Historical:** These documents cover legacy provider versions 0.x (AI SDK v4, `@anthropic-ai/claude-code`). For current documentation, see the [main README](../../README.md).
4
+
5
+ - [GUIDE.md](GUIDE.md) - Usage guide
6
+ - [TROUBLESHOOTING.md](TROUBLESHOOTING.md) - Common issues and solutions
7
+ - [DEVELOPMENT-STATUS.md](DEVELOPMENT-STATUS.md) - Development status
@@ -0,0 +1,249 @@
1
+ # Troubleshooting Guide
2
+
3
+ This guide documents common issues and solutions for the Claude Code AI SDK Provider.
4
+
5
+ ## Common Issues
6
+
7
+ ### 1. Authentication Errors
8
+
9
+ **Problem**: Getting authentication errors when trying to use the provider.
10
+
11
+ **Solution**:
12
+
13
+ ```bash
14
+ # Install Claude Code SDK globally
15
+ npm install -g @anthropic-ai/claude-code
16
+
17
+ # Authenticate with your Claude account
18
+ claude login
19
+ ```
20
+
21
+ **Verification**:
22
+
23
+ ```bash
24
+ # Check if authenticated
25
+ npx tsx ../examples/check-cli.ts
26
+ ```
27
+
28
+ ### 2. SDK Not Found
29
+
30
+ **Problem**: Error about `@anthropic-ai/claude-code` module not found.
31
+
32
+ **Solution**: The SDK is a dependency of this provider and should be installed automatically. If not:
33
+
34
+ ```bash
35
+ npm install @anthropic-ai/claude-code
36
+ ```
37
+
38
+ ### 3. Handling Long-Running Tasks
39
+
40
+ **Problem**: Complex queries with Claude Opus 4 may take longer due to extended thinking mode.
41
+
42
+ **Solution**: Use AbortSignal with custom timeouts:
43
+
44
+ ```typescript
45
+ import { generateText } from 'ai';
46
+ import { claudeCode } from 'ai-sdk-provider-claude-code';
47
+
48
+ // Create a custom timeout (5 minutes for complex tasks)
49
+ const controller = new AbortController();
50
+ const timeoutId = setTimeout(() => {
51
+ controller.abort(new Error('Request timeout'));
52
+ }, 300000);
53
+
54
+ try {
55
+ const { text } = await generateText({
56
+ model: claudeCode('opus'),
57
+ prompt: 'Complex reasoning task...',
58
+ abortSignal: controller.signal,
59
+ });
60
+ clearTimeout(timeoutId);
61
+ } catch (error) {
62
+ if (error.name === 'AbortError') {
63
+ console.log('Request timed out');
64
+ }
65
+ }
66
+ ```
67
+
68
+ **Guidelines**:
69
+
70
+ - Simple queries: Default timeout is sufficient
71
+ - Complex reasoning: 5-10 minutes may be needed
72
+ - Very long tasks: Consider breaking into smaller chunks
73
+
74
+ ### 4. Object Generation Issues
75
+
76
+ **Problem**: Claude returns text instead of valid JSON when using `generateObject`.
77
+
78
+ **Solutions**:
79
+
80
+ 1. **Simplify your schema** - Start with fewer fields
81
+ 2. **Clear prompts** - Be explicit: "Generate a user profile with name and age"
82
+ 3. **Use descriptions** - Add `.describe()` to schema fields
83
+ 4. **Retry logic** - Implement retries for production:
84
+
85
+ ```typescript
86
+ async function generateWithRetry(schema, prompt, maxRetries = 3) {
87
+ for (let i = 0; i < maxRetries; i++) {
88
+ try {
89
+ return await generateObject({
90
+ model: claudeCode('sonnet'),
91
+ schema,
92
+ prompt,
93
+ });
94
+ } catch (error) {
95
+ if (i === maxRetries - 1) throw error;
96
+ await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, i)));
97
+ }
98
+ }
99
+ }
100
+ ```
101
+
102
+ ### 5. Session Management
103
+
104
+ **Problem**: Conversations don't maintain context.
105
+
106
+ **Solution**: Use message history (recommended pattern):
107
+
108
+ ```typescript
109
+ const messages = [
110
+ { role: 'user', content: 'My name is Alice' },
111
+ { role: 'assistant', content: 'Nice to meet you, Alice!' },
112
+ { role: 'user', content: 'What is my name?' },
113
+ ];
114
+
115
+ const { text } = await generateText({
116
+ model: claudeCode('sonnet'),
117
+ messages, // Pass full conversation history
118
+ });
119
+ ```
120
+
121
+ **Note**: While the provider returns session IDs in metadata, the recommended approach is to use message history for conversation continuity.
122
+
123
+ ### 6. Error Handling
124
+
125
+ **Problem**: Need to handle different types of errors appropriately.
126
+
127
+ **Solution**: Use the provider's error utilities:
128
+
129
+ ```typescript
130
+ import { isAuthenticationError, getErrorMetadata } from 'ai-sdk-provider-claude-code';
131
+
132
+ try {
133
+ const { text } = await generateText({
134
+ model: claudeCode('sonnet'),
135
+ prompt: 'Hello',
136
+ });
137
+ } catch (error) {
138
+ if (isAuthenticationError(error)) {
139
+ console.error('Please run: claude login');
140
+ } else if (error.name === 'AbortError') {
141
+ console.error('Request was cancelled or timed out');
142
+ } else {
143
+ // Get additional error details
144
+ const metadata = getErrorMetadata(error);
145
+ console.error('Error details:', metadata);
146
+ }
147
+ }
148
+ ```
149
+
150
+ ## Debugging Tips
151
+
152
+ ### 1. Verify Setup
153
+
154
+ ```bash
155
+ # Check Claude CLI version
156
+ claude --version
157
+
158
+ # Test authentication
159
+ npx tsx ../examples/check-cli.ts
160
+
161
+ # Run integration tests
162
+ npx tsx ../examples/integration-test.ts
163
+ ```
164
+
165
+ ### 2. Enable Debug Logging
166
+
167
+ ```typescript
168
+ // Log provider metadata to debug issues
169
+ const { text, providerMetadata } = await generateText({
170
+ model: claudeCode('sonnet'),
171
+ prompt: 'Test',
172
+ });
173
+
174
+ console.log('Metadata:', providerMetadata);
175
+ // Shows: sessionId, costUsd, durationMs, rawUsage
176
+ ```
177
+
178
+ ### 3. Test Specific Features
179
+
180
+ ```bash
181
+ # Test streaming
182
+ npx tsx ../examples/streaming.ts
183
+
184
+ # Test object generation
185
+ npx tsx ../examples/generate-object-basic.ts
186
+
187
+ # Test conversations
188
+ npx tsx ../examples/conversation-history.ts
189
+
190
+ # Test long-running tasks
191
+ npx tsx ../examples/long-running-tasks.ts
192
+ ```
193
+
194
+ ## Platform-Specific Issues
195
+
196
+ ### Windows
197
+
198
+ - Ensure Claude CLI is in your PATH
199
+ - Use PowerShell or Command Prompt (not WSL) for installation
200
+
201
+ ### macOS
202
+
203
+ - May need to allow CLI in Security & Privacy settings
204
+ - Use Homebrew or direct npm installation
205
+
206
+ ### Linux
207
+
208
+ - Ensure Node.js ≥ 18 is installed
209
+ - May need to use `sudo` for global npm installs
210
+
211
+ ## Performance Tips
212
+
213
+ 1. **Model Selection**
214
+ - Use `sonnet` for faster responses
215
+ - Use `opus` for complex reasoning tasks
216
+
217
+ 2. **Request Optimization**
218
+ - Keep prompts concise and clear
219
+ - Use streaming for better UX
220
+ - Implement proper error handling
221
+
222
+ 3. **Resource Management**
223
+ - The provider manages concurrent requests automatically
224
+ - Use AbortSignal for cancellable requests
225
+ - Clean up timeouts in finally blocks
226
+
227
+ ## Known Limitations
228
+
229
+ 1. **No Image Support**: The Claude Code SDK doesn't support image inputs
230
+ 2. **No AI SDK Tool Calling**: The AI SDK's function calling interface isn't implemented, but Claude can use tools via MCP servers and built-in CLI tools
231
+ 3. **Object Generation**: Relies on prompt engineering rather than native JSON mode
232
+ 4. **Model Options**: Limited to 'opus' and 'sonnet' models
233
+
234
+ ## Getting Help
235
+
236
+ 1. **Check Examples**: Review the `../examples` directory for working code
237
+ 2. **Integration Test**: Run `npx tsx ../examples/integration-test.ts` to verify setup
238
+ 3. **GitHub Issues**: Report bugs at https://github.com/ben-vargas/ai-sdk-provider-claude-code/issues
239
+ 4. **Documentation**: See the main README.md and GUIDE.md for detailed API documentation
240
+
241
+ ## Common Error Messages
242
+
243
+ | Error | Cause | Solution |
244
+ | ---------------------------------- | --------------------- | ---------------------------------------------- |
245
+ | "Claude Code executable not found" | CLI not installed | Run `npm install -g @anthropic-ai/claude-code` |
246
+ | "Authentication required" | Not logged in | Run `claude login` |
247
+ | "No object generated" | Invalid JSON response | Simplify schema, improve prompt |
248
+ | "Request timeout" | Task took too long | Increase timeout with AbortSignal |
249
+ | "Session not found" | Invalid session ID | Use message history instead |
@@ -0,0 +1,309 @@
1
+ # Community Provider Status Analysis (v5)
2
+
3
+ ## Overview
4
+
5
+ This document analyzes the requirements for ai-sdk-provider-claude-code to achieve community provider status in the Vercel AI SDK v5 ecosystem.
6
+
7
+ ## Current Implementation Status
8
+
9
+ ### ✅ What We Have
10
+
11
+ #### Core Functionality
12
+
13
+ - **SDK Integration**: Uses official `@anthropic-ai/claude-agent-sdk` for all Claude interactions
14
+ - **Text Generation**: Full support for both streaming and non-streaming text generation with v5 patterns
15
+ - **Object Generation**: Reliable JSON generation through prompt engineering and extraction
16
+ - **Multi-turn Conversations**: Proper message history support with v5 message format
17
+ - **Provider Metadata**: Rich metadata including sessionId, costUsd, durationMs, and rawUsage
18
+ - **Error Handling**: Comprehensive error handling with authentication detection
19
+ - **AbortSignal Support**: Standard AI SDK pattern for timeouts and cancellation
20
+
21
+ #### v5 Specific Features
22
+
23
+ - **LanguageModelV2 Implementation**: Fully compliant with `specificationVersion: 'v2'`
24
+ - **Stream-Start Event**: Properly emits initial stream event with warnings
25
+ - **Token Usage Naming**: Uses v5 convention (inputTokens, outputTokens, totalTokens)
26
+ - **Message Format**: Supports v5's array-based content structure
27
+ - **Promise-based Streaming**: Implements v5's new streaming API pattern
28
+
29
+ #### Build & Distribution
30
+
31
+ - **TypeScript**: Full TypeScript support with proper type definitions
32
+ - **Dual Formats**: Both CommonJS and ES Module builds via tsup
33
+ - **Source Maps**: Generated for debugging support
34
+ - **Package Structure**: Proper exports configuration for modern Node.js
35
+ - **Beta Tag**: Published with `beta` tag on npm
36
+
37
+ #### Testing
38
+
39
+ - **Unit Tests**: Comprehensive test coverage with Vitest
40
+ - **Integration Tests**: Full integration test suite
41
+ - **Edge/Node Tests**: Separate configurations for different environments
42
+ - **Examples**: Extensive example collection demonstrating all v5 features
43
+
44
+ #### Documentation
45
+
46
+ - **README**: Comprehensive documentation with version compatibility matrix
47
+ - **CHANGELOG**: Proper version history following Keep a Changelog format
48
+ - **Examples README**: Detailed guide for all example files
49
+ - **API Documentation**: Clear documentation of all configuration options
50
+ - **Migration Guide**: Comprehensive v4 to v5 migration documentation
51
+
52
+ ### 🚀 Meeting AI SDK v5 Standards
53
+
54
+ Based on analysis of official v5 providers, we now meet all requirements:
55
+
56
+ 1. **Provider Pattern** ✅
57
+ - Factory function with provider instance
58
+ - Default export
59
+ - Proper settings interface
60
+ - Protection against `new` keyword misuse
61
+
62
+ 2. **Language Model Implementation** ✅
63
+ - `specificationVersion: 'v2'`
64
+ - Correct `doGenerate` and `doStream` methods for v5
65
+ - Proper provider metadata
66
+ - Object generation support
67
+ - Stream-start event emission
68
+
69
+ 3. **Build System** ✅
70
+ - tsup for dual format builds
71
+ - Source maps
72
+ - Proper package.json configuration
73
+ - Beta tag in publishConfig
74
+
75
+ 4. **Testing** ✅
76
+ - Separate edge/node configurations
77
+ - Unit and integration tests
78
+ - Example test coverage
79
+ - All tests passing with v5 patterns
80
+
81
+ 5. **Error Handling** ✅
82
+ - Standard AI SDK error classes
83
+ - Proper `isRetryable` flags
84
+ - AbortSignal support
85
+
86
+ ## 📁 Current Project Structure
87
+
88
+ ```
89
+ ai-sdk-provider-claude-code/
90
+ ├── src/
91
+ │ ├── index.ts # Main exports
92
+ │ ├── claude-code-provider.ts # Provider factory
93
+ │ ├── claude-code-language-model.ts # Language model implementation (v2)
94
+ │ ├── convert-to-claude-code-messages.ts # Message formatting (v5 format)
95
+ │ ├── extract-json.ts # JSON extraction (using jsonc-parser)
96
+ │ ├── errors.ts # Error utilities
97
+ │ ├── logger.ts # Logger abstraction
98
+ │ ├── map-claude-code-finish-reason.ts # Finish reason mapping
99
+ │ ├── mcp-helpers.ts # Helper for SDK MCP servers
100
+ │ ├── types.ts # TypeScript definitions
101
+ │ └── validation.ts # Settings validation (Zod)
102
+ ├── docs/
103
+ │ ├── ai-sdk-v4/ # v4-specific documentation (archived)
104
+ │ │ ├── DEVELOPMENT-STATUS.md
105
+ │ │ ├── GUIDE.md
106
+ │ │ └── TROUBLESHOOTING.md
107
+ │ └── ai-sdk-v5/ # v5 documentation
108
+ │ ├── DEVELOPMENT-STATUS.md # This document
109
+ │ ├── GUIDE.md # v5-specific usage guide
110
+ │ ├── TROUBLESHOOTING.md # v5-specific troubleshooting
111
+ │ ├── V5_BREAKING_CHANGES.md # User migration guide
112
+ │ ├── V5_MIGRATION_PLAN.md # Technical migration plan
113
+ │ ├── V5_MIGRATION_SUMMARY.md # Migration implementation summary
114
+ │ └── V5_MIGRATION_TASKS.md # Migration task tracking
115
+ ├── examples/
116
+ │ ├── README.md # Examples guide
117
+ │ ├── abort-signal.ts # Cancellation
118
+ │ ├── basic-usage.ts # Simple generation (v5 pattern)
119
+ │ ├── bull.webp # Default test image for images.ts
120
+ │ ├── check-cli.ts # Setup verification
121
+ │ ├── conversation-history.ts # Multi-turn conversations (v5 format)
122
+ │ ├── custom-config.ts # Configuration options
123
+ │ ├── generate-object-basic.ts # Object generation (basic)
124
+ │ ├── generate-object-constraints.ts # Object generation (constraints)
125
+ │ ├── generate-object-nested.ts # Object generation (nested)
126
+ │ ├── generate-object.ts # Object generation (general)
127
+ │ ├── hooks-callbacks.ts # Hooks example (PreToolUse/PostToolUse)
128
+ │ ├── images.ts # Image input with streaming mode
129
+ │ ├── integration-test.ts # Test suite
130
+ │ ├── limitations.ts # Limitations walkthrough
131
+ │ ├── long-running-tasks.ts # Timeout handling
132
+ │ ├── sdk-tools-callbacks.ts # In-process SDK tools example
133
+ │ ├── streaming.ts # Streaming demo (v5 pattern)
134
+ │ ├── tool-management.ts # Tool access control
135
+ │ └── tool-streaming.ts # Tool streaming events demo
136
+ ├── vitest.config.ts # Test configuration
137
+ ├── tsup.config.ts # Build configuration
138
+ ├── package.json # Package metadata
139
+ ├── CHANGELOG.md # Version history
140
+ ├── README.md # Main documentation with version matrix
141
+ └── LICENSE # MIT license
142
+ ```
143
+
144
+ ## 🎯 Ready for Community Status
145
+
146
+ The provider now meets all requirements for v5 community provider status:
147
+
148
+ ### Technical Requirements ✅
149
+
150
+ - Implements LanguageModelV2 specification
151
+ - Follows provider factory pattern
152
+ - Uses standard error handling
153
+ - Supports AbortSignal
154
+ - Has proper TypeScript types
155
+ - Includes comprehensive tests
156
+ - Emits stream-start event
157
+ - Uses v5 token naming convention
158
+
159
+ ### Build Requirements ✅
160
+
161
+ - Uses tsup for builds
162
+ - Generates both CJS and ESM
163
+ - Includes source maps
164
+ - Has proper package.json configuration
165
+ - Published with beta tag
166
+
167
+ ### Documentation Requirements ✅
168
+
169
+ - Comprehensive README with version compatibility
170
+ - CHANGELOG with version history
171
+ - Extensive examples using v5 patterns
172
+ - Clear setup instructions
173
+ - Migration guide from v4
174
+
175
+ ## Version Strategy
176
+
177
+ - **0.x versions**: AI SDK v4 compatibility (maintained on `ai-sdk-v4` branch)
178
+ - **1.x versions**: AI SDK v5 with `@anthropic-ai/claude-code` (maintained on `v1` branch)
179
+ - **2.x versions**: AI SDK v5 with `@anthropic-ai/claude-agent-sdk` (maintained on `main` branch)
180
+
181
+ ## Next Steps for Community Submission
182
+
183
+ 1. **Publish to npm with beta tag**
184
+
185
+ ```bash
186
+ npm publish --tag beta
187
+ ```
188
+
189
+ 2. **Prepare MDX Documentation**
190
+ Create a documentation file following the v5 community provider format (see example below)
191
+
192
+ 3. **Submit PR to AI SDK Repository**
193
+ - Add provider to v5 community providers list
194
+ - Include MDX documentation
195
+ - Reference npm package with beta tag
196
+
197
+ ## Example Community Provider MDX (v5)
198
+
199
+ ````mdx
200
+ ---
201
+ title: Claude Code (v5)
202
+ description: Use Claude via the official Claude Agent SDK with your Pro/Max subscription
203
+ ---
204
+
205
+ # Claude Code Provider (v5)
206
+
207
+ [ben-vargas/ai-sdk-provider-claude-code](https://github.com/ben-vargas/ai-sdk-provider-claude-code)
208
+ is a community provider that uses the official [Claude Agent SDK](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk)
209
+ to provide language model support for the AI SDK v5.
210
+
211
+ <Note type="warning">
212
+ This is the v5 compatible version. For AI SDK v4 support, use version 0.2.x.
213
+ </Note>
214
+
215
+ ## Setup
216
+
217
+ The Claude Code provider is available in the `ai-sdk-provider-claude-code` module. You can install it with:
218
+
219
+ <Tabs items={['pnpm', 'npm', 'yarn']}>
220
+ <Tab>
221
+ <Snippet text="pnpm add ai-sdk-provider-claude-code@beta ai@beta" dark />
222
+ </Tab>
223
+ <Tab>
224
+ <Snippet text="npm install ai-sdk-provider-claude-code@beta ai@beta" dark />
225
+ </Tab>
226
+ <Tab>
227
+ <Snippet text="yarn add ai-sdk-provider-claude-code@beta ai@beta" dark />
228
+ </Tab>
229
+ </Tabs>
230
+
231
+ ### Prerequisites
232
+
233
+ Install and authenticate the Claude CLI:
234
+
235
+ ```bash
236
+ npm install -g @anthropic-ai/claude-code
237
+ claude login
238
+ ```
239
+ ````
240
+
241
+ ## Provider Instance
242
+
243
+ You can import the default provider instance `claudeCode` from `ai-sdk-provider-claude-code`:
244
+
245
+ ```ts
246
+ import { claudeCode } from 'ai-sdk-provider-claude-code';
247
+ ```
248
+
249
+ ## Language Models
250
+
251
+ The Claude Code provider supports the following models:
252
+
253
+ - `haiku` - Claude 4.5 Haiku (fastest, most cost-effective)
254
+ - `sonnet` - Claude 4.5 Sonnet (balanced speed and capability)
255
+ - `opus` - Claude 4.1 Opus (most capable)
256
+
257
+ ```ts
258
+ import { generateText } from 'ai';
259
+ import { claudeCode } from 'ai-sdk-provider-claude-code';
260
+
261
+ const result = await generateText({
262
+ model: claudeCode('sonnet'),
263
+ prompt: 'Explain recursion in one sentence',
264
+ });
265
+
266
+ console.log(result.text);
267
+ ```
268
+
269
+ ### Model Capabilities
270
+
271
+ | Model | Text Generation | Object Generation | Image Input | AI SDK Tool Calling | MCP Tools |
272
+ | ------ | --------------- | ----------------- | ----------- | ------------------- | --------- |
273
+ | opus | ✅ | ✅ | ✅\* | ❌ | ✅ |
274
+ | sonnet | ✅ | ✅ | ✅\* | ❌ | ✅ |
275
+
276
+ \*Image inputs supported via streaming mode with base64/data URLs. Remote HTTP(S) URLs not supported.
277
+
278
+ <Note>
279
+ The provider uses the official Claude Agent SDK. While the models support tool use, this provider
280
+ doesn't implement the AI SDK's tool calling interface. However, you can configure MCP servers
281
+ for tool functionality, and Claude can use built-in tools (Bash, Read, Write, etc.) through
282
+ the Claude Agent SDK.
283
+ </Note>
284
+
285
+ ## v5 Specific Features
286
+
287
+ This version includes full support for AI SDK v5 features:
288
+
289
+ - **New streaming API** with promise-based result objects
290
+ - **Updated token usage** properties (inputTokens, outputTokens, totalTokens)
291
+ - **Stream-start events** for better stream initialization
292
+ - **Array-based message content** format
293
+
294
+ ```ts
295
+ // v5 streaming pattern
296
+ const result = streamText({
297
+ model: claudeCode('sonnet'),
298
+ prompt: 'Write a haiku',
299
+ });
300
+
301
+ const text = await result.text;
302
+ const usage = await result.usage;
303
+ ```
304
+
305
+ See the [migration guide](https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/ai-sdk-v5/V5_BREAKING_CHANGES.md) for details on upgrading from v0.x to v1.x-beta.
306
+
307
+ ```
308
+
309
+ ```