### Quick Start with AI SDK v6 Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Example of streaming text using the Claude Code provider with AI SDK v6. Ensure 'ai-sdk-provider-claude-code' and 'ai' are installed. ```typescript import { streamText } from 'ai'; import { claudeCode } from 'ai-sdk-provider-claude-code'; const result = streamText({ model: claudeCode('haiku'), prompt: 'Hello, Claude!', }); const text = await result.text; console.log(text); ``` -------------------------------- ### Quick Start with AI SDK v5 Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Example of streaming text using the Claude Code provider with AI SDK v5. Ensure 'ai-sdk-provider-claude-code@ai-sdk-v5' and 'ai@^5.0.0' are installed. ```typescript // npm install ai-sdk-provider-claude-code@ai-sdk-v5 ai@^5.0.0 import { streamText } from 'ai'; import { claudeCode } from 'ai-sdk-provider-claude-code'; const result = streamText({ model: claudeCode('haiku'), prompt: 'Hello, Claude!', }); const text = await result.text; console.log(text); ``` -------------------------------- ### Verify Setup Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Verifies the installation and setup of the Claude CLI and AI SDK provider. This ensures the environment is ready for use. ```bash npx tsx examples/check-cli.ts ``` -------------------------------- ### Optimize First Token Time with Warm Start Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Compare a warm start using `startup()`/`WarmQuery` against a cold start baseline to reduce time-to-first-token. It utilizes new timing metadata available in provider metadata. ```bash npx tsx examples/warm-start.ts ``` -------------------------------- ### Run Comprehensive Integration Test Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md A comprehensive test suite to verify your setup and all features. Run this example to check feature verification and error handling patterns. ```bash npx tsx examples/integration-test.ts ``` -------------------------------- ### Install and Authenticate Claude CLI Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Installs the Claude CLI and logs in the user for authentication. This is a prerequisite for using the provider. ```bash curl -fsSL https://claude.ai/install.sh | bash claude auth login ``` -------------------------------- ### Run SDK Tools with Callbacks Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Defines and uses in-process MCP tools with the Agent SDK. Run this example using the provided command. ```bash npx tsx examples/sdk-tools-callbacks.ts ``` -------------------------------- ### Install Claude CLI Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Use this command to install the Claude CLI. This is a prerequisite for authentication. ```bash curl -fsSL https://claude.ai/install.sh | bash ``` -------------------------------- ### Recommended Explicit Configuration for New Behavior Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md This example shows the new recommended behavior for version 2.0.0, where system prompts and filesystem settings are explicitly configured. ```typescript const model = claudeCode('sonnet', { systemPrompt: 'You are a helpful assistant specialized in ...', settingSources: ['project'], // or omit for no filesystem settings }); ``` -------------------------------- ### Build the Provider Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Builds the AI SDK provider using npm. This is a prerequisite for running the examples. ```bash npm run build ``` -------------------------------- ### Install ai-sdk-provider-claude-code for AI SDK v6 Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Install the provider and AI SDK for version 6, which is the recommended stable version. This command installs the latest version of the provider. ```bash # For AI SDK v6 (recommended) npm install ai-sdk-provider-claude-code ai@^6.0.0 # or explicitly: npm install ai-sdk-provider-claude-code@latest ``` -------------------------------- ### Install ai-sdk-provider-claude-code for AI SDK v5 Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Install the provider and AI SDK for version 5. This command uses the 'ai-sdk-v5' tag for the provider. ```bash # For AI SDK v5 npm install ai-sdk-provider-claude-code@ai-sdk-v5 ai@^5.0.0 ``` -------------------------------- ### Receive and Utilize Prompt Suggestions Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md This example demonstrates receiving the SDK's predicted next user prompt via the `onPromptSuggestion` callback and feeding it back as the next turn. It covers how suggestions are delivered and gated. ```bash npx tsx examples/prompt-suggestions.ts ``` -------------------------------- ### Install ai-sdk-provider-claude-code for AI SDK v4 (Legacy) Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Install the provider and AI SDK for version 4, which is a legacy version. This command uses the 'ai-sdk-v4' tag for the provider. ```bash # For AI SDK v4 (legacy) npm install ai-sdk-provider-claude-code@ai-sdk-v4 ai@^4.3.16 # or use a specific version: npm install ai-sdk-provider-claude-code@^0.2.2 ``` -------------------------------- ### Manage Session Lifecycle Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md This example demonstrates the full session lifecycle, including creating, resuming, forking, inspecting, and deleting persisted sessions. It utilizes session IDs and specific session management functions. ```bash npx tsx examples/session-management.ts ``` -------------------------------- ### Streaming Text Generation Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Demonstrates real-time streaming of text generation for responsive user experiences. This example shows how to process chunks of data as they arrive. ```bash npx tsx examples/streaming.ts ``` -------------------------------- ### Install ai-sdk-provider-claude-code with Zod 4 Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Install the provider and AI SDK, ensuring Zod version 4 is used. This is required for versions 3.2.0 and later. ```bash npm install ai-sdk-provider-claude-code ai zod@^4.0.0 ``` -------------------------------- ### Core Object Generation Patterns Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Demonstrates core object generation patterns from simple primitives to complex nested structures. Run this example to explore schema basics and best practices. ```bash npx tsx examples/generate-object.ts ``` -------------------------------- ### Track Session Context Window Usage Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md This example shows how to read the session's context-window usage by hooking into `onQueryCreated` and calling `query.getContextUsage()`. It also illustrates why a late call to this function might fail. ```bash npx tsx examples/context-usage.ts ``` -------------------------------- ### Bridge AI SDK Tools with MCP Server Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md This example bridges AI SDK tool definitions into an in-process MCP server using `createAiSdkMcpServer`. It demonstrates running tools locally and surfacing calls/results as provider-executed dynamic tool parts. ```bash npx tsx examples/ai-sdk-tools.ts ``` -------------------------------- ### Basic Text Generation Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Generates text using Claude and displays metadata such as token usage and provider cost. This is the simplest example of using the provider. ```bash npx tsx examples/basic-usage.ts ``` -------------------------------- ### Streaming Image Prompt Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Streams a prompt that includes a local image (PNG/JPG/GIF/WebP). This example demonstrates multimodal prompt capabilities. ```bash npx tsx examples/images.ts /absolute/path/to/image.png ``` -------------------------------- ### Demonstrate Mid-Stream Injection Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Re-steers a running query by injecting a new user message mid-stream. Run this example to observe streaming input and live prompt updates. ```bash npx tsx examples/mid-stream-injection.ts ``` -------------------------------- ### Run External MCP Server (Exa HTTP) Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Runs Exa's hosted MCP endpoint over HTTP with optional API key support. Run this example using the provided command. ```bash npx tsx examples/mcp-exa.ts ``` -------------------------------- ### Configure Skills Management Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Configures Skills support for custom tools defined in user or project settings. Run this example to see how to enable Skills and observe validation warnings. ```bash npx tsx examples/skills-management.ts ``` -------------------------------- ### Demonstrate Message Injection Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Injects messages mid-session to interrupt, redirect, or provide feedback to the agent. This example shows successful and failed injection scenarios with recovery. ```bash npx tsx examples/message-injection.ts ``` -------------------------------- ### Conversation History Management Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Shows the correct way to maintain context across multiple messages for multi-turn conversations. This example demonstrates the message history pattern. ```bash npx tsx examples/conversation-history.ts ``` -------------------------------- ### Implement Permission Hooks Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Use the SDK's permission vocabulary in hooks to control tool usage. This example shows a PreToolUse hook for allowing safe tools and a `canUseTool` callback to deny specific tools at call time. ```bash npx tsx examples/hooks-permission-denied.ts ``` -------------------------------- ### Stream Partial Objects Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Receives incremental partial objects as the AI generates structured data, enabling real-time UI updates. This example uses the streamObject() API. ```bash npx tsx examples/stream-object.ts ``` -------------------------------- ### Reproduce Structured Output Fallbacks Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Reproduces CLI structured output fallbacks for certain JSON Schema features like format constraints and regex limitations. Run this example to observe fallback behavior. ```bash npx tsx examples/structured-output-repro.ts ``` -------------------------------- ### Generate Structured Object with Zod Schema Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Use `generateObject` with a Zod schema to get a JSON object that conforms to the schema. The SDK handles validation and parsing. ```typescript import { generateObject } from 'ai'; import { claudeCode } from 'ai-sdk-provider-claude-code'; import { z } from 'zod'; const result = await generateObject({ model: claudeCode('sonnet'), schema: z.object({ name: z.string(), age: z.number(), email: z.string().describe('Email address (validate client-side)'), }), prompt: 'Generate a user profile for a software developer', }); console.log(result.object); // Matches the schema above // { name: "Alex Chen", age: 28, email: "alex@example.com" } ``` -------------------------------- ### Get Context Usage During Query Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Retrieve context usage information by calling `getContextUsage()` on the `Query` object within a `Stop` hook. Ensure the query is still active when calling this method. ```typescript import type { Query } from 'ai-sdk-provider-claude-code'; let activeQuery: Query | undefined; let contextUsage: unknown; const model = claudeCode('sonnet', { onQueryCreated: (query) => { activeQuery = query; }, hooks: { Stop: [ { hooks: [ async () => { contextUsage = await activeQuery?.getContextUsage(); return { continue: true }; }, ], }, ], }, }); const result = await generateText({ model, prompt: 'Hello' }); console.log(contextUsage); // tokens used / remaining in the session context window ``` -------------------------------- ### Enforce Validation Constraints in Object Generation Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Enforces data quality with number ranges, simple regex patterns, array length limits, enums, and multipleOf. Run this example to see complex combined validations. ```bash npx tsx examples/generate-object-constraints.ts ``` -------------------------------- ### Custom Provider and Model Configuration Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Demonstrates provider and model configuration options, including provider settings, model overrides, tool restrictions, and permission modes. ```bash npx tsx examples/custom-config.ts ``` -------------------------------- ### Lifecycle Hooks and Callbacks Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Demonstrates using lifecycle hooks (PreToolUse/PostToolUse) and dynamic permission callbacks (canUseTool) for permission control and event management. ```bash npx tsx examples/hooks-callbacks.ts ``` -------------------------------- ### Understand CLI Limitations Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Execute this script to understand which AI SDK features are not supported by the CLI. It outlines unsupported parameters and potential workarounds. ```bash npx tsx examples/limitations.ts ``` -------------------------------- ### Pre-warm CLI subprocess for faster queries Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Use `startup()` to pre-spawn the CLI subprocess and complete its handshake. This returns a `WarmQuery` handle that eliminates subprocess startup latency for subsequent queries. This method is for standalone queries and does not compose with `generateText`/`streamText`. ```typescript import { startup, type WarmQuery } from 'ai-sdk-provider-claude-code'; // Pre-warm during idle time (e.g. at server boot, or while the user types). // You can pass the same Options shape the SDK's query() accepts. const warm: WarmQuery = await startup({ options: { model: 'sonnet' } }); // Later — the prompt goes straight to the ready process (one query per handle): for await (const message of warm.query('Summarize the latest deploy log.')) { if (message.type === 'assistant') { // handle SDK messages directly (this is the SDK stream, not an AI SDK stream) } } // Or discard an unused warm handle: // warm.close(); // explicit // await using warm = ... // WarmQuery is AsyncDisposable ``` -------------------------------- ### Custom Logger Integration Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Demonstrates integrating with external logging systems (Winston, Pino, Datadog, etc.) by providing a custom logger implementation. This shows log formatting and integration patterns. ```bash npx tsx examples/logging-custom-logger.ts ``` -------------------------------- ### Restore Default System Prompt and Filesystem Settings Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Use this configuration to restore the previous default behavior of loading the system prompt and filesystem settings when migrating to version 2.0.0. ```typescript import { claudeCode } from 'ai-sdk-provider-claude-code'; const model = claudeCode('sonnet', { systemPrompt: { type: 'preset', preset: 'claude_code' }, settingSources: ['user', 'project', 'local'], }); ``` -------------------------------- ### Run External MCP Server (Filesystem) Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Runs an external MCP server over stdio using the official @modelcontextprotocol/server-filesystem package. An optional directory can be passed to scope filesystem access. ```bash npx tsx examples/mcp-filesystem.ts ``` ```bash npx tsx examples/mcp-filesystem.ts /absolute/path/to/inspect ``` -------------------------------- ### Bridge AI SDK Tools with Claude Code CLI Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Use `createAiSdkMcpServer` to expose AI SDK tools to the Claude Code CLI. Tools are defined using Zod schemas and their execution logic runs within your process. ```typescript import { generateText, tool } from 'ai'; import { z } from 'zod'; import { claudeCode, createAiSdkMcpServer } from 'ai-sdk-provider-claude-code'; const tools = { add: tool({ description: 'Add two numbers', inputSchema: z.object({ a: z.number(), b: z.number() }), execute: async ({ a, b }) => ({ sum: a + b }), }), }; const { text } = await generateText({ model: claudeCode('sonnet', { mcpServers: { myTools: createAiSdkMcpServer('myTools', tools) }, // Tools are exposed to the CLI as mcp____ allowedTools: ['mcp__myTools__add'], }), prompt: 'What is 2 + 3? Use the add tool.', }); ``` -------------------------------- ### Explicit Configuration for Migration from v1.x Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md If you relied on default system prompt or CLAUDE.md in v1.x, use this explicit configuration when upgrading to v2.0.0. ```typescript const model = claudeCode('sonnet', { systemPrompt: { type: 'preset', preset: 'claude_code' }, settingSources: ['user', 'project', 'local'], }); ``` -------------------------------- ### Verbose Logging for Development Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Enables detailed logging for development and troubleshooting, showing all log levels (debug, info, warn, error) for detailed provider activity. ```bash npx tsx examples/logging-verbose.ts ``` -------------------------------- ### Manage AI Sessions with Helper Functions Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Use these helper functions to interact with persisted AI sessions. Import them from 'ai-sdk-provider-claude-code'. ```typescript import { forkSession, getSessionInfo, renameSession, deleteSession, } from 'ai-sdk-provider-claude-code'; const info = await getSessionInfo(sessionId); console.log(info?.summary, info?.lastModified); const fork = await forkSession(sessionId, { title: 'experiment branch' }); // ...resume the fork via claudeCode('sonnet', { resume: fork.sessionId })... await renameSession(sessionId, 'main investigation'); await deleteSession(fork.sessionId); ``` -------------------------------- ### Authenticate Claude CLI Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Run this command to log in and authenticate your Claude CLI. ```bash claude auth login ``` -------------------------------- ### Handling User Dialogs with onUserDialog Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Configure the SDK to handle user dialogs by providing a `supportedDialogKinds` array and an `onUserDialog` callback. The callback should return a `UserDialogResult` or `{ behavior: 'cancelled' }` for unrecognized dialog kinds. ```typescript const model = claudeCode('sonnet', { supportedDialogKinds: ['refusal_fallback_prompt'], onUserDialog: async (request) => { // Each dialogKind defines its own payload/result shape; answer // unrecognized kinds with { behavior: 'cancelled' } so the CLI // applies the dialog's default behavior. if (request.dialogKind === 'refusal_fallback_prompt') { // Valid results for this kind: 'retry_fallback' | 'edit_prompt' | 'cancelled' return { behavior: 'completed', result: 'retry_fallback' }; } return { behavior: 'cancelled' }; }, }); ``` -------------------------------- ### importSessionToStore Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Copies a local JSONL session, including its subagent transcripts by default, into a custom `SessionStore`. This is an alpha feature. ```APIDOC ## importSessionToStore(sessionId, store, options?) ### Description Copy a local JSONL session (and, by default, its subagent transcripts) into a custom `SessionStore` (alpha). ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the local session to import. - **store** (SessionStore) - Required - The target `SessionStore` instance. #### Query Parameters - **options** (object) - Optional - Additional options for importing the session. ``` -------------------------------- ### Enable Prompt Suggestions Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Register a callback to receive prompt suggestions after each AI response. This feature is enabled by default unless explicitly disabled. ```typescript const model = claudeCode('sonnet', { promptSuggestions: true, onPromptSuggestion: (suggestion) => { console.log('Suggested next prompt:', suggestion); }, }); ``` -------------------------------- ### Configuring SDK Options with sdkOptions and other settings Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Configure advanced SDK settings using `sdkOptions` for overrides and other explicit options like `betas`, `sandbox`, and `persistSession`. Note that `sdkOptions` overrides explicit settings, and provider-managed fields within `sdkOptions` are ignored. ```typescript const model = claudeCode('sonnet', { betas: ['context-1m-2025-08-07'], sandbox: { enabled: true }, persistSession: false, // Don't persist session to disk sdkOptions: { maxBudgetUsd: 1, resume: 'session-abc', }, }); ``` -------------------------------- ### Default Logging Behavior Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Demonstrates the default logging behavior, which only shows warning and error messages for clean output. Debug and info logs are suppressed. ```bash npx tsx examples/logging-default.ts ``` -------------------------------- ### Handling Timeouts with AbortSignal Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Handles timeouts properly for long-running tasks using AI SDK's AbortSignal pattern, enabling graceful cancellation and retry logic. ```bash npx tsx examples/long-running-tasks.ts ``` -------------------------------- ### listSessions Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Lists metadata for all persisted sessions. This is useful for building session pickers and supports filtering options such as by project directory (`dir`), and limiting the number of results (`limit`). ```APIDOC ## listSessions(options?) ### Description Lists metadata for all persisted sessions. Supports filtering options (e.g. by project directory via `dir`, plus `limit`). ### Parameters #### Query Parameters - **options** (object) - Optional - Filtering and pagination options. - **dir** (string) - Optional - Filter by project directory. - **limit** (number) - Optional - Maximum number of sessions to return. ``` -------------------------------- ### Fine-grained Tool Access Control Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Shows fine-grained control over Claude's tool access for security purposes, using allow/deny lists for tool security. ```bash npx tsx examples/tool-management.ts ``` -------------------------------- ### Handle Authentication Errors Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Catch potential authentication errors using `isAuthenticationError` and provide guidance to the user, such as logging in. ```typescript import { isAuthenticationError } from '../dist/index.js'; try { // Your code here } catch (error) { if (isAuthenticationError(error)) { console.error('Please run: claude auth login'); } } ``` -------------------------------- ### Customizing Tool Permission Decisions with canUseTool Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Enhance the `canUseTool` callback to utilize SDK-provided prompt details like `title`, `displayName`, and `description`. The callback should return a `PermissionResult` indicating whether to allow or deny tool usage, optionally including a `decisionClassification`. ```typescript const model = claudeCode('sonnet', { canUseTool: async (toolName, input, options) => { // Prefer the SDK-provided prompt text over reconstructing it yourself. const approved = await askUser({ prompt: options.title ?? `Allow ${toolName}?`, // "Claude wants to read foo.txt" buttonLabel: options.displayName ?? toolName, // "Read file" subtitle: options.description, // "Claude will have read access to ..." }); return approved ? { behavior: 'allow', updatedInput: input, decisionClassification: 'user_temporary' } : { behavior: 'deny', message: 'Denied by user', decisionClassification: 'user_reject' }; }, }); ``` -------------------------------- ### Disabled Logging for Silent Operation Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Configures the provider for completely silent operation with no logs, suitable for production deployments. No provider logs will be displayed. ```bash npx tsx examples/logging-disabled.ts ``` -------------------------------- ### User-Initiated Cancellation Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Implements user-initiated cancellations and resource cleanup using the AbortSignal. This allows for request cancellation and proper resource management. ```bash npx tsx examples/abort-signal.ts ``` -------------------------------- ### Fork Session at Query Time Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Fork a session at query time using the `forkSession` setting. This creates a new session ID for an alternative conversational path while leaving the original transcript untouched. ```typescript const branched = await generateText({ model: claudeCode('sonnet', { resume: sessionId, forkSession: true }), prompt: 'Explore an alternative approach from here.', }); // branched runs under a NEW session ID; the original transcript is untouched. const forkId = branched.providerMetadata?.['claude-code']?.sessionId as string; ``` -------------------------------- ### Configure Logging Levels for AI SDK Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Customize the verbosity of AI SDK logs using the `verbose` option or by providing a custom `logger` object. Logging can also be disabled entirely. ```typescript import type { Logger } from '../dist/index.js'; // Default: warn and error only const result1 = streamText({ model: claudeCode('haiku'), prompt: 'Hello', }); // Verbose: all log levels const result2 = streamText({ model: claudeCode('haiku', { verbose: true }), prompt: 'Hello', }); // Custom logger const customLogger: Logger = { debug: (msg) => myLogger.debug(msg), info: (msg) => myLogger.info(msg), warn: (msg) => myLogger.warn(msg), error: (msg) => myLogger.error(msg), }; const result3 = streamText({ model: claudeCode('haiku', { verbose: true, logger: customLogger, }), prompt: 'Hello', }); // Disable all logging const result4 = streamText({ model: claudeCode('haiku', { logger: false }), prompt: 'Hello', }); ``` -------------------------------- ### Injecting Messages Mid-Session Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Demonstrates how to inject a message into an ongoing agent session using the `inject` method. Requires `streamingInput` to be set to 'always' or 'auto'. ```typescript import { streamText } from 'ai'; import { claudeCode, type MessageInjector } from 'ai-sdk-provider-claude-code'; let injector: MessageInjector | null = null; const result = streamText({ model: claudeCode('haiku', { streamingInput: 'always', // Required for injection onStreamStart: (inj) => { injector = inj; // Example: Inject after 5 seconds setTimeout(() => { injector?.inject('STOP! Change of plans - do something else.'); }, 5000); }, }), prompt: 'Write 10 files with poems...', }); for await (const chunk of result.textStream) { process.stdout.write(chunk); } ``` -------------------------------- ### Tool Streaming with Claude Code Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Observes tool-call events emitted by the provider while Claude Code executes built-in tools. This is useful for inspecting detailed stream events. ```bash npx tsx examples/tool-streaming.ts ``` -------------------------------- ### tagSession Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Sets or clears a tag for a given session. Passing `null` as the tag will clear it. ```APIDOC ## tagSession(sessionId, tag, options?) ### Description Set (or clear, with `null`) a session's tag. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to tag. - **tag** (string | null) - Required - The tag to set for the session, or `null` to clear it. #### Query Parameters - **options** (object) - Optional - Additional options for tagging the session. ``` -------------------------------- ### Resume Existing Session Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Resume an existing session using its ID. The conversation context is restored from the persisted transcript, allowing for continued dialogue. ```typescript const followUp = await generateText({ model: claudeCode('sonnet', { resume: sessionId }), prompt: 'What was the code word?', }); // followUp.text mentions "papaya"; the session keeps the same ID. ``` -------------------------------- ### Enabling Skills with Explicit 'allowedTools' Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Configures the Claude Code model to use skills by explicitly setting `settingSources` and including 'Skill' in the `allowedTools` array. This method provides more granular control over tool access. ```typescript const result = await streamText({ model: claudeCode('sonnet', { settingSources: ['user', 'project'], allowedTools: ['Skill', 'Read', 'Write', 'Bash'], }), prompt: 'Use my /custom-skill to help with this task', }); ``` -------------------------------- ### Stream Text Responses in Real-Time Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Use `streamText` to receive AI-generated content incrementally. This is useful for providing immediate feedback to the user as the response is generated. ```typescript import { streamText } from 'ai'; const result = streamText({ model: claudeCode('haiku'), prompt: 'Write a story...', }); // Stream the response in real-time for await (const chunk of result.textStream) { process.stdout.write(chunk); } ``` -------------------------------- ### Enabling Skills with 'skills' Option Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Configures the Claude Code model to use available skills by setting the `skills` option. This simplifies skill enablement compared to manually listing them in `allowedTools`. ```typescript import { claudeCode } from 'ai-sdk-provider-claude-code'; import { streamText } from 'ai'; const result = await streamText({ model: claudeCode('sonnet', { settingSources: ['user', 'project'], // still required for filesystem skill discovery skills: 'all', // or ['pdf', 'docx'] to enable only specific skills }), prompt: 'Use my /custom-skill to help with this task', }); ``` -------------------------------- ### getSessionInfo Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Reads metadata for a specific session, including its summary, custom title, first prompt, last modified date, current working directory, Git branch, and tag. Returns `undefined` if the session is not found. ```APIDOC ## getSessionInfo(sessionId, options?) ### Description Reads metadata for one session. Returns `undefined` if not found. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to retrieve information for. #### Query Parameters - **options** (object) - Optional - Additional options for retrieving session info. ``` -------------------------------- ### Tracking Message Injection Delivery Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Shows how to use the callback function provided by the `inject` method to track if an injected message was successfully delivered to the agent session. ```typescript injector.inject('STOP!', (delivered) => { if (!delivered) { // Session ended before message was delivered // Handle retry via session resume, etc. } }); ``` -------------------------------- ### Generate Structured Object with Zod Schema Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Use `generateObject` to create structured data based on a Zod schema. The schema is validated client-side, and format keywords are stripped by the provider. ```typescript import { generateObject } from 'ai'; import { z } from 'zod'; const { object } = await generateObject({ model: claudeCode('haiku'), schema: z.object({ name: z.string(), age: z.number(), // .email() works: the provider strips the `format` keyword for the CLI // (folding the hint into the description) and Zod validates client-side. email: z.string().email(), }), prompt: 'Generate a random user profile', }); ``` -------------------------------- ### forkSession Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Copies a session's transcript into a new session ID without running a query. Optionally, the new session can be retitled. This function returns a new `sessionId` which can be resumed later. ```APIDOC ## forkSession(sessionId, options?) ### Description Copies a session's transcript into a new session ID without running a query (optionally sliced via `upToMessageId`, retitled via `title`). Returns `{ sessionId }`, resumable via the `resume` setting. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to fork. #### Query Parameters - **options** (object) - Optional - Options for forking the session. - **upToMessageId** (string) - Optional - Slice the transcript up to this message ID. - **title** (string) - Optional - Set a custom title for the new forked session. ``` -------------------------------- ### foldSessionSummary Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md A pure utility function intended for `SessionStore` implementers. It folds appended entries into a `SessionSummaryEntry` within the `append()` method. This is an alpha feature. ```APIDOC ## foldSessionSummary(prev, key, entries, options?) ### Description Pure utility for `SessionStore` implementers: fold appended entries into a `SessionSummaryEntry` inside `append()` (alpha). ### Parameters #### Path Parameters - **prev** (SessionSummaryEntry) - Required - The previous summary entry. - **key** (string) - Required - The key for the current entry. - **entries** (Array) - Required - The entries to fold. #### Query Parameters - **options** (object) - Optional - Additional options for folding the summary. ``` -------------------------------- ### Implement Custom Timeouts for AI Requests Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Control the maximum duration of an AI request using `AbortController` and `setTimeout`. This prevents long-running operations from blocking the application. ```typescript const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 300000); // 5 minutes try { const { text } = await generateText({ model: claudeCode('haiku'), prompt: 'Complex analysis...', abortSignal: controller.signal, }); clearTimeout(timeoutId); } catch (error) { // Handle timeout } ``` -------------------------------- ### renameSession Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Renames an existing session by updating its title. ```APIDOC ## renameSession(sessionId, title, options?) ### Description Retitles an existing session. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to rename. - **title** (string) - Required - The new title for the session. #### Query Parameters - **options** (object) - Optional - Additional options for renaming the session. ``` -------------------------------- ### listSubagents Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Lists the agent IDs of all subagent transcripts recorded under a specific session. ```APIDOC ## listSubagents(sessionId, options?) ### Description List agent IDs of subagent transcripts recorded under a session. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session for which to list subagents. #### Query Parameters - **options** (object) - Optional - Additional options for listing subagents. ``` -------------------------------- ### Accessing Parent Tool Call ID Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md This metadata is available on tool-input-start, tool-call, tool-result, and tool-error events. It is null for top-level task tools and references the parent Task's ID for child tools. ```typescript providerMetadata['claude-code'].parentToolCallId: string | null; ``` -------------------------------- ### Extract Claude-Code Provider Metadata Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/README.md Retrieves and logs metadata for the Claude-Code provider from a non-streaming text generation response. Ensure the model and prompt are correctly configured. ```typescript const { providerMetadata } = await generateText({ model, prompt: 'Hello' }); const meta = providerMetadata?.['claude-code']; console.log(meta?.costUsd, meta?.ttftMs, meta?.terminalReason); ``` -------------------------------- ### Maintain Message History for Conversations Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/examples/README.md Utilize `ModelMessage` to structure conversational history for context-aware AI responses. This allows the model to remember previous turns in the dialogue. ```typescript import type { ModelMessage } from 'ai'; const messages: ModelMessage[] = [ { role: 'user', content: 'Hello, my name is Alice' }, { role: 'assistant', content: 'Nice to meet you, Alice!' }, { role: 'user', content: 'What did I just tell you?' }, ]; const { text } = await generateText({ model: claudeCode('haiku'), messages, }); ``` -------------------------------- ### Capture Session ID Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Capture the session ID from the provider metadata after a generateText call. This ID can be used to resume or fork the session later. ```typescript import { generateText } from 'ai'; import { claudeCode } from 'ai-sdk-provider-claude-code'; const result = await generateText({ model: claudeCode('sonnet'), prompt: 'Remember this code word: papaya. Reply with OK.', }); const sessionId = result.providerMetadata?.['claude-code']?.sessionId as string; ``` -------------------------------- ### deleteSession Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Deletes a session's persisted transcript. Use with caution as this action is irreversible. ```APIDOC ## deleteSession(sessionId, options?) ### Description Delete a session's persisted transcript. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to delete. #### Query Parameters - **options** (object) - Optional - Additional options for deleting the session. ``` -------------------------------- ### getSessionMessages Source: https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/docs/sessions.md Reads the main conversation transcript of a session. This function retrieves the top-level thread's messages, serving as the counterpart to `getSubagentMessages()`. ```APIDOC ## getSessionMessages(sessionId, options?) ### Description Reads the main conversation transcript of a session. ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to retrieve messages from. #### Query Parameters - **options** (object) - Optional - Additional options for retrieving messages. ```