### Claude CLI Configuration File Example Source: https://context7.com/shellicar/claude-cli/llms.txt An example of the Claude CLI's configuration file (`cli-config.json`). This file allows customization of model selection, timeouts, auto-approve behavior, and system prompt providers. ```json { "$schema": "https://raw.githubusercontent.com/shellicar/claude-cli/main/schema/cli-config.schema.json", "model": "claude-opus-4-6", "maxTurns": 100, "permissionTimeoutMs": 30000, "extendedPermissionTimeoutMs": 120000, "questionTimeoutMs": 60000, "drowningThreshold": 15, "autoApproveEdits": true, "autoApproveReads": true, "expandTilde": true, "providers": { "git": { "enabled": true, "branch": true, "status": true, "sha": true }, "usage": { "enabled": true, "time": true, "context": true, "cost": true } } } ``` -------------------------------- ### Install Claude CLI Globally Source: https://context7.com/shellicar/claude-cli/llms.txt Instructions for installing the Claude CLI globally using package managers like pnpm, npm, or yarn. This allows the CLI to be accessed from any directory. ```bash # Install globally pnpm add -g @shellicar/claude-cli # Or with npm npm install -g @shellicar/claude-cli # Run the CLI claude-cli # Initialize configuration file claude-cli --init-config ``` -------------------------------- ### Development Workflow Commands (Bash) Source: https://context7.com/shellicar/claude-cli/llms.txt Outlines the standard development commands for the project using pnpm scripts. This includes installing dependencies, running in development mode with hot reload, building for production, watching for changes, running the application, executing tests, performing type checks, and linting with Biome. ```bash # Install dependencies pnpm install # Development mode with hot reload pnpm dev # Build production bundle with esbuild pnpm build # Watch mode for continuous builds pnpm build:watch # Run the built bundle pnpm start # Run tests pnpm test # TypeScript type checking pnpm type-check pnpm type-check:watch # Lint with Biome pnpm ci # Check only pnpm ci:fix # Auto-fix issues # Find unused exports pnpm knip ``` -------------------------------- ### Monitor Claude CLI Audit Log Source: https://context7.com/shellicar/claude-cli/llms.txt This bash snippet shows how to monitor the Claude CLI's audit log, which records all SDK events to `.claude/audit.jsonl`. It provides the command `tail -f .claude/audit.jsonl` to watch the log in real-time and includes examples of typical log entries for system initialization, assistant messages, user tool results, and overall session results. The utility of the audit log for debugging, context transfer, session replay, and cost analysis is also highlighted. ```bash # Watch audit log in real-time tail -f .claude/audit.jsonl # Example audit log entries (one JSON object per line): {"type":"system","subtype":"init","session_id":"abc123","model":"claude-opus-4-6"} {"type":"assistant","uuid":"msg-123","message":{"role":"assistant","content":[...]}} {"type":"user","message":{"role":"user","content":[{"type":"tool_result",...}]}} {"type":"result","subtype":"success","total_cost_usd":0.0234,"num_turns":5} # Audit log is useful for: # - Debugging SDK interactions # - Context transfer (paste to another Claude for instant context) # - Session replay and review # - Cost analysis ``` -------------------------------- ### Handling Background Tasks in SDK Source: https://github.com/shellicar/claude-cli/blob/main/docs/sdk-findings.md When Claude runs tasks in the background (`run_in_background: true`), the SDK emits a `task_notification` and starts a new internal turn. This can lead to stale `canUseTool` handlers and potential 'Stream closed' errors if not managed properly. Mitigations involve checking `session.isActive` and the abort signal. ```typescript // Example mitigation in canUseTool handler if (!session.isActive) { // Handle stale session or abort return; } // Example mitigation in PermissionManager.resolve() if (abortSignal.aborted) { // Do not proceed if aborted return; } ``` -------------------------------- ### Configure Claude CLI System Prompt Providers Source: https://context7.com/shellicar/claude-cli/llms.txt This snippet illustrates the Claude CLI's modular provider system for appending contextual information to system prompts. It shows how to enable and configure the 'Git Provider' and 'Usage Provider' in `cli-config.json`. The Git provider can include branch, status, and SHA, while the Usage provider can show time, context usage, and cost. The output format of these providers when appended to the system prompt is also demonstrated. ```typescript // Git Provider - adds repository context // Enable/disable in cli-config.json: { "providers": { "git": { "enabled": true, "branch": true, // Shows: # gitBranch\nmain "status": true, // Shows: # gitStatus\nWorking tree: dirty "sha": true // Shows: # gitSha\nabc1234-dirty } } } // Usage Provider - adds session metrics { "providers": { "usage": { "enabled": true, "time": true, // Current time and seconds since last response "context": true, // Context usage percentage "cost": true // Session cost in USD } } } // Provider output is appended to the system prompt per query: // "# gitBranch\nmain\n# gitStatus\nWorking tree: clean\n# contextUsage\n45.2%" ``` -------------------------------- ### Claude CLI Arguments and Help Source: https://context7.com/shellicar/claude-cli/llms.txt Details on available command-line arguments for the Claude CLI, including options for showing version information, detailed version information, help messages, and initializing the configuration file. ```bash # Show version claude-cli --version claude-cli -v # Show detailed version information (branch, sha, commit date, build date) claude-cli --version-info # Show help claude-cli --help claude-cli -h claude-cli -? # Create default configuration file at ~/.claude/cli-config.json claude-cli --init-config ``` -------------------------------- ### Configuring SDK Plugins Source: https://github.com/shellicar/claude-cli/blob/main/docs/sdk-findings.md The SDK allows for the configuration of plugins, which can be loaded from local paths. This is specified within the `plugins` array in the SDK options, where each plugin object has a `type` and a `path`. ```typescript const sdkOptions = { plugins: [{ type: 'local', path: './my-plugin' }] }; // ... SDK initialization with sdkOptions ``` -------------------------------- ### Use Claude CLI Clipboard Integration Source: https://context7.com/shellicar/claude-cli/llms.txt This section describes the Claude CLI's clipboard integration for pasting images and text across platforms like WSL, macOS, and Linux. It details how to enter command mode using Ctrl+/ and lists the key bindings for pasting images ('i'), pasting text ('t'), managing attachments ('d', 'p', arrow keys), and the platform-specific methods used for detection and execution (wl-paste, xclip, pbpaste, PowerShell). ```typescript // Enter command mode with Ctrl+/ // Then use these keys: // Paste image from clipboard // Supports: PNG, BMP (auto-converted to PNG) // i → "Image attached (125KB, 1 total)" // Paste text from clipboard // Text is truncated to 10KB max // t → "Text attached (3KB, 2 total)" // Manage attachments // d → Delete selected attachment // p → Toggle preview (shows first 3 lines of text or image metadata) // ←/→ → Navigate between attachments // Attachments are sent with the next message // Duplicate detection prevents adding the same content twice // Platform detection and methods: // - WSL/Linux Wayland: wl-paste // - Linux X11: xclip // - macOS: pngpaste (images), pbpaste (text) // - Windows (Git Bash): PowerShell clipboard API ``` -------------------------------- ### Enabling Skills and Hooks with `settingSources` Source: https://github.com/shellicar/claude-cli/blob/main/docs/sdk-findings.md Configuring the `settingSources` option in the SDK to include 'local', 'project', and 'user' enables various features such as skills, `PreToolUse` hooks, reading settings.json, file change notifications, `permissions.deny` rules, and plugin loading. These are not enabled by default and require explicit configuration. ```typescript const sdkOptions = { settingSources: ['local', 'project', 'user'] }; // ... SDK initialization with sdkOptions ``` -------------------------------- ### Configure Claude CLI Permissions Source: https://context7.com/shellicar/claude-cli/llms.txt This section details the Claude CLI's hybrid permission system, which combines SDK-level auto-approvals with manual prompts for sensitive actions. It shows how to configure auto-approval for read and edit operations in `cli-config.json`. The snippet also explains the interactive permission prompts, including key bindings for navigation and approval, extended timeouts for planning operations, and a 'drowning alert' mechanism to signal when timers are critically low. ```typescript // Auto-approve configuration in cli-config.json: { "autoApproveReads": true, // Auto-approve Read, Glob, Grep, LS, Skill "autoApproveEdits": true // Auto-approve Edit, Write inside cwd } // Permission prompts appear with countdown timers: // "Allow? Edit src/file.ts (y/n) [30s]" // Keys during permission prompts: // y/Y → Allow the tool call // n/N → Deny the tool call // Left → Navigate to previous pending permission // Right → Navigate to next pending permission // Extended timeouts for planning operations: // - EnterPlanMode: 120 seconds (configurable via extendedPermissionTimeoutMs) // - ExitPlanMode: 120 seconds // - Standard tools: 30 seconds (configurable via permissionTimeoutMs) // Drowning alert: When timer reaches drowningThreshold (default 15s), // the terminal flashes and beeps to get your attention ``` -------------------------------- ### Claude CLI Keyboard Controls Source: https://context7.com/shellicar/claude-cli/llms.txt Overview of keyboard shortcuts for the Claude CLI, covering basic input, navigation, editing, control commands, and command mode operations for managing attachments. ```text # Basic Input Enter → Insert newline (multiline input) Ctrl+Enter → Send message to Claude # Navigation Arrow keys → Move cursor Home/End → Move to line start/end Ctrl+Home → Move to buffer start Ctrl+End → Move to buffer end Ctrl+Left → Move word left Ctrl+Right → Move word right # Editing Backspace → Delete character before cursor Delete → Delete character after cursor Ctrl+Backspace → Delete word backward Ctrl+Delete → Delete word forward # Control Escape → Abort current query / exit command mode Ctrl+/ → Toggle command mode Ctrl+C → Quit immediately Ctrl+D → Quit (at idle prompt) # Command Mode (after Ctrl+/) i → Paste image from clipboard t → Paste text from clipboard d → Delete selected attachment p → Toggle attachment preview Left/Right → Navigate between attachments Escape → Exit command mode ``` -------------------------------- ### Displaying Code Diffs with Colors (TypeScript) Source: https://context7.com/shellicar/claude-cli/llms.txt Demonstrates how the Claude CLI displays proposed code changes using colored unified diffs. It explains the meaning of red (-), green (+), and white (@@ @@) lines in the diff output, which helps users visualize modifications. ```typescript // When Claude uses the Edit tool, the CLI shows: // tool_use: Edit src/example.ts // --- a/src/example.ts // +++ b/src/example.ts // @@ -10,3 +10,5 @@ // function hello() { // - console.log("Hello"); // + console.log("Hello, World!"); // + return true; // } // Diff colors (when terminal supports them): // Red (-) lines: removed content // Green (+) lines: added content // White (@@ @@): hunk headers showing line numbers ``` -------------------------------- ### Text Buffer Management with Editor API (TypeScript) Source: https://context7.com/shellicar/claude-cli/llms.txt Showcases the pure functional editor API for managing text buffers and cursor positions. It covers creating an editor, inserting characters and newlines, navigating the buffer, performing word-level operations, and clearing the editor state. ```typescript import { createEditor, getText, insertChar, insertNewline, backspace, deleteChar, deleteWord, deleteWordBackward, moveLeft, moveRight, moveUp, moveDown, moveHome, moveEnd, moveBufferStart, moveBufferEnd, moveWordLeft, moveWordRight, clear } from './editor.js'; // Create a new editor state let editor = createEditor(); // { lines: [''], cursor: { row: 0, col: 0 } } // Insert characters editor = insertChar(editor, 'H'); editor = insertChar(editor, 'i'); // { lines: ['Hi'], cursor: { row: 0, col: 2 } } // Insert newline for multiline input editor = insertNewline(editor); editor = insertChar(editor, 'T'); editor = insertChar(editor, 'h'); editor = insertChar(editor, 'e'); editor = insertChar(editor, 'r'); editor = insertChar(editor, 'e'); // { lines: ['Hi', 'There'], cursor: { row: 1, col: 5 } } // Get full text content const text = getText(editor); // "Hi\nThere" // Navigation editor = moveHome(editor); // { cursor: { row: 1, col: 0 } } editor = moveBufferStart(editor); // { cursor: { row: 0, col: 0 } } editor = moveEnd(editor); // { cursor: { row: 0, col: 2 } } // Word-level operations editor = moveWordRight(editor); // Jump to next word boundary editor = deleteWordBackward(editor); // Delete word before cursor // Clear and reset editor = clear(editor); // Back to initial state ``` -------------------------------- ### Managing Claude API Interactions with QuerySession (TypeScript) Source: https://context7.com/shellicar/claude-cli/llms.txt Details the QuerySession class for managing interactions with the Claude API. It supports session resumption, handling tool permissions with custom logic, adding accessible directories, sending queries, and canceling ongoing requests. ```typescript import { QuerySession } from './session.js'; // Create a session with model and max turns const session = new QuerySession('claude-opus-4-6', 100); // Set up permission handler session.canUseTool = async (toolName, input, options) => { // Auto-approve read-only tools if (['Read', 'Glob', 'Grep'].includes(toolName)) { return { behavior: 'allow', updatedInput: input }; } // Deny dangerous operations if (toolName === 'Bash' && input.command?.includes('rm -rf')) { return { behavior: 'deny', message: 'Dangerous command blocked' }; } // Default: allow with original input return { behavior: 'allow', updatedInput: input }; }; // Resume an existing session session.setSessionId('existing-session-id'); // Add additional directories Claude can access session.addDirectory('/path/to/other/project'); // Send a query with message handler await session.send('Explain this codebase', (msg) => { switch (msg.type) { case 'system': console.log(`Session started: ${msg.session_id}`); break; case 'assistant': for (const block of msg.message.content) { if (block.type === 'text') { console.log(block.text); } } break; case 'result': console.log(`Cost: $${msg.total_cost_usd.toFixed(4)}`); break; } }); // Cancel an in-progress query session.cancel(); // Check session state console.log(session.isActive); // true while query is running console.log(session.currentSessionId); // current session ID console.log(session.wasAborted); // true if last query was cancelled ``` -------------------------------- ### Adding Additional Directories via CLI Source: https://github.com/shellicar/claude-cli/blob/main/docs/sdk-findings.md The official CLI supports the `additionalDirectories` option within the `query()` call to specify extra directories. These are persisted in `/.claude/settings.local.json` under `permissions.additionalDirectories` and are written atomically. ```javascript claude.query({ // ... other options additionalDirectories: ['/path/to/dir1', '/path/to/dir2'] }); ``` -------------------------------- ### Manage Claude CLI Sessions Source: https://context7.com/shellicar/claude-cli/llms.txt This snippet demonstrates how to manage sessions in the Claude CLI. Sessions are persisted automatically and can be resumed across restarts, keyed by session ID and working directory. It covers showing the current session, switching to a specific session, and resuming sessions from other tools like the official Claude CLI or VS Code extension. Context usage is visually indicated with color coding. ```typescript // Sessions are saved to .claude/cli-session in the working directory // The CLI automatically resumes the last session on startup // Manual session switching /session // Show current session ID /session abc123-def456 // Switch to specific session // Sessions from the official Claude CLI or VS Code extension // can be resumed - just use the session ID from those tools /session vscode-session-id-here // Context is tracked and displayed with color coding: // Green: < 50% context used // Yellow: 50-80% context used // Red: > 80% context used // At 85%+ context, tools are automatically disabled // At 90%+ context, tools are completely removed from the request ``` -------------------------------- ### SDK Options for Tool Permissions Source: https://github.com/shellicar/claude-cli/blob/main/docs/sdk-findings.md The Claude Agent SDK provides several options to manage tool permissions. `permissionMode` controls the general permission handling, `allowedTools` auto-approves specific tools, `disallowedTools` removes tools from the model's context, and `tools` acts as a whitelist, restricting available tools to only those specified. ```typescript const sdkOptions = { permissionMode: 'acceptEdits', // or 'dontAsk', 'bypassPermissions' allowedTools: ['Edit'], disallowedTools: ['Bash'], tools: ['Bash', 'Read'] // Whitelist }; // ... SDK initialization with sdkOptions ``` -------------------------------- ### Configure Ctrl+Enter for Multiline Editing (VS Code Terminal) Source: https://context7.com/shellicar/claude-cli/llms.txt Configuration snippet for VS Code's keybindings to enable multiline editing by mapping Ctrl+Enter to send a custom input sequence to the terminal. This ensures proper functionality within VS Code. ```json // VS Code - add to keybindings.json: { "key": "ctrl+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\u001b[13;5u" }, "when": "terminalFocus" } ``` -------------------------------- ### Claude CLI In-Session Commands Source: https://context7.com/shellicar/claude-cli/llms.txt A list of slash commands available within an active Claude CLI session. These commands control sessions, display information, manage directories, and exit the CLI. ```bash # Show version information /version # Show available commands and keyboard controls /help # Show current session ID /session # Switch to a different session /session abc123-session-id # Compact the session at a specific message UUID # (useful for reducing context when approaching token limits) /compact-at 550e8400-e29b-41d4-a716-446655440000 # Add an additional directory for Claude to access /add-dir ~/projects/other-repo /add-dir /absolute/path/to/directory # Exit the CLI /quit /exit ``` -------------------------------- ### Configure Ctrl+Enter for Multiline Editing (Windows Terminal) Source: https://context7.com/shellicar/claude-cli/llms.txt Configuration snippet for Windows Terminal to enable multiline editing by mapping Ctrl+Enter to send a custom input sequence. This is crucial for using the CLI effectively. ```json // Windows Terminal - add to settings.json actions array: { "command": { "action": "sendInput", "input": "\u001b[13;5u" }, "id": "User.sendInput.CTRL_ENTER" } // Windows Terminal - add to keybindings: { "id": "User.sendInput.CTRL_ENTER", "keys": "ctrl+enter" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.