cline/cline
TypeScript agent SDK behind a CLI, VS Code and desktop app: tool-calling loop, per-tool approval policies, git checkpoints, MCP and plugins.
Overview
At this commit Cline is a TypeScript monorepo built around an SDK. The agent itself lives in layered packages under sdk/packages/: @cline/shared (contracts), @cline/llms (providers), @cline/agents (the stateless loop) and @cline/core (sessions, tools, storage, plugins and the hub). Several hosts sit on top: the cline CLI with a terminal UI, the VS Code extension, a Tauri desktop example and a browser dashboard for the hub (ARCHITECTURE.md).
Cline is an autonomous tool-calling agent. The model gets a fixed set of tools (read files, search, run commands, edit, fetch web content, ask a question, spawn sub-agents) and calls them in a loop until it stops making tool calls. Safety comes from per-tool policies and an approval callback that each host implements, and from git checkpoints taken before each user turn. MCP servers, plugins, hook scripts, skills and AGENTS.md/.clinerules instructions extend it.
It suits developers who want an agent that works through a task on its own, in an editor or a terminal, and teams who want to embed the same agent in their own tools through @cline/core. Expect a large codebase: the core package alone has about 350 non-test source files.
Architecture
flowchart LR
H["Hosts: CLI / VS Code / desktop"] --> CC["ClineCore (@cline/core)"]
CC --> RH["RuntimeHost (local or hub)"]
RH --> HUB["Hub daemon (WebSocket)"]
RH --> SR["Session runtime"]
SR --> AR["AgentRuntime loop (@cline/agents)"]
SR --> CP["Compaction (prepareTurn)"]
SR --> CK["Checkpoint hooks (git)"]
AR --> GW["Gateway (@cline/llms)"]
GW --> AIS["Vercel AI SDK providers"]
AR --> TL["Tools: read, search, run_commands, editor, apply_patch"]
AR --> EXT["MCP / plugins / hooks / skills"]
AR --> AP["requestToolApproval (host UI)"]
| Component | Path | Role |
|---|---|---|
| Shared contracts | sdk/packages/shared/ |
Types, hook engine, storage paths, schemas |
| LLM gateway | sdk/packages/llms/src/providers/ |
Provider registry, model catalog, AI SDK handlers, usage and cost |
| Agent loop | sdk/packages/agents/src/agent-runtime.ts |
Turn loop, tool execution, approvals, retries, overflow recovery |
| Core orchestration | sdk/packages/core/src/ |
ClineCore, sessions, persistence, config watching, hub |
| Built-in tools | sdk/packages/core/src/extensions/tools/ |
Tool definitions, presets, executors, plan-mode command guard |
| Context compaction | sdk/packages/core/src/extensions/context/ |
Agentic (LLM summary) and basic (truncation) compaction |
| Checkpoints | sdk/packages/core/src/hooks/checkpoint-hooks.ts, session/checkpoint-restore.ts |
Git snapshots per run and restore |
| Extensions | sdk/packages/core/src/extensions/{mcp,plugin,agent-plugin,config}/ |
MCP clients, sandboxed plugins, agent plugins, rules and skills |
| CLI | apps/cli/ |
cline command, TUI, ACP mode |
| VS Code extension | apps/vscode/ |
Webview UI on top of the SDK, approval UI, diff view |
How a request flows
- A host calls
ClineCore.create()and thenstart()(ClineCore.ts).RuntimeHostruns the session in-process or in a detached hub daemon that several clients can attach to. - The runtime builder assembles the tools from a preset (
act,plan,yolo, …) (presets.ts). Routing rules swapeditorforapply_patchon OpenAI-native, GPT and Codex models (model-tool-routing.ts). AgentRuntime.execute()runsbeforeRunhooks, adds the input and loops until the run ends or the optionalmaxIterationscap is hit (agent-runtime.ts). Each turn callsprepareTurn, which is where core plugs in compaction, and then streams the model response with provider-error retry.- If the reply has no tool calls, the run ends, unless a completion policy injects a reminder and loops again (agent-runtime.ts). Hitting the output-token limit triggers a bounded “continue” recovery.
- For each tool call,
beforeToolhooks run first and can block it. Then the merged policy ("*"plus the tool’s entry) is checked. A disabled tool is skipped.autoApprove: falsecalls the host’srequestToolApproval(agent-runtime.ts). executeToolCalls()runs adjacent tools marked parallel withPromise.alland the others one by one (agent-runtime.ts). Results are appended as tool messages. A terminal tool such assubmit_and_exitends the run (agent-runtime.ts).
Key components
Agent loop
AgentRuntime holds no storage. It emits events (turn-started, message-added, run-finished, …) and exposes hooks around the model and around tools. If the provider rejects a request as too large, it retries once with a compacted request. If compaction did not shrink the request, it fails with a dedicated error (agent-runtime.ts). Sub-agents come from the spawn_agent tool and from “agent teams” under extensions/tools/team/. Each one is a child runtime.
Context management
There is no repo map and no embedding index. The model explores with read_files (2,000 lines and 48,000 characters per read) and search_codebase, which uses ripgrep and falls back to a regex scan (output-limits.ts, search.ts). MessageBuilder caps each tool result at 8,000 characters. It replaces stale reads of a file with [outdated - see the latest file content], in batches so provider prompt caches survive (message-builder.ts). Compaction triggers at 90% of the input window and targets 70%, keeping the last 20,000 tokens (compaction-shared.ts). The default strategy is agentic, an LLM summary that falls back to basic truncation if it fails (compaction.ts, compaction.ts).
Editing tools
editor replaces old_text with new_text only when it occurs exactly once. It can also create a file or insert at a line. apply_patch parses a patch format with add, update, move and delete operations. Both resolve relative paths inside the working directory, but absolute paths are accepted as they are (editor.ts). There is no automatic lint or test step. The model sees the tool result and decides.
Checkpoints
On the first model call of each root run, createCheckpointHooks snapshots the worktree with git stash create. It adds untracked files as a third parent commit and stores the result under refs/cline/checkpoints/<session>/<run>, so git stash list stays clean (checkpoint-hooks.ts, checkpoint-hooks.ts). Restore first saves the current state to a private transaction ref, so a failed restore can roll back.
Approvals and safety
The SDK treats a tool with no policy as auto-approved. Hosts decide what to ask about. The VS Code extension sets autoApprove: false for read, edit, command, web and every MCP tool, so each call reaches its approval callback, which checks the UI toggles (sdk-tool-policies.ts). With the default toggles, reads, edits, browser and MCP calls are approved silently, and only commands ask (AutoApprovalSettings.ts). The CLI defaults to autoApprove: true for all tools, unless --auto-approve false or a saved setting says otherwise. --yolo also forces it on and switches to a reduced tool set (main.ts, startup-settings.ts). In plan mode, a beforeTool guard blocks shell commands that look like file edits (rm, mv, sed -i, redirects). It is a word-list check, not a parser (command-guard.ts). Loop detection and a mistake tracker stop repeated failing calls.
Models
@cline/llms registers 211 generated provider IDs plus hand-written vendors (Anthropic, OpenAI, Google, Bedrock, Vertex, Mistral, Ollama, OpenAI-compatible, Cline’s own gateway). Calls go through the Vercel AI SDK (ai v7) with native tool calling. The gateway sets a default output budget of 32,000 tokens, raised to 30% of a model’s output limit when that is larger (gateway.ts). Usage is normalised per provider. Billed cost reported by the provider wins over a price-table estimate.
Extending it
- MCP: stdio, SSE and streamable-HTTP servers from JSON config, with OAuth support. Their tools are exposed as
server__tool. - Plugins: JS/TS modules in
.cline/pluginsrun in a subprocess sandbox over IPC and can add tools, commands, hooks and providers. Agent plugins with aplugin.jsonin the agent-plugins.org format live in.agents/plugins(paths.ts). - Hook files: scripts in
hooksdirectories (global,.clinerules/hooks,.cline/hooks) that run on task start, resume, cancel and complete, pre/post tool use, prompt submit and pre-compaction. - Rules and skills:
AGENTS.md,.clinerules, workflows and skills directories, reloaded by a config watcher. - SDK: embed
@cline/core(or the@cline/sdkalias), or use the bareAgentRuntimefrom@cline/agents.
Running it
npm i -g cline installs the CLI, which needs Node 22 or newer. The CLI starts a hub daemon in the background when it needs one. cline auth or a provider key such as ANTHROPIC_API_KEY configures the model. The VS Code extension installs from the marketplace. To build from source you need Bun (bun run build:sdk, then bun run cli). No database server is needed. State lives in the user’s Cline data directory (CLINE_DATA_DIR), in separate SQLite files for sessions, cron, connectors and tasks. Useful CLI flags: --plan, --json, --worktree (run in a separate git worktree), --data-dir (isolated state) and -z/--zen (run in the background hub). cline schedule runs agents from .cron.md and .event.md specs, which default to yolo mode, and cline connect attaches chat connectors such as Slack, Telegram or Linear.
Strengths and caveats
- Strength: one agent, many hosts. The same loop, tools and policies run in the CLI, VS Code, the desktop app and your own code. Hub sessions can be shared between clients.
- Strength: careful context handling. Truncation that keeps caches intact, stale-read rewriting, an LLM summary with a fallback, and overflow recovery are all built in and well tested.
- Strength: transparent checkpoints. Git snapshots include untracked files and stay out of the user’s stash list.
- Caveat: permissive approval defaults. The CLI auto-approves every tool by default, and VS Code’s default toggles approve edits and MCP calls without asking. There is no OS sandbox (no container, seatbelt or landlock), and absolute paths bypass the cwd check in the edit tools.
- Caveat: needs native tool calling. Models without function calling cannot drive the loop.
- Caveat: size and churn. The SDK is big and changes fast.
Sources: code at cd80a20, deepwiki-open wiki (13 pages), OpenDeepWiki wiki (29 pages), verified Q&A.
How it answers the Open-source coding agents questions
Each answer was drafted by a code-reading agent at commit cd80a20. Its citations were checked mechanically. Compare with the other open-source coding agents →
How is the agent loop implemented?
answeredCline implements a single-turn agent loop — there is no Planner/executor split. The core loop lives in AgentRuntime.execute() in @cline/agents (agent-runtime.ts:783). It iterates: prepare the model request → call the LLM provider → extract tool calls → execute each tool → collect results → repeat. Stop conditions are: (1) the assistant returns no tool calls and no completion reminders fire (agent-runtime.ts:936-957), (2) a terminal/completion tool was called (agent-runtime.ts:977-993), (3) maxIterations is exceeded (agent-runtime.ts:831-833), or (4) an error/abort occurs (agent-runtime.ts:1000-1024). The tool-call schema uses AgentToolCallPart objects with typed toolCallId, toolName, and input fields; the model's response is parsed into these structured parts. Sub-agents are supported via the spawn-agent tool (spawn-agent-tool.ts), creating child AgentRuntime instances inside separate session contexts. Each turn goes through beforeModel/afterModel and beforeTool/afterTool hooks for extension points. Output-token-limit recovery and provider-error retry with exponential backoff are built in (agent-runtime.ts:72-91).
How is repository context gathered and kept within the context window?
answeredContext is managed by the MessageBuilder (message-builder.ts) in @cline/core. It walks the conversation history and produces provider-ready message payloads, applying two compaction strategies: tool-result truncation (each tool result is capped at DEFAULT_MAX_TOOL_RESULT_CHARS = 8,000 chars) and outdated-file-content rewriting (re-read files replace stale content with [outdated - see the latest file content]). There is an aggregate text budget of 6 MB (DEFAULT_MAX_TOTAL_TEXT_BYTES) to prevent oversized requests. On context-window overflow, the runtime attempts recovery by compacting the conversation and retrying once; if that fails, it terminates with a specialized error message (agent-runtime.ts:106-133). The file-reading strategy uses line-range reads (file-read.ts) with limits of 10 MB file size and 50,000 un-ranged lines, and images are read as base64 inline content. Search/grep is a built-in tool backed by ripgrep via the search executor (search.ts). Checkpoints snapshot the workspace via git stash with a private ref (checkpoint-hooks.ts, checkpoint-restore.ts). The orchestrator (session-runtime-orchestrator.ts) ties these together per-session with a ConversationStore for the message transcript, a ToolResultCache for caching tool outputs, and a MistakeTracker/LoopDetectionTracker for safety.
extensions/context/compaction.ts: it triggers at 90% of the input window, defaults to the agentic (LLM summary) strategy with a basic truncation fallback, targets 70% and keeps the last 20K tokens. Checkpoint snapshots use git stash create, not git stash.How are code edits applied?
answeredCode edits are applied through three built-in tools: (1) editor — a search/replace tool that finds exact string matches in a file and replaces them (editor.ts), (2) apply_patch — a unified-diff parser that accepts standard patch format and tolerates legacy shell wrappers (apply-patch.ts), and (3) run_commands — shell execution that can invoke arbitrary editors, compilers, or scripts (bash.ts). The editor tool validates that the old string appears exactly once in the target file (unique match requirement), counts occurrences to prevent ambiguous replacements, and computes a line-based diff for display (editor.ts:67-98). The apply-patch tool parses hunk headers, line positions, and context lines; it supports adding, modifying, renaming, and deleting files, with guardrails like restrictToCwd to prevent path-traversal (apply-patch.ts:59-78). Validation is implicit: the tool returns success/failure and any diff output; the agent sees the result and can retry. There is no automatic lint or test-run after editing. Undo/checkpoint is backed by git: the checkpoint hooks use git stash push --include-untracked with a private refs/cline/restore-transactions/ ref, and checkpoint-restore.ts implements full worktree rollback with commit/rollback semantics (checkpoint-restore.ts:50-80). checkpoint-diff.ts compares checkpoints against the current workspace.
git stash create plus an untracked-files parent under refs/cline/checkpoints/<session>/<run>. stash push --include-untracked with refs/cline/restore-transactions/ is the restore rollback. restrictToCwd only restricts relative paths.How are shell commands and file writes kept safe?
answeredCline layers multiple safety mechanisms for shell commands and file writes. Tool-level approval is mediated by requestToolApproval callback on RuntimeBuilderInput; every tool call can be presented to the user for approval or rejection (runtime-builder.ts:87-89). Tool policies define per-tool enablement: the yolo preset auto-approves all tools, while the default preset requires user approval (presets.ts:133-143). The plan-mode command guard (command-guard-extension.ts) registers a beforeTool hook that blocks file-editing shell commands (rm, mv, cp, sed -i, git commit, redirects, etc.) from the run_commands tool when in plan mode, without prompting the user — the model receives the error directly (command-guard.ts:23-100). MCP server sandboxing validates server registrations using Zod schemas for transport type (stdio, SSE, streamable HTTP), restricts environment variable handling, and applies timeout policies (mcp/config-loader.ts:62-90, mcp/policies.ts). The RunCommandExecutionController tracks active shell processes and supports detaching them from the agent loop so long-running background commands persist across turns (run-command-execution-controller.ts). Checkpoints (git-based workspace snapshots) provide rollback with commit/rollback transactions (checkpoint-restore.ts). Network restrictions are not hard-coded — they depend on MCP server configurations. The filterToolsByPolicies function (runtime-builder.ts:85-99) lets tools be selectively disabled by name or via wildcard policies.
default policy preset returns no policies, and the SDK treats unlisted tools as auto-approved. The CLI defaults to autoApprove: true for all tools; the VS Code extension routes read, edit, command, web and MCP tools to its approval callback, whose default settings auto-approve everything except commands. MCP config validation is not a sandbox.Which models are supported and how are they called?
answeredThe @cline/llms package provides a gateway-based provider architecture (gateway.ts). A central GatewayRegistry routes requests to registered provider handlers. Supported vendors include Anthropic (vendors/anthropic.ts), OpenAI (vendors/openai.ts), Google (vendors/google.ts), Mistral (vendors/mistral.ts), AWS Bedrock (vendors/bedrock.ts), Vertex AI (vendors/vertex.ts), Ollama (local models, vendors/ollama.ts), OpenAI-compatible APIs (vendors/openai-compatible.ts), a community provider system (vendors/community.ts), the Cline managed API (vendors/cline.ts), and MiniMax Thinking (vendors/minimax-thinking.ts). There is also a generic ai-sdk provider (providers/ai-sdk.ts). Each provider implements a common ApiHandler interface that can operate in tool-calling mode (when the model supports it) or text-format mode (shimmed via structured prompts). A generated provider spec file (providers.generated.ts) and model catalog (catalog.generated.ts) register known model IDs, capabilities, and operation support. The model-tools system (model-tools.ts) detects which models support native tool definitions vs. requiring tool-use prompt shims. Cost tracking is handled through billing module (billing.ts) and telemetry events. Per-model prompt tuning is implemented via routing rules: reasoning effort, cache point placement, and max-token budgeting are adjusted per-provider/model in the routing modules (routing/anthropic-compatible.ts, routing/bedrock-cache-point.ts, routing/reasoning-options.ts).
model-tools.ts resolves provider-side model tools such as web_search, not native tool support.How can it be extended and customised?
answeredCline is extensible through six mechanisms. (1) MCP (Model Context Protocol) — servers can be registered via JSON config files (mcp/config-loader.ts) over stdio, SSE, or streamable HTTP transports. Tools from MCP servers are wrapped as AgentTool instances and exposed to the model (mcp/tools.ts). (2) Agent Plugins — directory-based packages with a cline-plugin.json manifest declaring capabilities, tools, MCP servers, and skills; loaded and validated against the agent-plugins.org schema (agent-plugin/loader.ts). (3) Hook files — user-customizable shell scripts that fire on lifecycle events (run start, tool call start/end, run end), defined by CLINE_HOOK_FILE config (hook-file-hooks.ts). (4) Agent Extensions — runtime hooks registered via the AgentExtension interface with beforeTool, afterTool, beforeRun, afterRun callbacks, packaged as plugins or built-in features (plugin-loader.ts). (5) Skills and workflows — markdown files with frontmatter that define reusable agent instructions or multi-agent orchestration scripts. (6) SDK/headless use — @cline/core exports ClineCore.create() and ClineCore.start() for programmatic integration (ClineCore.ts:99), while @cline/agents provides the lower-level AgentRuntime that can be embedded directly. User instruction files (user-instruction-config-loader.ts) let projects add custom rules, and the unified config file watcher picks up changes dynamically.
plugin.json (agent-plugins.org schema) under .agents/plugins; Cline plugins are JS/TS modules in .cline/plugins that run in a subprocess sandbox. Hook files are discovered in hooks config directories; there is no CLINE_HOOK_FILE setting.