### Permission Rule Examples Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/configuration.md Examples of different permission rules for tool execution, including file access, command execution, and web operations. ```text Read // All file reads Read(./.env) // Specific file Read(src/**) // Directory glob Bash(npm test) // Command prefix match Bash(npm run:*) // Wildcard in command Edit(*.py) // Pattern-based WebFetch // All web fetches WebSearch // All web searches ``` -------------------------------- ### Permission Rule Examples Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Illustrates the format for defining permission rules in settings, showing examples for different tools and rule scopes including specific paths, glob patterns, and wildcard commands. ```plaintext Read // All Read tool calls Read(./.env) // Specific path Read(./.env.*) // Glob pattern Read(./secrets/**) // Recursive glob Bash(npm run lint) // Exact command prefix Bash(npm run:*) // Wildcard in command ``` -------------------------------- ### Install Claude Agent ACP Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/README.md Install the @agentclientprotocol/claude-agent-acp package using npm. ```bash npm install @agentclientprotocol/claude-agent-acp ``` -------------------------------- ### NewSessionMeta Usage Example Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Demonstrates how to use the NewSessionMeta type when initiating a new agent session. This example configures Claude Code options and raw SDK message emission. ```typescript const response = await agent.newSession({ cwd: '/home/user/project', _meta: { claudeCode: { options: { maxThinkingTokens: 10000, tools: { type: 'preset', preset: 'claude_code' } }, emitRawSDKMessages: [ { type: 'stream_event', subtype: 'message_start' } ] } } }); ``` -------------------------------- ### Full Bedrock Deployment Example Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/docs/model-configuration.md A complete example demonstrating how to configure Claude Agent ACP for Bedrock. It sets the Bedrock usage flag, AWS region, and model overrides, then executes the Node.js application. ```bash CLAUDE_CODE_USE_BEDROCK=1 \ AWS_REGION=us-west-2 \ CLAUDE_MODEL_CONFIG='{"modelOverrides":{"claude-opus-4-6":"us.anthropic.claude-opus-4-6-v1"}}' \ node dist/index.js ``` -------------------------------- ### runAcp Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/runAcp.md Initializes and starts the ACP agent, connecting to the client via stdin/stdout. This is the primary entry point for running the agent as an ACP service. ```APIDOC ## runAcp ### Description Initializes and starts the ACP agent, connecting to the client via stdin/stdout. This is the primary entry point for running the agent as an ACP service. ### Function Signature ```typescript export function runAcp(): { connection: AgentSideConnection; agent: ClaudeAcpAgent; } ``` ### Returns Object containing the initialized connection and agent instances. ### Example ```typescript import { runAcp } from '@agentclientprotocol/claude-agent-acp'; const { connection, agent } = runAcp(); // Wait for connection to close (e.g., client disconnects) await connection.closed; // Clean up await agent.dispose(); ``` ### Details The `runAcp()` function performs the following steps: 1. Creates an `AgentSideConnection` using stdin/stdout for ACP protocol communication 2. Instantiates a `ClaudeAcpAgent` with the connection 3. Registers the agent with the connection to handle incoming ACP requests 4. Returns both the connection and agent for lifecycle management. ### Connection Lifecycle The agent remains active until the connection closes. This typically happens when: - The client closes the connection - A transport error occurs - The process receives a termination signal. ### Environment Variables The function respects these environment variables for configuration: | Variable | | Purpose | | CLAUDE_CONFIG_DIR | Override the Claude config directory (default: ~/.claude) | | CLAUDE_CODE_EXECUTABLE | Path to the Claude Code binary | | MAX_THINKING_TOKENS | Maximum tokens for extended thinking (if supported by model) | | CLAUDE_MODEL_CONFIG | JSON configuration for model overrides | | ANTHROPIC_MODEL | Override the default model | | NO_BROWSER | Detect remote environment (disable browser redirect) | | SSH_CONNECTION, SSH_CLIENT, SSH_TTY | Detect remote environment | | CLAUDE_CODE_REMOTE | Indicate running in remote environment | ### Error Handling Unhandled rejections are logged to stderr. Graceful shutdown is triggered by: - SIGTERM signal - SIGINT signal (Ctrl+C) - Connection.closed promise resolving. ### Integration with CLI When invoked with `--cli` flag, the agent spawns the Claude Code CLI directly: ```bash claude-agent-acp --cli [args...] ``` This allows the agent to act as a gateway to the native Claude Code application. ``` -------------------------------- ### Configure Both Model Overrides and Available Models Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/docs/model-configuration.md Combine model overrides with a restricted list of available models. This example sets specific Bedrock model IDs and limits usage to 'opus' and 'sonnet'. ```bash CLAUDE_MODEL_CONFIG='{"modelOverrides":{"claude-opus-4-6":"us.anthropic.claude-opus-4-6-v1","claude-sonnet-4-5":"us.anthropic.claude-sonnet-4-5-v1"},"availableModels":["opus","sonnet"]}' ``` -------------------------------- ### Example Usage of TaskState Map Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Demonstrates how to initialize and iterate over a TaskState Map. Note that iteration order follows insertion order. ```typescript const taskState: TaskState = new Map([ ['task-1', { subject: 'Implement feature', status: 'in_progress', description: 'Add new authentication method' }], ['task-2', { subject: 'Write tests', status: 'pending' }] ]); // Iteration order is insertion order for (const [id, task] of taskState) { console.log(`[${id}] ${task.subject}: ${task.status}`); } ``` -------------------------------- ### SDKMessageFilter Usage Example Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Provides an example of creating an array of SDKMessageFilter objects to configure raw SDK message emission. This filters for specific stream events and system status messages. ```typescript const filters: SDKMessageFilter[] = [ { type: 'stream_event', subtype: 'message_start' }, { type: 'system', subtype: 'status' }, { type: 'result' } ]; const meta: NewSessionMeta = { claudeCode: { emitRawSDKMessages: filters } }; ``` -------------------------------- ### Initialize and Run ACP Agent Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/runAcp.md Use `runAcp` to initialize and start the ACP agent, connecting to the client via stdin/stdout. This is the primary entry point for running the agent as an ACP service. It returns the initialized connection and agent instances for lifecycle management. ```typescript import { runAcp } from '@agentclientprotocol/claude-agent-acp'; const { connection, agent } = runAcp(); // Wait for connection to close (e.g., client disconnects) await connection.closed; // Clean up await agent.dispose(); ``` -------------------------------- ### Get Current Working Directory Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Returns the current working directory path that the SettingsManager is using. ```typescript getCwd(): string ``` -------------------------------- ### Get Current Settings Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Retrieve the current merged settings object. This object contains all resolved configuration values, such as model, effort level, and permissions. ```typescript const settings = manager.getSettings(); console.log(settings.model); // 'claude-opus-4-6' console.log(settings.permissions?.defaultMode); // 'default' console.log(settings.availableModels); // ['opus', 'sonnet', 'haiku'] ``` -------------------------------- ### Initialize and Use SettingsManager Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Demonstrates the complete workflow of creating, initializing, and using the SettingsManager. Includes setting up an onChange callback for dynamic updates and switching projects. ```typescript import { SettingsManager } from '@agentclientprotocol/claude-agent-acp'; // Create and initialize const manager = new SettingsManager(process.cwd(), { onChange: () => { const updated = manager.getSettings(); console.log('New settings:', updated); } }); await manager.initialize(); // Get current settings const settings = manager.getSettings(); if (settings.model) { console.log(`Using model: ${settings.model}`); } if (settings.permissions?.defaultMode) { console.log(`Permission mode: ${settings.permissions.defaultMode}`); } // Settings are automatically reloaded when files change // onChange callback fires when updates are detected // Later: switch projects await manager.setCwd('/home/user/other-project'); // Clean up manager.dispose(); ``` -------------------------------- ### initialize Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Loads all settings from disk and sets up file watchers. This method must be called before using other methods of the SettingsManager. It resolves settings, applies trust filters, sets up file system watchers, and debounces rapid file changes. ```APIDOC ## initialize ### Description Loads all settings from disk and sets up file watchers. This method must be called before using other methods of the SettingsManager. It resolves settings, applies trust filters, sets up file system watchers, and debounces rapid file changes. ### Signature ```typescript async initialize(): Promise ``` ### Returns - **Promise** - A promise that resolves when settings are loaded and watchers are set up. ### Behavior - Resolves settings through the SDK's merge engine - Applies the CLI's trust filter for `permissions.defaultMode` - Sets up FSWatchers on all settings files - Debounces rapid file changes (100ms) ### Example ```typescript await manager.initialize(); // Now safe to call: const settings = manager.getSettings(); ``` ``` -------------------------------- ### initialize Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Initializes the agent by responding to the client's capabilities query. Reports agent info, supported authentication methods, and agent capabilities. ```APIDOC ## initialize ### Description Initializes the agent by responding to the client's capabilities query. Reports agent info, supported authentication methods, and agent capabilities. ### Method POST ### Endpoint /initialize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (InitializeRequest) - Required - Client initialization request with capabilities ### Request Example ```typescript const response = await agent.initialize({ clientCapabilities: { promptCapabilities: { image: true, embeddedContext: true }, auth: { _meta: { gateway: true } } } }); console.log(response.agentInfo.name); // '@agentclientprotocol/claude-agent-acp' ``` ### Response #### Success Response (200) Promise with agent capabilities, info, and auth methods #### Response Example ```json { "agentInfo": { "name": "@agentclientprotocol/claude-agent-acp" } } ``` ### Error Handling Throws errors if client capabilities cannot be processed ``` -------------------------------- ### Initialize SettingsManager Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Load all settings from disk and set up file watchers. This method must be called before using other methods like `getSettings()`. It resolves settings, applies trust filters, and debounces rapid file changes. ```typescript await manager.initialize(); // Now safe to call: const settings = manager.getSettings(); ``` -------------------------------- ### BackgroundTerminal Type Definition Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Defines the possible states for a background terminal execution, including started, aborted, exited, killed, or timed out. ```typescript type BackgroundTerminal = | { handle: TerminalHandle; status: 'started'; lastOutput: TerminalOutputResponse | null; } | { status: 'aborted' | 'exited' | 'killed' | 'timedOut'; pendingOutput: TerminalOutputResponse; }; ``` -------------------------------- ### newSession Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Creates a new session with the given working directory and MCP servers. Returns session ID and initial configuration. ```APIDOC ## newSession ### Description Creates a new session with the given working directory and MCP servers. Returns session ID and initial configuration. ### Method POST ### Endpoint /newSession ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (NewSessionRequest) - Required - Session parameters including cwd, mcpServers, additionalDirectories ### Request Example ```typescript const response = await agent.newSession({ cwd: '/home/user/project', mcpServers: [ { name: 'filesystem', type: 'stdio', command: 'mcp-filesystem', args: ['/home/user/project'] } ] }); console.log(response.sessionId); ``` ### Response #### Success Response (200) Promise with sessionId, modes, and configOptions #### Response Example ```json { "sessionId": "some-session-id", "modes": [], "configOptions": {} } ``` ``` -------------------------------- ### SettingsManager Constructor Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Initializes a new instance of the SettingsManager. It takes the current working directory and optional configuration options, including an onChange callback and a custom logger. The constructor returns an uninitialized instance; `initialize()` must be called to load settings and set up watchers. ```APIDOC ## SettingsManager Constructor ### Description Initializes a new instance of the SettingsManager. It takes the current working directory and optional configuration options, including an onChange callback and a custom logger. The constructor returns an uninitialized instance; `initialize()` must be called to load settings and set up watchers. ### Signature ```typescript constructor(cwd: string, options?: SettingsManagerOptions) ``` ### Parameters #### Path Parameters - **cwd** (string) - Required - Working directory to load project settings from #### Query Parameters - **options** (SettingsManagerOptions) - Optional - Configuration options - **onChange** (() => void) - Optional - Callback when settings change - **logger** (Logger) - Optional - Custom logger (default: console) ### Example ```typescript import { SettingsManager } from '@agentclientprotocol/claude-agent-acp'; const manager = new SettingsManager('/home/user/project', { onChange: () => console.log('Settings updated'), logger: console }); await manager.initialize(); ``` ``` -------------------------------- ### Instantiate SettingsManager Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Create a new SettingsManager instance. Specify the working directory and optional configuration options like an onChange callback or a custom logger. This constructor does not initialize the manager; `initialize()` must be called separately. ```typescript import { SettingsManager } from '@agentclientprotocol/claude-agent-acp'; const manager = new SettingsManager('/home/user/project', { onChange: () => console.log('Settings updated'), logger: console }); await manager.initialize(); ``` -------------------------------- ### Initialize and Configure Claude Agent ACP Session Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/configuration.md Demonstrates how to initialize the ACP agent and create a new session with comprehensive configuration, including working directory, MCP servers, and Claude-specific options. ```typescript import { ClaudeAcpAgent, runAcp } from '@agentclientprotocol/claude-agent-acp'; // Start the agent const { connection, agent } = runAcp(); // Later: create a session with full configuration const sessionResponse = await agent.newSession({ cwd: '/home/user/project', mcpServers: [ { name: 'filesystem', type: 'stdio', command: 'mcp-filesystem', args: ['/home/user/project'] }, { name: 'github', type: 'http', url: 'http://localhost:3000', headers: { 'Authorization': 'Bearer token' } } ], _meta: { claudeCode: { options: { maxThinkingTokens: 10000, effortLevel: 'high', additionalDirectories: ['/home/user/shared'], tools: { type: 'preset', preset: 'claude_code' }, mcpServers: { // Additional servers merged with above } }, emitRawSDKMessages: [ { type: 'stream_event', subtype: 'message_start' } ] }, additionalRoots: ['/home/user/docs'] } }); console.log('Session created:', sessionResponse.sessionId); console.log('Available modes:', sessionResponse.modes.availableModes); console.log('Config options:', sessionResponse.configOptions); ``` -------------------------------- ### Settings File JSON Structure Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/configuration.md Defines the structure for user, project, or local settings files. Allows customization of the default model, effort level, permissions, and available models. ```json { "model": "claude-opus-4-6", "effortLevel": "high", "permissions": { "defaultMode": "default", "rules": [ "Bash(npm test)", "Read(.env*)", "Write(src/**)" ] }, "availableModels": [ "claude-opus-4-6", "claude-sonnet-4-5", "claude-haiku-4-5" ] } ``` -------------------------------- ### Create and Push Git Tag Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/docs/RELEASES.md After creating and merging the release branch, use these commands to create a new tag and push it to the remote repository. Replace X.X.X with the specific version. ```sh git tag vX.X.X git push origin vX.X.X ``` -------------------------------- ### Create New Session with ClaudeAcpAgent Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Create a new session with the specified working directory and MCP servers. Returns the session ID and initial configuration. ```typescript const response = await agent.newSession({ cwd: '/home/user/project', mcpServers: [ { name: 'filesystem', type: 'stdio', command: 'mcp-filesystem', args: ['/home/user/project'] } ] }); console.log(response.sessionId); ``` -------------------------------- ### Initialize ClaudeAcpAgent Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Initialize the agent by responding to the client's capabilities query. Use this to report agent info, supported authentication methods, and agent capabilities. ```typescript const response = await agent.initialize({ clientCapabilities: { promptCapabilities: { image: true, embeddedContext: true }, auth: { _meta: { gateway: true } } } }); console.log(response.agentInfo.name); // '@agentclientprotocol/claude-agent-acp' ``` -------------------------------- ### getSettings Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Retrieves the current merged settings object, which contains all resolved configuration values. This object includes keys such as `model`, `effortLevel`, and `permissions`. ```APIDOC ## getSettings ### Description Retrieves the current merged settings object, which contains all resolved configuration values. This object includes keys such as `model`, `effortLevel`, and `permissions`. ### Signature ```typescript getSettings(): Settings ``` ### Returns - **Settings** - An object containing the current merged settings. ### Example ```typescript const settings = manager.getSettings(); console.log(settings.model); // 'claude-opus-4-6' console.log(settings.permissions?.defaultMode); // 'default' console.log(settings.availableModels); // ['opus', 'sonnet', 'haiku'] ``` ``` -------------------------------- ### Create a New Git Branch Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/docs/RELEASES.md Use this command to create a new branch for preparing a release. Replace X.X.X with the desired version number. ```sh git checkout -b prep-vX.X.X ``` -------------------------------- ### Execute Prompt Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/README.md Execute a prompt within a given session, including text and resource content. Logs the stop reason and token usage from the response. ```typescript const response = await agent.prompt({ sessionId: sessionId, prompt: [ { type: 'text', text: 'What is the structure of this project?' }, { type: 'resource', resource: { uri: 'file:///path', text: 'content' } } ] }); console.log(response.stopReason); // 'end_turn', 'max_tokens', 'cancelled' console.log(response.usage); // Token counts ``` -------------------------------- ### resumeSession Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Resumes an existing session with the same parameters. Returns the current session state. ```APIDOC ## resumeSession ### Description Resumes an existing session with the same parameters. Returns the current session state. ### Method POST ### Endpoint /resumeSession ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (ResumeSessionRequest) - Required - Session ID and parameters to resume ### Request Example ```typescript const response = await agent.resumeSession({ sessionId: 'existing-session-id', cwd: '/home/user/project' }); ``` ### Response #### Success Response (200) Promise with current modes and configOptions #### Response Example ```json { "modes": [], "configOptions": {} } ``` ``` -------------------------------- ### writeTextFile Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Delegates a file write request to the client. This method allows you to write content to a specified file path on the client system. ```APIDOC ## writeTextFile ### Description Delegate file write request to the client. ### Method POST ### Endpoint /writeTextFile ### Parameters #### Request Body - **params** (WriteTextFileRequest) - Required - File path and content - **path** (string) - Required - The path to the file to write. - **contents** (string) - Required - The content to write to the file. ### Request Example ```json { "path": "/home/user/output.txt", "contents": "New content" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success or failure of the operation. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### toDisplayPath Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md Converts absolute file paths to project-relative paths for cleaner display in the UI. This helps in standardizing path representation. ```APIDOC ## toDisplayPath ### Description Converts absolute file paths to project-relative paths for cleaner display in the UI. ### Function Signature ```typescript export function toDisplayPath(filePath: string, cwd?: string): string ``` ### Parameters #### Path Parameters * **filePath** (string) - Required - Absolute file path * **cwd** (string) - Optional - Working directory for computing relative path ### Returns Relative path (if within cwd) or original path ### Example ```typescript import { toDisplayPath } from '@agentclientprotocol/claude-agent-acp'; toDisplayPath('/home/user/project/src/main.ts', '/home/user/project'); // Returns: 'src/main.ts' toDisplayPath('/etc/passwd', '/home/user/project'); // Returns: '/etc/passwd' (outside cwd) toDisplayPath('/home/user/project/file.ts'); // No cwd // Returns: '/home/user/project/file.ts' ``` ``` -------------------------------- ### prompt Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Executes a prompt within a given session. It streams messages back to the client via sessionUpdate notifications and returns a Promise with the stopReason and optional usage information. ```APIDOC ## prompt ### Description Execute a prompt in the session. Streams messages back to the client via sessionUpdate notifications. ### Method POST ### Endpoint /prompt ### Parameters #### Request Body - **params** (PromptRequest) - Required - Session ID and prompt content (text, images, resources) ### Request Example ```json { "sessionId": "session-id", "prompt": [ { "type": "text", "text": "Analyze this file" }, { "type": "resource", "resource": { "uri": "file:///path/to/file", "text": "content" } } ] } ``` ### Response #### Success Response (200) - **stopReason** (string) - Indicates why the prompt execution stopped (e.g., 'end_turn', 'max_tokens', 'cancelled'). - **usage** (object) - Optional. Contains information about token usage. #### Response Example ```json { "stopReason": "end_turn", "usage": { "input_tokens": 100, "output_tokens": 50 } } ``` ### Throws - `RequestError` - Auth required, internal error, or resource not found. - Errors from failed tool execution or session issues. ``` -------------------------------- ### Convert Todo Objects to Plan Entries Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md Transforms legacy todo objects into the ACP PlanEntry format. Ensures consistent status and priority for plan updates. ```typescript import { planEntries } from '@agentclientprotocol/claude-agent-acp'; const entries = planEntries({ todos: [ { content: 'Implement feature', status: 'in_progress', activeForm: 'Implementing' }, { content: 'Write tests', status: 'pending', activeForm: 'Writing' } ] }); // Each entry has status ('pending'|'in_progress'|'completed') and priority ('medium') ``` -------------------------------- ### Convert File Path to Display Path Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md Converts an absolute file path to a project-relative path for cleaner UI display. If no working directory is provided, it returns the original absolute path. ```typescript import { toDisplayPath } from '@agentclientprotocol/claude-agent-acp'; toDisplayPath('/home/user/project/src/main.ts', '/home/user/project'); // Returns: 'src/main.ts' toDisplayPath('/etc/passwd', '/home/user/project'); // Returns: '/etc/passwd' (outside cwd) toDisplayPath('/home/user/project/file.ts'); // No cwd // Returns: '/home/user/project/file.ts' ``` -------------------------------- ### readTextFile Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Delegates a file read request to the client, allowing access to files in restricted contexts. Returns a Promise with the file content. ```APIDOC ## readTextFile ### Description Delegate file read request to the client (for accessing files in restricted contexts). ### Method POST ### Endpoint /readTextFile ### Parameters #### Request Body - **params** (ReadTextFileRequest) - Required - File path and optional line range ### Request Example ```json { "path": "/home/user/document.txt", "startLine": 1, "endLine": 10 } ``` ### Response #### Success Response (200) - **contents** (string) - The content of the requested text file. #### Response Example ```json { "contents": "This is the content of the file." } ``` ### Throws - `RequestError` - If the file path is invalid, access is denied, or an internal error occurs. ``` -------------------------------- ### planEntries Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md Converts legacy todo objects to the ACP PlanEntry format. It takes an optional input object containing a list of todos and returns an array of PlanEntry objects, each with a status and priority. ```APIDOC ## planEntries Converts TodoWrite input objects (legacy todo format) to ACP PlanEntry format. ### Function Signature ```typescript export function planEntries( input: { todos: ClaudePlanEntry[] } | undefined ): PlanEntry[] ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | input | { todos: ClaudePlanEntry[] } | — | Todo list object | **Returns**: Array of PlanEntry objects with status and priority ### Example ```typescript import { planEntries } from '@agentclientprotocol/claude-agent-acp'; const entries = planEntries({ todos: [ { content: 'Implement feature', status: 'in_progress', activeForm: 'Implementing' }, { content: 'Write tests', status: 'pending', activeForm: 'Writing' } ] }); // Each entry has status ('pending'|'in_progress'|'completed') and priority ('medium') ``` ``` -------------------------------- ### getCwd Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Returns the current working directory that the SettingsManager is operating within. ```APIDOC ## getCwd ### Description Returns the current working directory that the SettingsManager is operating within. ### Signature ```typescript getCwd(): string ``` ### Returns - **string** - The current working directory path. ### Source `src/settings.ts:176-178` ``` -------------------------------- ### Update Working Directory Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Change the working directory and reload project-specific settings. This action disposes of existing watchers and reinitializes the manager with the new context. ```typescript // Switch to a different project await manager.setCwd('/home/user/other-project'); // Settings now reflect that project's .claude/settings.json ``` -------------------------------- ### Configure Bedrock Model Overrides Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/docs/model-configuration.md Map Anthropic model IDs to provider-specific model IDs, such as Bedrock model IDs or ARNs. This is useful when deploying with alternative providers. ```bash CLAUDE_MODEL_CONFIG='{"modelOverrides":{"claude-opus-4-6":"us.anthropic.claude-opus-4-6-v1","claude-sonnet-4-5":"us.anthropic.claude-sonnet-4-5-v1"}}' ``` -------------------------------- ### Run ACP Service Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/README.md Initialize and run the ACP agent, which handles the ACP protocol on stdin/stdout. Waits for the connection to close and the agent to dispose. ```typescript import { runAcp } from '@agentclientprotocol/claude-agent-acp'; const { connection, agent } = runAcp(); // Agent handles ACP protocol on stdin/stdout // Listens for initialize, newSession, prompt, etc. await connection.closed; // Wait for connection to close await agent.dispose(); ``` -------------------------------- ### ClaudeAcpAgent Constructor Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Initializes a new instance of the ClaudeAcpAgent. It requires an AgentSideConnection and optionally accepts a logger. ```APIDOC ## Constructor ClaudeAcpAgent ### Description Initializes a new instance of the ClaudeAcpAgent. It requires an AgentSideConnection and optionally accepts a logger. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { createAgentSideConnection, ndJsonStream } from '@agentclientprotocol/sdk'; import { ClaudeAcpAgent } from '@agentclientprotocol/claude-agent-acp'; const connection = await createAgentSideConnection({ stdio: { input: nodeToWebReadable(process.stdin), output: nodeToWebWritable(process.stdout), } }); const agent = new ClaudeAcpAgent(connection); ``` ### Response #### Success Response (200) ClaudeAcpAgent instance ``` -------------------------------- ### Pushable Methods Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/utilities.md Methods for the Pushable class, including pushing items, ending the stream, and making it iterable. ```APIDOC ## Pushable Methods ### push ```typescript push(item: T): void ``` Push an item to the queue or immediately resolve the next waiting iterator. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | item | T | ✓ | Item to enqueue | **Returns**: void **Example**: ```typescript const queue = new Pushable(); queue.push(42); queue.push(43); ``` ### end ```typescript end(): void ``` Signal that no more items will be pushed. Resolves all pending iterators with done=true. **Returns**: void **Example**: ```typescript queue.push(1); queue.push(2); queue.end(); // Iteration will stop after these items ``` ### [Symbol.asyncIterator] ```typescript [Symbol.asyncIterator](): AsyncIterator ``` Makes Pushable usable in `for await...of` loops. **Returns**: AsyncIterator **Example**: ```typescript for await (const item of pushable) { console.log(item); } ``` ``` -------------------------------- ### Execute a prompt in a session Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Use this method to send a prompt to the agent within an active session. It supports text and resource inputs and streams messages back via session updates. Ensure you have an active session and the necessary request parameters. ```typescript const response = await agent.prompt({ sessionId: session.sessionId, prompt: [ { type: 'text', text: 'Analyze this file' }, { type: 'resource', resource: { uri: 'file:///path/to/file', text: 'content' } } ] }); console.log(response.stopReason); // 'end_turn', 'max_tokens', 'cancelled' ``` -------------------------------- ### Create New Session Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/README.md Create a new session with Claude Code, specifying the current working directory and MCP servers. Retrieves the sessionId for subsequent operations. ```typescript const response = await agent.newSession({ cwd: '/home/user/project', mcpServers: [ { name: 'filesystem', type: 'stdio', command: 'mcp-filesystem' } ] }); const sessionId = response.sessionId; ``` -------------------------------- ### Define SettingsManagerOptions Interface Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Configuration options for the SettingsManager constructor, including optional callbacks and loggers. ```typescript export interface SettingsManagerOptions { onChange?: () => void; logger?: { log: (...args: any[]) => void; error: (...args: any[]) => void }; } ``` -------------------------------- ### createPostToolUseHook Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md A factory function that creates a HookCallback specifically for PostToolUse events. It allows for custom logic to be executed when the EnterPlanMode tool completes. ```APIDOC ## createPostToolUseHook ### Description Factory function that creates a HookCallback for PostToolUse events from Claude Code. Allows for custom logic when EnterPlanMode tool completes. ### Function Signature ```typescript export const createPostToolUseHook = ( logger: Logger = console, options?: { onEnterPlanMode?: () => Promise; } ): HookCallback ``` ### Parameters #### Path Parameters - **logger** (Logger) - Optional - Logger for error reporting - **options.onEnterPlanMode** (() => Promise) - Optional - Callback when EnterPlanMode tool completes ``` -------------------------------- ### NewSessionMeta Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Extra metadata passed when creating a new session, including Claude Code options and additional root directories. ```APIDOC ## NewSessionMeta ### Description Extra metadata passed when creating a new session, including Claude Code options and additional root directories. ### Fields - **claudeCode.options** (Options) - Claude Code initialization options - **claudeCode.emitRawSDKMessages** (boolean | SDKMessageFilter[]) - Configure raw SDK message emission - **additionalRoots** (string[]) - Additional root directories for context ### Usage Example ```typescript const response = await agent.newSession({ cwd: '/home/user/project', _meta: { claudeCode: { options: { maxThinkingTokens: 10000, tools: { type: 'preset', preset: 'claude_code' } }, emitRawSDKMessages: [ { type: 'stream_event', subtype: 'message_start' } ] } } }); ``` ``` -------------------------------- ### Logger Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Interface for customizing logging output. ```APIDOC ## Logger ### Description Interface for customizing logging output. ### Methods - **log** (...args: any[]) - General-purpose logging - **error** (...args: any[]) - Error-level logging ``` -------------------------------- ### NewSessionMeta Type Definition Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Defines the metadata for creating a new session, including Claude Code options and additional root directories. Use this to configure session initialization with specific Claude Code settings or custom root paths. ```typescript export type NewSessionMeta = { claudeCode?: { /** * Options forwarded to Claude Code when starting a new session. * These parameters will be ignored and managed by ACP: * - cwd, includePartialMessages, allowDangerouslySkipPermissions * - permissionMode, canUseTool, executable * These will be used and updated to work with ACP: * - hooks (merged with ACP's hooks) * - mcpServers (merged with ACP's mcpServers) * - disallowedTools (merged with ACP's disallowedTools) * - tools (passed through; defaults to claude_code preset) */ options?: Options; /** * When set, raw SDK messages are emitted as extNotification("_claude/sdkMessage", message) * - true: emit all messages * - false/undefined: emit nothing (default) * - SDKMessageFilter[]: emit only messages matching at least one filter */ emitRawSDKMessages?: boolean | SDKMessageFilter[]; }; additionalRoots?: string[]; }; ``` -------------------------------- ### MCP Server Configuration Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/configuration.md Specifies configurations for Message Communication Protocol (MCP) servers, supporting HTTP (including SSE) and stdio communication. Used for agent-to-agent or agent-to-tool communication. ```typescript mcpServers: { http: { type: 'http' | 'sse'; url: string; headers?: Record; }, stdio: { type: 'stdio'; command: string; args?: string[]; env?: Record; } } ``` -------------------------------- ### loadSession Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Loads a saved session and replays its history to the client. Used to restore previous conversation context. ```APIDOC ## loadSession ### Description Loads a saved session and replays its history to the client. Used to restore previous conversation context. ### Method POST ### Endpoint /loadSession ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (LoadSessionRequest) - Required - Session ID and parameters to load ### Request Example ```typescript const response = await agent.loadSession({ sessionId: 'saved-session-id', cwd: '/home/user/project' }); ``` ### Response #### Success Response (200) Promise with modes and configOptions #### Response Example ```json { "modes": [], "configOptions": {} } ``` ``` -------------------------------- ### Create Post Tool Use Hook Factory Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md A factory function that creates a HookCallback for PostToolUse events. It can optionally accept a logger and a callback for when the EnterPlanMode tool completes. ```typescript export const createPostToolUseHook = ( logger: Logger = console, options?: { onEnterPlanMode?: () => Promise; } ): HookCallback ``` -------------------------------- ### Create and use a Pushable async iterable Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/utilities.md Use Pushable to bridge push-based and async-iterator-based code patterns. Push items and then signal completion with end(). ```typescript import { Pushable } from '@agentclientprotocol/claude-agent-acp'; const messages = new Pushable(); // Producer: push items messages.push('Hello'); messages.push('World'); messages.end(); // Signal completion // Consumer: iterate for await (const msg of messages) { console.log(msg); } ``` -------------------------------- ### Iterate over a Pushable async iterable Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/utilities.md Use a for await...of loop to consume items from a Pushable, making it compatible with async iteration protocols. ```typescript for await (const item of pushable) { console.log(item); } ``` -------------------------------- ### taskStateToPlanEntries Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/tools.md Converts an accumulated task state Map into an array of PlanEntry objects, suitable for ACP plan updates. It accepts a TaskState Map and returns an array of PlanEntry objects, including content, status, and priority. ```APIDOC ## taskStateToPlanEntries Converts the accumulated task state Map to an array of PlanEntry objects for ACP plan updates. ### Function Signature ```typescript export function taskStateToPlanEntries(state: TaskState): PlanEntry[] ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | state | TaskState | ✓ | Map of task ID → TaskEntry | **Returns**: Array of PlanEntry with content (subject), status, and priority ### Example ```typescript import { taskStateToPlanEntries } from '@agentclientprotocol/claude-agent-acp'; const taskState = new Map([ ['task-1', { subject: 'Parse config', status: 'completed' }], ['task-2', { subject: 'Run tests', status: 'in_progress' }] ]); const entries = taskStateToPlanEntries(taskState); // [ // { content: 'Parse config', status: 'completed', priority: 'medium' }, // { content: 'Run tests', status: 'in_progress', priority: 'medium' } // ] ``` ``` -------------------------------- ### Push items to a Pushable queue Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/utilities.md Use the push method to add items to a Pushable queue. This can be used to enqueue items for later iteration. ```typescript const queue = new Pushable(); queue.push(42); queue.push(43); ``` -------------------------------- ### Resume Existing Session with ClaudeAcpAgent Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Resume an existing session using the provided session ID and parameters. Returns the current session state. ```typescript const response = await agent.resumeSession({ sessionId: 'existing-session-id', cwd: '/home/user/project' }); ``` -------------------------------- ### Define ToolInfo Interface Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md Represents information extracted from a tool use, intended for client-side presentation. Includes title, kind, content, and optional locations. ```typescript interface ToolInfo { title: string; kind: ToolKind; content: ToolCallContent[]; locations?: ToolCallLocation[]; } ``` -------------------------------- ### Run Claude Agent ACP via CLI Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/runAcp.md When invoked with the `--cli` flag, the `claude-agent-acp` command spawns the Claude Code CLI directly, allowing the agent to act as a gateway to the native Claude Code application. ```bash claude-agent-acp --cli [args...] ``` -------------------------------- ### listSessions Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Lists all saved sessions in a directory with their titles and last-modified timestamps. ```APIDOC ## listSessions ### Description Lists all saved sessions in a directory with their titles and last-modified timestamps. ### Method POST ### Endpoint /listSessions ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (ListSessionsRequest) - Required - Directory to list sessions from ### Request Example ```typescript const response = await agent.listSessions({ cwd: '/home/user/project' }); response.sessions.forEach(session => { console.log(`${session.sessionId}: ${session.title} (${session.updatedAt})`); }); ``` ### Response #### Success Response (200) Promise array of session summaries #### Response Example ```json { "sessions": [ { "sessionId": "session-1", "title": "Session 1", "updatedAt": "2023-01-01T10:00:00Z" } ] } ``` ``` -------------------------------- ### Instantiate ClaudeAcpAgent Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Create a new instance of ClaudeAcpAgent. Requires an AgentSideConnection and optionally accepts a custom logger. ```typescript import { createAgentSideConnection, ndJsonStream } from '@agentclientprotocol/sdk'; import { ClaudeAcpAgent } from '@agentclientprotocol/claude-agent-acp'; const connection = await createAgentSideConnection({ stdio: { input: nodeToWebReadable(process.stdin), output: nodeToWebWritable(process.stdout), } }); const agent = new ClaudeAcpAgent(connection); ``` -------------------------------- ### Write Text File using Claude ACP Agent Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Delegate file write requests to the client. Use this method to write content to a specified file path on the client side. ```typescript async writeTextFile(params: WriteTextFileRequest): Promise ``` ```typescript await agent.writeTextFile({ path: '/home/user/output.txt', contents: 'New content' }); ``` -------------------------------- ### Bump Version in package.json Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/docs/RELEASES.md Execute this npm command to update the version number in your package.json file. Ensure X.X.X matches your release version. ```sh npm version vX.X.X ``` -------------------------------- ### Agent Capabilities Advertisement Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/README.md The capabilities advertised by the agent to clients, including prompt processing, messaging protocol capabilities, and session management features. ```typescript { promptCapabilities: { image: true, embeddedContext: true }, mcpCapabilities: { http: true, sse: true }, sessionCapabilities: { additionalDirectories: {}, close: {}, delete: {}, fork: {}, list: {}, resume: {} }, _meta: { claudeCode: { promptQueueing: true } } } ``` -------------------------------- ### Environment Variables for Claude Agent ACP Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/README.md Key environment variables used to configure the Claude Agent ACP. These control the executable location, token limits, default model, and model-specific configurations. ```bash CLAUDE_CODE_EXECUTABLE=/path/to/claude # Claude Code binary location MAX_THINKING_TOKENS=10000 # Extended thinking limit ANTHROPIC_MODEL=claude-opus-4-6 # Default model CLAUDE_MODEL_CONFIG='...' # Model overrides (JSON) ``` -------------------------------- ### setCwd Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/SettingsManager.md Updates the working directory and reloads project-specific settings. This method disposes of existing watchers and reinitializes the manager with the new directory. It is an asynchronous operation. ```APIDOC ## setCwd ### Description Updates the working directory and reloads project-specific settings. This method disposes of existing watchers and reinitializes the manager with the new directory. It is an asynchronous operation. ### Signature ```typescript async setCwd(cwd: string): Promise ``` ### Parameters #### Path Parameters - **cwd** (string) - Required - New working directory ### Returns - **Promise** - A promise that resolves when the working directory has been updated and settings reloaded. ### Example ```typescript // Switch to a different project await manager.setCwd('/home/user/other-project'); // Settings now reflect that project's .claude/settings.json ``` ``` -------------------------------- ### ClaudePlanEntry Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md A single entry in a plan/todo list with content, status, and active form display. ```APIDOC ## ClaudePlanEntry ### Description A single entry in a plan/todo list with content, status, and active form display. ### Fields - **content** (string) - **status** ('pending' | 'in_progress' | 'completed') - **activeForm** (string) ``` -------------------------------- ### Pushable Async Iterable Class Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/types.md An async iterable class that allows pushing items and consuming them using for-await loops. Use `end()` to signal completion. ```typescript export class Pushable implements AsyncIterable { push(item: T): void; end(): void; [Symbol.asyncIterator](): AsyncIterator; } ``` -------------------------------- ### Read text file content Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/ClaudeAcpAgent.md Delegate file read requests to the client, enabling access to files in restricted environments. Provide the file path to retrieve its contents. Optional line ranges can be specified. ```typescript const response = await agent.readTextFile({ path: '/home/user/document.txt' }); console.log(response.contents); ``` -------------------------------- ### Check if Content is Local Command Metadata Source: https://github.com/agentclientprotocol/claude-agent-acp/blob/main/_autodocs/api-reference/runAcp.md Determines if user message content consists entirely of local command markers. Returns true if so, false otherwise. ```typescript import { isLocalCommandMetadata } from '@agentclientprotocol/claude-agent-acp'; isLocalCommandMetadata('/compact'); // true ``` ```typescript import { isLocalCommandMetadata } from '@agentclientprotocol/claude-agent-acp'; isLocalCommandMetadata('Some text and /model'); // false ``` ```typescript import { isLocalCommandMetadata } from '@agentclientprotocol/claude-agent-acp'; isLocalCommandMetadata('Normal message'); // false ```