### Initialize and Start CursorAgentAdapter with Stdio Transport Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Demonstrates how to initialize and start the CursorAgentAdapter using default configuration and stdio transport for JSON-RPC communication. It shows how to set up logging, session directories, tool enablement, and Cursor CLI timeouts. The example also includes retrieving adapter status and metrics, and performing a graceful shutdown. ```typescript import { CursorAgentAdapter, DEFAULT_CONFIG, createLogger, } from '@blowmage/cursor-agent-acp'; // Create adapter with configuration const config = { ...DEFAULT_CONFIG, logLevel: 'info', sessionDir: '~/.cursor-sessions', maxSessions: 100, sessionTimeout: 3600000, // 1 hour tools: { filesystem: { enabled: true }, terminal: { enabled: true, maxProcesses: 5 }, }, cursor: { timeout: 30000, retries: 3, }, }; const adapter = new CursorAgentAdapter(config); // Initialize and start with stdio transport await adapter.initialize(); await adapter.startStdio(); // Blocks until connection closes // Get adapter status and metrics const status = adapter.getStatus(); console.log('Running:', status.running); console.log('Sessions:', status.metrics.sessions); console.log('Tools:', status.metrics.tools); // Graceful shutdown await adapter.shutdown(); ``` -------------------------------- ### Run Cursor Agent ACP from CLI Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Provides examples of how to run the Cursor Agent ACP adapter directly from the command line. It covers starting with default settings, using `npx`, specifying a custom configuration file, setting the log level, and defining a session storage directory. ```bash # Start with default settings (stdio transport) cursor-agent-acp # Run with npx npx @blowmage/cursor-agent-acp # Custom configuration file cursor-agent-acp --config /path/to/config.json # Set log level for debugging cursor-agent-acp --log-level debug # Specify session storage directory cursor-agent-acp --session-dir ~/.cursor-sessions ``` -------------------------------- ### Cursor Agent ACP Development Setup with NPM Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Instructions for setting up the development environment for the cursor-agent-acp project using npm. This includes cloning the repository, installing dependencies, and building the project. ```bash # Clone the repository git clone https://github.com/blowmage/cursor-agent-acp.git cd cursor-agent-acp # Install dependencies npm install # Build the project npm run build ``` -------------------------------- ### Install Cursor CLI Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Installs the Cursor CLI using a curl command. This is a prerequisite for using the Cursor Agent ACP Adapter. ```bash # Install Cursor CLI curl https://cursor.com/install -fsSL | bash # Authenticate with your Cursor account cursor-agent login ``` -------------------------------- ### Cursor Agent ACP Configuration File Example Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md An example JSON configuration file for the Cursor Agent ACP. It outlines settings for logging, session management, and enables/configures various tools like filesystem access, terminal commands, and Cursor-specific features. ```json { "logLevel": "info", "sessionDir": "~/.cursor-sessions", "maxSessions": 100, "sessionTimeout": 3600000, "tools": { "filesystem": { "enabled": true, "allowedPaths": ["./"], "maxFileSize": 10485760, "allowedExtensions": [".ts", ".js", ".json", ".md"] }, "terminal": { "enabled": true, "maxProcesses": 5, "defaultOutputByteLimit": 10485760, "maxOutputByteLimit": 52428800, "forbiddenCommands": ["rm", "sudo", "su"], "allowedCommands": [], "defaultCwd": "./" }, "cursor": { "enabled": true, "enableCodeModification": true, "enableTestExecution": true, "maxSearchResults": 50 } }, "cursor": { "timeout": 30000, "retries": 3 } } ``` -------------------------------- ### Install and Verify Cursor CLI Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Installs the Cursor CLI using a curl command and verifies the installation by checking the agent version. This is a common first step for troubleshooting 'cursor-agent not found' errors. ```bash # Install Cursor CLI curl https://cursor.com/install -fsSL | bash # Verify installation cursor-agent --version ``` -------------------------------- ### Install Cursor Agent ACP Adapter (npm) Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Installs the Cursor Agent ACP Adapter globally or locally using npm. Requires Node.js 18+. ```bash # Install globally npm install -g @blowmage/cursor-agent-acp # Or install locally in your project npm install @blowmage/cursor-agent-acp ``` -------------------------------- ### Start Cursor Agent ACP Adapter Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Starts the ACP adapter using stdio transport. It reads JSON-RPC messages from stdin and writes responses to stdout. ```bash # Start the ACP adapter with stdio transport cursor-agent-acp # Or run directly with npx npx cursor-agent-acp ``` -------------------------------- ### File System Tools Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Tools for interacting with the file system, including reading, writing, listing, creating, deleting, and getting file information. ```APIDOC ## File System Tools ### Description Tools for interacting with the file system, including reading, writing, listing, creating, deleting, and getting file information. ### Method POST ### Endpoint `/acp` (Assumed, as specific endpoints are not provided in the source text) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (string) - Required - The tool to call (e.g., `read_file`, `write_file`). - **params** (object) - Required - Parameters specific to the tool. - **path** (string) - Required - The file or directory path. - **content** (string) - Optional (for `write_file`) - The content to write. - **recursive** (boolean) - Optional (for `list_directory`) - Whether to list recursively. ### Request Example ```json { "method": "read_file", "params": { "path": "/path/to/your/file.txt" } } ``` ### Response #### Success Response (200) - **result** (any) - The result of the tool call (e.g., file content, directory listing, file info). #### Response Example ```json { "result": "This is the content of the file." } ``` ``` -------------------------------- ### ExtensionRegistry API Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Manages extension methods and notifications for ACP extensibility. Extension names must start with underscore (_). ```APIDOC ## ExtensionRegistry ### Description Manages extension methods and notifications for ACP extensibility. Extension names must start with underscore (_). ### Method N/A (Class methods) ### Endpoint N/A (Class methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { ExtensionRegistry, ExtensionMethodHandler, ExtensionNotificationHandler, } from '@blowmage/cursor-agent-acp'; const extensions = new ExtensionRegistry(logger); // Register an extension method (for JSON-RPC requests) // Names MUST start with underscore and SHOULD use namespaces const customMethodHandler: ExtensionMethodHandler = async (params) => { const input = params.input as string; return { success: true, result: `Processed: ${input}`, timestamp: new Date().toISOString() }; }; extensions.registerMethod('_myapp/custom_action', customMethodHandler); // Register an extension notification (one-way, no response) const statusHandler: ExtensionNotificationHandler = async (params) => { console.log('Status update received:', params.status); }; extensions.registerNotification('_myapp/status_update', statusHandler); // Check if method/notification exists const hasMethod = extensions.hasMethod('_myapp/custom_action'); const hasNotification = extensions.hasNotification('_myapp/status_update'); // Call an extension method const result = await extensions.callMethod('_myapp/custom_action', { input: 'test' }); // Output: { success: true, result: 'Processed: test', timestamp: '...' } // Send an extension notification (ignores unrecognized notifications per ACP spec) await extensions.sendNotification('_myapp/status_update', { status: 'running' }); // Get registered methods/notifications for advertising capabilities const methods = extensions.getRegisteredMethods(); // Output: ['_myapp/custom_action'] const notifications = extensions.getRegisteredNotifications(); // Output: ['_myapp/status_update'] // Unregister handlers extensions.unregisterMethod('_myapp/custom_action'); extensions.unregisterNotification('_myapp/status_update'); // Clear all extensions.clear(); ``` ### Response #### Success Response (200) N/A (Class methods) #### Response Example N/A (Class methods) ``` -------------------------------- ### Configure Zed Editor with npx for Cursor Agent ACP Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Alternative configuration for Zed editor using `npx` to run the Cursor Agent ACP adapter. This is useful for executing the package without a global installation, specified in `~/.config/zed/settings.json`. ```json { "agent_servers": { "cursor-agent": { "command": "npx", "args": ["@blowmage/cursor-agent-acp"], "env": {} } } } ``` -------------------------------- ### Register and Manage Extensions with TypeScript Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Manages extension methods and notifications for ACP extensibility. Extension names must start with an underscore. It allows registering, calling, sending, checking, and unregistering methods and notifications. Dependencies include a logger. ```typescript import { ExtensionRegistry, ExtensionMethodHandler, ExtensionNotificationHandler, } from '@blowmage/cursor-agent-acp'; const extensions = new ExtensionRegistry(logger); // Register an extension method (for JSON-RPC requests) // Names MUST start with underscore and SHOULD use namespaces const customMethodHandler: ExtensionMethodHandler = async (params) => { const input = params.input as string; return { success: true, result: `Processed: ${input}`, timestamp: new Date().toISOString() }; }; extensions.registerMethod('_myapp/custom_action', customMethodHandler); // Register an extension notification (one-way, no response) const statusHandler: ExtensionNotificationHandler = async (params) => { console.log('Status update received:', params.status); }; extensions.registerNotification('_myapp/status_update', statusHandler); // Check if method/notification exists const hasMethod = extensions.hasMethod('_myapp/custom_action'); const hasNotification = extensions.hasNotification('_myapp/status_update'); // Call an extension method const result = await extensions.callMethod('_myapp/custom_action', { input: 'test' }); // Output: { success: true, result: 'Processed: test', timestamp: '...' } // Send an extension notification (ignores unrecognized notifications per ACP spec) await extensions.sendNotification('_myapp/status_update', { status: 'running' }); // Get registered methods/notifications for advertising capabilities const methods = extensions.getRegisteredMethods(); // Output: ['_myapp/custom_action'] const notifications = extensions.getRegisteredNotifications(); // Output: ['_myapp/status_update'] // Unregister handlers extensions.unregisterMethod('_myapp/custom_action'); extensions.unregisterNotification('_myapp/status_update'); // Clear all extensions.clear(); ``` -------------------------------- ### Handle Cursor Agent ACP Errors in TypeScript Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Demonstrates how to implement robust error handling for the Cursor Agent ACP adapter using specific error classes like `AdapterError`, `ProtocolError`, `CursorError`, `SessionError`, and `ToolError`. The example shows a try-catch block that checks the type of error caught and logs relevant information. ```typescript import { AdapterError, ProtocolError, CursorError, SessionError, ToolError, } from '@blowmage/cursor-agent-acp'; try { await adapter.initialize(); } catch (error) { if (error instanceof SessionError) { console.error(`Session error for ${error.sessionId}:`, error.message); } else if (error instanceof CursorError) { console.error('Cursor CLI error:', error.message); // User may need to run: cursor-agent login } else if (error instanceof ProtocolError) { console.error('ACP protocol error:', error.message); } else if (error instanceof ToolError) { console.error(`Tool ${error.toolName} failed:`, error.message); } else if (error instanceof AdapterError) { console.error(`Adapter error (${error.code}):`, error.message); } } ``` -------------------------------- ### Initialize and Use PromptHandler in TypeScript Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Demonstrates how to initialize the PromptHandler with necessary dependencies and use its methods to process prompts, send and update plan notifications, cancel sessions, collect metrics, and clean up resources. It requires sessionManager, cursorBridge, config, logger, and a sendNotification function. ```typescript import { PromptHandler, PlanEntry } from '@blowmage/cursor-agent-acp'; const promptHandler = new PromptHandler({ sessionManager, cursorBridge, config, logger, sendNotification: (notification) => { // Send JSON-RPC notification to client via stdout process.stdout.write(JSON.stringify(notification) + '\n'); }, slashCommandsRegistry: commands, }); // Process a prompt request (typically called by adapter) const response = await promptHandler.processPrompt({ jsonrpc: '2.0', id: 1, method: 'session/prompt', params: { sessionId: 'session-123', prompt: [{ type: 'text', text: 'Explain this function' }], stream: true, }, }); // Output: { jsonrpc: '2.0', id: 1, result: { stopReason: 'end_turn', _meta: {...} } } // Send a plan notification (for multi-step operations) const planEntries: PlanEntry[] = [ { content: [{ type: 'text', text: 'Analyze codebase' }], status: 'completed', priority: 1 }, { content: [{ type: 'text', text: 'Refactor functions' }], status: 'in_progress', priority: 2 }, { content: [{ type: 'text', text: 'Run tests' }], status: 'pending', priority: 3 }, ]; promptHandler.sendPlan('session-123', planEntries); // Update plan with new status (must send complete plan each time per ACP spec) planEntries[1].status = 'completed'; planEntries[2].status = 'in_progress'; promptHandler.updatePlan('session-123', planEntries); // Cancel an active session await promptHandler.cancelSession('session-123'); // Get active stream count const activeStreams = promptHandler.getActiveStreamCount(); // Collect metrics for prompt processing const metrics = promptHandler.collectMetrics( startTime, endTime, inputContent, outputContent, heartbeatCount, toolCalls, ); // Output: { totalDurationMs: 1234, inputBlocks: 1, outputBlocks: 5, ... } // Cleanup await promptHandler.cleanup(); ``` -------------------------------- ### Cursor Agent ACP Command Line Configuration Options Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Demonstrates various command-line arguments for configuring the `cursor-agent-acp` executable. This includes specifying a custom configuration file, setting the log level for debugging, and defining a directory for session storage. ```bash # Custom configuration file cursor-agent-acp --config /path/to/config.json # Set log level cursor-agent-acp --log-level debug # Specify session storage directory cursor-agent-acp --session-dir ~/.cursor-sessions ``` -------------------------------- ### Make Cursor Agent Binary Executable Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Sets the execute permission for the cursor-agent-acp binary located in the node_modules directory. This command is used to resolve 'Permission denied' errors. ```bash chmod +x ./node_modules/.bin/cursor-agent-acp ``` -------------------------------- ### Zed Editor Integration Configuration Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Configuration for integrating the Cursor Agent ACP Adapter with the Zed editor. Shows how to specify the command and arguments for the agent server. ```json { "agent_servers": { "cursor-agent": { "command": "cursor-agent-acp", "args": [], "env": {} } } } # If installed locally: { "agent_servers": { "cursor-agent": { "command": "npx", "args": ["@blowmage/cursor-agent-acp"], "env": {} } } } ``` -------------------------------- ### ACP Methods Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Core methods for interacting with the Cursor Agent ACP, including session management and prompt handling. ```APIDOC ## ACP Methods ### Description Core methods for interacting with the Cursor Agent ACP, including session management and prompt handling. ### Method POST ### Endpoint `/acp` (Assumed, as specific endpoints are not provided in the source text) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (string) - Required - The ACP method to call (e.g., `initialize`, `session/new`, `session/prompt`). - **params** (object) - Optional - Parameters specific to the called method. ### Request Example ```json { "method": "session/prompt", "params": { "sessionId": "some-session-id", "prompt": "What is the meaning of life?" } } ``` ### Response #### Success Response (200) - **result** (any) - The result of the ACP method call. #### Response Example ```json { "result": "The meaning of life is 42." } ``` ``` -------------------------------- ### Cursor Agent ACP Development Server with NPM Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Commands to run the development server for the cursor-agent-acp project using npm. This includes running in development mode with hot reloading and building the project while watching for file changes. ```bash # Run in development mode with hot reload npm run dev # Build and watch for changes npm run build:watch ``` -------------------------------- ### Cursor Agent ACP Testing Procedures with NPM Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Commands for running various tests within the cursor-agent-acp project using npm. This covers unit tests, integration tests, tests with code coverage, and running tests in watch mode for continuous development. ```bash # Run unit tests npm test # Run integration tests npm run test:integration # Run all tests with coverage npm run test:coverage # Watch mode for development npm run test:watch ``` -------------------------------- ### ToolRegistry API Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Manages available tools and their execution, including filesystem, terminal, and Cursor-specific tools. ```APIDOC ## ToolRegistry Manages available tools and their execution, including filesystem, terminal, and Cursor-specific tools. ### Methods - **registerProvider(provider: ToolProvider)**: Registers a custom tool provider. - **Parameters**: - `provider` (ToolProvider) - An object defining the tool provider. - `name` (string) - The name of the provider. - `description` (string) - A description of the provider. - `getTools()` (function) - A function that returns an array of `Tool` objects. - **getTools()**: Retrieves all available tools from registered providers. - **Returns**: `Promise`. Example: `[{ name: 'my_custom_tool', description: '...', parameters: {...} }, ...]` - **hasTool(toolName: string)**: Checks if a tool with the given name exists. - **Parameters**: - `toolName` (string) - The name of the tool to check. - **Returns**: `boolean` - **executeToolWithSession(call: ToolCall, sessionId: string)**: Executes a tool call within a specific session context. - **Parameters**: - `call` (ToolCall) - The tool call object. - `id` (string) - Unique identifier for the call. - `name` (string) - The name of the tool to execute. - `parameters` (object) - The parameters for the tool. - `sessionId` (string) - The ID of the session to execute the tool in. - **Returns**: `Promise`. Example: `{ success: true, result: 'Processed: test data', metadata: { toolName: '...', duration: 10 } }` - **getCapabilities()**: Retrieves the capabilities of the tool registry, including available tools, providers, and feature flags. - **Returns**: `object`. Example: `{ tools: [...], providers: [...], filesystem: true, cursor: true }` - **validateConfiguration()**: Validates the current tool registry configuration. - **Returns**: `string[]` - An array of error messages if validation fails, empty if successful. - **unregisterProvider(providerName: string)**: Unregisters a tool provider by its name. - **Parameters**: - `providerName` (string) - The name of the provider to unregister. - **cleanup()**: Cleans up resources used by the tool registry. - **Returns**: `Promise` ``` -------------------------------- ### Configure JetBrains IDE for Cursor Agent ACP Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Instructions for configuring JetBrains IDEs (version 25.3+) to use the Cursor Agent ACP adapter. This involves creating a `~/.jetbrains/acp.json` file to specify the agent's command and arguments. ```json { "agent_servers": { "Cursor Agent": { "command": "cursor-agent-acp", "args": [], "env": {} } } } ``` -------------------------------- ### Terminal Tools Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Tools for interacting with the terminal, including executing commands, managing shell sessions, and listing processes. ```APIDOC ## Terminal Tools ### Description Tools for interacting with the terminal, including executing commands, managing shell sessions, and listing processes. ### Method POST ### Endpoint `/acp` (Assumed, as specific endpoints are not provided in the source text) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (string) - Required - The tool to call (e.g., `execute_command`, `start_shell_session`). - **params** (object) - Required - Parameters specific to the tool. - **command** (string) - Optional (for `execute_command`) - The command to execute. - **sessionId** (string) - Optional (for shell session tools) - The ID of the shell session. - **input** (string) - Optional (for `send_to_shell`) - Input to send to the shell. ### Request Example ```json { "method": "execute_command", "params": { "command": "ls -l" } } ``` ### Response #### Success Response (200) - **result** (any) - The result of the tool call (e.g., command output, shell session ID). #### Response Example ```json { "result": { "stdout": "total 4\n-rw-r--r-- 1 user group 1024 Jan 1 10:00 file.txt\n", "stderr": "", "exitCode": 0 } } ``` ``` -------------------------------- ### Cursor-Specific Tools Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Tools tailored for Cursor, including code search, analysis, modification, testing, and project information retrieval. ```APIDOC ## Cursor-Specific Tools ### Description Tools tailored for Cursor, including code search, analysis, modification, testing, and project information retrieval. ### Method POST ### Endpoint `/acp` (Assumed, as specific endpoints are not provided in the source text) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (string) - Required - The tool to call (e.g., `search_codebase`, `analyze_code`). - **params** (object) - Required - Parameters specific to the tool. - **query** (string) - Optional (for `search_codebase`) - The search query. - **filePath** (string) - Optional (for `analyze_code`) - The path to the code file. - **changes** (object) - Optional (for `apply_code_changes`) - The code modifications. ### Request Example ```json { "method": "search_codebase", "params": { "query": "function findUserById" } } ``` ### Response #### Success Response (200) - **result** (any) - The result of the tool call (e.g., search results, analysis report, test results). #### Response Example ```json { "result": [ { "filePath": "src/users.js", "lineNumber": 50, "match": "function findUserById(id) {" } ] } ``` ``` -------------------------------- ### ToolRegistry: Manage and Execute Tools Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt The ToolRegistry manages a collection of tools, including custom providers, filesystem, and terminal tools. It allows for registering, retrieving, checking existence, and executing tools with session context. It also provides capabilities for ACP initialization and configuration validation. ```typescript import { ToolRegistry, ToolProvider, Tool, ToolResult } from '@blowmage/cursor-agent-acp'; const registry = new ToolRegistry(config, logger); // Create a custom tool provider const customProvider: ToolProvider = { name: 'custom', description: 'Custom tools for my application', getTools(): Tool[] { return [{ name: 'my_custom_tool', description: 'Performs a custom action', parameters: { type: 'object', properties: { input: { type: 'string', description: 'Input data' }, }, required: ['input'], }, handler: async (params): Promise => { return { success: true, result: `Processed: ${params.input}` }; }, }]; }, }; // Register the provider registry.registerProvider(customProvider); // Get all available tools const tools = registry.getTools(); // Output: [{ name: 'my_custom_tool', description: '...', parameters: {...} }, ...] // Check if a tool exists const hasTool = registry.hasTool('read_file'); // Execute a tool call with session context const result = await registry.executeToolWithSession({ id: 'call-123', name: 'my_custom_tool', parameters: { input: 'test data' }, }, 'session-id'); // Output: { success: true, result: 'Processed: test data', metadata: { toolName: '...', duration: 10 } } // Get tool capabilities for ACP initialization const capabilities = registry.getCapabilities(); // Output: { tools: [...], providers: [...], filesystem: true, cursor: true } // Validate tool configuration const errors = registry.validateConfiguration(); if (errors.length > 0) console.error('Config errors:', errors); // Unregister a provider registry.unregisterProvider('custom'); // Cleanup await registry.cleanup(); ``` -------------------------------- ### JetBrains IDE Configuration for Cursor Agent ACP Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Configuration for JetBrains IDEs (WebStorm, IntelliJ IDEA, PyCharm) version 25.3 and later to integrate with the Cursor Agent ACP. This involves creating or editing the `~/.jetbrains/acp.json` file with agent server details. ```json { "agent_servers": { "Cursor Agent": { "command": "cursor-agent-acp", "args": [], "env": {} } } } ``` -------------------------------- ### SlashCommandsRegistry API Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Manages slash commands that can be advertised to ACP clients for quick access to agent capabilities. ```APIDOC ## SlashCommandsRegistry ### Description Manages slash commands that can be advertised to ACP clients for quick access to agent capabilities. ### Method N/A (Class methods) ### Endpoint N/A (Class methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { SlashCommandsRegistry } from '@blowmage/cursor-agent-acp'; const commands = new SlashCommandsRegistry(logger); // Register commands with optional input hints commands.registerCommand('test', 'Run tests for the current project'); commands.registerCommand('plan', 'Create a detailed implementation plan', 'description of what to plan'); commands.registerCommand('web', 'Search the web for information', 'query to search for'); // Set up change notifications for available_commands_update commands.onChange((commandList) => { // Send notification to client when commands change sendNotification({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: currentSessionId, update: { sessionUpdate: 'available_commands_update', availableCommands: commandList, }, }, }); }); // Get all registered commands (for available_commands_update) const allCommands = commands.getCommands(); // Output: [{ name: 'test', description: '...' }, { name: 'plan', description: '...', input: { hint: '...' } }] // Check if command exists if (commands.hasCommand('test')) { const testCommand = commands.getCommand('test'); console.log(testCommand?.description); } // Update commands dynamically based on context commands.updateCommands([ { name: 'deploy', description: 'Deploy the application' }, { name: 'rollback', description: 'Rollback to previous version' }, ]); // Remove a command commands.removeCommand('test'); // Manually trigger update notification commands.triggerUpdate(); // Clear all commands commands.clear(); ``` ### Response #### Success Response (200) N/A (Class methods) #### Response Example N/A (Class methods) ``` -------------------------------- ### Manage ACP Session Lifecycle with SessionManager Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Illustrates the usage of the SessionManager class for handling ACP session lifecycles. This includes creating new sessions with metadata, loading existing sessions, listing sessions with pagination and filtering, and managing session modes and models. It also covers adding messages to a conversation and cleaning up expired sessions. ```typescript import { SessionManager } from '@blowmage/cursor-agent-acp'; const sessionManager = new SessionManager(config, logger); // Create a new session with metadata const session = await sessionManager.createSession({ name: 'My Coding Session', cwd: '/path/to/project', mode: 'agent', // 'agent', 'plan', or 'ask' model: 'auto', tags: ['typescript', 'refactoring'], }); // Output: { id: 'uuid-v4-session-id', metadata: {...}, conversation: [], ... } // Load existing session const loadedSession = await sessionManager.loadSession(session.id); // List sessions with pagination and filtering const sessions = await sessionManager.listSessions(50, 0, { tags: ['typescript'] }); // Output: { items: [...], total: 10, hasMore: false } // Get and set session modes (agent, plan, ask) const modes = sessionManager.getAvailableModes(); // Output: [{ id: 'agent', name: 'Agent', description: '...' }, ...] const previousMode = await sessionManager.setSessionMode(session.id, 'plan'); // Get and set session models const models = sessionManager.getAvailableModels(); // Output: [{ id: 'auto', name: 'Auto', provider: 'cursor' }, ...] await sessionManager.setSessionModel(session.id, 'gpt-4'); // Add message to conversation await sessionManager.addMessage(session.id, { id: 'msg_123', role: 'user', content: [{ type: 'text', text: 'Hello!' }], timestamp: new Date(), }); // Cleanup expired sessions const cleaned = await sessionManager.cleanupExpiredSessions(); ``` -------------------------------- ### Register and Manage Slash Commands with TypeScript Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Manages slash commands that can be advertised to ACP clients. It allows registering, updating, checking, and removing commands, and notifies clients of changes. Dependencies include a logger and potentially session management for notifications. ```typescript import { SlashCommandsRegistry } from '@blowmage/cursor-agent-acp'; const commands = new SlashCommandsRegistry(logger); // Register commands with optional input hints commands.registerCommand('test', 'Run tests for the current project'); commands.registerCommand('plan', 'Create a detailed implementation plan', 'description of what to plan'); commands.registerCommand('web', 'Search the web for information', 'query to search for'); // Set up change notifications for available_commands_update commands.onChange((commandList) => { // Send notification to client when commands change sendNotification({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: currentSessionId, update: { sessionUpdate: 'available_commands_update', availableCommands: commandList, }, }, }); }); // Get all registered commands (for available_commands_update) const allCommands = commands.getCommands(); // Output: [{ name: 'test', description: '...' }, { name: 'plan', description: '...', input: { hint: '...' } }] // Check if command exists if (commands.hasCommand('test')) { const testCommand = commands.getCommand('test'); console.log(testCommand?.description); } // Update commands dynamically based on context commands.updateCommands([ { name: 'deploy', description: 'Deploy the application' }, { name: 'rollback', description: 'Rollback to previous version' }, ]); // Remove a command commands.removeCommand('test'); // Manually trigger update notification commands.triggerUpdate(); // Clear all commands commands.clear(); ``` -------------------------------- ### Enable Debug Logging for Cursor Agent ACP Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Enables debug logging for the cursor-agent-acp command-line tool. This is essential for detailed troubleshooting of issues by providing verbose output. ```bash cursor-agent-acp --log-level debug ``` -------------------------------- ### CursorCliBridge API Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt Interface for communicating with the cursor-agent CLI, handling authentication, command execution, and prompt processing. ```APIDOC ## CursorCliBridge Interface for communicating with the cursor-agent CLI, handling authentication, command execution, and prompt processing. ### Methods - **checkAuthentication()**: Checks the authentication status of the cursor-agent. - **Returns**: `Promise<{ authenticated: boolean, user?: string, email?: string }>`. Example: `{ authenticated: true, user: 'username', email: 'user@example.com' }` - **getVersion()**: Retrieves the version of the cursor-agent. - **Returns**: `Promise`. Example: `'1.2.3'` - **executeCommand(command: string[])**: Executes a cursor-agent command. - **Parameters**: - `command` (string[]) - The command and its arguments to execute. - **Returns**: `Promise<{ success: boolean, stdout: string, exitCode: number }>`. Example: `{ success: true, stdout: '...', exitCode: 0 }` - **createChat()**: Creates a new chat session for continuity. - **Returns**: `Promise`. Example: `'chat-uuid-123'` - **sendPrompt(options: SendPromptOptions)**: Sends a prompt to the cursor-agent (non-streaming). - **Parameters**: - `options` (object) - Configuration for sending the prompt. - `sessionId` (string) - The session ID. - `content` (object) - The prompt content. - `value` (string) - The prompt text. - `metadata` (object) - Metadata for the content. - `metadata` (object) - Metadata for the prompt. - `cwd` (string) - Current working directory. - `model` (string) - The model to use ('auto' or specific model name). - `cursorChatId` (string) - The ID of the chat session. - **Returns**: `Promise<{ success: boolean, stdout: string, metadata: object }>`. Example: `{ success: true, stdout: 'The code does...', metadata: {...} }` - **sendStreamingPrompt(options: SendStreamingPromptOptions)**: Sends a prompt to the cursor-agent with streaming updates. - **Parameters**: - `options` (object) - Configuration for sending the streaming prompt. - `sessionId` (string) - The session ID. - `content` (object) - The prompt content. - `value` (string) - The prompt text. - `metadata` (object) - Metadata for the content. - `metadata` (object) - Metadata for the prompt. - `cwd` (string) - Current working directory. - `abortSignal` (AbortSignal) - Signal to abort the streaming request. - `onChunk` (function) - Callback function for receiving chunks of data. - `onProgress` (function) - Callback function for receiving progress updates. - **Example Usage**: ```typescript const controller = new AbortController(); await bridge.sendStreamingPrompt({ sessionId: 'session-id', content: { value: 'Write a function to...', metadata: {} }, metadata: { cwd: '/project' }, abortSignal: controller.signal, onChunk: async (chunk) => { if (chunk.type === 'content') console.log('Received:', chunk.data); }, onProgress: (progress) => console.log('Progress:', progress.message), }); ``` - **close()**: Closes the connection to the cursor-agent CLI bridge. - **Returns**: `Promise` ``` -------------------------------- ### CursorCliBridge: Authenticate, Execute Commands, and Manage Chats Source: https://context7.com/blowmage/cursor-agent-acp-npm/llms.txt The CursorCliBridge facilitates communication with the cursor-agent CLI. It handles authentication checks, command execution, version retrieval, chat creation, and sending prompts (both standard and streaming). Dependencies include configuration and a logger. ```typescript import { CursorCliBridge } from '@blowmage/cursor-agent-acp'; const bridge = new CursorCliBridge(config, logger); // Check authentication status const authStatus = await bridge.checkAuthentication(); // Output: { authenticated: true, user: 'username', email: 'user@example.com' } // Get cursor-agent version const version = await bridge.getVersion(); // Output: '1.2.3' // Execute cursor-agent commands const response = await bridge.executeCommand(['status']); // Output: { success: true, stdout: '...', exitCode: 0 } // Create a cursor-agent chat for session continuity const chatId = await bridge.createChat(); // Output: 'chat-uuid-123' // Send a prompt (non-streaming) const result = await bridge.sendPrompt({ sessionId: 'session-id', content: { value: 'Explain this code', metadata: {} }, metadata: { cwd: '/project', model: 'auto', cursorChatId: chatId }, }); // Output: { success: true, stdout: 'The code does...', metadata: {...} } // Send streaming prompt with real-time updates const streamResult = await bridge.sendStreamingPrompt({ sessionId: 'session-id', content: { value: 'Write a function to...', metadata: {} }, metadata: { cwd: '/project' }, abortSignal: controller.signal, onChunk: async (chunk) => { if (chunk.type === 'content') console.log('Received:', chunk.data); }, onProgress: (progress) => console.log('Progress:', progress.message), }); // Close the bridge await bridge.close(); ``` -------------------------------- ### Login and Check Cursor Agent Authentication Status Source: https://github.com/blowmage/cursor-agent-acp-npm/blob/main/README.md Logs into the Cursor service and checks the current authentication status using the cursor-agent CLI. This is useful for resolving 'Authentication required' issues. ```bash # Login to Cursor cursor-agent login # Check authentication status cursor-agent status ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.