### Initialize and Run Genetic Algorithm Source: https://github.com/s-soroosh/claude-code-js/blob/main/example/genetic-algorithm/README.md Commands to install necessary dependencies and execute the genetic algorithm implementation for the Traveling Salesman Problem. ```bash npm install npm start ``` -------------------------------- ### Automate Code Review and Testing Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Practical examples of using the SDK to perform security-focused code reviews and generate unit tests for existing functions. ```javascript const claude = new ClaudeCode({ workingDirectory: './my-app' }); // Code Review Example const reviewer = claude.newSession(); const initialReview = await reviewer.prompt({ prompt: "Review this Express route for security issues...", systemPrompt: 'You are a security-focused code reviewer.' }); // Test Generation Example const response = await claude.chat({ prompt: "Generate Jest unit tests for this function...", systemPrompt: 'Generate comprehensive Jest tests with edge cases' }); if (response.success) { await writeFile('./tests/calculateDiscount.test.js', response.message.result); } ``` -------------------------------- ### Initialize ClaudeCode Client Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Instantiates the main ClaudeCode class. This setup allows for configuring API keys, model selection, working directories, and OAuth credentials for persistent authentication. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode({ apiKey: process.env.CLAUDE_API_KEY, model: 'claude-3-sonnet', workingDirectory: './my-project', verbose: false, oauth: { accessToken: 'ACCESS_TOKEN_VALUE', refreshToken: 'REFRESH_TOKEN_VALUE', expiresAt: 1735689600000 } }); ``` -------------------------------- ### Configuration Management for Claude JS SDK Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Shows how to update and retrieve the configuration options for the Claude Code JS SDK. This includes setting the model and verbosity, and getting the current settings. ```javascript // Update configuration on the fly claude.setOptions({ model: 'claude-3-opus', verbose: true }); // Get current configuration const options = claude.getOptions(); console.log('Current model:', options.model); ``` -------------------------------- ### Get Claude Code CLI Version Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Shows how to retrieve the version string of the installed Claude Code CLI tool using the version() method. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode(); const version = await claude.version(); console.log('Claude Code CLI version:', version); // e.g., "1.0.3" ``` -------------------------------- ### Error Handling in Claude JS SDK Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Provides an example of how to implement robust error handling when interacting with the Claude Code JS SDK. It covers catching both SDK-specific errors and general network or unexpected errors. ```javascript try { const response = await claude.chat({ prompt: 'Refactor this function to use async/await' }); if (!response.success) { // Handle Claude Code specific errors console.error(`Error Code: ${response.error.code}`); console.error(`Message: ${response.error.message}`); if (response.error.details) { console.error('Details:', response.error.details); } } } catch (error) { // Handle network or other errors console.error('Unexpected error:', error); } ``` -------------------------------- ### TypeScript Type Definitions for Claude Code JS Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Highlights the availability of comprehensive TypeScript interfaces for type-safe development with the Claude Code JS SDK. It shows examples of using types like ClaudeCodeOptions, Prompt, and ClaudeCodeMessage for configuration and response handling. ```typescript import { ClaudeCode, ClaudeCodeOptions, ClaudeCodeResponse, ClaudeCodeError } from 'claude-code-js'; import type { Prompt, ClaudeCodeMessage } from 'claude-code-js'; // Type-safe configuration const options: ClaudeCodeOptions = { apiKey: process.env.CLAUDE_API_KEY, model: 'claude-3-sonnet', workingDirectory: './src', verbose: true }; const claude = new ClaudeCode(options); // Type-safe prompt const prompt: Prompt = { prompt: 'Generate unit tests for auth.js', systemPrompt: 'You are a test generation expert', appendSystemPrompt: 'Use Jest framework' }; // Type-safe response handling const response: ClaudeCodeResponse = await claude.chat(prompt); if (response.success && response.message) { const message: ClaudeCodeMessage = response.message; console.log('Result:', message.result); console.log('Cost in USD:', message.cost_usd); console.log('Duration (ms):', message.duration_ms); console.log('API Duration (ms):', message.duration_api_ms); console.log('Number of turns:', message.num_turns); } ``` -------------------------------- ### Initialize ClaudeCode SDK Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates how to import and initialize the ClaudeCode client with configuration options such as API keys, model selection, and OAuth credentials. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode({ apiKey: process.env.CLAUDE_API_KEY, model: 'claude-3-sonnet', workingDirectory: './my-project', verbose: false, oauth: { accessToken: "ACCESS_TOKENID", refreshToken: "REFRESH_TOKEN", expiresAt: EXPIRES_AT_VALUE } }); ``` -------------------------------- ### Initialize ClaudeCode Client Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates how to instantiate the ClaudeCode client with optional configuration settings including API keys, model selection, and OAuth credentials. ```javascript const claude = new ClaudeCode({ apiKey: 'your-api-key', model: 'claude-3-sonnet', workingDirectory: './path/to/project', verbose: false, oauth: { accessToken: "ACCESS_TOKENID", refreshToken: "REFRESH_TOKEN", expiresAt: EXPIRES_AT_VALUE } }); ``` -------------------------------- ### Execute System Commands Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates executing shell commands directly from the SDK, either by waiting for full output or streaming results in real-time. ```javascript import { executeCommand, streamCommand } from 'claude-code-js'; const { stdout, stderr, exitCode } = await executeCommand(['npm', 'test'], { cwd: './my-project', timeout: 30000 }); const stream = streamCommand(['npm', 'run', 'dev'], { onStdout: (data) => console.log('Output:', data), onStderr: (data) => console.error('Error:', data) }); await stream; ``` -------------------------------- ### Interactive Debugging with Claude Sessions Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates how to initialize a debugging session, provide context via prompts, and receive step-by-step guidance for troubleshooting code issues. ```javascript const debugSession = claude.newSession(); await debugSession.prompt({ prompt: 'I have a React component that re-renders infinitely. Help me debug it.', systemPrompt: 'You are a React debugging expert. Ask clarifying questions and provide solutions.' }); await debugSession.prompt({ prompt: `Here's my component: function UserList() { const [users, setUsers] = useState([]); const fetchUsers = async () => { const data = await api.getUsers(); setUsers(data); }; fetchUsers(); return
{users.map(u =>
{u.name}
)}
; }` }); const solution = await debugSession.prompt({ prompt: `What's causing the infinite re-render and how do I fix it?` }); ``` -------------------------------- ### Configuration Methods (setOptions/getOptions) Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Allows dynamic configuration updates on the ClaudeCode instance and retrieval of current settings. ```APIDOC ## setOptions() and getOptions() ### Description Allows dynamic configuration updates on the ClaudeCode instance. Use setOptions() to change model, verbosity, or other settings at runtime, and getOptions() to retrieve the current configuration. ### Method N/A (Class Methods) ### Request Example ```javascript claude.setOptions({ model: 'claude-3-opus', verbose: true }); const options = claude.getOptions(); ``` ### Response #### Success Response (200) - **options** (object) - Returns the current configuration object. ``` -------------------------------- ### Forking Sessions for Parallel Exploration Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Explains the use of the fork() method to create new sessions from an existing conversation history, allowing for parallel exploration of different solutions. ```javascript const claude = new ClaudeCode(); const mainSession = claude.newSession(); await mainSession.prompt({ prompt: 'Write a function to calculate factorial', systemPrompt: 'You are a helpful coding assistant' }); await mainSession.prompt({ prompt: 'Now make it recursive' }); const iterativeSession = mainSession.fork(); const recursiveSession = mainSession.fork(); await iterativeSession.prompt({ prompt: 'Actually, show me an iterative version instead' }); await recursiveSession.prompt({ prompt: 'Can you add memoization to the recursive version?' }); console.log('Main session messages:', mainSession.messages.length); console.log('Iterative fork messages:', iterativeSession.messages.length); console.log('Recursive fork messages:', recursiveSession.messages.length); ``` -------------------------------- ### Initialize ClaudeCode with OAuth for Automatic Token Refresh (JavaScript) Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Demonstrates how to initialize the ClaudeCode SDK with OAuth credentials. The SDK automatically handles token expiration by refreshing the token using provided refresh tokens and retrying the request. ```javascript import { ClaudeCode } from 'claude-code-js'; // Initialize with OAuth credentials for automatic token refresh const claude = new ClaudeCode({ oauth: { accessToken: 'your-access-token', refreshToken: 'your-refresh-token', expiresAt: Date.now() + 3600000 // 1 hour from now } }); // Token refresh happens transparently when needed // If the token expires during a request, the SDK will: // 1. Detect the "Invalid bearer token" error // 2. Refresh using the OAuth credentials // 3. Retry the original request with the new token const response = await claude.chat({ prompt: 'Help me debug this error' }); ``` -------------------------------- ### Retrieving OAuth Credentials from File (Linux) Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Shows the bash command to retrieve OAuth credentials stored in the default JSON file on Linux systems. ```bash cat ~/.claude/.credentials.json ``` -------------------------------- ### Chaining Claude Sessions Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Illustrates how to pass the output of one session as input to another, enabling multi-step workflows like calculation and validation. ```javascript const mathSession = claude.newSession(); const mathResult = await mathSession.prompt({ prompt: 'Calculate 15 * 23', systemPrompt: 'You are a math expert. Return only the numeric result.' }); const validationSession = claude.newSession(); const validationResult = await validationSession.prompt({ prompt: mathResult.result, systemPrompt: 'You are expert at validating math calculations.' }); console.log('Validation result:', validationResult.result); ``` -------------------------------- ### Execute Shell Commands with Claude Code JS Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Illustrates the use of the low-level executeCommand() utility function for running arbitrary shell commands. It returns the standard output, standard error, and exit code, utilizing execa for process management. ```javascript import { executeCommand } from 'claude-code-js'; // Execute a command and get full output const result = await executeCommand(['npm', 'test'], { cwd: './my-project', timeout: 30000, env: { NODE_ENV: 'test' } }); console.log('Exit code:', result.exitCode); console.log('Output:', result.stdout); if (result.stderr) { console.error('Errors:', result.stderr); } ``` -------------------------------- ### Manage Claude Code Instance Options Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Explains how to dynamically update configuration settings for a ClaudeCode instance using setOptions() and retrieve current settings with getOptions(). This allows runtime adjustments to parameters like model and verbosity. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode({ model: 'claude-3-sonnet', verbose: false }); // Check current configuration const currentOptions = claude.getOptions(); console.log('Current model:', currentOptions.model); // 'claude-3-sonnet' // Update configuration on the fly claude.setOptions({ model: 'claude-3-opus', verbose: true }); // Verify the update const updatedOptions = claude.getOptions(); console.log('Updated model:', updatedOptions.model); // 'claude-3-opus' ``` -------------------------------- ### Version Checking for Claude Code CLI Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates how to retrieve the version of the Claude Code CLI using the SDK. This is useful for ensuring compatibility or reporting issues. ```javascript // Get the Claude Code CLI version const version = await claude.version(); console.log('Claude Code CLI version:', version); ``` -------------------------------- ### A/B Testing Code Solutions with Claude JS SDK Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates how to use the Claude Code JS SDK to explore and compare different solutions for a given problem, such as processing large CSV files. It utilizes session forking to concurrently test streaming, chunking, and parallel processing approaches. ```javascript const claude = new ClaudeCode(); const session = claude.newSession(); // Set up the problem await session.prompt({ prompt: 'I need to process a large CSV file with millions of rows. What approach should I use?', systemPrompt: 'You are an expert in data processing and performance optimization' }); // Fork to explore different solutions const streamingFork = session.fork(); const chunkingFork = session.fork(); const parallelFork = session.fork(); // Explore streaming approach const streamingSolution = await streamingFork.prompt({ prompt: 'Show me how to implement this using Node.js streams' }); // Explore chunking approach const chunkingSolution = await chunkingFork.prompt({ prompt: 'Show me how to process this in chunks with a batch size' }); // Explore parallel processing const parallelSolution = await parallelFork.prompt({ prompt: 'Show me how to use worker threads for parallel processing' }); // Compare solutions console.log('Streaming approach:', streamingSolution.result); console.log('Chunking approach:', chunkingSolution.result); console.log('Parallel approach:', parallelSolution.result); // Pick the best approach and continue await parallelFork.prompt({ prompt: 'Add progress tracking to this implementation' }); ``` -------------------------------- ### Managing Multiple Independent Sessions Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Shows how to create and maintain multiple concurrent Claude sessions for different tasks, such as code reviews and debugging, without state interference. ```javascript const claude = new ClaudeCode(); const codeReviewSession = claude.newSession(); const debugSession = claude.newSession(); await codeReviewSession.prompt({ prompt: 'Review this code for best practices: function getData() { return fetch("/api").then(r => r.json()) }', systemPrompt: 'You are a code reviewer focused on best practices and performance' }); await debugSession.prompt({ prompt: 'Help me debug this error: ReferenceError: user is not defined', systemPrompt: 'You are a debugging expert' }); await codeReviewSession.prompt({ prompt: 'How can I add error handling?' }); await debugSession.prompt({ prompt: 'The error occurs in line 45 of auth.js' }); ``` -------------------------------- ### Manage Multi-turn Conversations Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Explains how to create and manage persistent conversation sessions, allowing for context-aware interactions and history retrieval. ```javascript const session = claude.newSession(); const firstMessage = await session.prompt({ prompt: 'What is 2 + 2?', systemPrompt: 'You are expert at math. Always return a single line of text in format: equation = result' }); const secondMessage = await session.prompt({ prompt: '3 + 3 = 6' }); const history = await session.prompt({ prompt: 'Send the history of all validations you have done so far' }); console.log('Total messages:', session.messages.length); console.log('All session IDs:', session.sessionIds); ``` -------------------------------- ### executeCommand() Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Low-level utility function for executing arbitrary shell commands. ```APIDOC ## executeCommand() ### Description Low-level utility function for executing arbitrary shell commands. Returns the stdout, stderr, and exit code. ### Method N/A (Utility Function) ### Parameters #### Request Body - **command** (array) - Required - The command and arguments to execute. - **options** (object) - Optional - Execution options including cwd, timeout, and env. ### Response #### Success Response (200) - **stdout** (string) - Standard output of the command. - **stderr** (string) - Standard error of the command. - **exitCode** (number) - The process exit code. ``` -------------------------------- ### Stream Shell Command Output in Real-Time Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Demonstrates the streamCommand() function, which executes a command and streams its output to the console in real-time. It returns an execa ResultPromise that resolves upon command completion. ```javascript import { streamCommand } from 'claude-code-js'; // Stream command output in real-time (output goes to stdout/stderr) const process = streamCommand(['npm', 'run', 'dev'], { cwd: './my-project', timeout: 60000 }); // Wait for completion await process; console.log('Dev server started'); ``` -------------------------------- ### TypeScript Support for Claude JS SDK Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates the full TypeScript support in the Claude Code JS SDK, including type-safe configuration, prompt creation, and response handling using exported types. ```typescript import { ClaudeCode, ClaudeCodeOptions, ClaudeCodeResponse, ClaudeCodeError, ClaudeCodeMessage, Prompt } from 'claude-code-js'; // Type-safe configuration const options: ClaudeCodeOptions = { apiKey: process.env.CLAUDE_API_KEY, model: 'claude-3-sonnet', workingDirectory: './src', verbose: true }; const claude = new ClaudeCode(options); // Type-safe prompt const prompt: Prompt = { prompt: 'Generate unit tests for auth.js', systemPrompt: 'You are a test generation expert', appendSystemPrompt: 'Use Jest framework' }; // Type-safe response handling const response: ClaudeCodeResponse = await claude.chat(prompt); if (response.success && response.message) { const message: ClaudeCodeMessage = response.message; console.log('Result:', message.result); console.log('Cost in USD:', message.cost_usd); console.log('Duration:', message.duration_ms); } ``` -------------------------------- ### Manage Multi-turn Conversations with Sessions Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Creates a new Session instance to maintain conversation history. This allows for context-aware follow-up prompts where the AI remembers previous interactions within the same session. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode(); const session = claude.newSession(); const firstMessage = await session.prompt({ prompt: 'What is 2 + 2?' }); console.log('First response:', firstMessage.result); const secondMessage = await session.prompt({ prompt: 'Now multiply that by 3' }); console.log('Second response:', secondMessage.result); ``` -------------------------------- ### Fork Conversation Sessions Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Creates a copy of an existing session to explore different conversation branches. Forks inherit the history of the parent session but proceed independently, allowing for parallel experimentation without affecting the original state. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode(); const mainSession = claude.newSession(); await mainSession.prompt({ prompt: 'Write a function to calculate factorial' }); const iterativeSession = mainSession.fork(); const memoizedSession = mainSession.fork(); await iterativeSession.prompt({ prompt: 'Show me an iterative version' }); await memoizedSession.prompt({ prompt: 'Add memoization to the recursive version' }); ``` -------------------------------- ### Perform Single Chat Interactions Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Shows how to send a single prompt to Claude and handle the response, including checking for success and accessing metadata like session IDs and costs. ```javascript const response = await claude.chat({ prompt: 'Explain this error: TypeError: Cannot read property of undefined', systemPrompt: 'You are a helpful coding assistant', appendSystemPrompt: 'Keep explanations concise' }); if (response.success) { console.log('Result:', response.message.result); console.log('Session ID:', response.message.session_id); console.log('Cost:', response.message.cost_usd); } else { console.error('Error:', response.error.message); } ``` -------------------------------- ### Retrieve OAuth Credentials (Shell) Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Provides shell commands to retrieve stored OAuth credentials on Linux and macOS systems. This is useful for debugging authentication issues or manually managing tokens. ```shell # On Linux, credentials are stored at ~/.claude/.credentials.json # Retrieve existing credentials: cat ~/.claude/.credentials.json # On macOS, credentials are stored in Keychain: security find-generic-password -l "Claude Code-credentials" -w ``` -------------------------------- ### Execute Single Chat Prompts Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Sends a prompt to Claude and processes the response. It supports both simple string inputs and structured objects containing system prompts, returning success status, message results, and metadata like cost and duration. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode(); const simpleResponse = await claude.chat('Explain this error: TypeError: Cannot read property of undefined'); const response = await claude.chat({ prompt: 'Review this code for security issues', systemPrompt: 'You are a security-focused code reviewer', appendSystemPrompt: 'Keep explanations concise' }); if (response.success) { console.log('Result:', response.message.result); console.log('Session ID:', response.message.session_id); } else { console.error('Error:', response.error.message); } ``` -------------------------------- ### Retrieving OAuth Credentials from Keychain (macOS) Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Provides the macOS terminal command to retrieve OAuth credentials stored in the system's Keychain. ```bash security find-generic-password -l "Claude Code-credentials" -w ``` -------------------------------- ### Reverting Session State Source: https://github.com/s-soroosh/claude-code-js/blob/main/README.md Demonstrates how to use the revert() method to undo conversation turns by removing recent messages from the session history. ```javascript const session = claude.newSession(); await session.prompt({ prompt: 'Write a Python hello world' }); await session.prompt({ prompt: 'Now add a loop that prints it 5 times' }); await session.prompt({ prompt: 'Add error handling' }); console.log('Messages before revert:', session.messages.length); session.revert(); console.log('Messages after single revert:', session.messages.length); session.revert(2); console.log('Messages after reverting 2:', session.messages.length); await session.prompt({ prompt: 'Write a JavaScript hello world instead' }); ``` -------------------------------- ### Session.revert() Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Removes the most recent messages and session IDs from the session, allowing you to undo conversation turns and continue from an earlier state. ```APIDOC ## Session.revert() ### Description Removes the most recent messages and session IDs from the session, allowing you to undo conversation turns and continue from an earlier state. ### Method N/A (Class Method) ### Parameters #### Path Parameters - **count** (number) - Optional - The number of messages to revert. Defaults to 1. ### Request Example ```javascript session.revert(2); ``` ### Response #### Success Response (void) - **void** - Updates the internal message state of the session instance. ``` -------------------------------- ### Revert Session Messages in Claude Code JS Source: https://context7.com/s-soroosh/claude-code-js/llms.txt Demonstrates how to remove recent messages and session IDs from a Claude Code session to undo conversation turns. It shows reverting a single message and multiple messages at once, allowing continuation from an earlier state. ```javascript import { ClaudeCode } from 'claude-code-js'; const claude = new ClaudeCode(); const session = claude.newSession(); // Build up a conversation await session.prompt({ prompt: 'Write a Python hello world' }); await session.prompt({ prompt: 'Now add a loop that prints it 5 times' }); await session.prompt({ prompt: 'Add error handling' }); console.log('Messages before revert:', session.messages.length); // 3 // Revert the last message session.revert(); console.log('After single revert:', session.messages.length); // 2 // Revert multiple messages at once session.revert(2); console.log('After reverting 2:', session.messages.length); // 0 // Continue from reverted state await session.prompt({ prompt: 'Write a JavaScript hello world instead' }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.