Cline SDK
The Cline SDK lets you embed Cline as a programmable coding agent in your Node.js applications. It exposes the same capabilities as the Cline CLI and VS Code extension — file editing, command execution, browser use, MCP servers — through a TypeScript API that conforms to the Agent Client Protocol (ACP).Installation
Quick Start
Core Concepts
Agent Lifecycle
The SDK follows the ACP lifecycle:| Step | Method | Purpose |
|---|---|---|
| Init | initialize() | Exchange protocol version and capabilities |
| Auth | authenticate() | OAuth flow for Cline or OpenAI Codex accounts. Optional step if cline config directory already has credentials |
| Session | newSession() | Create an isolated conversation context |
| Prompt | prompt() | Send user messages; blocks until the turn ends |
| Cancel | cancel() | Abort an in-progress prompt turn |
| Mode | setSessionMode() | Switch between "plan" and "act" modes |
| Model | unstable_setSessionModel() | Change the backing LLM (experimental) |
| Shutdown | shutdown() | Abort all tasks, flush state, release resources |
Sessions
A session is an independent conversation with its own task history and working directory. You can run multiple sessions concurrently.sessionId— use this in all subsequent callsmodes— available modes (plan,act) and the current modemodels— available models and the current model ID
sessions map:
Prompting
prompt() sends a user message and blocks until the agent finishes its turn. While the prompt is processing, the agent streams output via session events.
Content Block Types
| Type | Fields | Description |
|---|---|---|
TextContent | { type: "text", text: string } | Plain text message |
ImageContent | { type: "image", mimeType: string, data: string } | Base64-encoded image |
EmbeddedResource | { type: "resource", resource: { uri: string, mimeType?: string, text?: string, blob?: string } } | File or resource context |
Stop Reasons
prompt() resolves with a stopReason. The ACP StopReason type defines the full set of possible values:
| Value | Meaning |
|---|---|
"end_turn" | Agent finished normally (completed task or waiting for user input) |
"error" | An error occurred |
Note: Cline currently returns"end_turn"or"error". OtherStopReasonvalues like"max_tokens"or"cancelled"are part of the ACP type but may not be produced by the current implementation.
Streaming Events
Subscribe to real-time output viaClineSessionEmitter. Each session has its own emitter.
Event Types
All events correspond to ACPSessionUpdate types:
| Event | Payload | Description |
|---|---|---|
agent_message_chunk | { content: ContentBlock } | Streamed text from the agent |
agent_thought_chunk | { content: ContentBlock } | Internal reasoning / chain-of-thought |
tool_call | ToolCall | New tool invocation (file edit, command, etc.) |
tool_call_update | ToolCallUpdate | Progress/result update for an existing tool call |
plan | { entries: PlanEntry[] } | Agent’s execution plan |
available_commands_update | { availableCommands: AvailableCommand[] } | Slash commands the agent supports |
current_mode_update | { currentModeId: string } | Mode changed (plan/act) |
user_message_chunk | { content: ContentBlock } | User message chunks (for multi-turn) |
config_option_update | { configOptions: SessionConfigOption[] } | Configuration changed |
session_info_update | Session metadata | Session metadata changed |
error | Error | Session-level error (not an ACP update) |
on, once, off, and removeAllListeners.
Permission Handling
When the agent wants to execute a tool (edit a file, run a command, etc.), it requests permission. You must set a permission handler or all tool calls will be auto-rejected.Permission Options
Each permission request includes an array ofPermissionOption objects:
kind | Meaning |
|---|---|
allow_once | Approve this single operation |
allow_always | Approve and remember for future operations (sent for commands, tools, MCP servers) |
reject_once | Deny this single operation |
Modes
Cline supports two modes:plan— The agent gathers information and creates a plan without executing actionsact— The agent executes actions (file edits, commands, etc.)
newSession()
Model Selection
Change the backing model withunstable_setSessionModel(). The model ID format is "provider/modelId".
anthropic, openai-native, gemini, bedrock, deepseek, mistral, groq, xai, and others. Model Ids can be found in the NewSessionResponse object after calling agent.newSession(..)
Note: This API is experimental and may change.
Authentication
The SDK supports two OAuth flows:~/.cline/data/. Once configured, the SDK will use these credentials automatically — no authenticate() call needed.
Using a custom directory: If you specify a custom clineDir when creating ClineAgent, you must use the same path with --config when running cline auth:
Cancellation
Cancel an in-progress prompt turn:API Reference
Constructor
clineDir option lets you isolate configuration and task history per-application:
Methods
initialize(params): Promise<InitializeResponse>
Initialize the agent and negotiate protocol capabilities.
Client Capabilities
TheclientCapabilities object in initialize() declares what your environment supports. It is part of the ACP protocol handshake.
| Capability | Type | Description |
|---|---|---|
fs.readTextFile | boolean | Client supports file read requests |
fs.writeTextFile | boolean | Client supports file write requests |
terminal | boolean | Client supports terminal command execution |
ClineAgent directly (SDK use), the agent always uses standalone providers for file operations and terminal commands — it reads/writes files and runs shell commands on the local machine regardless of what you pass here. Simply pass {}:
ClineAgent is used through the AcpAgent stdio wrapper (e.g., IDE integrations), where an ACP connection delegates operations back to the client.
newSession(params): Promise<NewSessionResponse>
Create a new conversation session.
Note: newSession() may throw an auth-required error if credentials are not configured yet.
prompt(params): Promise<PromptResponse>
Send a user prompt to the agent. This is the main method for interacting with Cline. Blocks until the agent finishes its turn.
cancel(params): Promise<void>
Cancel an ongoing prompt operation.
setSessionMode(params): Promise<SetSessionModeResponse>
Switch between plan and act modes.
unstable_setSessionModel(params): Promise<SetSessionModelResponse>
Change the model for the session. Model ID format depends on the inference provider. See NewSessionResponse object to get modelIds.
authenticate(params): Promise<AuthenticateResponse>
Authenticate with a provider. Opens a browser window for OAuth flow.
| methodId | Description |
|---|---|
cline-oauth | use cline inference provider |
openai-codex-oauth | use your chatgpt subscription |
| more coming soon!… |
shutdown(): Promise<void>
Clean up all resources. Call this when done.
setPermissionHandler(handler)
Set a callback to handle tool permission requests. The handler receives a RequestPermissionRequest and must return a Promise<RequestPermissionResponse>.
emitterForSession(sessionId): ClineSessionEmitter
Get the typed event emitter for a session.
sessions (read-only Map)
Access active sessions:
Error Handling
SDK methods throw standard JavaScript errors. Key error scenarios:| Method | Error | Cause |
|---|---|---|
newSession() | RequestError (auth required) | No credentials configured — call authenticate() or pre-configure via CLI |
prompt() | Error("Session not found") | Invalid sessionId |
prompt() | Error("already processing") | Called prompt() while a previous prompt is still running on the same session |
unstable_setSessionModel() | Error("Invalid modelId format") | Model ID must be "provider/modelId" format (e.g., "anthropic/claude-sonnet-4-20250514") |
authenticate() | Error("Unknown authentication method") | Invalid methodId — use "cline-oauth" or "openai-codex-oauth" |
authenticate() | Error("Authentication timed out") | OAuth flow not completed within 5 minutes |
prompt() execution are emitted on the session emitter rather than thrown:
Full Example: Auto-Approve Agent
Full Example: Interactive Permission Flow
Exported Types
All types are re-exported from thecline package. Key types:
| Type | Description |
|---|---|
ClineAgent | Main agent class |
ClineSessionEmitter | Typed event emitter for session events |
ClineAgentOptions | Constructor options (debug, clineDir, hooksDir) |
ClineAcpSession | Session metadata (read-only) |
ClineSessionEvents | Event name → handler signature map |
AcpSessionStatus | Session lifecycle enum: Idle, Processing, Cancelled |
AcpSessionState | Session state tracking (status, pending tool calls) |
PermissionHandler | (request: RequestPermissionRequest) => Promise<RequestPermissionResponse> |
RequestPermissionRequest | Permission request details (sessionId, toolCall, options) |
RequestPermissionResponse | Permission response with outcome |
PermissionOption | Permission choice (kind, optionId, name) |
SessionUpdate | Union of all session update types |
SessionUpdateType | Discriminator values ("agent_message_chunk", "tool_call", etc.) |
SessionUpdatePayload | Typed payload for a given SessionUpdateType |
SessionModelState | Current model and available models |
ToolCall | Tool call details (id, title, kind, status, content) |
ToolCallUpdate | Partial update to an existing tool call |
ToolCallStatus | "pending" | "in_progress" | "completed" | "failed" |
ToolKind | "read" | "edit" | "delete" | "execute" | "search" | ... |
StopReason | "end_turn" | "cancelled" | "error" | "max_tokens" | ... |
ContentBlock | TextContent | ImageContent | AudioContent | ... |
TextContent / ImageContent / AudioContent | Individual content block types |
McpServer | MCP server configuration (stdio, http) |
ModelInfo | Model metadata (modelId, name) |
PromptRequest / PromptResponse | Prompt call types |
NewSessionRequest / NewSessionResponse | Session creation types |
InitializeRequest / InitializeResponse | Initialization types |
SetSessionModeRequest / SetSessionModeResponse | Mode switching types |
SetSessionModelRequest / SetSessionModelResponse | Model switching types |
TranslatedMessage | Result of translating a Cline message to ACP updates |
Relationship to ACP
The Cline SDK implements the Agent Client ProtocolAgent interface. The key difference from a standard ACP stdio agent is that the SDK uses an event emitter pattern instead of a transport connection:
ACP Stdio (via AcpAgent) | SDK (via ClineAgent) |
|---|---|
| Session updates sent over JSON-RPC stdio | Session updates emitted via ClineSessionEmitter |
Permissions requested via connection.requestPermission() | Permissions requested via setPermissionHandler() callback |
| Single process, single connection | Embeddable, multiple concurrent sessions |
cline CLI binary directly. The SDK is for embedding Cline in your own Node.js processes.
