import { Agent, AgentSideConnection, AuthenticateRequest, CancelNotification, ClientCapabilities, ForkSessionRequest, ForkSessionResponse, InitializeRequest, InitializeResponse, LoadSessionRequest, LoadSessionResponse, NewSessionRequest, NewSessionResponse, PromptRequest, PromptResponse, ReadTextFileRequest, ReadTextFileResponse, ResumeSessionRequest, ResumeSessionResponse, SessionModelState, SessionNotification, SetSessionModelRequest, SetSessionModelResponse, SetSessionModeRequest, SetSessionModeResponse, TerminalHandle, TerminalOutputResponse, WriteTextFileRequest, WriteTextFileResponse } from "@agentclientprotocol/sdk"; import { SettingsManager } from "./settings.js"; import { CanUseTool, Options, PermissionMode, Query, SDKPartialAssistantMessage, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk"; import { Pushable } from "./utils.js"; import { ContentBlockParam } from "@anthropic-ai/sdk/resources"; import { BetaContentBlock, BetaRawContentBlockDelta } from "@anthropic-ai/sdk/resources/beta.mjs"; export declare const CLAUDE_CONFIG_DIR: string; /** * Logger interface for customizing logging output */ export interface Logger { log: (...args: any[]) => void; error: (...args: any[]) => void; } /** * Internal state for tracking compaction. */ type CompactionState = { /** Whether auto-compaction is enabled for this session */ enabled: boolean; /** Token threshold that triggers compaction */ threshold: number; /** Custom instructions for compaction summary */ customInstructions?: string; /** Current total token count for this session */ currentTokens: number; /** Whether a compaction is currently in progress */ isCompacting: boolean; }; /** * Information about a skill available in the session. */ export type SkillInfo = { /** Skill name */ name: string; /** Skill description */ description?: string; /** Source of the skill */ source?: "user" | "project" | "plugin"; }; type Session = { query: Query; input: Pushable; cancelled: boolean; permissionMode: PermissionMode; settingsManager: SettingsManager; abortController: AbortController; cwd: string; /** Optional: the actual session file path (for forked sessions where filename differs from sessionId) */ sessionFilePath?: string; /** Auto-compaction state tracking */ compaction: CompactionState; /** Skills loaded for this session (populated from SDK init message) */ skills?: SkillInfo[]; }; type BackgroundTerminal = { handle: TerminalHandle; status: "started"; lastOutput: TerminalOutputResponse | null; } | { status: "aborted" | "exited" | "killed" | "timedOut"; pendingOutput: TerminalOutputResponse; }; /** * Configuration for automatic context compaction. * When enabled, the session will automatically trigger compaction when token usage exceeds the threshold. */ export type CompactionConfig = { /** * Whether automatic compaction is enabled. * @default false */ enabled: boolean; /** * Token threshold that triggers automatic compaction. * When the total token count exceeds this value, a /compact command is automatically sent. * @default 100000 */ contextTokenThreshold?: number; /** * Optional custom instructions for the compaction summary. * These instructions guide how Claude summarizes the conversation. */ customInstructions?: string; }; /** * Extra metadata that can be given to Claude Code when creating a new session. */ export type NewSessionMeta = { claudeCode?: { /** * Options forwarded to Claude Code when starting a new session. * Those parameters will be ignored and managed by ACP: * - cwd * - includePartialMessages * - allowDangerouslySkipPermissions * - permissionMode * - canUseTool * - executable * Those parameters will be used and updated to work with ACP: * - hooks (merged with ACP's hooks) * - mcpServers (merged with ACP's mcpServers) */ options?: Options; /** * Configuration for automatic context compaction. * When enabled, automatically triggers /compact when token usage exceeds the threshold. */ compaction?: CompactionConfig; }; }; /** * Extra metadata that the agent provides for each tool_call / tool_update update. */ export type ToolUpdateMeta = { claudeCode?: { toolName: string; toolResponse?: unknown; }; }; export type ToolUseCache = { [key: string]: { type: "tool_use" | "server_tool_use" | "mcp_tool_use"; id: string; name: string; input: unknown; }; }; export declare class ClaudeAcpAgent implements Agent { sessions: { [key: string]: Session; }; client: AgentSideConnection; toolUseCache: ToolUseCache; backgroundTerminals: { [key: string]: BackgroundTerminal; }; clientCapabilities?: ClientCapabilities; logger: Logger; constructor(client: AgentSideConnection, logger?: Logger); initialize(request: InitializeRequest): Promise; newSession(params: NewSessionRequest): Promise; /** * Fork an existing session to create a new independent session. * This is the ACP protocol method handler for session/fork. * Named unstable_forkSession to match SDK expectations (session/fork routes to this method). */ unstable_forkSession(params: ForkSessionRequest): Promise; /** * Get the directory where session files are stored for a given cwd. */ private getSessionDirPath; /** * Extract the internal sessionId from a session JSONL file. * The CLI stores the actual session ID inside the file, which may differ from the filename. * For forked sessions, the filename is "agent-xxx" but the internal sessionId is a UUID. */ private extractInternalSessionId; /** * Promote a sidechain session to a regular session by modifying the session file. * Forked sessions have "isSidechain": true which prevents them from being resumed. * This method changes it to false so the session can be resumed/forked again. */ private promoteToFullSession; /** * Update the sessionId in all lines of a session JSONL file. * This is used when we need to assign a new unique session ID to avoid collisions. */ private updateSessionIdInFile; /** * Discover the CLI-assigned session ID by looking for new session files. * Returns the CLI's session ID if found, or the original sessionId if not. */ private discoverCliSessionId; /** * Alias for unstable_forkSession for convenience. */ forkSession(params: ForkSessionRequest): Promise; /** * Load an existing session to resume a previous conversation. * This is the ACP protocol method handler for session/load. */ loadSession(params: LoadSessionRequest): Promise; /** * Resume an existing session. This delegates to loadSession for enhanced functionality. */ unstable_resumeSession(params: ResumeSessionRequest): Promise; authenticate(_params: AuthenticateRequest): Promise; prompt(params: PromptRequest): Promise; cancel(params: CancelNotification): Promise; /** * Handle extension methods from the client. * * Currently supports: * - `_session/inject`: Inject a message into an active session mid-execution * - `_session/flush`: Flush a session to disk for fork-with-flush support * - `_session/setCompaction`: Configure automatic context compaction for a session * - `_session/listSkills`: List available skills for a session */ extMethod(method: string, params: Record): Promise>; /** * Inject a message into an active session. * * This allows sending additional user input while a prompt() call is actively * processing. The injected message will be queued and processed by the agent * as part of the current conversation turn. * * Use cases: * - Providing clarification while the agent is working * - Adding context mid-execution * - Sending corrections before a tool completes * * @param params.sessionId - The session to inject the message into * @param params.message - Either a string or an array of ContentBlocks (same format as prompt) * @returns Success status and any error message */ private handleSessionInject; /** * Configure automatic context compaction for a session. * * When enabled, the session will automatically trigger compaction when token usage * exceeds the configured threshold. This helps manage context window limits during * long-running conversations. * * @param params.sessionId - The session to configure * @param params.enabled - Whether automatic compaction is enabled * @param params.contextTokenThreshold - Token count that triggers compaction (default: 100000) * @param params.customInstructions - Optional instructions for the compaction summary * @returns Success status and any error message */ private handleSessionSetCompaction; /** * List available skills for a session. * * Skills are loaded based on the session's settingSources and plugins configuration. * This method returns the skills that were discovered during session initialization. * * @param params.sessionId - The session to query skills for * @returns Success status, skills array, and any error message */ private handleSessionListSkills; /** * Flush a session to disk by aborting its query subprocess. * * This is used by the fork-with-flush mechanism to ensure session data * is persisted to disk before forking. When the Claude SDK subprocess * exits (via abort), it writes the session data to: * ~/.claude/projects//.jsonl * * After this method completes, the session is removed from memory and * must be reloaded via loadSession() to continue using it. */ private handleSessionFlush; /** * Get the file path where Claude Code stores session data. * * Claude Code stores sessions at: * ~/.claude/projects//.jsonl * * Where is the cwd with `/` replaced by `-` * Note: We resolve the real path to handle macOS symlinks like /var -> /private/var */ private getSessionFilePath; /** * Wait for a session file to appear on disk. * * @param filePath - Path to the session file * @param timeout - Maximum time to wait in milliseconds * @returns true if file appears, false if timeout */ private waitForSessionFile; unstable_setSessionModel(params: SetSessionModelRequest): Promise; setSessionMode(params: SetSessionModeRequest): Promise; readTextFile(params: ReadTextFileRequest): Promise; writeTextFile(params: WriteTextFileRequest): Promise; canUseTool(sessionId: string): CanUseTool; /** * Check if auto-compaction should be triggered based on current token usage. */ private shouldTriggerCompaction; /** * Trigger automatic compaction by sending a /compact command. */ private triggerAutoCompaction; private createSession; } export declare function getAvailableModels(query: Query): Promise; export declare function promptToClaude(prompt: PromptRequest): SDKUserMessage; /** * Convert an SDKAssistantMessage (Claude) to a SessionNotification (ACP). * Only handles text, image, and thinking chunks for now. */ export declare function toAcpNotifications(content: string | ContentBlockParam[] | BetaContentBlock[] | BetaRawContentBlockDelta[], role: "assistant" | "user", sessionId: string, toolUseCache: ToolUseCache, client: AgentSideConnection, logger: Logger): SessionNotification[]; export declare function streamEventToAcpNotifications(message: SDKPartialAssistantMessage, sessionId: string, toolUseCache: ToolUseCache, client: AgentSideConnection, logger: Logger): SessionNotification[]; export declare function runAcp(): void; export {}; //# sourceMappingURL=acp-agent.d.ts.map