Compare commits

..

1 Commits

Author SHA1 Message Date
John Simone 8e7d30be29 fix browser scrolling on multi-agent example 2026-05-12 14:48:23 -07:00
3272 changed files with 537491 additions and 146501 deletions
-208
View File
@@ -1,208 +0,0 @@
---
name: cline-sdk
description: Comprehensive Cline SDK skill for building AI agents. Covers the Agent runtime, ClineCore sessions, custom tools, plugins, events, LLM providers, scheduling, multi-agent teams, and production deployment. Use for any task involving @cline/sdk or its sub-packages.
metadata:
references: agent, clinecore
---
# Cline SDK Skill
Consolidated skill for building AI agents with the Cline SDK. Use the decision trees below to find the right entry point and API surface, then load detailed references.
## Critical Rules
Follow these rules in all Cline SDK code:
1. Install with `npm install @cline/sdk`. The `@cline/sdk` package re-exports everything from `@cline/core`, `@cline/agents`, `@cline/llms`, and `@cline/shared`.
2. Requires Node.js 22 or later.
3. Use `createTool()` from `@cline/sdk` (or `@cline/shared`) to define tools. Tool names must be `snake_case`.
4. Return errors as structured data from tool `execute` functions. Throwing counts as a "mistake" against the agent's mistake limit.
5. Use `lifecycle: { completesRun: true }` on tools that should end the agent loop (e.g. a "submit answer" tool).
6. When using `ClineCore`, always call `dispose()` when done to clean up resources.
7. The standalone `Agent` and `ClineCore` have different event systems. For `Agent`: use `agent.subscribe()` to get `AgentRuntimeEvent` types (text streaming is `"assistant-text-delta"`, result text is `result.outputText`). For `ClineCore`: use `cline.subscribe()` to get `CoreSessionEvent` types (text streaming is `"chunk"` with `payload.type === "text"`, result text is `result.text`). There is no top-level `onEvent` field on `AgentRuntimeConfig` -- use `agent.subscribe()` or `hooks.onEvent` instead. Do not use event types like `"content_update"` or `"content_start"` with `agent.subscribe()` -- those are internal legacy types from the ClineCore adapter layer.
## How to Use This Skill
### Reference File Structure
The two main API surfaces (`Agent` and `ClineCore`) follow a 4-file pattern. Cross-cutting concepts are single-file guides.
Each main API surface in `./references/<api>/` contains:
| File | Purpose | When to Read |
|------|---------|--------------|
| `REFERENCE.md` | Overview, when to use, quick start | Always read first |
| `api.md` | Full API: classes, methods, config, types | Writing code |
| `patterns.md` | Common patterns, best practices | Implementation guidance |
| `gotchas.md` | Pitfalls, limitations, debugging | Troubleshooting |
Cross-cutting concepts in `./references/<concept>/` have `REFERENCE.md` as the entry point.
### Reading Order
1. Start with `REFERENCE.md` for your chosen API surface
2. Then read additional files relevant to your task:
- Writing agent code -> `api.md`
- Common patterns -> `patterns.md`
- Creating tools -> `tools/REFERENCE.md`
- Adding plugins/hooks -> `plugins/REFERENCE.md`
- Configuring LLM providers -> `providers/REFERENCE.md`
- Streaming events -> `events/REFERENCE.md`
- Deploying to production -> `production/REFERENCE.md`
- Scheduling agents -> `scheduling/REFERENCE.md`
- Multi-agent orchestration -> `multi-agent/REFERENCE.md`
- Debugging -> `gotchas.md`
### Example Paths
```
./references/agent/REFERENCE.md # Start here for lightweight agents
./references/clinecore/REFERENCE.md # Start here for full runtime
./references/agent/api.md # Agent class, config, methods
./references/tools/REFERENCE.md # Creating and using tools
./references/plugins/REFERENCE.md # Plugin system
./references/providers/REFERENCE.md # LLM provider configuration
```
## Quick Decision Trees
### "Which API surface should I use?"
```
Which API?
+-- I want a simple, stateless agent with custom tools
| +-- agent/ (Agent class from @cline/agents)
+-- I need session persistence, built-in tools, config discovery
| +-- clinecore/ (ClineCore from @cline/core)
+-- I want built-in file/shell/search/web tools
| +-- clinecore/ (has built-in tools; Agent does not)
+-- I want scheduled or recurring agents
| +-- clinecore/ (automation API)
+-- I need multi-process or multi-client session sharing
| +-- clinecore/ (hub-backed runtime)
+-- I'm building a browser-compatible agent
| +-- agent/ (no Node.js dependencies)
```
### "I need to create tools"
```
Tools?
+-- Define a custom tool with schema -> tools/REFERENCE.md
+-- Use built-in tools (bash, editor, read_files) -> tools/REFERENCE.md (built-in section)
+-- Control tool approval/policies -> tools/REFERENCE.md (policies section)
+-- Tool that ends the agent loop -> tools/REFERENCE.md (completion tools)
+-- Package tools as a reusable plugin -> plugins/REFERENCE.md
```
### "I need to handle events"
```
Events?
+-- Stream text/reasoning in real time -> events/REFERENCE.md
+-- Track token usage and costs -> events/REFERENCE.md
+-- Watch tool calls -> events/REFERENCE.md
+-- Detect completion/errors -> events/REFERENCE.md
+-- Hook into lifecycle stages -> plugins/REFERENCE.md
```
### "I need to configure a model provider"
```
Providers?
+-- Anthropic (Claude) -> providers/REFERENCE.md
+-- OpenAI (GPT) -> providers/REFERENCE.md
+-- Google (Gemini/Vertex) -> providers/REFERENCE.md
+-- AWS Bedrock -> providers/REFERENCE.md
+-- Mistral -> providers/REFERENCE.md
+-- OpenAI-compatible (vLLM, Together, etc.) -> providers/REFERENCE.md
+-- Custom/self-hosted provider -> providers/REFERENCE.md
```
### "I need plugins or hooks"
```
Plugins?
+-- Package tools + hooks together -> plugins/REFERENCE.md
+-- Observe tool calls (logging, metrics) -> plugins/REFERENCE.md
+-- Intercept lifecycle events -> plugins/REFERENCE.md
+-- Add system prompt rules -> plugins/REFERENCE.md
+-- Distribute via npm/git -> plugins/REFERENCE.md
```
### "I need multi-agent coordination"
```
Multi-agent?
+-- Spawn one-off background agents -> multi-agent/REFERENCE.md (sub-agents)
+-- Persistent cross-session teams -> multi-agent/REFERENCE.md (teams)
+-- Parent-child delegation -> multi-agent/REFERENCE.md (sub-agents)
+-- Peer-to-peer task board -> multi-agent/REFERENCE.md (teams)
```
### "I need scheduling or automation"
```
Scheduling?
+-- Recurring cron jobs -> scheduling/REFERENCE.md
+-- One-off scheduled tasks -> scheduling/REFERENCE.md
+-- Event-driven triggers -> scheduling/REFERENCE.md
+-- CLI schedule management -> scheduling/REFERENCE.md
```
### "I need to go to production"
```
Production?
+-- Error handling and status checks -> production/REFERENCE.md
+-- Cost control and token limits -> production/REFERENCE.md
+-- Observability (OpenTelemetry) -> production/REFERENCE.md
+-- Security and sandboxing -> production/REFERENCE.md
+-- Deployment patterns -> production/REFERENCE.md
```
### Troubleshooting Index
- Agent loop not stopping -> `tools/REFERENCE.md` (completion tools)
- Tool errors crashing the agent -> `agent/gotchas.md` or `clinecore/gotchas.md`
- Provider auth failures -> `providers/REFERENCE.md`
- Session not persisting -> `clinecore/gotchas.md`
- Token usage too high -> `production/REFERENCE.md` (cost control)
- Hub connection issues -> `clinecore/gotchas.md`
- Plugin not loading -> `plugins/REFERENCE.md`
- Events not firing -> `events/REFERENCE.md`
## Product Index
### API Surfaces
| API | Entry File | Description |
|-----|------------|-------------|
| Agent | `./references/agent/REFERENCE.md` | Lightweight stateless agent loop |
| ClineCore | `./references/clinecore/REFERENCE.md` | Full runtime with sessions, persistence, built-in tools |
### Cross-Cutting Concepts
| Concept | Entry File | Description |
|---------|------------|-------------|
| Tools | `./references/tools/REFERENCE.md` | Built-in and custom tool creation |
| Plugins | `./references/plugins/REFERENCE.md` | Extension system with hooks |
| Events | `./references/events/REFERENCE.md` | Real-time streaming events |
| Providers | `./references/providers/REFERENCE.md` | LLM provider configuration |
| Production | `./references/production/REFERENCE.md` | Deployment, security, observability |
| Scheduling | `./references/scheduling/REFERENCE.md` | Cron jobs and automation |
| Multi-Agent | `./references/multi-agent/REFERENCE.md` | Teams and sub-agents |
### Package Map
| Package | Purpose |
|---------|---------|
| `@cline/sdk` | Everything you need, install this one |
| `@cline/core` | Sessions, persistence, built-in tools, config, hub |
| `@cline/agents` | Stateless agent loop, tool orchestration, streaming |
| `@cline/llms` | LLM provider gateway |
| `@cline/shared` | Types, tool helpers, hook engine |
## Resources
Repository: https://github.com/cline/cline
SDK Source: https://github.com/cline/cline/tree/main/sdk
Documentation: https://docs.cline.bot/sdk/overview
Discord: https://discord.gg/cline
@@ -1,107 +0,0 @@
# Agent Runtime
The `Agent` class (also exported as `AgentRuntime`) is the lightweight, stateless agent loop from `@cline/agents`. It handles the core iteration cycle: send messages to an LLM, execute tool calls, collect results, and repeat until the task is done.
## When to Use Agent
| Use Agent when... | Use ClineCore instead when... |
|---|---|
| You want a simple agent with custom tools | You need built-in tools (bash, editor, etc.) |
| You want minimal dependencies | You need session persistence |
| You need browser compatibility | You need config discovery from `.cline/` |
| You're building a stateless worker | You need multi-process session sharing |
| You want full control over the runtime | You want batteries-included setup |
## Quick Start
```typescript
import { Agent } from "@cline/sdk"
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
systemPrompt: "You are a helpful assistant.",
tools: [],
})
const result = await agent.run("What is the capital of France?")
console.log(result.outputText)
```
## Core Concepts
The Agent operates in a loop:
1. Accept user input (string, message, or array of messages)
2. Build turn context (system prompt, messages, tools)
3. Call the LLM provider
4. If the model returns tool calls, execute them and loop back to step 3
5. If the model returns text without tool calls, the run completes
6. Emit events throughout for streaming
The agent is stateless in the sense that it does not persist anything to disk. Conversation history is held in memory and can be accessed via `snapshot()`.
## Key APIs
- `new Agent(config)` or `createAgent(config)` - Create an agent
- `agent.run(input)` - Start a run with user input
- `agent.continue(input?)` - Continue an existing conversation
- `agent.abort(reason?)` - Cancel an active run
- `agent.subscribe(listener)` - Listen to streaming events
- `agent.snapshot()` - Get current runtime state
- `agent.restore(messages)` - Replace message history
See `api.md` for full API details.
## Multi-Turn Conversations
```typescript
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "You are a helpful assistant.",
tools: [],
})
const first = await agent.run("What is 2 + 2?")
console.log(first.outputText)
const second = await agent.continue("Now multiply that by 3")
console.log(second.outputText)
```
Use `agent.hasRun` to check if a run has already been executed, which determines whether to call `run()` or `continue()`.
## Event Streaming
Use `agent.subscribe()` to stream events in real time. Register the listener before calling `run()` to avoid missing early events.
There is no top-level `onEvent` field on the Agent config. For an async alternative, use `hooks.onEvent` (see `api.md` and `gotchas.md`).
```typescript
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "You are a helpful assistant.",
tools: [],
})
agent.subscribe((event) => {
if (event.type === "assistant-text-delta") {
process.stdout.write(event.text)
}
})
const result = await agent.run("What is the capital of France?")
```
See `events/REFERENCE.md` for the full event type catalog.
## Next Steps
- `api.md` - Full Agent API reference
- `patterns.md` - Common patterns and best practices
- `gotchas.md` - Pitfalls and debugging
- `../tools/REFERENCE.md` - Creating custom tools
- `../events/REFERENCE.md` - Event system details
- `../providers/REFERENCE.md` - Provider configuration
@@ -1,231 +0,0 @@
# Agent API Reference
## Constructor
```typescript
import { Agent } from "@cline/sdk"
const agent = new Agent(config: AgentRuntimeConfig)
```
Also available via factory function:
```typescript
import { createAgent } from "@cline/sdk"
const agent = createAgent(config)
```
## AgentRuntimeConfig
Two config forms exist as a discriminated union:
### With Provider ID (recommended)
```typescript
interface AgentRuntimeConfigWithProvider {
providerId: string // e.g. "anthropic", "openai", "gemini"
modelId: string // e.g. "claude-sonnet-4-6", "gpt-5.5"
apiKey?: string // provider API key
baseUrl?: string // custom endpoint
headers?: Record<string, string>
systemPrompt?: string
tools?: AgentTool[]
initialMessages?: AgentMessage[]
toolPolicies?: Record<string, ToolPolicy>
hooks?: Partial<AgentRuntimeHooks>
plugins?: AgentPlugin[]
}
```
### With Pre-built Model
```typescript
interface AgentRuntimeConfigWithModel {
model: AgentModel // pre-built model from gateway
systemPrompt?: string
tools?: AgentTool[]
initialMessages?: AgentMessage[]
toolPolicies?: Record<string, ToolPolicy>
hooks?: Partial<AgentRuntimeHooks>
plugins?: AgentPlugin[]
}
```
Note: there is no top-level `onEvent` field on `AgentRuntimeConfig`. For event streaming, use `agent.subscribe()` or `hooks.onEvent` (see AgentRuntimeHooks below).
## Methods
### run(input)
Start the agent with user input. Returns when the agent loop completes.
```typescript
const result: AgentRunResult = await agent.run("Build a REST API")
```
Input can be a string, an `AgentMessage`, or an array of `AgentMessage[]`.
### continue(input?)
Continue an existing conversation with optional new input.
```typescript
const result = await agent.continue("Now add authentication")
```
### abort(reason?)
Cancel the currently active run.
```typescript
agent.abort("User cancelled")
```
### subscribe(listener)
Register a listener for streaming events.
```typescript
const unsubscribe = agent.subscribe((event: AgentRuntimeEvent) => {
// handle event
})
// Later: stop listening
unsubscribe()
```
### snapshot()
Get the current runtime state including message history.
```typescript
const state: AgentRuntimeStateSnapshot = agent.snapshot()
```
### restore(messages)
Replace the agent's message history.
```typescript
agent.restore(previousMessages)
```
### hasRun
Boolean property indicating whether `run()` has been called at least once.
```typescript
if (agent.hasRun) {
await agent.continue(input)
} else {
await agent.run(input)
}
```
## AgentRunResult
Returned by `run()` and `continue()`.
```typescript
interface AgentRunResult {
agentId: string
agentRole?: string
runId: string
status: "completed" | "aborted" | "failed"
iterations: number
outputText: string
messages: readonly AgentMessage[]
usage: AgentUsage
error?: Error
}
```
### Status Values
- `"completed"` - Agent finished normally
- `"aborted"` - Cancelled via `abort()`
- `"failed"` - Unrecoverable error
## AgentMessage
```typescript
interface AgentMessage {
id: string
role: "user" | "assistant" | "tool"
content: AgentMessagePart[]
createdAt: number
metadata?: Record<string, unknown>
modelInfo?: { id: string; provider: string; family?: string }
metrics?: {
inputTokens: number
outputTokens: number
cacheReadTokens?: number
cacheWriteTokens?: number
cost?: number
}
}
```
## AgentUsage
```typescript
interface AgentUsage {
inputTokens: number
outputTokens: number
cacheReadTokens: number
cacheWriteTokens: number
totalInputTokens: number
totalOutputTokens: number
totalCost?: number
}
```
## AgentRuntimeHooks
```typescript
interface AgentRuntimeHooks {
beforeRun?(context): AgentStopControl | undefined
afterRun?(context): void
beforeModel?(context): AgentBeforeModelResult | undefined
afterModel?(context): AgentStopControl | undefined
beforeTool?(context): AgentBeforeToolResult | undefined
afterTool?(context): AgentAfterToolResult | undefined
onEvent?(event: AgentRuntimeEvent): void | Promise<void>
}
```
Hooks can intercept and modify behavior at each stage. Return a stop control from `beforeRun`, `afterModel`, or `beforeTool` to halt the agent loop.
`hooks.onEvent` receives the same `AgentRuntimeEvent` types as `agent.subscribe()`, but hook callbacks are awaited (can be async), while `subscribe()` listeners are called synchronously. Use `subscribe()` for UI streaming and `hooks.onEvent` for async side effects like logging to an external service.
## AgentRuntimeStateSnapshot
```typescript
interface AgentRuntimeStateSnapshot {
messages: readonly AgentMessage[]
usage: AgentUsage
iterations: number
status: string
}
```
## Factory: createAgentRuntime
Lower-level factory that returns the same `Agent` class:
```typescript
import { createAgentRuntime } from "@cline/sdk"
const runtime = createAgentRuntime(config)
```
## See Also
- `REFERENCE.md` - Overview and quick start
- `patterns.md` - Common patterns
- `../tools/REFERENCE.md` - Tool creation
- `../events/REFERENCE.md` - Event types
- `../providers/REFERENCE.md` - Provider setup
@@ -1,134 +0,0 @@
# Agent Gotchas
## Agent Loop Never Stops
If the agent keeps iterating without completing:
- Make sure at least one tool has `lifecycle: { completesRun: true }` if you want the agent to explicitly finish.
- Without any tools, the agent will complete after the model returns text without tool calls.
- If using tools, ensure the system prompt guides the model toward calling the completion tool when done.
- Check that `completesRun` tools return successfully (not throwing errors).
## Tool Errors Count as Mistakes
When a tool's `execute` function throws an exception, the SDK counts it as a "mistake." After too many mistakes, the agent stops with a `mistake_limit` finish reason.
Instead, return errors as structured data:
```typescript
// Bad: throwing
execute: async (input) => {
throw new Error("File not found")
}
// Good: returning error data
execute: async (input) => {
return { error: "File not found", path: input.path }
}
```
## run() vs continue()
- Call `run()` for the first interaction. It sets up the conversation.
- Call `continue()` for subsequent messages. It appends to the existing conversation.
- Calling `run()` a second time resets the conversation history.
- Use `agent.hasRun` to check which method to call.
## Browser Compatibility
`@cline/agents` (and by extension, the `Agent` class) is browser-safe with no Node.js dependencies. However, `@cline/core` and `ClineCore` require Node.js 22+. If you import from `@cline/sdk`, you get everything including the Node-only code. For browser usage, import directly from `@cline/agents`:
```typescript
import { Agent } from "@cline/agents"
```
## No Top-Level onEvent on Agent Config
`AgentRuntimeConfig` does not have a top-level `onEvent` field. Passing `onEvent` to `new Agent({ onEvent: ... })` has no effect. There are two ways to receive events:
```typescript
// Option 1: subscribe() - synchronous, best for UI streaming
const agent = new Agent({ ...config })
agent.subscribe((event) => {
if (event.type === "assistant-text-delta") {
process.stdout.write(event.text)
}
})
// Option 2: hooks.onEvent - awaited, best for async side effects
const agent = new Agent({
...config,
hooks: {
onEvent: async (event) => {
if (event.type === "assistant-text-delta") {
await logToService(event.text)
}
},
},
})
```
Both receive the same `AgentRuntimeEvent` types. Prefer `subscribe()` for streaming UI.
## Event Listener Timing
Register event listeners via `subscribe()` before calling `run()`:
```typescript
// Good: subscribe before run
agent.subscribe(handler)
const result = await agent.run(input)
// Bad: subscribing after run starts loses early events
const promise = agent.run(input)
agent.subscribe(handler) // may miss events
```
## Tool Input Schema Matters
The model uses the tool's `inputSchema` to decide what arguments to pass. A vague or missing schema leads to incorrect tool calls.
- Use `z.enum()` for fixed value sets, not free-form strings
- Describe every property with `.describe()` in Zod or `description` in JSON Schema
- Include constraints (rate limits, max values) in the tool description
## Memory and Long Conversations
The Agent holds all messages in memory. For long-running conversations, memory usage grows with each turn. Consider:
- Using `ClineCore` with compaction for long sessions
- Periodically creating a new agent with a summary of the conversation
- Monitoring `result.usage.totalInputTokens` to track context growth
## Abort Signal Handling in Tools
Long-running tools should respect the abort signal:
```typescript
execute: async (input, context) => {
for (const item of items) {
if (context.abortSignal?.aborted) {
return { partial: results, aborted: true }
}
results.push(await process(item))
}
return { results }
}
```
## Provider API Key
If you get authentication errors, check:
- `apiKey` is set in the config or via environment variables
- The key matches the `providerId` (e.g., Anthropic key for `providerId: "anthropic"`)
- For OpenAI-compatible providers, both `apiKey` and `baseUrl` are set
See `../providers/REFERENCE.md` for provider-specific setup.
## See Also
- `api.md` - Full API reference
- `patterns.md` - Common patterns
- `../tools/REFERENCE.md` - Tool creation
- `../clinecore/REFERENCE.md` - Use ClineCore for persistence
@@ -1,258 +0,0 @@
# Agent Patterns
## Interactive CLI Agent
A multi-turn conversational agent in the terminal with streaming output:
```typescript
import { Agent } from "@cline/sdk"
import * as readline from "node:readline"
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
systemPrompt: "You are a helpful assistant. Keep responses concise.",
tools: [],
})
agent.subscribe((event) => {
if (event.type === "assistant-text-delta") {
process.stdout.write(event.text)
}
})
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
function prompt(): void {
rl.question("\nYou: ", async (input) => {
const trimmed = input.trim()
if (!trimmed || trimmed === "exit") {
rl.close()
return
}
process.stdout.write("\nAssistant: ")
if (agent.hasRun) {
await agent.continue(trimmed)
} else {
await agent.run(trimmed)
}
process.stdout.write("\n")
prompt()
})
}
prompt()
```
## Conversational Agent (Slack Bot, Chat App)
Maintain per-thread agents with conversation memory:
```typescript
import { Agent } from "@cline/sdk"
const agents = new Map<string, Agent>()
async function handleMessage(threadId: string, message: string) {
let agent = agents.get(threadId)
if (!agent) {
agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "You are a concise assistant.",
tools: [],
})
agents.set(threadId, agent)
}
const result = agent.hasRun
? await agent.continue(message)
: await agent.run(message)
return result.outputText
}
```
## Streaming UI
Build a real-time UI by handling events via `subscribe()`:
```typescript
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "You are a helpful assistant.",
tools: [myTool],
})
agent.subscribe((event) => {
switch (event.type) {
case "assistant-text-delta":
ui.appendText(event.text)
break
case "assistant-message":
ui.endText()
break
case "turn-started":
ui.startTurn(event.iteration)
break
case "turn-finished":
if (event.toolCallCount > 0) ui.showToolCount(event.toolCallCount)
break
case "usage-updated":
ui.updateUsage(event.usage.inputTokens, event.usage.outputTokens)
break
}
})
const result = await agent.run("Hello!")
```
## Structured Output via Completion Tool
Use a tool with `completesRun: true` to extract structured data:
```typescript
import { Agent, createTool } from "@cline/sdk"
import { z } from "zod"
const submitReview = createTool({
name: "submit_review",
description: "Submit the final code review with structured feedback.",
inputSchema: z.object({
summary: z.string(),
issues: z.array(z.object({
file: z.string(),
line: z.number(),
severity: z.enum(["error", "warning", "info"]),
message: z.string(),
})),
approved: z.boolean(),
}),
lifecycle: { completesRun: true },
execute: async (input) => input,
})
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "Review the code diff and submit structured feedback.",
tools: [submitReview],
})
const result = await agent.run(diffContent)
const review = result.toolCalls.find(tc => tc.name === "submit_review")
console.log(review?.output)
```
## Agent with Abort/Timeout
```typescript
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "Analyze this data.",
tools: [],
})
const timeout = setTimeout(() => agent.abort("Timeout"), 30_000)
try {
const result = await agent.run(data)
if (result.status === "aborted") {
console.log("Agent was aborted")
} else {
console.log(result.outputText)
}
} finally {
clearTimeout(timeout)
}
```
## Agent with Plugins
```typescript
import { Agent } from "@cline/sdk"
import type { AgentPlugin } from "@cline/sdk"
const loggingPlugin: AgentPlugin = {
name: "logging",
manifest: { capabilities: ["hooks"] },
setup() {},
hooks: {
beforeTool({ toolCall }) {
console.log(`Calling tool: ${toolCall.toolName}`)
},
afterRun({ result }) {
console.log(`Completed in ${result.iterations} iterations`)
},
},
}
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
systemPrompt: "You are a helpful assistant.",
tools: [myTool],
plugins: [loggingPlugin],
})
```
## Restoring State Across Sessions
Save and restore agent state manually:
```typescript
// Save state
const snapshot = agent.snapshot()
const serialized = JSON.stringify(snapshot.messages)
// Later: restore
const agent2 = new Agent({ ...config })
const messages = JSON.parse(serialized)
agent2.restore(messages)
const result = await agent2.continue("Continue where we left off")
```
For automatic persistence, use `ClineCore` instead.
## Pre-Built Model via Gateway
For advanced provider configuration:
```typescript
import { Agent } from "@cline/sdk"
import { createGateway } from "@cline/llms"
const gateway = createGateway({
providerConfigs: [
{ providerId: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY },
{ providerId: "openai", apiKey: process.env.OPENAI_API_KEY },
],
})
const model = gateway.createAgentModel({
providerId: "anthropic",
modelId: "claude-opus-4-7",
})
const agent = new Agent({
model,
systemPrompt: "You are a helpful assistant.",
tools: [],
})
```
## See Also
- `api.md` - Full API reference
- `gotchas.md` - Common pitfalls
- `../tools/REFERENCE.md` - Creating tools
- `../plugins/REFERENCE.md` - Plugin system
@@ -1,131 +0,0 @@
# ClineCore Runtime
`ClineCore` is the full-featured runtime from `@cline/core`. It wraps the `Agent` loop with session persistence, built-in tools (bash, editor, file reading, search, web fetch), config discovery, plugin loading, and optional hub-backed multi-process support.
## When to Use ClineCore
| Use ClineCore when... | Use Agent instead when... |
|---|---|
| You need built-in tools (bash, editor, etc.) | You only need custom tools |
| You want session persistence to disk | Stateless is fine |
| You need config discovery from `.cline/` dirs | You handle config yourself |
| You want scheduled/automated agents | You don't need scheduling |
| You need multi-client session sharing | Single-process is fine |
| You're building a full application | You want minimal dependencies |
## Quick Start
```typescript
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create({ clientName: "my-app" })
const session = await cline.start({
prompt: "Set up CI with GitHub Actions",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
cwd: "/path/to/project",
enableTools: true,
},
})
console.log(session.result?.text)
await cline.dispose()
```
## Core Concepts
### Sessions
Every `cline.start()` call creates a session with a unique ID. Sessions persist their messages and metadata to SQLite. You can list, read, resume, and delete sessions.
### Built-in Tools
ClineCore provides these tools automatically when `enableTools: true`:
| Tool | Description |
|------|-------------|
| `bash` | Execute shell commands |
| `editor` | Edit files |
| `read_files` | Read file contents |
| `apply_patch` | Apply unified diffs |
| `search` | Search file contents and structure |
| `fetch_web` | HTTP requests and web content |
### Config Discovery
ClineCore watches `.cline/` directories for:
- Rules (system prompt additions)
- Skills (domain knowledge)
- Workflows (multi-step procedures)
- Hooks (lifecycle logic)
- Plugins (tool + hook bundles)
- MCP servers (external tool providers)
### Backend Modes
| Mode | Description |
|------|-------------|
| `"auto"` (default) | Tries to connect to a local hub; falls back to in-process if unavailable |
| `"local"` | In-process execution, local SQLite storage, no hub |
| `"hub"` | Requires a compatible local WebSocket hub; fails if unavailable |
| `"remote"` | Connects to an explicit remote hub endpoint |
The default mode is `"auto"`. For simple scripts and CLI tools, `"local"` avoids hub discovery overhead. Hub mode enables multi-client session sharing (e.g., a dashboard watching a running session from another process).
## Key APIs
- `ClineCore.create(options)` - Create and initialize
- `cline.start(input)` - Start a new session
- `cline.send({ sessionId, prompt })` - Send follow-up message
- `cline.subscribe(listener)` - Listen to session events
- `cline.list()` - List sessions
- `cline.get(sessionId)` - Get session metadata
- `cline.readMessages(sessionId)` - Read persisted messages
- `cline.getAccumulatedUsage(sessionId)` - Token/cost totals
- `cline.abort(sessionId)` - Abort a session
- `cline.delete(sessionId)` - Delete a session
- `cline.dispose()` - Clean up resources
See `api.md` for full API details.
## Event Streaming
`cline.subscribe()` emits `CoreSessionEvent` types. These are different from the `AgentRuntimeEvent` types emitted by the standalone `Agent` class -- see `../events/REFERENCE.md` for the full comparison.
```typescript
cline.subscribe((event) => {
switch (event.type) {
case "chunk":
if (event.payload.type === "text") {
process.stdout.write(event.payload.text)
}
break
case "ended":
console.log(`Session ended: ${event.payload.finishReason}`)
break
}
})
```
ClineCore results use `AgentResult` with `.text` (not `.outputText` like the standalone Agent's `AgentRunResult`).
## Session Persistence
Sessions are stored at:
```
~/.cline/data/sessions/
sessions.db # SQLite database
[session-id].json # Message history
```
## Next Steps
- `api.md` - Full ClineCore API reference
- `patterns.md` - Common patterns and best practices
- `gotchas.md` - Pitfalls and debugging
- `../tools/REFERENCE.md` - Custom tool creation
- `../plugins/REFERENCE.md` - Plugin system
- `../scheduling/REFERENCE.md` - Scheduled agents
@@ -1,304 +0,0 @@
# ClineCore API Reference
## Creating ClineCore
```typescript
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create(options: ClineCoreOptions)
```
### ClineCoreOptions
```typescript
interface ClineCoreOptions {
clientName: string // identifies your app
distinctId?: string // user/instance identifier
backendMode?: "auto" | "local" | "hub" | "remote"
hub?: HubOptions
remote?: RemoteOptions
capabilities?: RuntimeCapabilities
toolPolicies?: Record<string, ToolPolicy>
automation?: boolean | ClineCoreAutomationOptions
fetch?: typeof fetch
}
```
### RuntimeCapabilities
```typescript
interface RuntimeCapabilities {
requestToolApproval?: (request: ToolApprovalRequest) => Promise<ToolApprovalResult>
// ... other capability callbacks
}
```
## Starting Sessions
### start(input)
```typescript
const session = await cline.start(input: ClineCoreStartInput)
```
Returns a `StartSessionResult`:
```typescript
interface StartSessionResult {
sessionId: string
manifest: SessionManifest
manifestPath: string
messagesPath: string
result?: AgentResult
}
```
### ClineCoreStartInput
```typescript
interface ClineCoreStartInput {
prompt: string
config: CoreSessionConfig
source?: string
interactive?: boolean
sessionMetadata?: Record<string, unknown>
initialMessages?: AgentMessage[]
toolPolicies?: Record<string, ToolPolicy>
capabilities?: RuntimeCapabilities
}
```
### CoreSessionConfig
```typescript
interface CoreSessionConfig {
cwd?: string // working directory
providerId: string // LLM provider
modelId: string // model identifier
apiKey?: string // provider API key
systemPrompt?: string // custom system prompt
tools?: readonly AgentTool[] // additional custom tools
enableTools?: boolean // enable built-in tools
hooks?: Partial<AgentRuntimeHooks> // runtime hooks
extensions?: AgentPlugin[] // plugins loaded inline
pluginPaths?: string[] // paths to plugin packages
extensionLoading?: "isolated" | "direct"
extensionContext?: { // context passed to plugin setup()
workspace?: { rootPath: string; cwd: string }
}
checkpointConfig?: CoreCheckpointConfig
compactionConfig?: CoreCompactionConfig
telemetry?: ITelemetryService
logger?: BasicLogger
enableSpawnAgent?: boolean // enable sub-agent spawning
enableAgentTeams?: boolean // enable team coordination
teamName?: string // team identifier
}
```
`extensions` passes plugin objects directly. `pluginPaths` points to directories with `package.json` containing a `cline.plugins` field. Set `extensionContext.workspace` so plugins receive `ctx.workspaceInfo` in their `setup()` call -- without it, `ctx.workspaceInfo` is undefined.
## Follow-Up Messages
### send({ sessionId, prompt })
Send a follow-up message to an existing session:
```typescript
const result = await cline.send({
sessionId: session.sessionId,
prompt: "Now add authentication",
})
```
Returns `AgentResult | undefined`.
## Event Subscription
### subscribe(listener, options?)
```typescript
const unsubscribe = cline.subscribe(
(event: CoreSessionEvent) => {
// handle events
},
{ sessionId: "optional-filter" }
)
```
### CoreSessionEvent
```typescript
type CoreSessionEvent =
| { type: "chunk"; payload: SessionChunkEvent }
| { type: "agent_event"; payload: { sessionId: string, event: AgentEvent } }
| { type: "ended"; payload: SessionEndedEvent }
| { type: "team_progress"; payload: SessionTeamProgressEvent }
| { type: "status"; payload: { sessionId: string, status: string } }
| { type: "hook"; payload: SessionToolEvent }
```
## Session Management
### list(limit?, options?)
```typescript
const sessions: SessionRecord[] = await cline.list(50)
```
### get(sessionId)
```typescript
const session: SessionRecord = await cline.get(sessionId)
```
### readMessages(sessionId)
```typescript
const messages: AgentMessage[] = await cline.readMessages(sessionId)
```
### getAccumulatedUsage(sessionId)
```typescript
const usage = await cline.getAccumulatedUsage(sessionId)
// usage.usage - root agent only
// usage.aggregateUsage - root + subagents/teammates
```
### update(sessionId, updates)
```typescript
await cline.update(sessionId, { title: "New title" })
```
### abort(sessionId, reason?)
```typescript
await cline.abort(sessionId, "User cancelled")
```
### stop(sessionId)
```typescript
await cline.stop(sessionId)
```
### delete(sessionId)
```typescript
await cline.delete(sessionId)
```
### restore(input)
Restore a session from a checkpoint:
```typescript
await cline.restore({ sessionId, checkpointId })
```
### dispose(reason?)
Clean up all resources. Always call this when done:
```typescript
await cline.dispose("Shutting down")
```
## AgentResult
Returned by session operations:
```typescript
interface AgentResult {
text: string
usage: LegacyAgentUsage
messages: MessageWithMetadata[]
toolCalls: ToolCallRecord[]
iterations: number
finishReason: "completed" | "max_iterations" | "aborted" | "mistake_limit" | "error"
model: { id: string; provider: string; info?: ModelInfo }
startedAt: Date
endedAt: Date
durationMs: number
}
```
## Tool Policies
Control tool access at the session level:
```typescript
const session = await cline.start({
prompt: "Review the code",
config: { ... },
toolPolicies: {
read_files: { autoApprove: true },
bash: { autoApprove: false },
editor: { enabled: false },
},
})
```
### ToolPolicy
```typescript
interface ToolPolicy {
enabled?: boolean // false = tool is hidden from the model
autoApprove?: boolean // false = requires approval callback
}
```
## Interactive Approval
```typescript
const cline = await ClineCore.create({
clientName: "my-app",
capabilities: {
requestToolApproval: async (request) => {
console.log(`Tool: ${request.toolName}, Input: ${JSON.stringify(request.input)}`)
const approved = await askUser(`Allow ${request.toolName}?`)
return { approved }
},
},
})
```
## Automation API
When `automation` is enabled in `ClineCore.create()`:
```typescript
const cline = await ClineCore.create({
clientName: "my-app",
automation: true,
})
// Access automation methods
cline.automation.start()
cline.automation.stop()
cline.automation.reconcile(specs)
cline.automation.ingestEvent(event)
cline.automation.listEvents()
cline.automation.listSpecs()
cline.automation.listRuns()
```
## Settings API
```typescript
// Read settings
const settings = await cline.settings.list()
// Toggle tools, plugins, MCP servers
await cline.settings.toggle({ type: "tool", name: "bash", enabled: true })
```
## See Also
- `REFERENCE.md` - Overview and quick start
- `patterns.md` - Common patterns
- `gotchas.md` - Pitfalls
- `../tools/REFERENCE.md` - Tool creation
- `../plugins/REFERENCE.md` - Plugin system
@@ -1,148 +0,0 @@
# ClineCore Gotchas
## Always Call dispose()
`ClineCore` holds resources (file watchers, database connections, hub connections). Failing to call `dispose()` can leave orphan processes and file locks.
```typescript
const cline = await ClineCore.create({ clientName: "my-app" })
try {
// ... use cline
} finally {
await cline.dispose()
}
```
## Node.js 22 Required
ClineCore and `@cline/core` require Node.js 22 or later. If you're on an older version, you'll get runtime errors. Check with `node --version`.
## Session Config vs Global Config
Tool policies can be set at two levels:
- Global: in `ClineCore.create({ toolPolicies })` -- applies to all sessions
- Per-session: in `cline.start({ toolPolicies })` -- overrides global for that session
Per-session policies take precedence.
## enableTools Must Be Explicit
Built-in tools (bash, editor, read_files, etc.) are not available unless you set `enableTools: true` in the session config:
```typescript
await cline.start({
prompt: "Read package.json",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
enableTools: true, // required for built-in tools
},
})
```
Without this, the agent only has access to custom tools you provide via `config.tools`.
## cwd Matters for Built-in Tools
Built-in tools like `bash`, `editor`, and `read_files` operate relative to `config.cwd`. If not set, they use the process working directory. Always set it explicitly for predictable behavior:
```typescript
config: {
cwd: "/absolute/path/to/project",
// ...
}
```
## Hub Startup Latency
With `backendMode: "auto"`, the first session may be slow if a hub daemon needs to be spawned. For immediate responsiveness:
- Use `backendMode: "local"` for in-process execution (fastest startup)
- Pre-warm the hub with `cline hub ensure` CLI command
- Accept the one-time startup cost and let subsequent sessions reuse the hub
## Session Storage Location
Sessions are stored at `~/.cline/data/sessions/`. This includes:
- `sessions.db` - SQLite database with session metadata
- `[session-id].json` - Individual message history files
If you're running in a container or ephemeral environment, these paths may not persist across restarts.
## requestToolApproval Blocks Execution
When a tool policy has `autoApprove: false` and you provide a `requestToolApproval` callback, the agent loop blocks until your callback resolves. If your callback never resolves (e.g., waiting for user input that never comes), the session hangs.
For automated pipelines, either:
- Set all tools to `autoApprove: true`
- Implement a timeout in your approval callback
## Plugin Discovery Paths
ClineCore discovers plugins from:
- Global: `~/.cline/plugins/`
- Workspace: `.cline/plugins/`
For SDK consumers, pass plugins via `extensions: [plugin]` or `pluginPaths: ["./path"]` in the session config.
If a plugin isn't loading, verify:
- The file is in one of the discovery directories, or passed via `extensions`/`pluginPaths`
- The file exports a default plugin object with a non-empty `manifest.capabilities` array
- Every `api.register*` call in `setup()` has a matching capability declared
- If `hooks` is present on the plugin, `"hooks"` is in `capabilities`
## extensionContext.workspace Is Required for Plugins
If your plugins use `ctx.workspaceInfo` (e.g., to resolve workspace paths), you must set `extensionContext.workspace` in the session config. Without it, `ctx.workspaceInfo` is undefined:
```typescript
await cline.start({
config: {
extensions: [myPlugin],
extensionContext: {
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
},
},
})
```
The CLI sets this automatically, but SDK consumers must set it explicitly.
## send() Requires an Active Session
`cline.send()` only works on sessions that are still active. If a session has already completed, `send()` may return `undefined` or fail. Check session status with `cline.get(sessionId)` first.
## Result May Be Undefined
`session.result` can be `undefined` if the session was started but hasn't completed yet (e.g., in a non-blocking hub mode). Check for this:
```typescript
const session = await cline.start({ ... })
if (session.result) {
console.log(session.result.text)
} else {
console.log("Session started but not yet complete")
}
```
## Compaction and Long Sessions
For long-running sessions, message history grows and eventually exceeds the model's context window. ClineCore handles this via compaction, which summarizes older messages. Configure it via `compactionConfig`:
```typescript
config: {
compactionConfig: {
strategy: "summarize",
// ...
},
}
```
The default strategy works for most cases, but extremely long sessions may benefit from tuning.
## See Also
- `api.md` - Full API reference
- `patterns.md` - Common patterns
- `../agent/gotchas.md` - Agent-level gotchas
- `../tools/REFERENCE.md` - Tool troubleshooting
- `../providers/REFERENCE.md` - Provider troubleshooting
@@ -1,279 +0,0 @@
# ClineCore Patterns
## Basic Session with Built-in Tools
```typescript
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create({ clientName: "my-app" })
const session = await cline.start({
prompt: "Read package.json and summarize the dependencies",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
cwd: process.cwd(),
enableTools: true,
},
})
console.log(session.result?.text)
await cline.dispose()
```
## Streaming Session with UI Updates
```typescript
const cline = await ClineCore.create({ clientName: "my-app" })
cline.subscribe((event) => {
switch (event.type) {
case "chunk":
if (event.payload.type === "text") {
ui.appendText(event.payload.text)
}
break
case "ended":
ui.showComplete(event.payload.finishReason)
break
}
})
await cline.start({
prompt: "Refactor the auth module",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
cwd: "/path/to/project",
enableTools: true,
},
})
```
## Multi-Turn Session
```typescript
const cline = await ClineCore.create({ clientName: "my-app" })
const session = await cline.start({
prompt: "Create a new Express server",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
cwd: "/path/to/project",
enableTools: true,
},
})
// Follow-up
const result = await cline.send({
sessionId: session.sessionId,
prompt: "Now add a health check endpoint",
})
console.log(result?.text)
await cline.dispose()
```
## Tiered Permission Model
Auto-approve reads, require approval for writes:
```typescript
const cline = await ClineCore.create({
clientName: "my-app",
toolPolicies: {
read_files: { autoApprove: true },
search: { autoApprove: true },
fetch_web: { autoApprove: true },
bash: { autoApprove: false },
editor: { autoApprove: false },
apply_patch: { autoApprove: false },
},
capabilities: {
requestToolApproval: async (request) => {
const approved = await promptUser(
`Allow ${request.toolName}?\n${JSON.stringify(request.input, null, 2)}`
)
return { approved }
},
},
})
```
## Custom Tools Alongside Built-ins
```typescript
import { ClineCore, createTool } from "@cline/sdk"
import { z } from "zod"
const deployTool = createTool({
name: "deploy",
description: "Deploy the application to the specified environment.",
inputSchema: z.object({
environment: z.enum(["staging", "production"]),
}),
execute: async (input) => {
const result = await runDeployment(input.environment)
return { url: result.url, status: "deployed" }
},
})
const cline = await ClineCore.create({ clientName: "my-app" })
await cline.start({
prompt: "Deploy the app to staging",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
cwd: process.cwd(),
enableTools: true,
tools: [deployTool],
},
})
```
## Session with Plugins
Load plugins inline with `extensions` and provide workspace context so plugins can access `ctx.workspaceInfo`:
```typescript
import { ClineCore } from "@cline/sdk"
import myPlugin from "./my-plugin"
const cline = await ClineCore.create({
clientName: "my-app",
backendMode: "local",
})
await cline.start({
prompt: "Do the thing my plugin enables",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
cwd: process.cwd(),
enableTools: true,
extensions: [myPlugin],
extensionContext: {
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
},
},
})
await cline.dispose()
```
For directory-based plugin packages, use `pluginPaths` instead:
```typescript
config: {
pluginPaths: ["./my-cline-plugin"],
extensionContext: {
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
},
}
```
See `../plugins/REFERENCE.md` for the full plugin authoring guide.
## Session Listing and Replay
```typescript
const cline = await ClineCore.create({ clientName: "my-app" })
// List recent sessions
const sessions = await cline.list(10)
for (const session of sessions) {
console.log(`${session.id}: ${session.title}`)
}
// Read messages from a past session
const messages = await cline.readMessages(sessions[0].id)
for (const msg of messages) {
console.log(`[${msg.role}] ${msg.content}`)
}
// Check usage
const usage = await cline.getAccumulatedUsage(sessions[0].id)
console.log(`Total tokens: ${usage.aggregateUsage.totalInputTokens + usage.aggregateUsage.totalOutputTokens}`)
```
## Graceful Shutdown
```typescript
const cline = await ClineCore.create({ clientName: "my-app" })
process.on("SIGTERM", async () => {
await cline.dispose("SIGTERM received")
process.exit(0)
})
// Run sessions...
```
## Stateless Worker Pattern
For request/response workloads (API endpoints, queue consumers):
```typescript
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create({
clientName: "worker",
backendMode: "local",
})
async function handleRequest(prompt: string, workspace: string) {
const session = await cline.start({
prompt,
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
cwd: workspace,
enableTools: true,
},
})
return {
text: session.result?.text,
usage: session.result?.usage,
sessionId: session.sessionId,
}
}
```
## Hub-Backed Multi-Client
Multiple clients can attach to the same session:
```typescript
// Process 1: start session
const cline = await ClineCore.create({
clientName: "backend",
backendMode: "hub",
})
const session = await cline.start({
prompt: "Long running refactor task",
config: { ... },
})
// Process 2: attach and stream events
const viewer = await ClineCore.create({
clientName: "dashboard",
backendMode: "hub",
})
viewer.subscribe((event) => {
dashboard.render(event)
}, { sessionId: session.sessionId })
```
## See Also
- `api.md` - Full API reference
- `gotchas.md` - Common pitfalls
- `../tools/REFERENCE.md` - Tool creation
- `../plugins/REFERENCE.md` - Plugin system
- `../scheduling/REFERENCE.md` - Scheduled agents
@@ -1,269 +0,0 @@
# Events
The Cline SDK has three event layers. Which one you use depends on whether you're working with the standalone `Agent` class or `ClineCore`.
## Which Events Do I Get?
| If you use... | You subscribe with... | You receive... | Text streaming event |
|---|---|---|---|
| Standalone `Agent` | `agent.subscribe()` | `AgentRuntimeEvent` | `assistant-text-delta` |
| `ClineCore` | `cline.subscribe()` | `CoreSessionEvent` | `chunk` (with `payload.type === "text"`) |
These are different event types with different shapes. Do not mix them up.
## Layer 1: AgentRuntimeEvent (Standalone Agent)
Emitted by the `Agent` class via `agent.subscribe()`. This is what you get when using `new Agent(...)` directly. Every event includes a `snapshot` field with the current `AgentRuntimeStateSnapshot`.
### Run Lifecycle
```typescript
{ type: "run-started", snapshot }
{ type: "run-finished", snapshot, result: AgentRunResult }
{ type: "run-failed", snapshot, error: Error }
```
### Turns
```typescript
{ type: "turn-started", snapshot, iteration: number }
{ type: "turn-finished", snapshot, iteration: number, toolCallCount: number }
```
### Text Streaming
```typescript
// Streaming text delta (arrives as chunks during generation)
{ type: "assistant-text-delta", snapshot, iteration: number, text: string, accumulatedText: string }
// Streaming reasoning delta (when model uses extended thinking)
{ type: "assistant-reasoning-delta", snapshot, iteration: number, text: string }
// Complete assistant message after model finishes
{ type: "assistant-message", snapshot, iteration: number, message: AgentMessage, finishReason: string }
```
### Messages
```typescript
// Fired when any message (user or assistant) is added to conversation history
{ type: "message-added", snapshot, message: AgentMessage }
```
### Tool Events
```typescript
{ type: "tool-started", snapshot, toolCall: { toolName: string, toolCallId: string, input: unknown } }
{ type: "tool-updated", snapshot, toolCall: { toolName: string, toolCallId: string }, update: string }
{ type: "tool-finished", snapshot, toolCall: { toolName: string, toolCallId: string }, message: AgentMessage }
```
### Usage
```typescript
{
type: "usage-updated",
snapshot,
usage: {
inputTokens: number,
outputTokens: number,
cacheReadTokens?: number,
cacheWriteTokens?: number,
totalCost?: number,
},
}
```
### Notices
```typescript
{ type: "status-notice", snapshot, message: string, metadata?: Record<string, unknown> }
```
### Subscribing
Use `agent.subscribe()`. Register the listener before calling `run()` to avoid missing early events.
```typescript
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
systemPrompt: "You are a helpful assistant.",
tools: [],
})
agent.subscribe((event) => {
switch (event.type) {
case "assistant-text-delta":
process.stdout.write(event.text)
break
case "tool-started":
console.log(`\nUsing tool: ${event.toolCall.toolName}`)
break
case "usage-updated":
console.log(`Cost: $${event.usage.totalCost?.toFixed(4)}`)
break
case "run-finished":
console.log(`\nDone: ${event.result.status}`)
break
}
})
const result = await agent.run("Hello!")
```
You can also receive events through hooks (these are awaited, so they can be async):
```typescript
const agent = new Agent({
...config,
hooks: {
onEvent: async (event) => {
// Same AgentRuntimeEvent types as subscribe()
},
},
})
```
## Layer 2: AgentEvent (ClineCore Internal)
When using `ClineCore`, a `RuntimeEventAdapter` translates Layer 1 events into a legacy format called `AgentEvent`. You do not interact with this layer directly -- it is projected into `CoreSessionEvent` for subscribers. The key mappings:
| AgentRuntimeEvent (Layer 1) | AgentEvent (Layer 2) |
|---|---|
| `turn-started` | `iteration_start` |
| `turn-finished` | `iteration_end` |
| `assistant-text-delta` | `content_start` (text) |
| `assistant-message` | `content_end` (text) |
| `tool-started` | `content_start` (tool) |
| `tool-updated` | `content_update` (tool) |
| `tool-finished` | `content_end` (tool) |
| `usage-updated` | `usage` (with computed deltas) |
| `run-finished` | `done` |
| `run-failed` | `error` |
| `run-started`, `message-added` | (suppressed, not emitted) |
This layer exists for backwards compatibility. If you see event types like `content_update` or `iteration_start` in other documentation, they refer to this layer, not to what `agent.subscribe()` emits.
## Layer 3: CoreSessionEvent (ClineCore Subscriber)
Emitted by `ClineCore` via `cline.subscribe()`. These are higher-level session events.
```typescript
type CoreSessionEvent =
| { type: "chunk"; payload: SessionChunkEvent }
| { type: "agent_event"; payload: { sessionId: string, event: AgentEvent } }
| { type: "ended"; payload: SessionEndedEvent }
| { type: "team_progress"; payload: SessionTeamProgressEvent }
| { type: "status"; payload: { sessionId: string, status: string } }
| { type: "hook"; payload: SessionToolEvent }
```
### SessionChunkEvent
```typescript
interface SessionChunkEvent {
type: "text" | "reasoning"
text: string
sessionId: string
}
```
### SessionEndedEvent
```typescript
interface SessionEndedEvent {
sessionId: string
finishReason: "completed" | "max_iterations" | "aborted" | "mistake_limit" | "error"
result?: AgentResult
}
```
### Subscribing
```typescript
cline.subscribe((event) => {
switch (event.type) {
case "chunk":
if (event.payload.type === "text") {
process.stdout.write(event.payload.text)
}
break
case "ended":
console.log(`Finished: ${event.payload.finishReason}`)
break
}
})
```
Filter by session:
```typescript
cline.subscribe(handler, { sessionId: "specific-session-id" })
```
## Hub Events (Layer 3b)
When ClineCore runs in hub mode (via `backendMode: "hub"` or `"auto"` when a hub is available), events are projected over WebSocket using `HubEventName` types like `assistant.delta`, `iteration.started`, `tool.started`, etc. You do not interact with these directly -- `cline.subscribe()` still gives you `CoreSessionEvent` regardless of backend mode.
## Result Type Differences
The standalone Agent and ClineCore return different result types:
| API | Result type | Text property |
|---|---|---|
| `agent.run()` | `AgentRunResult` | `result.outputText` |
| `cline.start()` / `cline.send()` | `AgentResult` | `result.text` |
## Common Patterns
### Streaming Text (Standalone Agent)
```typescript
agent.subscribe((event) => {
if (event.type === "assistant-text-delta") {
process.stdout.write(event.text)
}
})
```
### Streaming Text (ClineCore)
```typescript
cline.subscribe((event) => {
if (event.type === "chunk" && event.payload.type === "text") {
process.stdout.write(event.payload.text)
}
})
```
### Usage Tracking (Standalone Agent)
```typescript
agent.subscribe((event) => {
if (event.type === "usage-updated" && event.usage.totalCost) {
console.log(`Running cost: $${event.usage.totalCost.toFixed(4)}`)
}
})
```
### Tool Call Logging (Standalone Agent)
```typescript
agent.subscribe((event) => {
if (event.type === "tool-started") {
console.log(`Tool started: ${event.toolCall.toolName}`)
}
if (event.type === "tool-finished") {
console.log(`Tool finished: ${event.toolCall.toolName}`)
}
})
```
## See Also
- `../agent/REFERENCE.md` - Agent runtime overview
- `../clinecore/REFERENCE.md` - ClineCore session management
- `../plugins/REFERENCE.md` - Plugin hooks for lifecycle events
- `../production/REFERENCE.md` - Observability in production
@@ -1,157 +0,0 @@
# Multi-Agent Coordination
The Cline SDK supports two models for multi-agent work: sub-agents (parent-child) and teams (peer-to-peer).
## Sub-Agents vs Teams
| Feature | Sub-Agents | Teams |
|---------|-----------|-------|
| Enable with | `enableSpawnAgent: true` | `enableAgentTeams: true` |
| Persistence | Session-scoped only | Across sessions |
| Coordination | Parent-child hierarchy | Peer-to-peer |
| Shared state | None | Task board, mailbox, mission log |
| Best for | One-off delegation | Complex multi-session projects |
## Sub-Agents
Sub-agents are spawned by a parent agent during a run. They execute independently and report results back.
### Enabling Sub-Agents
```typescript
const cline = await ClineCore.create({ clientName: "my-app" })
await cline.start({
prompt: "Refactor the auth module and update tests",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
enableSpawnAgent: true,
enableTools: true,
},
})
```
When `enableSpawnAgent` is true, the agent gets access to sub-agent tools:
| Tool | Description |
|------|-------------|
| `start_subagent` | Spawn a background agent with a task |
| `message_subagent` | Send a message to a running sub-agent |
| `handoff_to_agent` | Delegate the current task entirely |
| `submit_and_exit` | Signal completion |
### How Sub-Agents Work
1. The parent agent decides a subtask can be delegated
2. It calls `start_subagent` with a role, task description, and optionally a preset
3. The sub-agent runs independently in the background
4. The parent can check status or send follow-up messages
5. Sub-agent results are available to the parent when complete
## Teams
Teams provide persistent, cross-session coordination between agents.
### Enabling Teams
```typescript
await cline.start({
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
enableAgentTeams: true,
teamName: "auth-sprint",
enableTools: true,
},
})
```
### Team Tools
When `enableAgentTeams` is true, the coordinator agent gets:
| Tool | Description |
|------|-------------|
| `team_spawn_teammate` | Create a new agent with a role and task |
| `team_delegate_task` | Assign a task to an existing teammate |
| `team_check_status` | Check on a delegated task's progress |
| `team_get_result` | Get the completed result from a teammate |
### Team Persistence
Teams store shared state in:
```
~/.cline/data/teams/[team-name]/
task-board.json # task assignments and status
mailbox.json # inter-agent messages
mission-log.json # coordination log
```
This state persists across sessions, so team members can pick up where they left off.
### CLI Team Access
```bash
cline --team-name auth-sprint "Continue the auth refactor"
```
## Choosing Between Sub-Agents and Teams
Use sub-agents when:
- You need one-off parallel execution within a single session
- Tasks are independent and don't need to communicate with each other
- Results only matter to the parent agent
Use teams when:
- Work spans multiple sessions over time
- Agents need to coordinate and share progress
- Tasks have dependencies between them
- You want a persistent record of multi-agent collaboration
## Patterns
### Parallel Research with Sub-Agents
A parent agent spawns multiple sub-agents to research different topics simultaneously:
```typescript
await cline.start({
prompt: `Research these three topics in parallel:
1. Current best practices for JWT auth
2. OAuth 2.0 provider comparison
3. Session management patterns
Spawn a sub-agent for each topic, then synthesize the results.`,
config: {
enableSpawnAgent: true,
enableTools: true,
// ...
},
})
```
### Team Sprint
A coordinator manages a multi-session project:
```typescript
await cline.start({
prompt: `You are the coordinator for the auth-sprint team.
Review the task board and delegate the next highest-priority task
to a teammate. Check status on any in-progress tasks.`,
config: {
enableAgentTeams: true,
teamName: "auth-sprint",
enableTools: true,
// ...
},
})
```
## See Also
- `../clinecore/REFERENCE.md` - ClineCore runtime
- `../clinecore/api.md` - Session config for teams
- `../tools/REFERENCE.md` - Tool system
- `../plugins/REFERENCE.md` - Plugin system
@@ -1,649 +0,0 @@
# Plugins
A Cline plugin is a TypeScript module that extends any agent built on the Cline SDK. The same plugin runs in the Cline CLI, VS Code and JetBrains extensions, and any custom app built on `@cline/core`.
A plugin can:
- Register tools the model can call.
- Hook into the agent loop before/after runs, model calls, and tool calls.
- Rewrite provider messages before they hit the model (custom compaction, redaction, context shaping).
- Register slash commands, prompt rules, providers, and automation event types.
A plugin ships in one of two shapes:
1. Single-file plugin -- one `.ts` file that exports a default plugin object. Drop it in a discovery folder and it loads.
2. Plugin package -- a directory with `package.json`, npm dependencies, and optionally bundled assets. Installable via `cline plugin install`.
Both shapes use the same plugin API.
## The Mental Model
When the host starts a session, it builds a registry of plugins and runs four phases:
1. resolve -- collect the plugin objects.
2. validate -- check each plugin's `manifest`. Capabilities must be non-empty; declared hook stages must have matching handlers; if `hooks` is present, `"hooks"` must be in `capabilities`.
3. setup -- call each plugin's `setup(api, ctx)` once. This is where you `registerTool`, `registerCommand`, etc.
4. activate -- registry is frozen, the agent loop starts, and your hooks/tools are live.
Two invariants the registry enforces:
- Every contribution requires a matching capability. Calling `api.registerRule(...)` without `"rules"` in `manifest.capabilities` throws.
- Capabilities and handlers must agree. Declaring `"hooks"` without a `hooks` object, or vice versa, fails validation.
After validation, registration is one-shot -- no dynamic register/unregister during the session.
## The Smallest Working Plugin
```typescript
import type { AgentPlugin } from "@cline/core"
import { createTool } from "@cline/core"
const plugin: AgentPlugin = {
name: "hello-plugin",
manifest: {
capabilities: ["tools"],
},
setup(api, ctx) {
api.registerTool(
createTool({
name: "say_hello",
description: "Greet a person by name.",
inputSchema: {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
},
async execute({ name }: { name: string }) {
return { greeting: `Hello, ${name}!` }
},
}),
)
},
}
export default plugin
```
The agent will see `say_hello` as a callable tool.
## The Manifest
```typescript
manifest: {
capabilities: ["tools", "hooks"], // required, non-empty array
paths?: string[], // optional, multi-entry packages
providerIds?: string[], // optional, provider plugins
modelIds?: string[], // optional, model plugins
}
```
### The Complete Capability List
| Capability | What It Unlocks in `api` |
|-----------|--------------------------|
| `"tools"` | `api.registerTool()` |
| `"commands"` | `api.registerCommand()` (slash commands in chat surfaces) |
| `"rules"` | `api.registerRule()` (string injected into the system prompt) |
| `"messageBuilders"` | `api.registerMessageBuilder()` (rewrites provider-bound messages) |
| `"providers"` | `api.registerProvider()` (custom model provider) |
| `"automationEvents"` | `api.registerAutomationEventType()` and `ctx.automation?.ingestEvent()` |
| `"hooks"` | The runtime `hooks` object on the plugin (lifecycle callbacks) |
You declare any combination -- most real plugins need 1-3 capabilities.
## setup(api, ctx) -- The Registration Phase
`setup()` runs once per session before the agent loop starts. Everything you register here is frozen for the lifetime of the session.
### The api Object
Each `register*` method requires the matching capability in your manifest:
```typescript
api.registerTool(tool) // requires "tools"
api.registerCommand({ name, description, handler }) // requires "commands"
api.registerRule({ id, content, source }) // requires "rules"
api.registerMessageBuilder({ name, build }) // requires "messageBuilders"
api.registerProvider({ name, description }) // requires "providers"
api.registerAutomationEventType({ eventType, source }) // requires "automationEvents"
```
### The ctx Object -- Host-Provided Session Context
The second argument carries everything the host knows about the current session. All fields are optional, so feature-detect before using them -- the same plugin must work in hosts that supply less context (unit tests, sandboxed plugin processes).
```typescript
ctx.session?.sessionId // string, stable core session id
ctx.client?.name // host: "cline-cli", "cline-vscode", etc.
ctx.user // authenticated user/org info, when available
ctx.workspaceInfo // { rootPath, hint, latestGitBranchName,
// latestGitCommitHash, associatedRemoteUrls }
ctx.automation?.ingestEvent // emit normalized automation events
ctx.logger?.log // structured logger scoped to this plugin
ctx.telemetry // ITelemetryService, only present in-process
```
Two rules about `ctx.workspaceInfo`:
1. Always prefer `ctx.workspaceInfo?.rootPath` over `process.cwd()`. The CLI may have been launched with `--cwd` without calling `chdir`, and VS Code workspaces don't share a single CWD. `workspaceInfo` is sourced from the session config and is always correct.
2. Don't use `import.meta.url` tricks to find "the workspace". That gives you the plugin's own location, not the user's project.
### Persisting State Across Hooks
`setup()` runs first; hooks fire later. The simplest way to share state is module-level variables:
```typescript
let sessionWorkspaceRoot: string | undefined
let sessionBranch: string | undefined
const plugin: AgentPlugin = {
name: "metrics",
manifest: { capabilities: ["hooks"] },
setup(api, ctx) {
sessionWorkspaceRoot = ctx.workspaceInfo?.rootPath
sessionBranch = ctx.workspaceInfo?.latestGitBranchName
},
hooks: {
beforeTool({ toolCall, input }) {
if (sessionBranch === "main" && toolCall.toolName === "run_commands") {
// inspect input, optionally block
}
return undefined
},
},
}
```
A single Node process may host multiple sessions concurrently. If your plugin will run in a multi-session host, key your state by `ctx.session?.sessionId`:
```typescript
const stateBySession = new Map<string, MyState>()
setup(api, ctx) {
const id = ctx.session?.sessionId
if (id) stateBySession.set(id, /* ... */)
}
```
## Runtime Hooks
Runtime hooks are typed in-process callbacks on the same hook layer the runtime uses internally. They run inside the agent loop with full type information -- no IPC, no JSON marshaling.
Declare `"hooks"` in `manifest.capabilities`, then add a `hooks` property:
```typescript
const plugin: AgentPlugin = {
name: "metrics",
manifest: { capabilities: ["hooks"] },
hooks: {
beforeRun(ctx) { /* ... */ },
beforeTool({ toolCall, input }) { /* ... */ },
afterTool({ toolCall, result }) { /* ... */ },
afterRun({ result }) { /* ... */ },
onEvent(event) { /* ... */ },
},
}
```
### The Seven Hooks
| Hook | Fires | Can Stop the Loop? | Common Uses |
|------|-------|--------------------|-------------|
| `beforeRun` | Before the runtime loop starts | Yes | Greet, log, attach session metadata |
| `afterRun` | After the runtime loop finishes (success, abort, or fail) | No | Notifications, metrics, persistent logs |
| `beforeModel` | Before each model request | Yes (mutate req) | Inject context, last-mile prompt edits |
| `afterModel` | After each model response, before tool execution | Yes | Block based on model output |
| `beforeTool` | Before each tool execution | Yes (`{ stop }`) | Audit, redact, block dangerous tools |
| `afterTool` | After each tool execution | Can replace result | Post-process, redact secrets in tool output |
| `onEvent` | On every `AgentRuntimeEvent` emitted by the runtime | No | Streaming UIs, telemetry pipes |
### Stopping the Loop from a Hook
Several hooks return an optional control object. The most common pattern is `beforeTool` blocking a destructive tool call:
```typescript
beforeTool({ toolCall, input }) {
if (toolCall.toolName === "run_commands") {
const { commands } = input as { commands?: string[] }
if (sessionBranch === "main" && commands?.some(c => c.startsWith("git push"))) {
return { stop: true, reason: "Blocked git push on protected branch" }
}
}
return undefined // explicit "continue"
}
```
Returning `undefined` (or omitting `return`) lets execution continue normally.
### afterRun Semantics
`afterRun` fires for every terminal status -- `completed`, `aborted`, `failed`. If you only want to act on success:
```typescript
afterRun({ result }) {
if (result.status !== "completed") return
// notify, log success metrics, etc.
}
```
### Plugin Hooks vs File Hooks
The runtime supports two hook systems:
- File hooks -- external scripts in `.cline/hooks/` invoked with serialized JSON. Right for user/workspace-specific scripts that don't ship with code.
- Plugin runtime hooks -- typed in-process callbacks. Right when the behavior belongs to a reusable extension and needs typed access to the runtime.
Core adapts file hooks onto the runtime hook layer, so you don't need both. If you're shipping a plugin, write it as runtime hooks.
## Message Builders
Message builders rewrite the provider-bound message list before the model call. They run after runtime messages are converted into SDK message blocks but before core's built-in safety builder.
Use them for:
- Custom compaction policies (replace middle history with a summary).
- Redacting PII or secrets before they reach the provider.
- Reshaping context for a specific model's strengths.
```typescript
api.registerMessageBuilder({
name: "summarize-middle-history",
build(messages) {
if (estimateTokens(messages) < THRESHOLD) return messages
return [...prefix, summary, ...recent]
},
})
```
Multiple builders run in registration order; the output of one is the input of the next.
When to use `beforeModel` instead: reach for the `beforeModel` hook only if you need the runtime snapshot or want to mutate the request object itself. Pure message rewrites belong in a builder.
## Automation Events
Plugins can declare normalized event types and emit them into Cline automation. Hosts that don't have automation enabled simply ignore both -- feature-detect `ctx.automation`.
```typescript
manifest: { capabilities: ["automationEvents"] },
setup(api, ctx) {
api.registerAutomationEventType({
eventType: "github.pull_request.opened",
source: "github",
description: "A new GitHub PR was opened",
attributesSchema: { /* JSON Schema for envelope.attributes */ },
})
if (!ctx.automation) return // host has no automation
ctx.automation.ingestEvent({
eventId: "pr-1234",
eventType: "github.pull_request.opened",
source: "github",
subject: "owner/repo#1234",
occurredAt: new Date().toISOString(),
attributes: { /* ... */ },
})
}
```
## Loading a Plugin
There are three ways a plugin gets into a session:
### Auto-Discovery (CLI)
The CLI scans these directories on startup:
- `<workspace>/.cline/plugins/` -- project-scoped plugins.
- `~/.cline/plugins/` -- user-scoped plugins.
Drop a `.ts` or `.js` file in, run `cline`, done:
```bash
mkdir -p .cline/plugins
cp my-plugin.ts .cline/plugins/
cline -i "do the thing my plugin enables"
```
### Explicit extensions in SDK Config
When you build your own host with `ClineCore`, pass the plugin object directly:
```typescript
import plugin from "./my-plugin"
import { ClineCore } from "@cline/core"
const host = await ClineCore.create({ backendMode: "local" })
await host.start({
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY ?? "",
cwd: process.cwd(),
enableTools: true,
systemPrompt: "You are a helpful assistant.",
extensions: [plugin],
extensionContext: {
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
},
},
prompt: "...",
interactive: false,
})
```
### pluginPaths for Directory-Based Plugins
When the plugin is a directory with `package.json`, point `pluginPaths` at the directory:
```typescript
config: {
pluginPaths: ["./path/to/my-plugin-package"],
}
```
Or install with the CLI:
```bash
cline plugin install ./path/to/my-plugin-package
cline plugin install @scope/my-cline-plugin # from npm
cline plugin install --git github.com/owner/repo # from git
```
## Single-File Plugin Template
Save as `my-plugin.ts`, drop in `.cline/plugins/`:
```typescript
import { type AgentPlugin, ClineCore, createTool } from "@cline/core"
let sessionRoot: string | undefined
const plugin: AgentPlugin = {
name: "my-plugin",
manifest: {
capabilities: ["tools", "hooks"],
},
setup(api, ctx) {
sessionRoot = ctx.workspaceInfo?.rootPath
api.registerTool(
createTool({
name: "do_thing",
description: "Do the thing this plugin exists for.",
inputSchema: {
type: "object",
properties: { target: { type: "string" } },
required: ["target"],
},
async execute(input) {
const { target } = input as { target: string }
return { ok: true, target, root: sessionRoot }
},
}),
)
},
hooks: {
beforeRun() {
console.log("[my-plugin] run started")
},
afterRun({ result }) {
if (result.status !== "completed") return
console.log(`[my-plugin] done in ${result.iterations} iteration(s)`)
},
},
}
async function runDemo(): Promise<void> {
const host = await ClineCore.create({ backendMode: "local" })
try {
const result = await host.start({
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY ?? "",
cwd: process.cwd(),
enableTools: true,
systemPrompt: "You are a helpful assistant. Use tools when needed.",
extensions: [plugin],
extensionContext: {
workspace: { rootPath: process.cwd(), cwd: process.cwd() },
},
},
prompt: "Use do_thing on the target 'world'.",
interactive: false,
})
console.log(result.result?.text ?? "")
} finally {
await host.dispose()
}
}
if (import.meta.main) {
await runDemo()
}
export { plugin, runDemo }
export default plugin
```
Copy it, rename the tool, swap in your logic. The `runDemo()` function lets you test with `ANTHROPIC_API_KEY=sk-... bun run my-plugin.ts`.
## Plugin Package
Use a plugin package when you need npm dependencies, multiple entry points, bundled assets, or npm/git distribution.
### Layout
```
my-cline-plugin/
+-- package.json
+-- tsconfig.json (optional, for local typechecking)
+-- index.ts (the plugin entry point)
+-- README.md
+-- assets/ (optional, bundled content)
+-- templates/
+-- schemas/
```
### package.json -- The Discovery Contract
```json
{
"name": "my-cline-plugin",
"version": "0.1.0",
"private": true,
"description": "What this plugin does, in one sentence.",
"type": "module",
"exports": {
".": "./index.ts"
},
"cline": {
"plugins": [
{
"paths": ["./index.ts"],
"capabilities": ["tools", "hooks"]
}
]
},
"peerDependencies": {
"@cline/core": "*"
},
"peerDependenciesMeta": {
"@cline/core": { "optional": true }
},
"dependencies": {
"zod": "^4.1.5"
}
}
```
Key fields:
- `type: "module"` -- required. Cline plugins are ES modules.
- `cline.plugins` -- the discovery contract. Array of entries, each with `paths` (entry files) and `capabilities` (pre-declared, validated before importing).
- `peerDependencies` for `@cline/core` -- the host already provides it. Marking it optional lets you typecheck in isolation.
### Bundling Assets
Resolve asset paths with `import.meta.url`, not `process.cwd()`:
```typescript
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
import { readFileSync, existsSync } from "node:fs"
const MODULE_DIR = dirname(fileURLToPath(import.meta.url))
const TEMPLATES_DIR = join(MODULE_DIR, "assets", "templates")
function loadTemplate(name: string): string | undefined {
const path = join(TEMPLATES_DIR, `${name}.md`)
return existsSync(path) ? readFileSync(path, "utf8") : undefined
}
```
This is the only place `import.meta.url` is appropriate in a plugin -- locating files inside the plugin package. For workspace paths, always use `ctx.workspaceInfo?.rootPath`.
### The Override Pattern (Bundled / Global / Project)
A package can ship default assets and let users override them. The convention is a three-tier lookup, last write wins by `name`:
1. bundled -- files inside the plugin package (defaults shipped with the plugin).
2. global -- files under `~/.cline/data/settings/<kind>/` (user overrides).
3. project -- files under `<workspace>/.cline/<kind>/` (project overrides).
### Multiple Plugin Entries
If your package exposes more than one plugin, list each in `cline.plugins`:
```json
"cline": {
"plugins": [
{ "paths": ["./tools-plugin.ts"], "capabilities": ["tools"] },
{ "paths": ["./hooks-plugin.ts"], "capabilities": ["hooks"] }
]
}
```
Each entry file should `export default` its own plugin object.
## Testing Your Plugin
### Unit Tests
The plugin object is plain data. Drive `setup()` against a minimal context and exercise tools directly:
```typescript
import plugin from "../my-plugin"
const tools: unknown[] = []
const api = {
registerTool: (t: unknown) => tools.push(t),
registerCommand: () => {},
registerRule: () => {},
registerMessageBuilder: () => {},
registerProvider: () => {},
registerAutomationEventType: () => {},
}
await plugin.setup?.(api as never, {
workspaceInfo: { rootPath: "/tmp/fake-workspace" },
})
// Now `tools` contains the registered tools -- call tool.execute(input, ctx)
```
### End-to-End with runDemo()
Add a `runDemo()` in your plugin file (see the single-file template above) that boots a real `ClineCore` session:
```bash
ANTHROPIC_API_KEY=sk-... bun run my-plugin.ts
```
### CLI Smoke Test
```bash
mkdir -p .cline/plugins
cp my-plugin.ts .cline/plugins/
cline -i "trigger something that exercises the plugin"
```
For packages:
```bash
cline plugin install ./my-cline-plugin
cline -i "..."
```
If the plugin fails validation or setup, the CLI prints a clear error and continues without it.
## Common Gotchas
- "capabilities must be a non-empty array" -- you forgot `manifest.capabilities`, or it's `[]`.
- "registerRule requires the 'rules' capability" -- capability/handler drift. Add `"rules"` to capabilities, or stop calling `registerRule`.
- Tool not visible to the model -- check `enableTools: true` on the session config, and that you're declaring `"tools"` in capabilities.
- `ctx.workspaceInfo` is undefined in SDK tests -- the host didn't pass `extensionContext.workspace`. In SDK code, set it explicitly (see the ClineCore loading example above).
- State leaking across sessions -- module-level variables are shared across sessions in the same process. Key by `ctx.session?.sessionId` if your host runs multiple sessions concurrently.
- `afterRun` firing on aborts -- guard with `if (result.status !== "completed") return`.
- Heavy work in `setup()` -- `setup()` blocks session start. Defer expensive work into the first tool call or `beforeRun`.
- Importing host internals -- only import from `@cline/core`. Reaching into host-specific packages (e.g. CLI internals) will break in non-CLI hosts.
- Sandboxed plugins and `telemetry` -- telemetry is process-local. Feature-detect `ctx.telemetry` and expect it to be undefined in sandboxed plugin processes.
- Resolving bundled assets -- use `import.meta.url` + `fileURLToPath` to find files inside your package; never `process.cwd()`. For workspace paths, do the opposite: use `ctx.workspaceInfo?.rootPath`, never `import.meta.url`.
- Plugin name collisions -- `name` must be unique within a session. If two plugins share a name, validation fails. Namespace by package (`my-org-redactor`, not `redactor`).
## Decision Guide -- Which Extension Point?
| You want to... | Use |
|----------------|-----|
| Give the model a new capability | `registerTool` |
| Add a slash command in chat surfaces | `registerCommand` |
| Inject text into the system prompt | `registerRule` |
| Rewrite messages before they hit the provider | `registerMessageBuilder` |
| Add a custom model provider | `registerProvider` |
| Emit normalized cron/webhook events | `registerAutomationEventType` + `ctx.automation` |
| Observe or steer the agent loop | `hooks.*` |
| Block a dangerous tool call | `hooks.beforeTool` returning `{ stop: true }` |
| Notify on completion | `hooks.afterRun` (gate on `status === "completed"`) |
| Tweak each model request | `hooks.beforeModel` |
| Stream events to a UI | `hooks.onEvent` |
| Ship reusable templates with the plugin | Bundle assets next to `index.ts`, resolve via `import.meta.url` |
| Let users override defaults globally or per-project | Three-tier lookup: bundled / global / project |
## Pre-Ship Checklist
- `manifest.capabilities` is a non-empty array.
- Every `api.register*` call has a matching capability declared.
- If `hooks` is present, `"hooks"` is in `capabilities`.
- `ctx.workspaceInfo?.rootPath` is used for workspace paths (not `process.cwd()`).
- Optional `ctx` fields are feature-detected.
- Tool names are snake_case verbs; descriptions are written for the model.
- Tool inputs have JSON Schema with `required` set.
- `afterRun` handlers gate on `result.status === "completed"` if they only want successes.
- State that must not leak between concurrent sessions is keyed by `ctx.session?.sessionId`.
- (Package) `package.json` has `type: "module"`, `cline.plugins`, and `@cline/core` as an optional peer dep.
- (Package) Bundled assets resolved via `import.meta.url`, not `process.cwd()`.
- Smoke test: drop the plugin into `.cline/plugins/` (or `cline plugin install`), run `cline -i "..."`, watch it work.
## Plugin Examples from SDK
The SDK repo includes these example plugins:
| Plugin | Description |
|--------|-------------|
| `weather-metrics.ts` | Tool registration + lifecycle metrics |
| `mac-notify.ts` | macOS Notification Center alerts |
| `custom-compaction.ts` | Custom message compaction via message builders |
| `background-terminal.ts` | Detached shell job management |
| `automation-events.ts` | Plugin-emitted automation events |
| `gitignore-read-files-guard.ts` | File access policy enforcement via beforeTool |
| `web-search.ts` | Web search via Exa API |
| `typescript-lsp/` | TypeScript Language Service tools (plugin package) |
| `agents-squad/` | Multi-agent team orchestration (plugin package) |
## See Also
- `../tools/REFERENCE.md` - Tool creation
- `../events/REFERENCE.md` - Event system
- `../agent/REFERENCE.md` - Using plugins with Agent
- `../clinecore/REFERENCE.md` - Using plugins with ClineCore
@@ -1,253 +0,0 @@
# Going to Production
Guidelines for deploying Cline SDK agents in production environments.
## Error Handling
Always check the result status:
```typescript
const result = await agent.run(input)
switch (result.status) {
case "completed":
console.log("Success:", result.outputText)
break
case "aborted":
console.log("Cancelled:", result.error?.message)
break
case "failed":
console.error("Failed:", result.error)
break
}
```
For ClineCore, check `finishReason`:
```typescript
const session = await cline.start({ ... })
switch (session.result?.finishReason) {
case "completed":
// normal completion
break
case "max_iterations":
// agent hit iteration limit
break
case "aborted":
// manually cancelled
break
case "mistake_limit":
// too many tool errors
break
case "error":
// unrecoverable error
break
}
```
## Cost Control
### Token Limits
Set maximum tokens per turn and iteration limits:
```typescript
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
maxTokensPerTurn: 4096,
maxIterations: 10,
tools: [...],
})
```
### Model Selection
Use cheaper models for simple tasks:
```typescript
// Simple classification or formatting
{ providerId: "anthropic", modelId: "claude-haiku-4-5" }
// Complex reasoning and code generation
{ providerId: "anthropic", modelId: "claude-sonnet-4-6" }
// Hardest tasks requiring deep reasoning
{ providerId: "anthropic", modelId: "claude-opus-4-7" }
```
### Usage Tracking
Monitor spending in real time:
```typescript
agent.subscribe((event) => {
if (event.type === "usage-updated" && event.usage.totalCost) {
if (event.usage.totalCost > MAX_BUDGET) {
agent.abort("Budget exceeded")
}
}
})
```
## Observability
### OpenTelemetry Integration
The SDK supports OpenTelemetry for traces, metrics, and logs:
```typescript
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create({
clientName: "my-app",
// OpenTelemetry config is picked up from environment
// OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_SERVICE_NAME, etc.
})
```
### Structured Logging
Use the `BasicLogger` interface for injectable logging:
```typescript
import type { BasicLogger } from "@cline/sdk"
const logger: BasicLogger = {
debug: (msg, meta) => console.debug(msg, meta),
log: (msg, meta) => console.log(msg, meta),
error: (msg, meta) => console.error(msg, meta),
}
await cline.start({
config: {
logger,
// ...
},
})
```
### Custom Metrics via Plugins
```typescript
const metricsPlugin: AgentPlugin = {
name: "metrics",
manifest: { capabilities: ["hooks"] },
setup() {},
hooks: {
beforeRun() {
metrics.increment("agent.runs.started")
},
afterRun({ result }) {
metrics.increment("agent.runs.completed")
metrics.histogram("agent.iterations", result.iterations)
metrics.histogram("agent.tokens.output", result.usage.outputTokens)
},
beforeTool({ toolCall }) {
metrics.increment(`agent.tools.${toolCall.toolName}`)
},
},
}
```
## Security
### Sandbox Tool Execution
Validate tool inputs to prevent path traversal and injection:
```typescript
execute: async (input) => {
const safePath = path.resolve(WORKSPACE_ROOT, input.path)
if (!safePath.startsWith(WORKSPACE_ROOT)) {
return { error: "Path traversal attempt blocked" }
}
return await readFile(safePath, "utf-8")
}
```
### API Key Management
- Use environment variables, never hardcode keys
- Rotate keys regularly
- Use different keys for development and production
```typescript
{
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY, // never a literal string
}
```
### Tool Policy Hardening
Disable tools you don't need and require approval for dangerous ones:
```typescript
toolPolicies: {
read_files: { autoApprove: true },
search: { autoApprove: true },
bash: { autoApprove: false }, // require approval
editor: { autoApprove: false },
apply_patch: { autoApprove: false },
fetch_web: { enabled: false }, // disable entirely
}
```
## Deployment Patterns
### Stateless Worker
For request/response workloads (API endpoints, queue consumers):
```typescript
const cline = await ClineCore.create({
clientName: "worker",
backendMode: "local",
})
app.post("/agent", async (req, res) => {
const session = await cline.start({
prompt: req.body.prompt,
config: { ... },
})
res.json({ text: session.result?.text, usage: session.result?.usage })
})
```
### Persistent Service
For long-running services with session management:
```typescript
const cline = await ClineCore.create({
clientName: "service",
backendMode: "hub",
})
process.on("SIGTERM", async () => {
await cline.dispose("SIGTERM")
process.exit(0)
})
```
### Scheduled Automation
See `../scheduling/REFERENCE.md` for recurring agent tasks.
## Retry and Resilience
- Tool `execute` functions support `retryable: true` (default) and `maxRetries: 3` (default)
- Provider API calls are retried automatically on transient failures
- Use `timeoutMs` on tools to prevent hanging
- Monitor `mistake_limit` finish reason to detect systematic tool failures
## See Also
- `../agent/REFERENCE.md` - Agent overview
- `../clinecore/REFERENCE.md` - ClineCore overview
- `../tools/REFERENCE.md` - Tool configuration
- `../plugins/REFERENCE.md` - Metrics plugins
- `../scheduling/REFERENCE.md` - Scheduled agents
@@ -1,257 +0,0 @@
# Model Providers
The Cline SDK supports every major LLM provider out of the box via `@cline/llms`.
## Supported Providers
| Provider ID | Models |
|-------------|--------|
| `"anthropic"` | Claude Opus 4.7, Sonnet 4.6, Haiku 4.5 |
| `"openai"` | GPT-5.5, GPT-5.3 Codex |
| `"gemini"` | Gemini 3.1 Pro Preview, Gemini 3 Flash Preview |
| `"vertex"` | Google models via Vertex AI |
| `"bedrock"` | Claude, Llama via AWS Bedrock |
| `"mistral"` | Mistral Large, Codestral |
| `"openai-compatible"` | vLLM, Together, Fireworks, Groq, etc. |
## Basic Configuration
### With Agent
```typescript
import { Agent } from "@cline/sdk"
const agent = new Agent({
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
systemPrompt: "You are a helpful assistant.",
tools: [],
})
```
### With ClineCore
```typescript
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create({ clientName: "my-app" })
await cline.start({
prompt: "Hello",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
},
})
```
## Provider-Specific Configuration
### Anthropic
```typescript
{
providerId: "anthropic",
modelId: "claude-opus-4-7", // or "claude-sonnet-4-6", "claude-haiku-4-5"
apiKey: process.env.ANTHROPIC_API_KEY,
}
```
### OpenAI
```typescript
{
providerId: "openai",
modelId: "gpt-5.5",
apiKey: process.env.OPENAI_API_KEY,
}
```
### Google (Gemini)
```typescript
{
providerId: "gemini",
modelId: "gemini-3.1-pro-preview",
apiKey: process.env.GOOGLE_API_KEY,
}
```
### Google (Vertex AI)
```typescript
{
providerId: "vertex",
modelId: "gemini-3.1-pro-preview",
// Uses application default credentials or service account
}
```
### AWS Bedrock
```typescript
{
providerId: "bedrock",
modelId: "anthropic.claude-sonnet-4-6",
// Uses AWS credential chain (env vars, config file, IAM role)
// Set AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
}
```
### Mistral
```typescript
{
providerId: "mistral",
modelId: "mistral-large-latest",
apiKey: process.env.MISTRAL_API_KEY,
}
```
### OpenAI-Compatible
For any provider with an OpenAI-compatible API:
```typescript
{
providerId: "openai-compatible",
modelId: "my-model",
apiKey: process.env.API_KEY,
baseUrl: "https://api.together.xyz/v1",
}
```
Works with: vLLM, Together AI, Fireworks, Groq, Ollama, LiteLLM, etc.
## Custom Base URL
Override the API endpoint for any provider:
```typescript
{
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.API_KEY,
baseUrl: "https://my-proxy.example.com/v1",
}
```
## Custom Headers
Pass additional headers to API requests:
```typescript
{
providerId: "openai",
modelId: "gpt-5.5",
apiKey: process.env.API_KEY,
headers: {
"X-Custom-Header": "value",
},
}
```
## Gateway API
For advanced multi-provider setups, use the Gateway directly:
```typescript
import { createGateway, DefaultGateway } from "@cline/llms"
const gateway = createGateway({
providerConfigs: [
{ providerId: "anthropic", apiKey: process.env.ANTHROPIC_API_KEY },
{ providerId: "openai", apiKey: process.env.OPENAI_API_KEY },
],
})
// Create a model for a specific provider
const model = gateway.createAgentModel({
providerId: "anthropic",
modelId: "claude-opus-4-7",
})
// Use with Agent
const agent = new Agent({ model, systemPrompt: "...", tools: [] })
```
### Gateway Methods
```typescript
gateway.registerProvider(registration) // add a custom provider
gateway.configureProvider(config) // update provider settings
gateway.listProviders() // list available providers
gateway.listModels(providerId?) // list available models
gateway.createAgentModel(selection) // create model for agent
gateway.stream(request) // raw streaming (AsyncIterable)
```
## Provider Registry
Query and register providers programmatically:
```typescript
import {
getAllProviders,
getProviderIds,
getProvider,
getModelsForProvider,
registerProvider,
registerModel,
createHandler,
} from "@cline/llms"
// List all registered providers
const providers = getAllProviders()
// Get models for a provider
const models = getModelsForProvider("anthropic")
// Register a custom provider
registerProvider({
id: "my-provider",
name: "My Custom Provider",
handler: createHandler({ ... }),
})
```
## Model Metadata
Access model info (context window, pricing, capabilities):
```typescript
import { getModelsForProvider } from "@cline/llms"
const models = getModelsForProvider("anthropic")
for (const model of models) {
console.log(`${model.id}: context=${model.contextWindow}, input=$${model.inputPrice}/MTok`)
}
```
## Cost Tracking
Track per-request and cumulative costs:
```typescript
// Via events
agent.subscribe((event) => {
if (event.type === "usage-updated") {
console.log(`Cost: $${event.usage.totalCost?.toFixed(4)}`)
}
})
// Via result
const result = await agent.run("...")
console.log(`Total cost: $${result.usage.totalCost?.toFixed(4)}`)
// Via ClineCore accumulated usage
const usage = await cline.getAccumulatedUsage(sessionId)
```
## See Also
- `../agent/REFERENCE.md` - Using providers with Agent
- `../clinecore/REFERENCE.md` - Using providers with ClineCore
- `../production/REFERENCE.md` - Cost control in production
@@ -1,227 +0,0 @@
# Scheduling and Automation
The Cline SDK supports scheduled, one-off, and event-driven agent execution through the automation subsystem in `@cline/core`.
## Overview
Three trigger types:
| Trigger | Description |
|---------|-------------|
| `schedule` | Recurring jobs via cron expressions |
| `one_off` | Single execution tasks |
| `event` | Triggered by external events (GitHub, Linear, custom) |
## CLI Schedule Management
```bash
# Create a recurring schedule
cline schedule create "Daily standup" \
--cron "0 9 * * MON-FRI" \
--prompt "Summarize open PRs and blockers" \
--workspace /path/to/project \
--model anthropic/claude-sonnet-4-6
# List schedules
cline schedule list
# Trigger a schedule immediately
cline schedule trigger <schedule-id>
# Pause/resume
cline schedule pause <schedule-id>
cline schedule resume <schedule-id>
# Delete
cline schedule delete <schedule-id>
# View past executions
cline schedule executions <schedule-id>
```
## Cron Expressions
| Expression | Meaning |
|-----------|---------|
| `0 9 * * MON-FRI` | 9 AM weekdays |
| `0 */6 * * *` | Every 6 hours |
| `0 8 * * MON` | Mondays at 8 AM |
| `*/30 * * * *` | Every 30 minutes |
| `0 0 1 * *` | First of every month |
## File-Based Specs
Create Markdown files in `~/.cline/cron/` (global) or `.cline/cron/` (workspace):
### Recurring Schedule
```markdown
---
trigger: schedule
schedule: "0 9 * * MON-FRI"
timezone: America/New_York
mode: exclusive
prompt: "Check for dependency updates and create PRs for any outdated packages."
modelSelection:
providerId: anthropic
modelId: claude-sonnet-4-6
tools:
enabled: true
---
Additional context or instructions for the agent go in the body.
```
### One-Off Task
```markdown
---
trigger: one_off
prompt: "Generate a comprehensive test coverage report."
modelSelection:
providerId: anthropic
modelId: claude-sonnet-4-6
---
```
### Event-Driven
```markdown
---
trigger: event
eventType: github.pull_request.opened
filters:
repository: myorg/myrepo
debounceMs: 5000
cooldownMs: 60000
prompt: "Review the PR for security issues and code quality."
modelSelection:
providerId: anthropic
modelId: claude-sonnet-4-6
---
```
## CronSpec Types
```typescript
interface CronScheduleSpec {
trigger: "schedule"
schedule: string // cron expression
timezone?: string
mode?: "exclusive" | "concurrent"
prompt: string
modelSelection?: { providerId: string; modelId?: string }
extensionLoading?: "isolated" | "direct"
configExtensions?: RuntimeConfigExtensionKind[]
tools?: { enabled?: boolean; names?: string[] }
}
interface CronOneOffSpec {
trigger: "one_off"
prompt: string
modelSelection?: { providerId: string; modelId?: string }
}
interface CronEventSpec {
trigger: "event"
eventType: string // e.g., "github.pull_request.opened"
filters?: Record<string, unknown>
debounceMs?: number
cooldownMs?: number
prompt: string
modelSelection?: { providerId: string; modelId?: string }
}
```
## Programmatic Automation API
```typescript
const cline = await ClineCore.create({
clientName: "my-app",
automation: true,
})
// Start automation service
cline.automation.start()
// Ingest an external event
cline.automation.ingestEvent({
eventId: "evt-123",
eventType: "github.pull_request.opened",
source: "github",
timestamp: Date.now(),
payload: { pr: { number: 42, title: "..." } },
})
// List specs, runs, events
const specs = await cline.automation.listSpecs()
const runs = await cline.automation.listRuns()
const events = await cline.automation.listEvents()
// Reconcile specs from directory
await cline.automation.reconcile(specDirectory)
// Stop automation
cline.automation.stop()
```
## Event Ingestion from Plugins
Plugins can declare and emit automation events:
```typescript
const webhookPlugin: AgentPlugin = {
name: "webhook-events",
manifest: { capabilities: ["automationEvents"] },
setup(api) {
api.registerAutomationEventType({
type: "webhook.received",
description: "External webhook received",
})
},
}
```
Submit events via the plugin context:
```typescript
ctx.automation.ingestEvent({
eventId: "evt-456",
eventType: "webhook.received",
source: "custom",
timestamp: Date.now(),
payload: { ... },
})
```
## Concurrency Control
| Mode | Behavior |
|------|----------|
| `"exclusive"` | Skip if previous run still active |
| `"concurrent"` | Allow overlapping runs |
## Run Reports
Each completed run writes a Markdown report to `.cline/cron/reports/<run-id>.md` with:
- Run metadata (spec, trigger, timing)
- Summary of agent output
- Usage (tokens, cost)
- Tool calls made
- Trigger event context (for event-driven runs)
## Use Cases
- Daily standup summaries
- Automated dependency update checks
- PR review on open
- Codebase health reports
- Scheduled security scans
- Event-driven CI/CD workflows
## See Also
- `../clinecore/REFERENCE.md` - ClineCore runtime
- `../clinecore/api.md` - Automation API details
- `../plugins/REFERENCE.md` - Plugin events
- `../production/REFERENCE.md` - Production deployment
@@ -1,259 +0,0 @@
# Tools
Tools are how agents interact with the world. The Cline SDK supports both built-in tools (via ClineCore) and custom tools you define yourself.
## Creating Custom Tools
Use `createTool()` from `@cline/sdk` (or `@cline/shared`):
```typescript
import { createTool } from "@cline/sdk"
const myTool = createTool({
name: "search_issues",
description: "Search GitHub issues by query. Returns up to 10 results.",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search query" },
state: { type: "string", enum: ["open", "closed", "all"] },
},
required: ["query"],
},
execute: async (input) => {
const issues = await github.searchIssues(input.query, input.state)
return { issues, count: issues.length }
},
})
```
### With Zod Schema
```typescript
import { createTool } from "@cline/sdk"
import { z } from "zod"
const deployTool = createTool({
name: "deploy",
description: "Deploy the app to the specified environment.",
inputSchema: z.object({
environment: z.enum(["staging", "production"]).describe("Target environment"),
version: z.string().optional().describe("Version tag, defaults to latest"),
}),
execute: async (input) => {
const result = await deploy(input.environment, input.version)
return { url: result.url, status: "deployed" }
},
})
```
### Tool Config Options
```typescript
createTool({
name: string, // snake_case, unique per agent
description: string, // what the tool does (model reads this)
inputSchema: JSONSchema | ZodSchema, // input validation
execute: async (input, context, onChange?) => output,
timeoutMs?: number, // default: 30000
retryable?: boolean, // default: true
maxRetries?: number, // default: 3
lifecycle?: {
completesRun?: boolean // true = ends agent loop on success
},
})
```
### AgentToolContext
The second argument to `execute` provides runtime context:
```typescript
interface AgentToolContext {
agentId: string
conversationId: string
iteration: number
abortSignal?: AbortSignal
metadata?: Record<string, unknown>
}
```
## Tool Naming Rules
- Names must be `snake_case` (e.g., `search_issues`, `deploy_app`)
- Names must be unique within a single agent's tool set
- Choose descriptive names since the model uses them to decide which tool to call
## Tool Descriptions Matter
The model reads the tool description to decide when and how to use it. Write clear, specific descriptions:
```typescript
// Bad: vague
description: "Does deployment stuff"
// Good: specific with constraints
description: "Deploy the application to staging or production. " +
"Staging deployments are immediate. Production requires a passing CI build. " +
"Returns the deployment URL and status."
```
Include constraints, rate limits, and expected behavior in the description.
## Error Handling in Tools
Return errors as structured data instead of throwing:
```typescript
// Good: return error data
execute: async (input) => {
const file = await readFile(input.path).catch(() => null)
if (!file) {
return { error: "File not found", path: input.path }
}
return { content: file }
}
```
Thrown exceptions count as "mistakes" against the agent's mistake limit. Returned error data lets the agent adjust its approach.
## Completion Tools
Tools with `lifecycle: { completesRun: true }` end the agent loop when they execute successfully:
```typescript
const submitAnswer = createTool({
name: "submit_answer",
description: "Submit the final answer and end the task.",
inputSchema: z.object({
answer: z.string(),
confidence: z.number().min(0).max(1),
}),
lifecycle: { completesRun: true },
execute: async (input) => input,
})
```
The model sees the tool result and the run ends. Access the output via `result.toolCalls`.
## Built-in Tools (ClineCore Only)
When using `ClineCore` with `enableTools: true`, these tools are available automatically:
| Tool | Name | What It Does |
|------|------|-------------|
| Shell | `bash` | Execute shell commands in the session workspace |
| Editor | `editor` | Create and edit files |
| Read | `read_files` | Read file contents |
| Patch | `apply_patch` | Apply unified diffs to files |
| Search | `search` | Search file contents and directory structure |
| Web | `fetch_web` | Fetch web content via HTTP |
Built-in tools respect the `cwd` setting in `CoreSessionConfig`.
## Tool Policies
Control which tools are available and whether they require approval:
```typescript
// In Agent config
const agent = new Agent({
tools: [toolA, toolB, toolC],
toolPolicies: {
tool_a: { autoApprove: true }, // runs without asking
tool_b: { autoApprove: false }, // requires approval
tool_c: { enabled: false }, // hidden from model
},
})
// In ClineCore session
await cline.start({
prompt: "...",
config: { ... },
toolPolicies: {
bash: { autoApprove: true },
editor: { autoApprove: false },
},
})
```
### Policy Options
| Policy | Effect |
|--------|--------|
| `{ autoApprove: true }` | Tool runs without approval |
| `{ autoApprove: false }` | Triggers approval callback before running |
| `{ enabled: false }` | Tool is hidden from the model entirely |
| No policy set | Defaults to enabled and auto-approved |
## Abort Signal in Long-Running Tools
Respect the abort signal for tools that take a long time:
```typescript
execute: async (input, context) => {
const results = []
for (const item of input.items) {
if (context.abortSignal?.aborted) {
return { results, aborted: true, processed: results.length }
}
results.push(await processItem(item))
}
return { results, processed: results.length }
}
```
## Streaming Tool Output
Use the `onChange` callback (third argument) to stream partial results:
```typescript
execute: async (input, context, onChange) => {
let progress = 0
for (const step of steps) {
progress++
onChange?.(`Processing step ${progress}/${steps.length}...`)
await processStep(step)
}
return { completed: true }
}
```
## Testing Tools
Tools are plain async functions, so they're straightforward to test:
```typescript
import { describe, it, expect } from "vitest"
describe("deploy tool", () => {
it("deploys to staging", async () => {
const context = { agentId: "test", conversationId: "test", iteration: 1 }
const result = await deployTool.execute({ environment: "staging" }, context)
expect(result.status).toBe("deployed")
})
})
```
## MCP Tool Integration
ClineCore can connect to MCP (Model Context Protocol) servers for additional tools. Configure in `.cline/mcp-servers.json`:
```json
{
"servers": {
"my-server": {
"command": "node",
"args": ["./mcp-server.js"]
}
}
}
```
MCP tools appear alongside built-in and custom tools automatically.
## See Also
- `../agent/REFERENCE.md` - Using tools with Agent
- `../clinecore/REFERENCE.md` - Using tools with ClineCore
- `../plugins/REFERENCE.md` - Packaging tools as plugins
-5
View File
@@ -1,5 +0,0 @@
---
"claude-dev": patch
---
fix: use correct base URL for Vertex AI global endpoint with Claude models
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/cline-sdk
-266
View File
@@ -1,266 +0,0 @@
---
name: publish-cli
description: Use when preparing, tagging, and publishing an apps/cli npm release. Guides changelog drafting, apps/cli/package.json version bumps, cli-vX.Y.Z tags, local npm publishing, and the publish-cli GitHub workflow.
---
# CLI Release
Use this skill when the user asks to release the CLI, publish `cline`, bump the CLI version, draft release notes, create a `cli-vX.Y.Z` tag, or trigger the CLI publish workflow.
The CLI is npm-only. Do not add alternate distribution or signing steps.
> Working directory: run every command below from the repository root. Paths and scripts (e.g. `apps/cli/package.json`, `sdk/packages/`, `bun release cli`, `bun run version`) are written relative to the repo root.
The skill should guide the user through one release preparation flow, then offer the publish path options. The two normal publish paths are GitHub Actions and local publishing from an authenticated machine.
## Release contract
- SDK prerequisite: the CLI depends on the SDK via `workspace:*` (`@cline/core`, `@cline/shared`, and friends). If the SDK changed since its last release, release the SDK first and wait for it to finish publishing before releasing the CLI. See "Step 0: Release the SDK first if it changed" below.
- Version source: `apps/cli/package.json`.
- Main release tag: `cli-vX.Y.Z`, where `X.Y.Z` matches `apps/cli/package.json`.
- Nightly release version: `X.Y.Z-nightly.TIMESTAMP`.
- Release prep includes approved release notes, a version bump, and an `apps/cli/CHANGELOG.md` update.
- Publish paths:
- GitHub workflow: `.github/workflows/cli-publish.yml`.
- Local publish helper: `bun release cli`.
- npm dist-tags and git tags are separate. `--tag latest` and `--tag nightly` are npm registry channels. `cli-vX.Y.Z` is a git tag for source history and GitHub releases.
- The GitHub main release workflow runs from `main`, requires an existing `cli-vX.Y.Z` tag, checks out that tag, and publishes from it.
- The GitHub nightly workflow publishes to npm with the `nightly` dist-tag and does not create a tag.
- The local release helper requires a clean checkout and `cli-vX.Y.Z` to point at `HEAD` locally and on `origin` before publishing.
- Local GitHub release creation requires `gh` to be authenticated with release permissions for the repo.
- Always ask before pushing commits or tags.
- Do not amend commits unless explicitly requested.
## Step 0: Release the SDK first if it changed
Do this before anything else in the Workflow below.
The CLI builds and ships against the SDK source in the monorepo (`workspace:*` for `@cline/core`, `@cline/shared`, and the rest), so a CLI release always contains the latest SDK code whether or not the SDK was released. The build and tests use that source too, not anything from npm. Releasing the SDK alongside the CLI is still worth doing for two reasons:
- Hub freshness. The hub daemon lives in `@cline/core` and stamps a `buildId` that defaults to the `@cline/core` package version (`resolveHubBuildId` in `sdk/packages/core/src/hub/discovery/index.ts`). A running hub is only retired and respawned when that `buildId` changes (`isCompatibleHubRecord` / `retireIncompatibleHub` in `sdk/packages/core/src/hub/daemon/index.ts`). So if the SDK code changed but the version did not, a user who upgrades the CLI keeps talking to their already-running hub, which is still executing the old SDK code. Bumping the SDK version makes the new CLI's `buildId` differ, so the stale hub is detected as incompatible and respawned with the fresh code.
- Release hygiene. We want regular SDK releases; cutting one whenever we cut a CLI release keeps the published SDK in step with what the CLI ships.
So when the SDK has changed, release it first (which bumps the `@cline/core` version), then cut the CLI release on top of that bump. Leave the CLI's SDK dependency as `workspace:*` — the fix is to release the SDK, not to pin the CLI.
1. Check for unreleased SDK changes.
```sh
git fetch origin --tags
git tag --list 'sdk/sdk/v*' 'sdk-v*' --sort=-v:refname | head -1
git log <last-sdk-tag>..origin/main --oneline --no-merges -- sdk/packages
```
`sdk/<pkg>/v*` tags are created by the `sdk-publish.yml` workflow; `sdk-v*` tags are created by the local `bun release sdk` helper. Use whichever is newest as the baseline.
If `git log` prints no commits, the SDK is already up to date. Skip the rest of Step 0 and continue with the Workflow below.
If it prints commits, sanity-check the diff (ignore entries that are only the previous version-bump commit's lockfile or generated files), then release the SDK.
2. Decide the SDK version bump.
All SDK packages share one version, read from `sdk/packages/llms/package.json`. Ask whether this is patch, minor, major, or an explicit version. Patch is the default. Do not guess if the user has not made it clear.
3. Draft the SDK release notes and update the changelog.
Draft user-facing notes from the SDK commits found in step 1, translating commit messages into user-facing language (same approach as the CLI release notes below). Prepend a new `## <version>` section with those notes to the top of `sdk/CHANGELOG.md`, using the header format `## <version>` with no date — the same flat, newest-on-top format as `apps/cli/CHANGELOG.md`. This is the SDK changelog (all SDK packages share one version) and it is maintained by hand; the `sdk-publish.yml` workflow does not read it.
4. Bump versions and regenerate.
```sh
bun run version <version>
```
This bumps every SDK `package.json` to the new version, regenerates the lockfile and the generated model catalog, formats, and builds. Review the result.
5. Commit and push the bump to `main`.
The `sdk-publish.yml` workflow publishes the version that is committed on `main` and tags that commit, so the bump must land on `main` before the workflow runs.
```sh
git add -A
git commit -m "chore(sdk): release v<version>"
```
Ask before pushing:
```sh
git push origin HEAD
```
6. Trigger the SDK publish workflow on the `latest` channel.
```sh
gh workflow run sdk-publish.yml -f channel=latest -f confirm_publish=publish
gh run list --workflow=sdk-publish.yml --limit=1 --json databaseId,url,status,createdAt --jq '.[0]'
```
The workflow runs the SDK tests, publishes `@cline/shared`, `@cline/llms`, `@cline/agents`, `@cline/core`, and `@cline/sdk` to npm with the `latest` dist-tag in dependency order, and pushes `sdk/<pkg>/v<version>` git tags.
7. Wait for the SDK workflow to succeed before starting the CLI release.
```sh
gh run watch <run-id> --exit-status
```
Do not start the CLI release until this run has finished successfully. The CLI does not install the SDK from npm, but cutting the CLI release on top of a clean, completed SDK release keeps the two in step: the CLI release commit then sits on top of the `@cline/core` version bump, so the shipped CLI carries the new version that forces a running hub to respawn with the new code, and you are not building a CLI release on top of an SDK release that failed midway.
After the SDK release succeeds, pull `main` so the CLI release is prepared on top of the SDK version bump:
```sh
git checkout main && git pull --ff-only
```
Then continue with the Workflow below.
For a local SDK publish from an authenticated machine instead of the workflow, `bun release sdk <version>` exists, but prefer the `sdk-publish.yml` workflow for normal releases so the CLI release can gate on a single GitHub Actions run.
## Workflow
Complete Step 0 first. Only proceed once the SDK is released (or you confirmed no SDK release was needed).
1. Gather context.
```sh
git status --short --branch
git fetch origin --tags
git tag --list 'cli-v*' --sort=-v:refname | head -10
node -p "require('./apps/cli/package.json').version"
```
Find the latest CLI tag. If there is no `cli-v*` tag, use the first relevant CLI release commit as the baseline and say that the baseline is inferred.
2. Collect release commits.
```sh
git log <last-cli-tag>..HEAD --oneline --no-merges -- apps/cli sdk/packages sdk/scripts .github/workflows/cli-publish.yml
```
The `sdk/packages` commits matter here even though the SDK was released separately in Step 0: the CLI bundles the SDK, so SDK changes ship in this CLI release too. Read those commits and fold anything user-relevant to the CLI into the release notes (provider/model updates, behavior changes, fixes the CLI inherits). Skip SDK changes that are purely internal or have no CLI-visible effect.
3. Draft user-facing release notes.
Include user-facing features, fixes, behavior changes, compatibility changes, and notable install or release changes. Exclude pure refactors, tests, style, chores, and internal file moves unless they matter to users.
Write a flat bullet list. Translate commit messages into user-facing language. If a commit is unclear, read the full commit before summarizing it.
Present the draft and wait for approval before editing files.
4. Decide the version bump.
Ask whether this should be patch, minor, major, or an explicit version. Do not guess if the user has not made it clear.
5. Update release files.
Update `apps/cli/package.json` to the approved version.
Prepend a section to `apps/cli/CHANGELOG.md` for the approved version using the approved release notes. Use the header format `## X.Y.Z` with no date. The publish workflow extracts the top section of the changelog by matching `^## [0-9]` and pastes it verbatim into the GitHub release body and the Slack release announcement, so the section content is the release notes that get shipped.
6. Verify before committing.
Run focused checks first:
```sh
bun -F @cline/cli typecheck
bun -F @cline/cli test:unit
```
For higher confidence, run:
```sh
bun run types
bun --cwd apps/cli run build:platforms:single
```
If the user wants full release confidence before tagging, run:
```sh
bun run test
bun --cwd apps/cli run build:platforms
```
Known local-only test failure: `src/commands/distribution-package.test.ts > rejects direct source package packing by default` will fail on machines that have `ignore-scripts=true` in `~/.npmrc` (set by the npm supply-chain hardening guide). Bun reads npm's `ignore-scripts` from `~/.npmrc`, so `bun pm pack --dry-run` skips the source-publish `prepack` guard and exits 0, which the test reads as a failure. CI does not set `ignore-scripts`, so the test passes there. Confirm by running `bun pm pack --dry-run` directly: with `~/.npmrc` in place it exits 0 with no guard output; with `~/.npmrc` moved aside it exits 1 and prints the guard message. This is not a release blocker by itself, but it does mean the local-publish path (`bun release cli`) will also bypass the source-publish guard on this machine; prefer the GitHub Actions publish path on machines with `ignore-scripts=true` set globally, or temporarily unset it (`npm config delete ignore-scripts` or `mv ~/.npmrc ~/.npmrc.bak`) for the duration of a local publish.
7. Commit release changes.
Only after the user approves the notes and version:
```sh
git add apps/cli/package.json apps/cli/CHANGELOG.md
git commit -m "chore(cli): release vX.Y.Z"
```
Ask before pushing the release commit:
```sh
git push origin HEAD
```
For the GitHub main release path, ask before creating and pushing the release tag:
```sh
git tag -a cli-vX.Y.Z -m "CLI vX.Y.Z"
git push origin refs/tags/cli-vX.Y.Z
```
8. Publish.
Ask the user which path to use:
- GitHub main release. Use this after the release commit is on `main` and the matching `cli-vX.Y.Z` tag has been pushed. The workflow publishes to npm from that tag, creates the GitHub release, and posts to Slack.
- Local release. Use this when the user wants to publish from this machine. The local machine must be authenticated to npm and GitHub.
- GitHub nightly release.
- Stop after the version commit.
For GitHub main release:
```sh
gh workflow run cli-publish.yml -f publish_target=main -f git_tag=cli-vX.Y.Z -f confirm_publish=publish
gh run list --workflow=cli-publish.yml --limit=1 --json url,status,conclusion,createdAt --jq '.[0]'
```
For GitHub nightly release:
```sh
gh workflow run cli-publish.yml -f publish_target=nightly
```
For forced GitHub nightly release:
```sh
gh workflow run cli-publish.yml -f publish_target=nightly -f force_nightly_publish=true
```
For local publish:
```sh
gh auth status
npm whoami
git tag -a cli-vX.Y.Z -m "CLI vX.Y.Z"
git push origin refs/tags/cli-vX.Y.Z
bun release cli
```
After a successful local publish, ask before running:
```sh
gh release create cli-vX.Y.Z --verify-tag --title "CLI vX.Y.Z" --notes "Paste the approved release notes here."
```
If publishing with another npm dist-tag:
```sh
bun release cli --tag next
```
9. Final response.
Report:
- version
- tag
- changelog file updated
- commit hash
- whether anything was pushed
- publish path selected
- workflow URL or local publish result
- tests and builds run
+33
View File
@@ -0,0 +1,33 @@
# CLI Development
The CLI lives in `cli/` and uses React Ink for terminal UI.
- If needed, look at `cli/src/constants/colors.ts` for re-used terminal colors, e.g. `COLORS.primaryBlue` highlight color (selections, spinners, success states).
- Never use `dimColor` with gray (e.g. `<Text color="gray" dimColor>`) - it's too hard to read. Use `color="gray"` for secondary text and normal foreground (no color) for primary text.
- When thinking about how to handle state or messages from core, look at webview for how it communicates with the vs code extension.
- When updating the webview, consider and suggest to the user to update the CLI TUI since we want to provide a similar experience to our terminal users as we do our vs code extension users.
## Adding New API Providers
When adding a new API provider to the extension, you must also update the CLI:
1. **Update `cli/src/components/ModelPicker.tsx`**: Add the provider to the `providerModels` map so `getDefaultModelId()` returns the correct default model. Import the models and default ID from `@shared/api`:
```typescript
import { newProviderDefaultModelId, newProviderModels } from "@/shared/api"
export const providerModels = {
// ...existing providers
"new-provider": { models: newProviderModels, defaultId: newProviderDefaultModelId },
}
```
2. **Use `applyProviderConfig()` for auth flows**: When implementing OAuth or other auth flows for the provider, use the shared utility at `cli/src/utils/provider-config.ts`:
```typescript
import { applyProviderConfig } from "../utils/provider-config"
// After successful auth:
await applyProviderConfig({ providerId: "new-provider", controller })
```
This handles setting provider, default model, API key mapping, state persistence, and rebuilding the API handler.
3. **Provider-specific auth**: If the provider uses OAuth (like `openai-codex`), add handling in `SettingsPanelContent.tsx`'s `handleProviderSelect` callback. See the existing Codex OAuth flow as a reference.
-128
View File
@@ -1,128 +0,0 @@
# Debug Harness
HTTP-controlled debugger for the VSCode extension at `src/dev/debug-harness/server.ts`.
## Quick start
```bash
# Build extension first if needed (protos + esbuild):
npm run protos && IS_DEV=true node esbuild.mjs
# Launch (skip-build if already built):
npx tsx src/dev/debug-harness/server.ts --skip-build --auto-launch
# In another terminal:
curl localhost:19229/api -d '{"method":"status"}'
```
## Data Isolation
The debugee runs with `CLINE_DIR=~/.cline2` by default, separate from your real `~/.cline`.
This prevents the debugee's logout from logging out the debugger, and vice versa.
Override with `--cline-dir /tmp/test-dir`. Check with `status()``clineDir`.
## Browser Capture & OAuth
The debugee runs with `CLINE_CAPTURE_BROWSER=1`, which intercepts `openExternal()` in
`src/utils/env.ts`. URLs are captured instead of opening a real browser:
- Logged to `$CLINE_DIR/data/debug-captured-urls.jsonl`
- POSTed in real-time to `/captured-url` on the harness server
- Queryable via `oauth.captured_urls`
### OAuth API
- **`oauth.captured_urls`** `{clear?}` — URLs the debugee tried to open
- **`oauth.read_stored_token`** — Check auth token presence in secrets.json
- **`oauth.simulate_callback`** `{path, code?, state?, provider?, token?}` — Build vscode:// callback URI
- **`oauth.read_captured_urls_file`** — Read on-disk JSONL of captured URLs
### OAuth testing flow
For **Cline OAuth** (SDK local callback): The SDK starts a local HTTP server, the auth URL
is captured. To complete: open the captured URL in a real browser (it redirects back to the
SDK's callback server), OR extract the callback port and `curl http://127.0.0.1:PORT/callback?code=...`.
For **MCP/Provider OAuth** (vscode:// URI): The redirect goes to a vscode:// URI.
`oauth.simulate_callback` only *builds* the URI — it does not deliver it, and the ESM
extension host can't `require()` the handler. To actually deliver the callback, call the
debug-only hook via `ext.evaluate` (with `awaitPromise: true`):
`globalThis.__clineHandleUri("vscode://saoudrizwan.claude-dev/...?code=...&state=...")`.
It runs the same `SharedUriHandler.handleUri` as VSCode's real URI handler and exists only
when `CLINE_CAPTURE_BROWSER` is set (the harness always sets it; never ships in prod).
For end-to-end MCP OAuth, get a real `code` from the local MCP OAuth test server
(`npm run dev:mcp-oauth-test-server`).
## Navigating Views — Use Commands, Not Clicks
Don't try to find/click small sidebar icons. Use VSCode commands via command palette.
Registered in `src/registry.ts`:
| Command | View |
|---------|------|
| `cline.accountButtonClicked` | Account / sign-in |
| `cline.historyButtonClicked` | Task history |
| `cline.settingsButtonClicked` | Settings |
| `cline.mcpButtonClicked` | MCP servers |
| `cline.plusButtonClicked` | New task (chat) |
| `cline.worktreesButtonClicked` | Worktrees |
```bash
curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
```
## Key commands
All via `POST localhost:19229/api` with `{"method":"...", "params":{...}}`:
- **`launch`** / **`shutdown`** — lifecycle
- **`ui.screenshot`** — screenshot to `/tmp/cline-debug/`; returns `{path}`**use `read_file` on the path to examine, do NOT `open` the file** (Preview.app covers the VSCode window)
- **`ui.open_sidebar`** — open the Cline sidebar
- **`ext.set_breakpoint`** `{file, line, condition?}` — breakpoint by source file (sourcemap-resolved)
- **`ext.evaluate`** `{expression, callFrameId?}` — eval in extension host
- **`ext.resume`** / **`ext.step_over`** / **`ext.step_into`** — stepping
- **`ext.call_stack`** — inspect when paused
- **`web.evaluate`** `{expression}` — eval in webview
- **`web.post_message`** `{message}` — send postMessage to extension host via exposed vsCodeApi
- **`wait_for_pause`** `{timeout?}` — block until breakpoint hit
- **`ui.locator`** `{role?, testId?, text?, frame?}` — Playwright locator (auto-retries on stale sidebar frame)
- **`ui.react_input`** `{text, selector?, clear?, submit?}` — set React textarea value via `execCommand('insertText')`; works reliably across multiple tasks
- **`ui.send_message`** `{text, images?, files?, responseType?}` — send chat message bypassing the textarea entirely (via gRPC postMessage)
- **`ui.command_palette`** `{command}` — run VSCode command
## Typical Session
```bash
# 1. Launch
curl localhost:19229/api -d '{"method":"launch","params":{"skipBuild":true}}'
# 2. Open sidebar + dismiss overlays (ALWAYS do this first)
curl localhost:19229/api -d '{"method":"ui.open_sidebar"}'
curl localhost:19229/api -d '{"method":"web.evaluate","params":{"expression":"document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
# 3. Navigate to view
curl localhost:19229/api -d '{"method":"ui.command_palette","params":{"command":"cline.accountButtonClicked"}}'
# 4. Check captured OAuth URLs if testing auth
curl localhost:19229/api -d '{"method":"oauth.captured_urls"}'
# 5. Verify
curl localhost:19229/api -d '{"method":"ui.screenshot"}'
```
## Caveats
- **⚠️ Dismiss promotional overlays FIRST**: On fresh launches, full-screen promo overlays block the sidebar. **Dismiss immediately after `ui.open_sidebar`**, before any other interaction or screenshot. May need to run twice:
```bash
curl localhost:19229/api -d '{"method": "ui.open_sidebar"}'
curl localhost:19229/api -d '{"method": "web.evaluate", "params": {"expression": "document.querySelectorAll(\".sr-only\").forEach(el => el.parentElement?.click())"}}'
```
- **Screenshots — don't open the file**: `ui.screenshot` and `ui.sidebar_screenshot` save PNGs to `/tmp/cline-debug/` and return the `{path}`. Use `read_file` on that path to examine screenshots. Running `open <path>` launches Preview.app on macOS which covers the VSCode window.
- **Scripts count = 0 after launch**: CDP connects after extension host starts, so scripts parsed during startup aren't tracked. Breakpoints still work via sourcemap resolution.
- **Port 9230**: Extension host inspector. If another VSCode instance uses this port, the harness will fail to connect. Kill other debug instances first.
- **macOS only** for now (Playwright Electron launch behavior).
- **Webview CDP**: `connect_webview` may fail depending on Electron version. `web.evaluate` still works via Playwright's `frame.evaluate()` fallback.
- **Sourcemap paths**: esbuild outputs relative paths like `../src/extension.ts` in the sourcemap. The resolver handles this, but if a file isn't found, use `ext.source_files` to see exact paths.
- **OAuth with fake codes**: Browser capture intercepts the URL but doesn't provide a valid auth code. For real OAuth testing, open the captured URL in a browser. For unit testing, mock the token exchange.
See `src/dev/debug-harness/README.md` for full API reference.
+100 -98
View File
@@ -13,55 +13,11 @@ This file is the secret sauce for working effectively in this codebase. It captu
**What NOT to add:** Stuff you can figure out from reading a few files, obvious patterns, or standard practices. This file should be high-signal, not comprehensive.
## Miscellaneous
- Avoid provider-specific string matching / hardcoded provider branches when fixing provider/config plumbing. Prefer provider metadata, shared catalog/defaults, explicit protocol/client capabilities, or centralized normalization utilities that apply by data shape rather than `providerId === "..."`. If a provider exception seems necessary, stop and explain why instead of adding ad-hoc string matching.
- This is a VS Code extension—check `package.json` for available scripts before trying to verify builds (e.g., `npm run compile`, not `npm run build`).
- When creating PRs, contributors should not create changelog-entry files. Maintainers handle release versioning and changelog curation during the release process.
- When adding new feature flags, see this PR as a reference https://github.com/cline/cline/pull/7566
- Additional instructions about making requests: @.clinerules/network.md
## Searching the Codebase — Avoiding Build Output
Several directories contain build output or generated code that produces
noisy or unusable results with `search_files` / `grep`:
| Directory | What it is | Why it's a problem |
|-----------|-----------|-------------------|
| `out/` | esbuild bundle output | Mirrors `src/` structure as minified JS — every search gets duplicate hits on single-line files |
| `dist/` | Packaged extension | Entire extension bundled into one minified `extension.js` (~1 long line) |
| `dist-standalone/` | Standalone build output | Same minification issue |
| `src/generated/` | Generated protobuf code | Auto-generated from `proto/`; not the source of truth |
| `src/shared/proto/` | Generated proto type defs | Auto-generated from `proto/`; not the source of truth |
| `node_modules/` | Dependencies | Huge, not project source |
### How to skip build output
**`search_files`** — Point at `src/` (not the project root) and use `file_pattern`:
```
search_files(path="src/core", regex="myFunction", file_pattern="*.ts")
```
The `file_pattern` parameter is the most effective filter — e.g. `"*.ts"`,
`"*.tsx"`, `"*.proto"`.
**`grep` directly** — Exclude build dirs and restrict to source extensions:
```bash
grep -rn "myFunction" src/ --include="*.ts" --exclude-dir={out,dist,node_modules,generated}
```
### When you must search minified files
Sometimes you need to verify what got bundled (e.g., checking if a change
made it into the build). Minified files are typically one long line, so
normal `grep` shows the entire file as context. Use these approaches:
- **`grep -oP`** to extract just the match with limited surrounding context:
```bash
grep -oP '.{0,40}myFunction.{0,40}' dist/extension.js
```
- **`read_file`** on files in `out/src/` — these have source maps and are
more readable than `dist/extension.js` (which is the fully bundled output).
- **Source maps** — `out/src/*.js.map` and `dist/extension.js.map` can be
used to trace minified output back to original source locations.
## gRPC/Protobuf Communication
The extension and webview communicate via gRPC-like protocol over VS Code message passing.
@@ -92,15 +48,104 @@ The extension and webview communicate via gRPC-like protocol over VS Code messag
- `src/core/controller/task/explainChanges.ts` - Handler implementation
- `webview-ui/src/components/chat/ChatRow.tsx` - UI rendering
## Adding a New API Provider
When adding a new provider (e.g., "openai-codex"), you must update the proto conversion layer in THREE places or the provider will silently reset to Anthropic:
1. `proto/cline/models.proto` - Add to the `ApiProvider` enum (e.g., `OPENAI_CODEX = 40;`)
2. `convertApiProviderToProto()` in `src/shared/proto-conversions/models/api-configuration-conversion.ts` - Add case mapping string to proto enum
3. `convertProtoToApiProvider()` in the same file - Add case mapping proto enum back to string
**Why this matters:** Without these, the provider string hits the `default` case and returns `ANTHROPIC`. The webview, provider list, and handler all work fine, but the state silently resets when it round-trips through proto serialization. No error is thrown.
**Other files to update when adding a provider:**
- `src/shared/api.ts` - Add to `ApiProvider` union type, define models
- `src/shared/providers/providers.json` - Add to provider list for dropdown
- `src/core/api/index.ts` - Register handler in `createHandlerForProvider()`
- `webview-ui/src/components/settings/utils/providerUtils.ts` - Add cases in `getModelsForProvider()` and `normalizeApiConfiguration()`
- `webview-ui/src/utils/validate.ts` - Add validation case
- `webview-ui/src/components/settings/ApiOptions.tsx` - Render provider component
## Responses API Providers (OpenAI Codex, OpenAI Native)
Providers using OpenAI's Responses API require native tool calling. XML tools don't work with the Responses API.
**Symptoms of broken native tool calling:**
- Tools get called multiple times (e.g., `ask_followup_question` asks the same question twice)
- Tool arguments get duplicated or malformed
- The model responds but tools aren't recognized
**Root causes to check:**
1. **Provider missing from `isNextGenModelProvider()`** in `src/utils/model-utils.ts`. The native variant matchers (e.g., `native-gpt-5/config.ts`) call this function. If your provider isn't in the list, the matcher returns false and falls back to XML tools.
2. **Model missing `apiFormat: ApiFormat.OPENAI_RESPONSES`** in its model info (`src/shared/api.ts`). This property signals that the model requires native tool calling. The task runner in `src/core/task/index.ts` checks this and forces `enableNativeToolCalls: true` regardless of user settings.
**When adding a new Responses API provider:**
1. Add provider to `isNextGenModelProvider()` list in `src/utils/model-utils.ts`
2. Set `apiFormat: ApiFormat.OPENAI_RESPONSES` on all models that use the Responses API
3. The variant matcher and task runner will handle the rest automatically
## Adding Tools to System Prompt
This is tricky—multiple prompt variants and configs. **Always search for existing similar tools first and follow their pattern.** Look at the full chain from prompt definition → variant configs → handler → UI before implementing.
1. **Add to `ClineDefaultTool` enum** in `src/shared/tools.ts`
2. **Tool definition** in `src/core/prompts/system-prompt/tools/` (create file like `generate_explanation.ts`)
- Define variants for each `ModelFamily` (generic, next-gen, xs, etc.)
- Export variants array (e.g., `export const my_tool_variants = [GENERIC, NATIVE_NEXT_GEN, XS]`)
- **Fallback behavior**: If a variant isn't defined for a model family, `ClineToolSet.getToolByNameWithFallback()` automatically falls back to GENERIC. So you only need to export `[GENERIC]` unless the tool needs model-specific behavior.
3. **Register in `src/core/prompts/system-prompt/tools/init.ts`** - Import and spread into `allToolVariants`
4. **Add to variant configs** - Each model family has its own config in `src/core/prompts/system-prompt/variants/*/config.ts`. Add your tool's enum to the `.tools()` list:
- `generic/config.ts`, `next-gen/config.ts`, `gpt-5/config.ts`, `native-gpt-5/config.ts`, `native-gpt-5-1/config.ts`, `native-next-gen/config.ts`, `gemini-3/config.ts`, `glm/config.ts`, `hermes/config.ts`, `xs/config.ts`
- **Important**: If you add to a variant's config, make sure the tool spec exports a variant for that ModelFamily (or relies on GENERIC fallback)
5. **Create handler** in `src/core/task/tools/handlers/`
6. **Wire up in `ToolExecutor.ts`** if needed for execution flow
7. **Add to tool parsing** in `src/core/assistant-message/index.ts` if needed
8. **If tool has UI feedback**: add `ClineSay` enum in proto, update `src/shared/ExtensionMessage.ts`, update `src/shared/proto-conversions/cline-message.ts`, update `webview-ui/src/components/chat/ChatRow.tsx`
## Modifying System Prompt
**Read these first:** `src/core/prompts/system-prompt/README.md`, `tools/README.md`, `__tests__/README.md`
System prompt is modular: **components** (reusable sections) + **variants** (model-specific configs) + **templates** (with `{{PLACEHOLDER}}` resolution).
**Key directories:**
- `components/` - Shared sections: `rules.ts`, `capabilities.ts`, `editing_files.ts`, etc.
- `variants/` - Model-specific: `generic/`, `next-gen/`, `xs/`, `gpt-5/`, `gemini-3/`, `hermes/`, `glm/`, etc.
- `templates/` - Template engine and placeholder definitions
**Variant tiers (ask user which to modify):**
- **Next-gen** (Claude 4, GPT-5, Gemini 2.5): `next-gen/`, `native-next-gen/`, `native-gpt-5/`, `native-gpt-5-1/`, `gemini-3/`, `gpt-5/`
- **Standard** (default fallback): `generic/`
- **Local/small models**: `xs/`, `hermes/`, `glm/`
**How overrides work:** Variants can override components via `componentOverrides` in their `config.ts`, or provide a custom template in `template.ts` (e.g., `next-gen/template.ts` exports `rules_template`). If no override, the shared component from `components/` is used.
**Example: Adding a rule to RULES section**
1. Check if variant overrides rules: look for `rules_template` in `variants/*/template.ts` or `componentOverrides.RULES` in `config.ts`
2. If shared: modify `components/rules.ts`
3. If overridden: modify that variant's template
4. XS variant is special—has heavily condensed inline content in `template.ts`
**After any changes, regenerate snapshots:**
```bash
UPDATE_SNAPSHOTS=true npm run test:unit
```
Snapshots live in `__tests__/__snapshots__/`. Tests validate across model families and context variations (browser, MCP, focus chain).
## Modifying Default Slash Commands
Three places need updates:
- `src/core/slash-commands/index.ts` - Command definitions
- `src/core/prompts/commands.ts` - System prompt integration
- `webview-ui/src/utils/slash-commands.ts` - Webview autocomplete
## Adding New Global State Keys
Adding a new key to global state requires updates in multiple places. Missing any step causes silent failures.
Required steps:
1. Type definition in `src/shared/storage/state-keys.ts` - Add to `GlobalState` or `Settings` interface
2. Add any default value or transform in `src/shared/storage/state-keys.ts` if the key needs one
3. Read and write the value through `StateManager` (`setGlobalState()` / `getGlobalStateKey()`) after initialization
2. Read from globalState in `src/core/storage/utils/state-helpers.ts`:
- Add `const myKey = context.globalState.get<GlobalStateAndSettings["myKey"]>("myKey")` in `readGlobalStateFromDisk()`
- Add to the return object: `myKey: myKey ?? defaultValue,`
3. StateManager handles read/write via `setGlobalState()`/`getGlobalStateKey()` after initialization
Persistent state is file-backed through `StateManager`; do not add new runtime reads or writes against VS Code `ExtensionContext` storage. That storage is only a legacy migration source.
Common mistake: Adding only the return value without the `context.globalState.get()` call. This compiles but the value is always `undefined` on load.
Settings plumbing gotcha: if a key is user-toggleable from settings, wire both controller update paths:
- `src/core/controller/state/updateSettings.ts` for webview `updateSetting(...)`
@@ -114,20 +159,22 @@ Webview toggle gotcha: settings changes must also round-trip back in state paylo
If this round-trip wiring is missing, the backend value can update but the toggle in webview appears stuck or reverts.
## StateManager Cache vs Direct globalState Access
StateManager uses an in-memory cache populated during `StateManager.initialize()` from file-backed storage. For most state, use `controller.stateManager.setGlobalState()`/`getGlobalStateKey()`.
StateManager uses an in-memory cache populated during `StateManager.initialize(context)` in `common.ts`. For most state, use `controller.stateManager.setGlobalState()`/`getGlobalStateKey()`.
Exception: host migration code may read legacy VS Code storage before file-backed storage is initialized.
Exception: State needed immediately at extension startup (before cache is ready)
Example pattern:
When Window A sets state and immediately opens Window B, the new window's StateManager cache is populated from `context.globalState` during initialization. If you need to read state in Window B right at startup (e.g., in `common.ts` during `initialize()`), read directly from `context.globalState.get()` instead of StateManager's cache.
Example pattern (see `lastShownAnnouncementId` and `worktreeAutoOpenPath`):
```typescript
// Writing (normal pattern)
controller.stateManager.setGlobalState("myKey", value)
// Reading after initialization
const value = controller.stateManager.getGlobalStateKey("myKey")
// Reading at startup in common.ts (bypass cache)
const value = context.globalState.get<string>("myKey")
```
Use `context.globalState` only in VS Code migration code that copies legacy ExtensionContext values into the shared file-backed stores.
This is only needed for cross-window state read during the brief startup window before StateManager cache is fully usable. Normal state access after initialization should use StateManager.
## ChatRow Cancelled/Interrupted States
When a ChatRow displays a loading/in-progress state (spinner), you must handle what happens when the task is cancelled. This is non-obvious because cancellation doesn't update the message content—you have to infer it from context.
@@ -156,48 +203,3 @@ const isGenerating = explanationInfo.status === "generating" && !wasCancelled
**See also:** `BrowserSessionRow.tsx` uses similar pattern with `isLastApiReqInterrupted` and `isLastMessageResume`.
**Backend side:** When streaming is cancelled, clean up properly (close tabs, clear comments, etc.) by checking `taskState.abort` after the streaming function returns.
## Debug Harness: clear inherited VSCode/Electron env vars before launching
The debug harness (`apps/vscode/src/dev/debug-harness/server.ts`) launches a child
VSCode via Playwright's `_electron.launch({ env: { ...process.env, ... } })`. If you
run the harness from a process that was itself spawned by VSCode (e.g. the Cline
extension host, an integrated terminal, or an agent running inside VSCode), the
parent's VSCode/Electron env vars leak into the child and break the launch.
The fatal one is **`ELECTRON_RUN_AS_NODE=1`**: it makes the child VSCode binary run
as plain Node, so it rejects every VSCode CLI flag. Symptom:
```
.../Visual Studio Code.app/Contents/MacOS/Code: bad option: --extensionDevelopmentPath=...
Error: Process failed to launch! (Playwright _electron.launch)
```
This is NOT the macOS Playwright flakiness mentioned in the harness README — it's
env inheritance. Fix: strip the inherited vars before starting the harness:
```bash
env -u ELECTRON_RUN_AS_NODE -u ELECTRON_NO_ATTACH_CONSOLE \
-u VSCODE_CLI -u VSCODE_CODE_CACHE_PATH -u VSCODE_CRASH_REPORTER_PROCESS_TYPE \
-u VSCODE_CWD -u VSCODE_ESM_ENTRYPOINT -u VSCODE_HANDLES_UNCAUGHT_ERRORS \
-u VSCODE_IPC_HOOK -u VSCODE_NLS_CONFIG -u VSCODE_PID -u VSCODE_L10N_BUNDLE_LOCATION \
npx tsx src/dev/debug-harness/server.ts --auto-launch --skip-build
```
Check your own env with `env | grep -iE 'electron|vscode_'` first; `ELECTRON_RUN_AS_NODE=1`
present means you must scrub before launching.
Other harness notes confirmed in practice:
- The extension host is **ESM** (`VSCODE_ESM_ENTRYPOINT`), so `ext.evaluate` has no
`require` and module-internal functions aren't reachable as globals. To inspect
internal builders (e.g. `buildBedrockProviderConfig`), set a breakpoint with
`ext.set_breakpoint` and read locals via `ext.evaluate` with the paused `callFrameId`
— don't try to `require()` the bundle.
- `web.evaluate` wraps the expression as a single returned expression; multi-statement
snippets must be an IIFE `(() => { ...; return x; })()`, otherwise you get
`SyntaxError: Unexpected token ';'`.
- Webview settings inputs are `vscode-text-field` web components with debounced React
onChange. Setting `.value` + dispatching events via `web.evaluate` is unreliable for
some fields; focus the inner shadow `input` then use real keystrokes (`ui.type` +
`ui.press Tab`, or click the dropdown option) to make the value persist.
-26
View File
@@ -1,26 +0,0 @@
# SDK Adapter
The VSCode extension runs on the Cline SDK (`@cline/core`, `@cline/llms`,
`@cline/shared`) through an adapter layer in `apps/vscode/src/sdk/`. The
webview still talks gRPC; the adapter translates between gRPC handlers and SDK
calls. See `apps/vscode/src/dev/debug-harness/README.md` for the debug harness.
## Conventions
1. **Look up SDK APIs, don't guess.** Use `kb_search(name="sdk", query="...")`
before implementing against an SDK surface.
2. **Reference the pre-SDK implementation when replacing a module.** Add a
`// Replaces classic src/core/... (see origin/main)` header and use
`kb_search(name="cline", commit="origin/main")` or
`git show origin/main:path` to consult the prior implementation.
3. **Single entry point.** There is one codepath — the SDK adapter. No
`CLINE_SDK` env flag.
4. **Use `{appBaseUrl}`**, never hardcode `app.cline.bot`.
5. **Avoid `as` casts.** Use explicit conversion functions with tests. The
branded types in `apps/vscode/src/sdk/model-catalog/contracts.ts` exist so
casts are unnecessary outside parse/compute boundaries.
## Debug harness
- **Dismiss the Kanban/promo overlay** before any debug harness interaction.
- **Use the command palette** to navigate tabs in the debug harness.
+1 -1
View File
@@ -176,7 +176,7 @@ Present a final summary:
- Slack message copied to clipboard: yes
Remind the user to:
1. Manually trigger the publish release GitHub Action at: https://github.com/cline/cline/actions/workflows/ext-vscode-publish-stable.yml (paste `v{VERSION}` as the tag)
1. Manually trigger the publish release GitHub Action at: https://github.com/cline/cline/actions/workflows/publish.yml (paste `v{VERSION}` as the tag)
2. Post the Slack message to announce the hotfix
## Important Notes
+1 -1
View File
@@ -43,7 +43,7 @@ git push origin v<version>
### 4) Trigger publish workflow
Tell the maintainer to run:
https://github.com/cline/cline/actions/workflows/ext-vscode-publish-stable.yml
https://github.com/cline/cline/actions/workflows/publish.yml
Use `v<version>` as the release tag.
+2 -3
View File
@@ -20,9 +20,8 @@ command = "chmod +x ./scripts/run-extension-host.sh && ./scripts/run-extension-h
name = "CLI"
icon = "run"
command = '''
cd sdk
bun install
bun run cli
npm run cli:build
npm run cli:run
'''
[[actions]]
+2
View File
@@ -1,4 +1,6 @@
demo.gif filter=lfs diff=lfs merge=lfs -text
assets/docs/demo.gif filter=lfs diff=lfs merge=lfs -text
webview-ui/src/assets/cline_kanban_demo.mp4 filter=lfs diff=lfs merge=lfs -text
webview-ui/src/assets/cline_kanban_demo.webm filter=lfs diff=lfs merge=lfs -text
* text=auto eol=lf
+1 -1
View File
@@ -1,2 +1,2 @@
/.github/ @saoudrizwan @arafatkatze @maxpaulus43 @dominiccooney
/.github/ @saoudrizwan @arafatkatze @maxpaulus43 @candieduniverse
/README.md @saoudrizwan @juanpflores
+3 -2
View File
@@ -5,6 +5,7 @@ This is a VS Code extension. Read `.clinerules/general.md` for tribal knowledge
## Architecture
- **Core** (`src/`): `extension.ts``WebviewProvider``Controller` (single source of truth) → `Task` (agent loop).
- **Webview** (`webview-ui/`): React/Vite app. State via `ExtensionStateContext.tsx`, synced through message passing.
- **CLI** (`cli/`): React Ink terminal UI sharing core logic. Update CLI when changing webview features.
- **Communication**: Protobuf-defined gRPC-like protocol over VS Code message passing. Schemas in `proto/`.
- **MCP**: `src/services/mcp/McpHub.ts`.
@@ -27,7 +28,7 @@ Three proto conversion updates are **required** or the provider silently resets
2. `convertApiProviderToProto()` in `src/shared/proto-conversions/models/api-configuration-conversion.ts`.
3. `convertProtoToApiProvider()` in the same file.
Also update: `src/shared/api.ts`, `src/shared/providers/providers.json`, `src/core/api/index.ts`, `webview-ui/.../providerUtils.ts`, `webview-ui/.../validate.ts`, `webview-ui/.../ApiOptions.tsx`.
Also update: `src/shared/api.ts`, `src/shared/providers/providers.json`, `src/core/api/index.ts`, `webview-ui/.../providerUtils.ts`, `webview-ui/.../validate.ts`, `webview-ui/.../ApiOptions.tsx`, and `cli/src/components/ModelPicker.tsx`.
For Responses API providers: add to `isNextGenModelProvider()` in `src/utils/model-utils.ts` and set `apiFormat: ApiFormat.OPENAI_RESPONSES` on models.
@@ -44,7 +45,7 @@ For Responses API providers: add to `isNextGenModelProvider()` in `src/utils/mod
Modular: `components/` (shared) + `variants/` (model-specific) + `templates/` (`{{PLACEHOLDER}}`). Variants override components via `componentOverrides` in `config.ts` or custom `template.ts`. XS variant is heavily condensed inline. Always regenerate snapshots after changes.
## Global State Keys (silent failure risk)
Adding a key requires updating the typed storage definitions in `src/shared/storage/state-keys.ts`; runtime reads and writes should go through `StateManager`, not VS Code `ExtensionContext` storage. Persistent state is file-backed so it works across VS Code, CLI, and JetBrains hosts.
Adding a key requires: type in `src/shared/storage/state-keys.ts`, read via `context.globalState.get()` in `src/core/storage/utils/state-helpers.ts` `readGlobalStateFromDisk()`, and add to return object. Missing the `.get()` call compiles fine but value is always `undefined`.
## Slash Commands (3 places)
- `src/core/slash-commands/index.ts` — definitions.
+2 -2
View File
@@ -2,7 +2,7 @@ version: 2
updates:
# Main extension dependencies
- package-ecosystem: "npm"
directory: "/apps/vscode"
directory: "/"
schedule:
interval: "weekly"
# Group all updates into a single PR
@@ -20,7 +20,7 @@ updates:
# Webview UI dependencies
- package-ecosystem: "npm"
directory: "/apps/vscode/webview-ui"
directory: "/webview-ui"
schedule:
interval: "weekly"
groups:
@@ -0,0 +1,78 @@
name: Smoke Tests
# Temporarily disabled: this workflow built and linked the legacy CLI
# (`cd cli && npm install && npm run build && npm link`) before running the
# smoke-test scenarios. The legacy CLI publish chain has been retired in
# favor of the SDK CLI at `sdk/apps/cli/`. The scenarios under
# `evals/smoke-tests/scenarios/` are CLI-agnostic and should be re-enabled
# once the build step is repointed at the new SDK CLI. Until then, only
# manual `workflow_dispatch` runs are accepted (and will fail in their
# current form).
on:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: smoke-tests-${{ github.ref }}
cancel-in-progress: true
jobs:
smoke-tests:
name: Smoke Tests
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build and install CLI
run: |
npm run protos
cd cli && npm install && npm run build && npm link
echo "$(npm config get prefix)/bin" >> $GITHUB_PATH
- name: Verify CLI
run: cline --version
- name: Run smoke tests
env:
CLINE_API_KEY: ${{ secrets.CLINE_API_KEY }}
run: |
cline auth -p cline -k "$CLINE_API_KEY" -m "anthropic/claude-sonnet-4.5"
max_attempts=3
for attempt in $(seq 1 $max_attempts); do
echo "::group::Attempt $attempt of $max_attempts"
if npx tsx evals/smoke-tests/run-smoke-tests.ts --trials 1 --parallel; then
echo "::endgroup::"
echo "Smoke tests passed on attempt $attempt"
exit 0
fi
echo "::endgroup::"
if [ $attempt -lt $max_attempts ]; then
echo "::warning::Smoke tests failed on attempt $attempt, retrying..."
sleep 10
fi
done
echo "::error::Smoke tests failed after $max_attempts attempts"
exit 1
- name: Generate summary
if: always()
run: cat evals/smoke-tests/results/latest/summary.md >> $GITHUB_STEP_SUMMARY
- name: Upload results
uses: actions/upload-artifact@v4
if: always()
with:
name: smoke-test-results-${{ github.run_id }}
path: evals/smoke-tests/results/latest/
retention-days: 30
@@ -1,4 +1,4 @@
name: ext-vscode-test-e2e
name: E2E Tests
on:
push:
@@ -12,53 +12,8 @@ concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: read
jobs:
detect-changes:
runs-on: ubuntu-latest
name: Detect Changes
outputs:
e2e: ${{ steps.force.outputs.run_all == 'true' || steps.filter.outputs.e2e == 'true' }}
steps:
- id: force
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
run: echo "run_all=true" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
if: steps.force.outputs.run_all != 'true'
- uses: dorny/paths-filter@v3
if: steps.force.outputs.run_all != 'true'
id: filter
with:
filters: |
e2e:
- 'apps/vscode/src/**'
- 'apps/vscode/webview-ui/**'
- 'apps/vscode/proto/**'
- 'apps/vscode/tests/**'
- 'apps/vscode/scripts/**'
- 'apps/vscode/standalone/**'
- 'apps/vscode/assets/**'
- 'apps/vscode/walkthrough/**'
- 'apps/vscode/package.json'
- 'apps/vscode/package-lock.json'
- 'apps/vscode/buf.yaml'
- 'apps/vscode/tsconfig*.json'
- 'apps/vscode/biome.jsonc'
- 'apps/vscode/esbuild.mjs'
- 'apps/vscode/.mocharc.json'
- 'apps/vscode/.vscode-test.mjs'
- 'apps/vscode/.vscodeignore'
- 'apps/vscode/playwright*.ts'
- '.github/workflows/ext-vscode-test-e2e.yml'
matrix_prep:
needs: detect-changes
if: needs.detect-changes.outputs.e2e == 'true'
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
@@ -68,8 +23,7 @@ jobs:
echo 'matrix=[{"runner":"ubuntu"},{"runner":"windows"},{"runner":"macos"}]' >> $GITHUB_OUTPUT
e2e:
needs: [detect-changes, matrix_prep]
if: needs.detect-changes.outputs.e2e == 'true'
needs: matrix_prep
strategy:
fail-fast: false
matrix:
@@ -79,9 +33,6 @@ jobs:
permissions:
id-token: write
contents: read
defaults:
run:
working-directory: apps/vscode
steps:
- uses: actions/checkout@v4
- name: Setup Node.js environment
@@ -94,24 +45,24 @@ jobs:
uses: actions/cache@v4
id: root-cache
with:
path: apps/vscode/node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('apps/vscode/package-lock.json') }}
path: node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
# Cache webview-ui dependencies - only reuse if package-lock.json exactly matches
- name: Cache webview-ui dependencies
uses: actions/cache@v4
id: webview-cache
with:
path: apps/vscode/webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('apps/vscode/webview-ui/package-lock.json') }}
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
# Cache VS Code installation
- name: Cache VS Code
uses: actions/cache@v4
id: vscode-cache
with:
path: apps/vscode/.vscode-test
key: vscode-${{ runner.os }}-stable-${{ hashFiles('apps/vscode/.vscode-test.mjs', 'apps/vscode/package.json') }}
path: .vscode-test
key: vscode-${{ runner.os }}-stable-${{ hashFiles('.vscode-test.mjs', 'package.json') }}
restore-keys: |
vscode-${{ runner.os }}-stable-
@@ -124,19 +75,17 @@ jobs:
~/.cache/ms-playwright
~/Library/Caches/ms-playwright
~/AppData/Local/ms-playwright
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('apps/vscode/package-lock.json') }}
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: |
playwright-browsers-${{ runner.os }}-
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode ci
- name: Install root dependencies
run: npm ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/webview-ui ci
run: cd webview-ui && npm ci
- name: Install vsce
run: npm install -g @vscode/vsce
-370
View File
@@ -1,370 +0,0 @@
name: ext-vscode-test
on:
push:
branches:
- main
workflow_dispatch:
pull_request:
branches:
- main
workflow_call:
# Set default permissions for all jobs
permissions:
contents: read # Needed to check out code
pull-requests: read # Needed for changed-file detection on pull requests
jobs:
detect-changes:
runs-on: ubuntu-latest
name: Detect Changes
outputs:
vscode: ${{ steps.force.outputs.run_all == 'true' || steps.filter.outputs.vscode == 'true' }}
testing_platform: ${{ steps.force.outputs.run_all == 'true' || steps.filter.outputs.testing_platform == 'true' }}
steps:
- id: force
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call'
run: echo "run_all=true" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
if: steps.force.outputs.run_all != 'true'
- uses: dorny/paths-filter@v3
if: steps.force.outputs.run_all != 'true'
id: filter
with:
filters: |
vscode:
- 'apps/vscode/src/**'
- 'apps/vscode/webview-ui/**'
- 'apps/vscode/proto/**'
- 'apps/vscode/tests/**'
- 'apps/vscode/scripts/**'
- 'apps/vscode/standalone/**'
- 'apps/vscode/assets/**'
- 'apps/vscode/walkthrough/**'
- 'apps/vscode/package.json'
- 'apps/vscode/package-lock.json'
- 'apps/vscode/buf.yaml'
- 'apps/vscode/tsconfig*.json'
- 'apps/vscode/biome.jsonc'
- 'apps/vscode/esbuild.mjs'
- 'apps/vscode/.mocharc.json'
- 'apps/vscode/.nycrc*.json'
- 'apps/vscode/.vscode-test.mjs'
- 'apps/vscode/test-setup.js'
- '.github/workflows/ext-vscode-test.yml'
testing_platform:
- 'apps/vscode/src/**'
- 'apps/vscode/proto/**'
- 'apps/vscode/standalone/**'
- 'apps/vscode/testing-platform/**'
- 'apps/vscode/tests/specs/**'
- 'apps/vscode/package.json'
- 'apps/vscode/package-lock.json'
- 'apps/vscode/buf.yaml'
- 'apps/vscode/tsconfig*.json'
- 'apps/vscode/esbuild.mjs'
- 'apps/vscode/.vscodeignore'
- 'apps/vscode/scripts/**'
- '.github/workflows/ext-vscode-test.yml'
quality-checks:
needs: detect-changes
if: needs.detect-changes.outputs.vscode == 'true' || needs.detect-changes.outputs.testing_platform == 'true'
runs-on: ubuntu-latest
name: Quality Checks
defaults:
run:
working-directory: apps/vscode
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
apps/vscode/package-lock.json
apps/vscode/webview-ui/package-lock.json
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode ci --include=optional
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/webview-ui ci --include=optional
- name: Run Quality Checks (Parallel)
run: npm run ci:check-all
vscode-test:
needs: [detect-changes, quality-checks]
if: needs.detect-changes.outputs.vscode == 'true'
env:
VSCODE_TEST_VERSION: 1.103.0
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
name: ${{ matrix.os == 'ubuntu-latest' && 'vscode test' || format('vscode test ({0})', matrix.os) }}
defaults:
run:
shell: bash
working-directory: apps/vscode
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
apps/vscode/package-lock.json
apps/vscode/webview-ui/package-lock.json
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode ci --include=optional
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/webview-ui ci --include=optional
- name: Set up NPM on Windows
if: runner.os == 'Windows'
working-directory: ${{ github.workspace }}
run: |
npm config set script-shell "C:\\Program Files\\Git\\bin\\bash.exe"
- name: Cache VS Code test runtime
if: runner.os == 'Windows'
uses: actions/cache@v4
with:
path: .vscode-test
key: vscode-test-runtime-${{ runner.os }}-${{ env.VSCODE_TEST_VERSION }}
# Build the extension and tests (without redundant checks)
- name: Build Tests and Extension
id: build_step
run: npm run ci:build
- name: Vitest Suites (SDK adapter + model catalog)
id: vitest_tests
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
run: npm run test:vitest
- name: Unit Tests with coverage - Linux
id: unit_tests_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
run: |
npx nyc --nycrc-path .nycrc.unit.json --reporter=lcov npm run test:unit
- name: Unit Tests - Non-Linux
id: unit_tests_non_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
run: |
npm run test:unit
- name: Extension Integration Tests - Linux
id: integration_tests_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
run: xvfb-run -a npm run test:coverage
- name: Extension Integration Tests - Non-Linux
id: integration_tests_non_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
run: |
for attempt in 1 2 3; do
echo "Running extension integration tests (attempt ${attempt}/3)"
if npm run test:integration; then
exit 0
fi
if [ "$attempt" -eq 3 ]; then
echo "Extension integration tests failed after 3 attempts"
exit 1
fi
echo "Extension integration tests failed; retrying after short delay"
sleep 5
done
- name: Webview Tests with Coverage
id: webview_tests
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
run: |
cd webview-ui
npm run test:coverage
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
# Only upload artifacts on Linux - We only need coverage from one OS
if: runner.os == 'Linux'
with:
name: pr-coverage-reports
path: |
apps/vscode/coverage-unit/lcov.info
apps/vscode/webview-ui/coverage/lcov.info
test-platform-integration:
needs: [detect-changes, quality-checks]
if: needs.detect-changes.outputs.testing_platform == 'true'
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/vscode
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
apps/vscode/package-lock.json
apps/vscode/webview-ui/package-lock.json
apps/vscode/testing-platform/package-lock.json
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode ci --include=optional
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/webview-ui ci --include=optional
- name: Download ripgrep binaries
run: npm run download-ripgrep
- name: Compile Standalone
run: npm run compile-standalone
- name: Install testing platform dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/testing-platform ci --include=optional
- name: Running testing platform integration spec tests
timeout-minutes: 7
run: npm run test:tp-orchestrator -- tests/specs/ --count=1 --coverage
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
with:
name: test-platform-integration-core-coverage
path: apps/vscode/coverage/**/lcov.info
# Keep the required "test" check as a tiny aggregate gate instead of the conditional
# VS Code matrix. GitHub treats conditionally skipped jobs as successful required
# checks, so the gate below preserves the old required check name while making sure
# whichever filtered test jobs were selected actually passed.
test:
needs: [detect-changes, quality-checks, vscode-test, test-platform-integration]
if: ${{ !cancelled() }}
runs-on: ubuntu-latest
name: test
steps:
- name: Verify selected test jobs
env:
DETECT_CHANGES_RESULT: ${{ needs.detect-changes.result }}
QUALITY_CHECKS_RESULT: ${{ needs.quality-checks.result }}
VSCODE_CHANGED: ${{ needs.detect-changes.outputs.vscode }}
TESTING_PLATFORM_CHANGED: ${{ needs.detect-changes.outputs.testing_platform }}
VSCODE_TEST_RESULT: ${{ needs.vscode-test.result }}
TEST_PLATFORM_RESULT: ${{ needs.test-platform-integration.result }}
run: |
if [ "$DETECT_CHANGES_RESULT" != "success" ]; then
echo "detect-changes did not succeed: $DETECT_CHANGES_RESULT"
exit 1
fi
if [ "$VSCODE_CHANGED" != "true" ] && [ "$TESTING_PLATFORM_CHANGED" != "true" ]; then
echo "No root test paths changed; skipping root test requirements."
exit 0
fi
if [ "$QUALITY_CHECKS_RESULT" != "success" ]; then
echo "quality-checks did not succeed: $QUALITY_CHECKS_RESULT"
exit 1
fi
if [ "$VSCODE_CHANGED" = "true" ] && [ "$VSCODE_TEST_RESULT" != "success" ]; then
echo "vscode-test did not succeed: $VSCODE_TEST_RESULT"
exit 1
fi
if [ "$TESTING_PLATFORM_CHANGED" = "true" ] && [ "$TEST_PLATFORM_RESULT" != "success" ]; then
echo "test-platform-integration did not succeed: $TEST_PLATFORM_RESULT"
exit 1
fi
echo "Selected root test jobs passed."
qlty:
needs: [detect-changes, quality-checks, vscode-test, test-platform-integration]
if: ${{ !cancelled() && needs.quality-checks.result == 'success' && (needs.vscode-test.result == 'success' || needs.vscode-test.result == 'skipped') && (needs.test-platform-integration.result == 'success' || needs.test-platform-integration.result == 'skipped') && (needs.detect-changes.outputs.vscode == 'true' || needs.detect-changes.outputs.testing_platform == 'true') }}
runs-on: ubuntu-latest
# Run on PRs to main, pushes to main, and manual dispatches
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Download unit tests coverage reports
if: needs.detect-changes.outputs.vscode == 'true'
uses: actions/download-artifact@v4
with:
name: pr-coverage-reports
path: apps/vscode
- name: Upload core unit tests coverage to Qlty
if: needs.detect-changes.outputs.vscode == 'true'
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
apps/vscode/coverage-unit/lcov.info
tag: unit:core
- name: Upload webview-ui unit tests coverage to Qlty
if: needs.detect-changes.outputs.vscode == 'true'
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
apps/vscode/webview-ui/coverage/lcov.info
tag: unit:webview-ui
add-prefix: webview-ui/
- name: Download test platform integration core coverage artifact
if: needs.detect-changes.outputs.testing_platform == 'true'
uses: actions/download-artifact@v4
continue-on-error: true
id: download-integration-coverage
with:
name: test-platform-integration-core-coverage
path: apps/vscode/integration-core-coverage-reports
- name: Upload core integration tests coverage to Qlty
if: needs.detect-changes.outputs.testing_platform == 'true' && steps.download-integration-coverage.outcome == 'success'
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
files: apps/vscode/integration-core-coverage-reports/**/lcov.info
tag: integration:core
@@ -1,4 +1,4 @@
name: repo-label-issues
name: Auto-label Issues
on:
issues:
@@ -15,7 +15,7 @@ jobs:
script: |
const body = context.payload.issue.body || '';
const labels = context.payload.issue.labels.map(l => l.name);
// Check if JetBrains Plugin is selected
if (body.match(/###\s*Plugin Type\s*\n+JetBrains Plugin/i)) {
if (!labels.includes('JetBrains')) {
@@ -1,4 +1,4 @@
name: cli-publish
name: Publish CLI to NPM
on:
schedule:
@@ -33,7 +33,7 @@ permissions:
defaults:
run:
working-directory: .
working-directory: sdk
jobs:
publish-main:
@@ -88,9 +88,9 @@ jobs:
- name: Validate release tag
id: version
env:
TAG: ${{ github.event.inputs.git_tag }}
run: |
TAG="${{ github.event.inputs.git_tag }}"
if [ -z "$TAG" ]; then
echo "git_tag is required when publish_target=main"
exit 1
@@ -105,12 +105,12 @@ jobs:
PACKAGE_VERSION=$(node -p "require('./apps/cli/package.json').version")
if [ "$PACKAGE_VERSION" != "$VERSION" ]; then
echo "apps/cli/package.json version ${PACKAGE_VERSION} does not match ${TAG}"
echo "sdk/apps/cli/package.json version ${PACKAGE_VERSION} does not match ${TAG}"
exit 1
fi
if ! printf "%s\n" "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
echo "apps/cli/package.json has invalid version: ${VERSION}"
echo "sdk/apps/cli/package.json has invalid version: ${VERSION}"
exit 1
fi
@@ -132,36 +132,17 @@ jobs:
- name: Build SDK packages
run: bun run build:sdk
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
- name: Run tests
run: bun run test
- name: Build platform binaries
run: bun script/build.ts --install-native-variants --skip-sdk-build
working-directory: apps/cli
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
working-directory: sdk/apps/cli
- name: Verify build output
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
VERSION="${{ steps.version.outputs.version }}"
EXPECTED=(
"@cline/cli-darwin-arm64"
"@cline/cli-darwin-x64"
@@ -194,41 +175,23 @@ jobs:
env:
NPM_CONFIG_PROVENANCE: "true"
run: bun script/publish-npm.ts --tag latest
working-directory: apps/cli
working-directory: sdk/apps/cli
- name: Get Previous CLI Tag
id: prev_tag
- name: Create GitHub release
env:
CURRENT_TAG: ${{ steps.version.outputs.tag }}
GH_TOKEN: ${{ github.token }}
run: |
PREV_TAG=$(git describe --tags --abbrev=0 --match 'cli-v*' "$CURRENT_TAG^" 2>/dev/null || echo "")
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
TAG="${{ steps.version.outputs.tag }}"
VERSION="${{ steps.version.outputs.version }}"
- name: Get Changelog Entry
id: changelog
run: |
# Grab content between the first "## " header and the next one in apps/cli/CHANGELOG.md
CONTENT=$(awk '/^## [0-9]/{if(found) exit; found=1; next} found{print}' apps/cli/CHANGELOG.md)
echo "content<<EOF" >> $GITHUB_OUTPUT
echo "$CONTENT" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.version.outputs.tag }}
name: "CLI v${{ steps.version.outputs.version }}"
body: |
${{ steps.changelog.outputs.content }}
${{ steps.prev_tag.outputs.prev_tag != '' && format('**Full Changelog**: https://github.com/{0}/compare/{1}...{2}', github.repository, steps.prev_tag.outputs.prev_tag, steps.version.outputs.tag) || '' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
gh release create "$TAG" \
--verify-tag \
--title "CLI v${VERSION}" \
--notes "Published cline@${VERSION} to npm."
- name: Summary
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
VERSION="${{ steps.version.outputs.version }}"
echo "Published cline@${VERSION} to npm with dist-tag 'latest'"
echo "Install with: npm install -g cline"
@@ -239,20 +202,16 @@ jobs:
token: ${{ secrets.SLACK_RELEASE_BOT_TOKEN }}
payload: |
channel: "C0APVKGGZFC"
text: "Cline CLI v${{ steps.version.outputs.version }}"
text: "Cline SDK CLI v${{ steps.version.outputs.version }}"
blocks:
- type: "section"
text:
type: "mrkdwn"
text: "Cline CLI v${{ steps.version.outputs.version }}"
- type: "section"
text:
type: "mrkdwn"
text: ${{ toJSON(steps.changelog.outputs.content) }}
text: "Cline SDK CLI v${{ steps.version.outputs.version }}"
- type: "context"
elements:
- type: "mrkdwn"
text: "<https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}|View on npm>${{ steps.prev_tag.outputs.prev_tag != '' && format(' | Full Changelog: https://github.com/{0}/compare/{1}...{2}', github.repository, steps.prev_tag.outputs.prev_tag, steps.version.outputs.tag) || '' }}"
text: "<https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}|View on npm>"
publish-nightly:
name: Publish cline nightly
@@ -331,15 +290,6 @@ jobs:
- name: Build SDK packages
if: steps.check_commits.outputs.skip != 'true'
run: bun run build:sdk
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
- name: Run tests
if: steps.check_commits.outputs.skip != 'true'
@@ -360,9 +310,8 @@ jobs:
- name: Update nightly package version
if: steps.check_commits.outputs.skip != 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
VERSION="${{ steps.version.outputs.version }}"
node -e '
const fs = require("node:fs");
const path = "apps/cli/package.json";
@@ -371,26 +320,18 @@ jobs:
fs.writeFileSync(path, `${JSON.stringify(pkg, null, "\t")}\n`);
'
cat apps/cli/package.json | grep '"version"'
env:
VERSION: ${{ steps.version.outputs.version }}
- name: Build platform binaries
if: steps.check_commits.outputs.skip != 'true'
run: bun script/build.ts --install-native-variants --skip-sdk-build
working-directory: apps/cli
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
working-directory: sdk/apps/cli
- name: Verify build output
if: steps.check_commits.outputs.skip != 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
VERSION="${{ steps.version.outputs.version }}"
EXPECTED=(
"@cline/cli-darwin-arm64"
"@cline/cli-darwin-x64"
@@ -424,12 +365,11 @@ jobs:
env:
NPM_CONFIG_PROVENANCE: "true"
run: bun script/publish-npm.ts --tag nightly
working-directory: apps/cli
working-directory: sdk/apps/cli
- name: Summary
if: steps.check_commits.outputs.skip != 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
VERSION="${{ steps.version.outputs.version }}"
echo "Published cline@${VERSION} to npm with dist-tag 'nightly'"
echo "Install with: npm install -g cline@nightly"
@@ -0,0 +1,72 @@
name: "Publish New SDK Extension Nightly"
on:
schedule:
- cron: '0 12 * * *' # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: read
packages: write
checks: write
pull-requests: write
env:
# Keep the publish source pinned to one reviewed branch instead of accepting arbitrary refs.
SDK_NIGHTLY_REF: dpc/sdk-migration-simpler-login
jobs:
publish:
name: Publish Cline New SDK Extension Nightly
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: PublishNightly
steps:
- name: Checkout trusted SDK nightly branch
uses: actions/checkout@v4
with:
ref: ${{ env.SDK_NIGHTLY_REF }}
lfs: true
persist-credentials: false
- name: Setup Node.js
uses: actions/setup-node@v4
with:
# Keep publish environment aligned with test workflow/tooling lockfile expectations.
# Newer LTS (Node 24 / npm 11) can make `npm list` fail with ELSPROBLEMS during vsce packaging.
node-version: 22
- name: Install root dependencies
run: npm ci --include=optional
- name: Install webview-ui dependencies
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
- name: Verify LFS media assets are resolved
run: |
for FILE in webview-ui/src/assets/cline_kanban_demo.mp4 webview-ui/src/assets/cline_kanban_demo.webm; do
if grep -q "git-lfs.github.com/spec/v1" "$FILE"; then
echo "Error: $FILE is still a Git LFS pointer in CI checkout"
exit 1
fi
done
- name: Publish SDK nightly extension
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
OVSX_PAT: ${{ secrets.OVSX_PAT }}
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
# OpenTelemetry production defaults (can be overridden at runtime)
OTEL_TELEMETRY_ENABLED: ${{ secrets.OTEL_TELEMETRY_ENABLED }}
OTEL_LOGS_EXPORTER: otlp
OTEL_METRICS_EXPORTER: otlp
OTEL_EXPORTER_OTLP_PROTOCOL: ${{ secrets.OTEL_EXPORTER_OTLP_PROTOCOL }}
OTEL_EXPORTER_OTLP_ENDPOINT: ${{ secrets.OTEL_EXPORTER_OTLP_ENDPOINT }}
OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.OTEL_EXPORTER_OTLP_HEADERS }}
run: npm run publish:marketplace:nightly
@@ -1,4 +1,4 @@
name: ext-vscode-publish-nightly
name: "Publish Nightly Release"
on:
workflow_dispatch:
@@ -10,33 +10,24 @@ run-name: "Publish Nightly from ${{ github.ref_name }} @ ${{ github.sha }}"
# runs on the same ref can collide on the same version and cause publish failures
# or inconsistent tagging. Runs on different branches proceed independently.
concurrency:
group: ext-vscode-publish-nightly-${{ github.ref }}
group: publish-nightly-${{ github.ref }}
cancel-in-progress: false
permissions: {}
permissions:
contents: write
checks: write
jobs:
test:
if: github.repository == 'cline/cline' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dpc/sdk-migration-simpler-login')
permissions:
contents: read
pull-requests: read
uses: ./.github/workflows/ext-vscode-test.yml
uses: ./.github/workflows/test.yml
publish:
needs: test
permissions:
contents: write
name: Publish Cline (Nightly) Extension
if: github.repository == 'cline/cline' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dpc/sdk-migration-simpler-login')
runs-on: ubuntu-latest
environment: PublishNightly
# The VS Code extension's package.json and lockfiles live under apps/vscode/
# (the repo root has no package.json). Mirror ext-vscode-test.yml so install
# and publish steps run in the correct workspace.
defaults:
run:
working-directory: apps/vscode
steps:
- name: Checkout selected branch
@@ -47,7 +38,6 @@ jobs:
persist-credentials: false
- name: Show build source
working-directory: ${{ github.workspace }}
run: |
echo "Building ref: $GITHUB_REF"
echo "Building sha: $GITHUB_SHA"
@@ -59,22 +49,25 @@ jobs:
# Keep publish environment aligned with test workflow/tooling lockfile expectations.
# Newer LTS (Node 24 / npm 11) can make `npm list` fail with ELSPROBLEMS during vsce packaging.
node-version: 22
cache: 'npm'
cache-dependency-path: |
apps/vscode/package-lock.json
apps/vscode/webview-ui/package-lock.json
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode ci --include=optional
- name: Install root dependencies
run: npm ci --include=optional
- name: Install webview-ui dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/webview-ui ci --include=optional
run: cd webview-ui && npm ci --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
- name: Verify LFS media assets are resolved
run: |
for FILE in webview-ui/src/assets/cline_kanban_demo.mp4 webview-ui/src/assets/cline_kanban_demo.webm; do
if grep -q "git-lfs.github.com/spec/v1" "$FILE"; then
echo "Error: $FILE is still a Git LFS pointer in CI checkout"
exit 1
fi
done
- name: Publish Nightly Extension
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
@@ -92,7 +85,6 @@ jobs:
run: npm run publish:marketplace:nightly
- name: Tag published commit
working-directory: ${{ github.workspace }}
env:
GH_TOKEN: ${{ github.token }}
run: |
@@ -1,4 +1,4 @@
name: sdk-publish
name: Publish Main SDK Packages
on:
workflow_dispatch:
@@ -26,7 +26,7 @@ on:
defaults:
run:
working-directory: .
working-directory: sdk
jobs:
test:
@@ -59,23 +59,19 @@ jobs:
- name: Determine publish channel
id: channel
env:
EVENT_NAME: ${{ github.event_name }}
INPUT_CHANNEL: ${{ inputs.channel }}
run: |
# Default to nightly for scheduled runs
if [ "$EVENT_NAME" = "schedule" ]; then
if [ "${{ github.event_name }}" = "schedule" ]; then
echo "channel=nightly" >> $GITHUB_OUTPUT
else
echo "channel=$INPUT_CHANNEL" >> $GITHUB_OUTPUT
echo "channel=${{ inputs.channel }}" >> $GITHUB_OUTPUT
fi
- name: Check for recent commits
id: check_commits
env:
CHANNEL: ${{ steps.channel.outputs.channel }}
FORCE_PUBLISH: ${{ inputs.force_publish }}
run: |
CHANNEL="${{ steps.channel.outputs.channel }}"
# Always publish for latest (production) releases
if [ "$CHANNEL" = "latest" ]; then
echo "Production release requested, proceeding with publish"
@@ -83,7 +79,7 @@ jobs:
exit 0
fi
if [ "$FORCE_PUBLISH" = "true" ]; then
if [ "${{ inputs.force_publish }}" = "true" ]; then
echo "force_publish enabled, proceeding with publish"
echo "skip=false" >> $GITHUB_OUTPUT
exit 0
@@ -145,10 +141,9 @@ jobs:
- name: Generate shared version
if: steps.check_commits.outputs.skip != 'true'
id: version
env:
CHANNEL: ${{ steps.channel.outputs.channel }}
run: |
BASE_VERSION=$(node -p "require('./sdk/packages/llms/package.json').version")
CHANNEL="${{ steps.channel.outputs.channel }}"
BASE_VERSION=$(node -p "require('./packages/llms/package.json').version")
if [ "$CHANNEL" = "nightly" ]; then
TIMESTAMP=$(date +%s)
@@ -164,13 +159,11 @@ jobs:
- name: Update all package versions and lockfile
if: steps.check_commits.outputs.skip != 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
run: bun sdk/scripts/version.ts "$VERSION"
run: bun scripts/version.ts "${{ steps.version.outputs.version }}"
- name: Verify publishability
if: steps.check_commits.outputs.skip != 'true'
run: bun sdk/scripts/check-publish.ts
run: bun scripts/check-publish.ts
- name: Prepare package tarball directory
if: steps.check_commits.outputs.skip != 'true'
@@ -183,11 +176,10 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
env:
NPM_CONFIG_PROVENANCE: "true"
CHANNEL: ${{ steps.channel.outputs.channel }}
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "Publishing @cline/shared@${VERSION} with tag '${CHANNEL}'..."
cd sdk/packages/shared
CHANNEL="${{ steps.channel.outputs.channel }}"
echo "Publishing @cline/shared@${{ steps.version.outputs.version }} with tag '${CHANNEL}'..."
cd packages/shared
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
@@ -195,11 +187,10 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
env:
NPM_CONFIG_PROVENANCE: "true"
CHANNEL: ${{ steps.channel.outputs.channel }}
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "Publishing @cline/llms@${VERSION} with tag '${CHANNEL}'..."
cd sdk/packages/llms
CHANNEL="${{ steps.channel.outputs.channel }}"
echo "Publishing @cline/llms@${{ steps.version.outputs.version }} with tag '${CHANNEL}'..."
cd packages/llms
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
@@ -207,11 +198,10 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
env:
NPM_CONFIG_PROVENANCE: "true"
CHANNEL: ${{ steps.channel.outputs.channel }}
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "Publishing @cline/agents@${VERSION} with tag '${CHANNEL}'..."
cd sdk/packages/agents
CHANNEL="${{ steps.channel.outputs.channel }}"
echo "Publishing @cline/agents@${{ steps.version.outputs.version }} with tag '${CHANNEL}'..."
cd packages/agents
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
@@ -219,11 +209,10 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
env:
NPM_CONFIG_PROVENANCE: "true"
CHANNEL: ${{ steps.channel.outputs.channel }}
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "Publishing @cline/core@${VERSION} with tag '${CHANNEL}'..."
cd sdk/packages/core
CHANNEL="${{ steps.channel.outputs.channel }}"
echo "Publishing @cline/core@${{ steps.version.outputs.version }} with tag '${CHANNEL}'..."
cd packages/core
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
@@ -231,19 +220,18 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
env:
NPM_CONFIG_PROVENANCE: "true"
CHANNEL: ${{ steps.channel.outputs.channel }}
VERSION: ${{ steps.version.outputs.version }}
run: |
echo "Publishing @cline/sdk@${VERSION} with tag '${CHANNEL}'..."
cd sdk/packages/sdk
CHANNEL="${{ steps.channel.outputs.channel }}"
echo "Publishing @cline/sdk@${{ steps.version.outputs.version }} with tag '${CHANNEL}'..."
cd packages/sdk
TARBALL=$(bun pm pack --destination "$RUNNER_TEMP/sdk-npm-packs" --quiet)
npm publish "$RUNNER_TEMP/sdk-npm-packs/$(basename "$TARBALL")" --tag "$CHANNEL" --access public
- name: Create package tags for production publish
if: steps.check_commits.outputs.skip != 'true' && steps.channel.outputs.channel == 'latest'
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
VERSION="${{ steps.version.outputs.version }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
@@ -262,10 +250,9 @@ jobs:
- name: Summary
if: steps.check_commits.outputs.skip != 'true'
env:
VERSION: ${{ steps.version.outputs.version }}
CHANNEL: ${{ steps.channel.outputs.channel }}
run: |
VERSION="${{ steps.version.outputs.version }}"
CHANNEL="${{ steps.channel.outputs.channel }}"
echo "Published SDK packages with tag '${CHANNEL}':"
echo " - @cline/shared@${VERSION}"
echo " - @cline/llms@${VERSION}"
@@ -1,4 +1,4 @@
name: ext-vscode-publish-stable
name: "Publish Release"
on:
workflow_dispatch:
@@ -29,16 +29,13 @@ permissions:
jobs:
test:
uses: ./.github/workflows/ext-vscode-test.yml
uses: ./.github/workflows/test.yml
publish:
needs: test
name: Publish Extension
runs-on: ubuntu-latest
environment: publish
defaults:
run:
working-directory: apps/vscode
steps:
- uses: actions/checkout@v4
@@ -50,7 +47,6 @@ jobs:
- name: Resolve Release Tag
id: resolve_tag
working-directory: ${{ github.workspace }}
env:
TAG: ${{ github.event.inputs.tag }}
AUTO_CREATE: ${{ github.event.inputs.auto_create_tag_from_main }}
@@ -114,13 +110,11 @@ jobs:
with:
node-version: 22
- name: Install extension dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode install --include=optional
- name: Install root dependencies
run: npm install --include=optional
- name: Install webview-ui dependencies
working-directory: ${{ github.workspace }}
run: npm --prefix apps/vscode/webview-ui install --include=optional
run: cd webview-ui && npm install --include=optional
- name: Install Publishing Tools
run: npm install -g @vscode/vsce ovsx
@@ -141,6 +135,15 @@ jobs:
fi
echo "Tag and package version match: $TAG"
- name: Verify LFS media assets are resolved
run: |
for FILE in webview-ui/src/assets/cline_kanban_demo.mp4 webview-ui/src/assets/cline_kanban_demo.webm; do
if grep -q "git-lfs.github.com/spec/v1" "$FILE"; then
echo "Error: $FILE is still a Git LFS pointer in CI checkout"
exit 1
fi
done
- name: Package and Publish Extension
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}
@@ -177,7 +180,6 @@ jobs:
- name: Get Previous Tag
id: prev_tag
working-directory: ${{ github.workspace }}
run: |
CURRENT_TAG="${{ steps.resolve_tag.outputs.tag }}"
PREV_TAG=$(git describe --tags --abbrev=0 "$CURRENT_TAG^" 2>/dev/null || echo "")
@@ -185,7 +187,6 @@ jobs:
- name: Get Changelog Entry
id: changelog
working-directory: ${{ github.workspace }}
run: |
# Get content between first ## [ and second ## [
CONTENT=$(awk '/^## \[/{if(found) exit; found=1; next} found{print}' CHANGELOG.md)
@@ -197,7 +198,7 @@ jobs:
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ steps.resolve_tag.outputs.tag }}
files: "apps/vscode/*.vsix"
files: "*.vsix"
body: |
${{ steps.changelog.outputs.content }}
+5 -5
View File
@@ -1,4 +1,4 @@
name: sdk-test
name: SDK Tests
on:
push:
@@ -21,7 +21,7 @@ permissions:
defaults:
run:
working-directory: .
working-directory: sdk
jobs:
quality-checks:
@@ -96,12 +96,12 @@ jobs:
- name: Run SDK Tests (Windows)
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'windows-latest' }}
run: bun -F './sdk/packages/**' test
run: bun -F './packages/**' test
- name: Smoke test SQLite under Node
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && matrix.os != 'windows-latest' }}
timeout-minutes: 10
run: bun sdk/scripts/ci-node-smoke.ts
run: bun scripts/ci-node-smoke.ts
- name: Run TUI e2e tests
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'ubuntu-latest' && matrix.node-version == '24.x' }}
@@ -109,4 +109,4 @@ jobs:
- name: Verify packages are publishable
if: ${{ !cancelled() && steps.build_sdk_step.outcome == 'success' && steps.build_cli_step.outcome == 'success' && matrix.os == 'ubuntu-latest' && matrix.node-version == '24.x' }}
run: bun sdk/scripts/check-publish.ts
run: bun scripts/check-publish.ts
@@ -1,6 +1,6 @@
# This workflow will only label and/or close 30 issues at a time in order to avoid exceeding a rate limit.
# More info: https://docs.github.com/en/actions/use-cases-and-examples/project-management/closing-inactive-issues
name: repo-stale-issues
name: Close inactive issues
on:
schedule:
- cron: "30 1 * * *"
+32
View File
@@ -0,0 +1,32 @@
name: Test Stale Issues Workflow
on:
workflow_dispatch:
inputs:
days-before-stale:
description: "Days before an issue becomes stale"
required: true
default: "1"
days-before-close:
description: "Days before a stale issue is closed"
required: true
default: "1"
jobs:
test-stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@28ca103
with:
days-before-issue-stale: ${{ github.event.inputs.days-before-stale }}
days-before-issue-close: ${{ github.event.inputs.days-before-close }}
stale-issue-label: "stale"
stale-issue-message: "This issue is stale because it has been open for ${{ github.event.inputs.days-before-stale }} days with no activity."
close-issue-message: "This issue was closed because it has been inactive for ${{ github.event.inputs.days-before-close }} days since being marked as stale."
days-before-pr-stale: -1
days-before-pr-close: -1
exempt-issue-labels: "pinned,security"
repo-token: ${{ secrets.GITHUB_TOKEN }}
debug-only: true
+247
View File
@@ -0,0 +1,247 @@
name: Tests
on:
push:
branches:
- main
workflow_dispatch:
pull_request:
branches:
- main
workflow_call:
# Set default permissions for all jobs
permissions:
contents: read # Needed to check out code
checks: write # Needed to report test results
pull-requests: write # Needed to add comments/annotations to PRs
jobs:
quality-checks:
runs-on: ubuntu-latest
name: Quality Checks
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
package-lock.json
webview-ui/package-lock.json
- name: Install root dependencies
run: npm ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
run: cd webview-ui && npm ci
- name: Run Quality Checks (Parallel)
run: npm run ci:check-all
test:
needs: quality-checks
env:
VSCODE_TEST_VERSION: 1.103.0
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
name: ${{ matrix.os == 'ubuntu-latest' && 'test' || format('test ({0})', matrix.os) }}
defaults:
run:
shell: bash
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
package-lock.json
webview-ui/package-lock.json
- name: Install root dependencies
run: npm ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
run: cd webview-ui && npm ci
- name: Set up NPM on Windows
if: runner.os == 'Windows'
run: |
npm config set script-shell "C:\\Program Files\\Git\\bin\\bash.exe"
- name: Cache VS Code test runtime
if: runner.os == 'Windows'
uses: actions/cache@v4
with:
path: .vscode-test
key: vscode-test-runtime-${{ runner.os }}-${{ env.VSCODE_TEST_VERSION }}
# Build the extension and tests (without redundant checks)
- name: Build Tests and Extension
id: build_step
run: npm run ci:build
- name: Unit Tests with coverage - Linux
id: unit_tests_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
run: |
npx nyc --nycrc-path .nycrc.unit.json --reporter=lcov npm run test:unit
- name: Unit Tests - Non-Linux
id: unit_tests_non_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
run: |
npm run test:unit
- name: Extension Integration Tests - Linux
id: integration_tests_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os == 'Linux' }}
run: xvfb-run -a npm run test:coverage
- name: Extension Integration Tests - Non-Linux
id: integration_tests_non_linux
if: ${{ !cancelled() && steps.build_step.outcome == 'success' && runner.os != 'Linux' }}
run: |
for attempt in 1 2 3; do
echo "Running extension integration tests (attempt ${attempt}/3)"
if npm run test:integration; then
exit 0
fi
if [ "$attempt" -eq 3 ]; then
echo "Extension integration tests failed after 3 attempts"
exit 1
fi
echo "Extension integration tests failed; retrying after short delay"
sleep 5
done
- name: Webview Tests with Coverage
id: webview_tests
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
run: |
cd webview-ui
npm run test:coverage
- name: CLI Tests
id: cli_tests
if: ${{ !cancelled() && steps.build_step.outcome == 'success' }}
run: cd cli && npm run test:run
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
# Only upload artifacts on Linux - We only need coverage from one OS
if: runner.os == 'Linux'
with:
name: pr-coverage-reports
path: |
coverage-unit/lcov.info
webview-ui/coverage/lcov.info
test-platform-integration:
needs: quality-checks
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js environment
uses: actions/setup-node@v4
with:
node-version: 22
cache: 'npm'
cache-dependency-path: |
package-lock.json
webview-ui/package-lock.json
testing-platform/package-lock.json
- name: Install root dependencies
run: npm ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install webview-ui dependencies
run: cd webview-ui && npm ci
- name: Download ripgrep binaries
run: npm run download-ripgrep
- name: Compile Standalone
run: npm run compile-standalone
- name: Install testing platform dependencies
run: cd testing-platform && npm ci
- name: Running testing platform integration spec tests
timeout-minutes: 7
run: npm run test:tp-orchestrator -- tests/specs/ --count=1 --coverage
- name: Save Coverage Reports
uses: actions/upload-artifact@v4
with:
name: test-platform-integration-core-coverage
path: coverage/**/lcov.info
qlty:
needs: [test, test-platform-integration]
runs-on: ubuntu-latest
# Run on PRs to main, pushes to main, and manual dispatches
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Download unit tests coverage reports
uses: actions/download-artifact@v4
with:
name: pr-coverage-reports
path: .
- name: Upload core unit tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
coverage-unit/lcov.info
tag: unit:core
- name: Upload webview-ui unit tests coverage to Qlty
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
# we can merge multiple files if necessary
files: |
webview-ui/coverage/lcov.info
tag: unit:webview-ui
add-prefix: webview-ui/
- name: Download test platform integration core coverage artifact
uses: actions/download-artifact@v4
continue-on-error: true
id: download-integration-coverage
with:
name: test-platform-integration-core-coverage
path: integration-core-coverage-reports
- name: Upload core integration tests coverage to Qlty
if: steps.download-integration-coverage.outcome == 'success'
uses: qltysh/qlty-action/coverage@v2
with:
token: ${{ secrets.QLTY_COVERAGE_TOKEN }}
files: integration-core-coverage-reports/**/lcov.info
tag: integration:core
@@ -1,4 +1,4 @@
name: ext-jb-test-integration
name: Trigger Jetbrains Plugin <-> Cline Tests
on:
pull_request_target:
types: [opened, reopened]
@@ -15,11 +15,9 @@ jobs:
trigger-integration-test:
name: Run Tests
runs-on: ubuntu-latest
# Auto-run only for trusted PR authors. Anyone else needs a maintainer
# to opt their PR in by commenting /test-jetbrains.
# Run on PR open/reopen, or when someone comments /test-jetbrains on a PR
if: |
(github.event_name == 'pull_request_target' &&
contains(fromJSON('["MEMBER","OWNER","COLLABORATOR"]'), github.event.pull_request.author_association)) ||
github.event_name == 'pull_request_target' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request &&
contains(github.event.comment.body, '/test-jetbrains') &&
@@ -29,8 +27,8 @@ jobs:
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ vars.CLINE_JETBRAINS_APP_ID }}
private-key: ${{ secrets.CLINE_JETBRAINS_APP_KEY }}
app-id: 1998650
private-key: ${{ secrets.CLINE_JETBRAINS_WORKFLOW_KEY }}
owner: cline
repositories: intellij-plugin
+5 -29
View File
@@ -13,15 +13,12 @@ tmp
pnpm-lock.yaml
.clineignore
.cline/enterprise
.cline/remote-config
**/.cline/remote-config
.venv
.actrc
CLAUDE.local.md
apps/vscode/webview-ui/src/**/*.js
apps/vscode/webview-ui/src/**/*.js.map
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
# Ignore coverage directories and files
coverage
@@ -38,9 +35,9 @@ coverage-unit
.worktrees
## Generated files ##
apps/vscode/src/generated/
apps/vscode/src/shared/proto/
apps/vscode/webview-ui/src/services/grpc-client.ts
src/generated/
src/shared/proto/
webview-ui/src/services/grpc-client.ts
*.tsbuildinfo
# E2E Tests
@@ -63,24 +60,3 @@ tests/**/cache
# Backup created by scripts/marketplace-readme.mjs while publishing.
# Should never be committed: only exists if a publish aborts mid-swap.
.README.github.bak
# Tauri generated code
apps/*/src-tauri/gen
apps/*/src-tauri/bin
apps/examples/*/src-tauri/gen
apps/examples/*/src-tauri/bin
# Tauri UI test snapshots
apps/*/src/tests/.tui-test
apps/*/src/tests/tui-traces
apps/vscode/webview-ui/src/**/*.js
apps/vscode/webview-ui/src/**/*.js.map
# SDK Session files / User data
.cline/data
.cline/tmp
*.db
*.db-shm
*.db-wal
.cline/**/managed.json
.cline/**/bundle.json
+1 -11
View File
@@ -1,11 +1 @@
if ! command -v gitleaks >/dev/null 2>&1; then
echo "gitleaks is required for the pre-commit secret scan."
echo "Install it with: brew install gitleaks"
echo "Other install options: https://github.com/gitleaks/gitleaks#installing"
exit 1
fi
gitleaks git --pre-commit --redact --staged --verbose || exit 1
cd apps/vscode && lint-staged
lint-staged
+16
View File
@@ -0,0 +1,16 @@
{
"extension": [
"ts"
],
"spec": [
"src/**/__tests__/*.ts",
"src/test/services/**/*.test.ts"
],
"require": [
"ts-node/register",
"source-map-support/register",
"./src/test/requires.ts"
],
"recursive": true,
"exit": true
}
+1 -1
View File
@@ -1 +1 @@
22
lts/*
@@ -1,13 +1,9 @@
import { defineConfig } from "@vscode/test-cli"
import path from "path"
const vscodeTestVersion = process.env.VSCODE_TEST_VERSION ?? "stable"
export default defineConfig({
files: [
"out/src/{core,test,utils,shared,integrations,hosts,services}/**/*.test.js",
"src/{core,test,utils,shared,integrations,hosts,services}/**/*.test.js",
],
files: "{out/**/*.test.js,src/**/*.test.js,!src/test/e2e/**/*.test.js,!out/src/test/e2e/**/*.test.js}",
mocha: {
ui: "bdd",
timeout: 20000, // Maximum time (in ms) that a test can run before failing
+1 -2
View File
@@ -5,7 +5,6 @@
"connor4312.esbuild-problem-matchers",
"ms-vscode.extension-test-runner",
"bradlc.vscode-tailwindcss",
"biomejs.biome",
"oven.bun-vscode"
"biomejs.biome"
]
}
+31 -144
View File
@@ -10,23 +10,23 @@
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}/apps/vscode",
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}/apps/vscode",
"${workspaceFolder}",
"--disable-extensions"
],
"outFiles": [
"${workspaceFolder}/apps/vscode/dist/**/*.js"
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}",
"envFile": "${workspaceFolder}/apps/vscode/.env",
"envFile": "${workspaceFolder}/.env",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}/apps/vscode",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
@@ -35,22 +35,22 @@
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}/apps/vscode",
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}/apps/vscode"
"${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/apps/vscode/dist/**/*.js"
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}",
"envFile": "${workspaceFolder}/apps/vscode/.env",
"envFile": "${workspaceFolder}/.env",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}/apps/vscode",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "staging"
}
},
@@ -59,22 +59,22 @@
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}/apps/vscode",
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}/apps/vscode"
"${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/apps/vscode/dist/**/*.js"
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "${defaultBuildTask}",
"envFile": "${workspaceFolder}/apps/vscode/.env",
"envFile": "${workspaceFolder}/.env",
"env": {
"IS_DEV": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}/apps/vscode",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "local"
}
},
@@ -84,27 +84,27 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--user-data-dir=${workspaceFolder}/apps/vscode/dist/tmp/user",
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync=off",
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--extensionDevelopmentPath=${workspaceFolder}/apps/vscode",
"${workspaceFolder}/apps/vscode"
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/apps/vscode/dist/**/*.js"
"${workspaceFolder}/dist/**/*.js"
],
"preLaunchTask": "clean-tmp-user",
"internalConsoleOptions": "openOnSessionStart",
"postDebugTask": "stop",
"envFile": "${workspaceFolder}/apps/vscode/.env",
"envFile": "${workspaceFolder}/.env",
"env": {
"IS_DEV": "true",
"TEMP_PROFILE": "true",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}/apps/vscode",
"DEV_WORKSPACE_FOLDER": "${workspaceFolder}",
"CLINE_ENVIRONMENT": "production"
}
},
@@ -117,13 +117,13 @@
],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/apps/vscode/**",
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}/apps/vscode",
"cwd": "${workspaceFolder}",
"outFiles": [
"${workspaceFolder}/apps/vscode/dist/**/*.js",
"${workspaceFolder}/apps/vscode/dist-standalone/**/*.js"
"${workspaceFolder}/dist/**/*.js",
"${workspaceFolder}/dist-standalone/**/*.js"
],
"preLaunchTask": "compile-standalone",
"runtimeExecutable": "npx",
@@ -131,11 +131,11 @@
"tsx"
],
"program": "scripts/test-standalone-core-api-server.ts",
"envFile": "${workspaceFolder}/apps/vscode/.env",
"envFile": "${workspaceFolder}/.env",
"env": {
"PROTOBUS_PORT": "26040",
"HOSTBRIDGE_PORT": "26041",
"WORKSPACE_DIR": "${workspaceFolder}/apps/vscode",
"WORKSPACE_DIR": "${workspaceFolder}",
"E2E_TEST": "true",
"CLINE_ENVIRONMENT": "local"
},
@@ -151,10 +151,10 @@
],
"sourceMaps": true,
"resolveSourceMapLocations": [
"${workspaceFolder}/apps/vscode/**",
"${workspaceFolder}/**",
"!**/node_modules/**"
],
"cwd": "${workspaceFolder}/apps/vscode",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "npx",
"runtimeArgs": [
"mocha"
@@ -169,7 +169,7 @@
"--exit",
"${file}"
],
"envFile": "${workspaceFolder}/apps/vscode/.env",
"envFile": "${workspaceFolder}/.env",
"env": {
"TS_NODE_PROJECT": "./tsconfig.unit-test.json",
"NODE_ENV": "test",
@@ -188,7 +188,7 @@
"run",
"storybook"
],
"cwd": "${workspaceFolder}/apps/vscode/webview-ui",
"cwd": "${workspaceFolder}/webview-ui",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"serverReadyAction": {
@@ -199,119 +199,6 @@
"env": {
"IS_DEV": "true"
}
},
{
"name": "Launch Bun CLI (Prompt)",
"type": "bun",
"request": "launch",
"cwd": "${workspaceFolder}/sdk/apps/cli",
"runtime": "bun",
"runtimeArgs": [
"--conditions=development"
],
"program": "${workspaceFolder}/sdk/apps/cli/src/index.ts",
"args": [
"${input:cliPrompt}"
],
"env": {
"CLINE_BUILD_ENV": "development"
},
"presentation": {
"hidden": true
}
},
{
"name": "Launch RPC Server",
"type": "bun",
"request": "launch",
"cwd": "${workspaceFolder}/sdk/apps/cli",
"runtime": "bun",
"runtimeArgs": [
"--conditions=development"
],
"program": "${workspaceFolder}/sdk/apps/cli/src/index.ts",
"args": [
"rpc",
"start"
],
"env": {
"CLINE_BUILD_ENV": "development",
"CLINE_DEBUG_PORT_BASE": "9230"
},
"presentation": {
"hidden": true
}
},
{
"name": "Attach RPC Runtime (9230)",
"type": "bun",
"request": "attach",
"url": "ws://127.0.0.1:9230",
"localRoot": "${workspaceFolder}/sdk",
"remoteRoot": "${workspaceFolder}/sdk",
"presentation": {
"hidden": true
}
},
{
"name": "Attach Hook Worker (9231)",
"type": "bun",
"request": "attach",
"url": "ws://127.0.0.1:9231",
"localRoot": "${workspaceFolder}/sdk",
"remoteRoot": "${workspaceFolder}/sdk",
"presentation": {
"hidden": true
}
},
{
"name": "Attach Plugin Sandbox (9232)",
"type": "bun",
"request": "attach",
"url": "ws://127.0.0.1:9232",
"localRoot": "${workspaceFolder}/sdk",
"remoteRoot": "${workspaceFolder}/sdk",
"presentation": {
"hidden": true
}
},
{
"name": "Attach Connector Child (9233)",
"type": "bun",
"request": "attach",
"url": "ws://127.0.0.1:9233",
"localRoot": "${workspaceFolder}/sdk",
"remoteRoot": "${workspaceFolder}/sdk",
"presentation": {
"hidden": true
}
}
],
"compounds": [
{
"name": "Launch RPC Server Debugger",
"configurations": [
"Launch RPC Server",
"Attach RPC Runtime (9230)"
]
},
{
"name": "Launch CLI Debugger",
"configurations": [
"Launch Bun CLI (Prompt)",
"Attach RPC Runtime (9230)",
"Attach Hook Worker (9231)",
"Attach Plugin Sandbox (9232)",
"Attach Connector Child (9233)"
]
}
],
"inputs": [
{
"id": "cliPrompt",
"type": "promptString",
"description": "Prompt to send to the CLI",
"default": "hey"
}
]
}
+1 -2
View File
@@ -1,6 +1,5 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.insertFinalNewline": true,
"files.exclude": {
"out": false, // set this to true to hide the "out" folder with the compiled JS files
"dist": false // set this to true to hide the "dist" folder with the compiled JS files
@@ -17,7 +16,7 @@
// Protobuf settings
"protoc": {
"options": [
"--proto_path=apps/vscode/proto"
"--proto_path=proto"
]
},
// Enable Lint and format using Biome
+22 -50
View File
@@ -5,28 +5,24 @@
"tasks": [
{
"label": "compile-standalone",
"type": "shell",
"command": "npm run compile-standalone",
"type": "npm",
"script": "compile-standalone",
"group": "build",
"problemMatcher": [],
"presentation": {
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode"
}
},
{
"label": "npm: protos",
"type": "shell",
"command": "npm run protos",
"type": "npm",
"script": "protos",
"problemMatcher": [],
"isBackground": false,
"presentation": {
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true"
}
@@ -64,8 +60,8 @@
"group": "build"
},
{
"type": "shell",
"command": "npm run build:webview",
"type": "npm",
"script": "build:webview",
"group": "build",
"problemMatcher": [],
"isBackground": true,
@@ -78,15 +74,14 @@
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true"
}
}
},
{
"type": "shell",
"command": "npm run build:webview:test",
"type": "npm",
"script": "build:webview:test",
"group": "build",
"problemMatcher": [],
"isBackground": true,
@@ -99,7 +94,6 @@
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true",
"IS_TEST": "true"
@@ -107,8 +101,8 @@
}
},
{
"type": "shell",
"command": "npm run dev:webview",
"type": "npm",
"script": "dev:webview",
"group": "build",
"problemMatcher": [
{
@@ -137,15 +131,14 @@
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true"
}
}
},
{
"type": "shell",
"command": "npm run watch:esbuild",
"type": "npm",
"script": "watch:esbuild",
"group": "build",
"problemMatcher": {
"pattern": [
@@ -176,15 +169,14 @@
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true"
}
}
},
{
"type": "shell",
"command": "npm run watch:esbuild:test",
"type": "npm",
"script": "watch:esbuild:test",
"group": "build",
"problemMatcher": {
"pattern": [
@@ -215,7 +207,6 @@
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true",
"IS_TEST": "true"
@@ -223,8 +214,8 @@
}
},
{
"type": "shell",
"command": "npm run watch:tsc",
"type": "npm",
"script": "watch:tsc",
"group": "build",
"problemMatcher": "$tsc-watch",
"isBackground": true,
@@ -235,15 +226,11 @@
"presentation": {
"group": "watch",
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode"
}
},
{
"type": "shell",
"command": "npm run watch-tests",
"label": "npm: watch-tests",
"type": "npm",
"script": "watch-tests",
"problemMatcher": "$tsc-watch",
"isBackground": true,
"dependsOn": [
@@ -253,10 +240,7 @@
"reveal": "always",
"group": "watchers"
},
"group": "build",
"options": {
"cwd": "${workspaceFolder}/apps/vscode"
}
"group": "build"
},
{
"label": "tasks: watch-tests",
@@ -278,11 +262,11 @@
"dependsOn": [
"watch"
],
"command": "rm -rf ${workspaceFolder}/apps/vscode/dist/tmp/user && mkdir -p ${workspaceFolder}/apps/vscode/dist/tmp/user"
"command": "rm -rf ${workspaceFolder}/dist/tmp/user && mkdir -p ${workspaceFolder}/dist/tmp/user"
},
{
"type": "shell",
"command": "npm run storybook",
"type": "npm",
"script": "storybook",
"group": "build",
"problemMatcher": [],
"isBackground": false,
@@ -295,22 +279,10 @@
"reveal": "always"
},
"options": {
"cwd": "${workspaceFolder}/apps/vscode",
"env": {
"IS_DEV": "true"
}
}
},
{
"label": "build-sdk",
"type": "shell",
"command": "bun run build:sdk",
"problemMatcher": [
"$tsc"
],
"options": {
"cwd": "${workspaceFolder}"
}
}
],
"inputs": [
+3 -4
View File
@@ -2,10 +2,6 @@
.vscode/**
.vscode-test/**
.worktrees/**
# Agent tooling, never shipped in the VSIX
.agents/**
.claude/**
.codex/**
CLAUDE.local.md
out/
dist-standalone/
@@ -26,6 +22,9 @@ eslint-rules/**
.husky/**
.env
# cli
cli/**
# sdk (separate monorepo with its own build/release pipeline)
sdk/**
-86
View File
@@ -1,91 +1,5 @@
# Changelog
## [3.87.0]
### Added
- Add MiniMax M3 model support.
### Fixed
- Update VS Code extension dependencies to resolve security issues in `@xmldom/xmldom`, `basic-ftp`, `axios`, `undici`, and other direct/transitive packages.
## [3.86.2]
### Fixed
- Fix `@` file mentions and workspace file search on VS Code 1.122+ by resolving the new bundled `@vscode/ripgrep-universal` per-platform binary layout before falling back to legacy ripgrep paths.
## [3.86.1]
### Fixed
- Fix `@` file mentions failing to find files in some environments (notably VS Code Remote SSH, and after certain VS Code updates) by keeping the file-search fallback alive when the workspace index or bundled ripgrep binary is unavailable.
## [3.86.0]
### Added
- Add Claude Opus 4.8 provider support, including 1M-context variants where available.
- Add Moonshot Kimi K2.6 model support.
### Fixed
- Show prompt-cache support for Qwen 3.7 Max in the Cline provider.
- Fix the VS Code nightly publish workflow startup permissions.
### Changed
- Move the VS Code extension project into `apps/vscode`.
## [3.85.0]
### Added
- Add GPT-5.5 support to SAP AI Core.
- Add DeepSeek V4 Flash and Pro models.
- Add Gemini 3.5 Flash to Gemini and Vertex providers.
- Add `/lg-task` URI webhook integration for LG dashboard flows.
### Fixed
- Fix Vertex AI global endpoint handling for Claude models.
- Route Poolside Laguna models through next-gen prompts and native tool calling.
### Changed
- Update `diff` and `protobufjs` dependencies.
## [3.84.0]
### Added
- Add SAP AI Core support for additional hosted models
### Fixed
- Disable the MCP "Restart Server" button when a server is toggled off.
### Changed
- Remove the Cline Kanban launch modal and bundled demo media from the VS Code extension startup flow.
## [3.83.0]
### Fixed
- Show a clear "Searching..." state in the @-mention file picker
- Improve @-mention file search performance
- Allow `write_to_file` to create or overwrite files with empty content.
- Fix validation failures for MCP servers that require an object.
- Enable OpenRouter prompt cache control for Qwen models.
- Update Axios and SAP Connectivity dependencies
### Changed
- Use the VS Code-specific `README.marketplace.md` when packaging and publishing the VS Code extension
- Add telemetry to @-mention search to help diagnose local, remote, and multi-root workspace search behavior.
## [3.82.0]
### Added
+2
View File
@@ -1 +1,3 @@
@.clinerules/general.md
@.clinerules/network.md
@.clinerules/cli.md
+2 -3
View File
@@ -45,7 +45,7 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
3. Install [bun](https://bun.com)
4. Install the necessary dependencies for the extension and webview-gui:
```bash
cd apps/vscode && npm run install:all && cd ../..
npm run install:all
cd sdk && bun run build && cd ..
```
5. Generate Protocol Buffer files (required before first build):
@@ -61,7 +61,7 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
2. Push your branch and create a PR on GitHub. Our CI will:
- Run tests and checks
3. Testing
- Run `cd apps/vscode && npm run test` to run tests locally.
- Run `npm run test` to run tests locally.
- Before submitting PR, run `npm run format:fix` to format your code
### Extension
@@ -73,7 +73,6 @@ We also welcome contributions to our [documentation](https://github.com/cline/cl
- If you dismissed the prompts, you can install them manually from the Extensions panel
2. **Local Development**
- cd into the vscode extension, `cd apps/vscode`
- Run `npm run install:all` to install dependencies
- Run `npm run protos` to generate Protocol Buffer files (required before first build)
- Run `npm run test` to run tests locally
@@ -19,7 +19,7 @@ English | <a href="https://github.com/cline/cline/blob/main/locales/es/README.md
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
</td>
<td align="center">
<a href="https://docs.cline.bot/getting-started/installing-cline" target="_blank"><strong>Getting Started</strong></a>
<a href="https://docs.cline.bot/getting-started/for-new-coders" target="_blank"><strong>Getting Started</strong></a>
</td>
</tbody>
</table>
+34 -54
View File
@@ -5,32 +5,12 @@
<h1 align="center">Cline</h1>
<p align="center">
The open source coding agent in your IDE and terminal.
Autonomous AI coding agents for your IDE, terminal, and applications.
</p>
<div align="center">
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://docs.cline.bot" target="_blank"><strong>Docs</strong></a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank"><strong>Discord</strong></a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank"><strong>r/cline</strong></a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank"><strong>Feature Requests</strong></a>
</td>
<td align="center">
<a href="https://cline.bot/join-us" target="_blank"><strong>Join us!</strong></a>
</td>
</tbody>
</table>
</div>
[Discord](https://discord.gg/cline) | [Documentation](https://docs.cline.bot) | [Reddit](https://www.reddit.com/r/cline/) | [Feature Requests](https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop) | [Careers](https://cline.bot/join-us)
</div>
@@ -51,7 +31,7 @@ for CI/CD and scripting.
npm i -g cline
```
<a href="./apps/cli/README.md">Learn more</a>
<a href="./sdk/apps/cli/README.md">Learn more</a>
<br><br>
</td>
@@ -64,7 +44,7 @@ web-based task board. Each card gets its own
worktree, auto-commit, and dependency chains.
```
npm i -g kanban
npx kanban
```
<a href="https://github.com/cline/kanban">Learn more</a>
@@ -124,22 +104,24 @@ npm install @cline/sdk
---
## Index
## Repository Map
| Product | Description | Location | CHANGELOG |
|---------|------------|--------------|--------------|
| **SDK** | Node.js programmatic agent API and extension exports. | [`sdk/`](https://github.com/cline/cline/tree/main/sdk) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/sdk/CHANGELOG.md) |
| **CLI** | Terminal UI, headless mode, shell commands, and CLI-specific flows. | [`apps/cli/`](https://github.com/cline/cline/tree/main/apps/cli) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/apps/cli/CHANGELOG.md) |
| **VS Code Extension** | The Marketplace extension and extension host integration. | [`/`](https://github.com/cline/cline/tree/main) (WIP migrating) | [CHANGELOG.md](https://github.com/cline/cline/blob/main/CHANGELOG.md) |
| **JetBrains Plugin** | JetBrains-hosted client that talks to the shared agent core. | Currently we are not open-sourcing JetBrains plugins | - |
| **Kanban** | Web-based multi-agent task board. | [`cline/kanban`](https://github.com/cline/kanban) | [CHANGELOG.md](https://github.com/cline/kanban/blob/main/CHANGELOG.md) |
| **Docs site** | Public documentation pages. | [`docs/`](https://docs.cline.bot/) | - |
Cline ships across multiple surfaces. When you are reading about a feature below, use the applicability notes to know where it is available and these paths to find the implementation.
## Edits Code Across Your Project
| Surface | What it is | Pointers |
|---------|------------|--------------|
| **SDK** | Node.js programmatic agent API and extension exports. | [`./sdk/`](https://github.com/cline/cline/tree/main/sdk) |
| **CLI** | Terminal UI, headless mode, shell commands, and CLI-specific flows. | [`./sdk/apps/cli/`](https://github.com/cline/cline/tree/main/sdk/apps/cli) |
| **VS Code Extension** | The Marketplace extension and extension host integration. | [`./`](https://github.com/cline/cline/tree/main) (WIP migrating) |
| **JetBrains Plugin** | JetBrains-hosted client that talks to the shared agent core. | Currently we are not open-sourcing JetBrains plugins |
| **Kanban** | Web-based multi-agent task board. | Kanban app code lives in [`cline/kanban`](https://github.com/cline/kanban). |
| **Docs site** | Public documentation pages. | `docs/` |
Cline reads your project structure, understands the relationships between files, and makes coordinated changes across your codebase. It monitors linter and compiler errors as it works, fixing issues like missing imports, type mismatches, and syntax errors before you even see them. In VS Code and JetBrains, every edit shows up as a diff you can review, modify, or revert. All changes are tracked with checkpoints, so you can easily undo the agent's work.
## Edit Code Across All Your Codebases
## Runs Bash Commands
Cline reads your project structure, understands the relationships between files, and makes coordinated changes across your codebase. It monitors linter and compiler errors as it works, fixing issues like missing imports, type mismatches, and syntax errors before you even see them. In VS Code and JetBrains, every edit shows up as a diff you can review, modify, or revert. All changes are tracked in your file timeline.
## Run Commands and Act to Output
Cline executes commands directly in your terminal and watches the output in real time. Install packages, run build scripts, execute tests, deploy applications, manage databases. For long-running processes like dev servers, Cline continues working in the background and reacts to new output as it appears, catching compile errors, test failures, and server crashes as they happen.
@@ -147,11 +129,11 @@ Cline executes commands directly in your terminal and watches the output in real
Toggle between Plan mode and Act mode. In Plan mode, Cline explores your codebase, asks clarifying questions, and lays out a strategy. Once you're aligned, switch to Act mode and Cline executes the plan. Every file edit and terminal command requires your approval, so you stay in control of what actually changes. Or toggle auto-approve and let Cline run autonomously.
## Rules and Skills
## Rules and Configuration
Define project-specific rules in `.clinerules` files that guide how Cline works in your codebase: coding standards, architecture conventions, deployment procedures, testing requirements. Rules are picked up automatically by the CLI, VS Code extension, and JetBrains plugin. Use skills to let the model load specific rules when needed.
Define project-specific rules in `.clinerules` files that guide how Cline works in your codebase: coding standards, architecture conventions, deployment procedures, testing requirements. Rules are picked up automatically by the CLI, VS Code extension, and JetBrains plugin. Import rules from Cursor or Windsurf formats.
## Works With Every Model
## Works With Every Major Model
Cline is not locked to a single AI provider. Use whichever model fits your workflow:
@@ -168,9 +150,11 @@ Cline is not locked to a single AI provider. Use whichever model fits your workf
| Ollama / LM Studio | Run local models on your machine |
| Any OpenAI-compatible API | Self-hosted or third-party endpoints |
## Extend With Plugins or MCP Servers
## Extend With MCP Servers and Plugins
Extend Cline's capabilities with plugins. Using the SDK, register tools and lifecycle hooks programmatically through the plugin system for logging, auditing, policy enforcement, or adding domain-specific capabilities. Simple plugin example below.
Cline's capabilities are extensible.
1. MCP: Use [MCP servers](https://github.com/modelcontextprotocol) to connect to databases, query APIs, manage cloud infrastructure, and interact with external systems. Use [community-built servers](https://github.com/modelcontextprotocol/servers) or ask Cline to create custom tools on the fly. In the CLI, manage servers with `cline mcp`.
2. Plugins: With the SDK, register tools and lifecycle hooks programmatically through the plugin system for logging, auditing, policy enforcement, or adding domain-specific capabilities. Simple plugin example below.
```typescript
import { Agent, createTool } from "@cline/sdk"
@@ -186,17 +170,15 @@ const deployTool = createTool({
const agent = new Agent({ tools: [deployTool], /* ... */ })
```
...or use [MCP servers](https://github.com/modelcontextprotocol) to connect to databases, query APIs, manage cloud infrastructure, and interact with external systems. Use [community-built servers](https://github.com/modelcontextprotocol/servers) or ask Cline to create custom tools on the fly. In the CLI, manage servers with `cline mcp`.
## Multi-Agent Teams
## Multi-Agent Teams for Cline SDK and Cline CLI
Coordinate multiple agents working together on complex tasks. A coordinator agent breaks the work into subtasks and delegates to specialist agents, each with their own tools and context. Team state persists across sessions so you can pick up where you left off.
```bash
cline --team-name auth-sprint "Plan and implement user authentication with tests"
```
## Scheduled Agents
## Scheduled Agents for Cline SDK and Cline CLI
Run agents on cron schedules for recurring automations. Daily PR summaries, weekly dependency checks, codebase health reports. Schedules persist across restarts and run independently of any terminal session.
@@ -207,20 +189,18 @@ cline schedule create "PR summary" \
--workspace /path/to/repo
```
## Connect to Slack, Telegram, Discord, and More
## Connect to Slack, Telegram, Discord, and More with Cline CLI
Chat with your agent from any messaging platform: Telegram, Slack, Discord, Google Chat, WhatsApp, and Linear. Each conversation thread maps to an agent session with full context. Set up access control to restrict who can interact with your agent.
Chat with your agent from any messaging platform. Each conversation thread maps to an agent session with full context. Set up access control to restrict who can interact with your agent.
```bash
# Connect to Telegram
cline connect telegram -k $BOT_TOKEN
# Connect to Slack through webhook
cline connect slack --bot-token $SLACK_TOKEN --signing-secret $SECRET --base-url $URL
# Connect to Slack using socket mode
cline connect slack --bot-token $SLACK_TOKEN --app-token $SLACK_APP_TOKEN
cline connect telegram -m my_bot -k $BOT_TOKEN
cline connect slack --token $SLACK_TOKEN --signing-secret $SECRET --base-url $URL
```
## Headless CLI for CI/CD
Supported platforms: Telegram, Slack, Discord, Google Chat, WhatsApp, and Linear.
## Headless Mode for CI/CD with Cline CLI
Run Cline with zero interaction for scripting and automation. Pipe input, get JSON output, chain commands, integrate into CI/CD pipelines.
-12
View File
@@ -1,12 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.5/schema.json",
"root": false,
"extends": ["../sdk/biome.json"],
"linter": {
"rules": {
"a11y": {
"noStaticElementInteractions": "warn"
}
}
}
}
-282
View File
@@ -1,282 +0,0 @@
# Cline CLI Changelog
## 3.0.20
- Installed plugin wrappers are now named from their source (npm package name, git repo, remote filename, official slug, or local directory) instead of an opaque hash, making installed plugins easier to identify.
## 3.0.19
- Fixed CLI auto-update to use `npm update` so updates apply reliably, while preserving the installed release channel (e.g. nightly).
## 3.0.18
- Fix Slack channel mentions so replies post in the original message's thread.
- Fix the abort indicator to clear immediately when a task is cancelled.
- Sync the Fireworks AI model registry and refresh the bundled model catalog with current platform offerings.
- Bump the bundled SDK to v0.0.43, which forces a running Cline Hub to restart so it picks up the latest SDK code.
## 3.0.17
- Fix a regression introduced in 3.0.15 where the interactive CLI could get stuck after stopping and restarting Cline Hub and then pressing Escape to cancel a request. The CLI now detects stale or missing sessions, recovers any pending messages, and starts a fresh session instead of failing with "session not found".
- Fix Ctrl+C and Hub shutdown races that surfaced as "hook dispatch failed" and WebSocket connection errors from late hook events racing against Hub shutdown.
- Fix the Hub daemon being shut down prematurely when a runtime request was aborted, so the daemon now stays alive.
- Improve the Telegram connector with a new `--allowed-user-id` flag to restrict which Telegram users are authorized to interact with the agent.
## 3.0.16
- Install official Cline plugins by slug off the new github.com/cline/plugins collection.
- Uninstall plugins using `cline plugin uninstall <plugin>` or in the TUI.
- Plugins can now bundle skills, and plugin skills are grouped together in settings.
- Add Slack socket mode support.
- Allow a custom base URL for Anthropic vendor-type providers.
- Fix OAuth token migration for users signed in through the old extension.
- Use a union schema for read-files tool input validation.
- Add a `CLINE_PLUGIN_IMPORT_TIMEOUT_MS` env override to control the plugin import timeout.
## 3.0.15
- Add Cline Hub, a web app for monitoring connected clients, viewing and driving sessions, streaming assistant output, and restarting the local hub, with local, LAN, and tunnel usage gated by a room secret.
- Support global AGENTS rules so agent rules can be applied across all sessions, not just per-project.
- Let plugins contribute static or dynamic rule content when installed in the sandbox.
- Bind Discord sessions to individual message authors so different Discord users no longer share chat state in a thread.
- Support participant mute targets in Discord: resolve `/mute` and `/unmute` from user mentions or raw user IDs to mute a specific participant in a thread.
- Make OAuth URLs clickable in the TUI.
- Refresh the bundled model catalog, adding Claude Opus 4.8, Moonshot Kimi K2.6, and Qwen3.7 Max (with cache support).
- Discover SDK skill directories that are symlinked, including handling circular symlinks.
- Steer active connector sessions across turn keys by matching on session ID, so replies continue the existing session instead of starting a duplicate.
- Stop the Discord connector after repeated identical errors (per thread, within a time window) to prevent error messages from flooding a channel.
- Fix Discord connector registration and reply fallback handling.
- Fix SAP AI Core to use the AI SDK community provider.
- Log ACP output as diagnostics instead of errors so normal output no longer appears as errors.
## 3.0.14
- Fix OTEL telemetry variable bundling so telemetry is correctly enabled in compiled CLI builds: guard against environments where `process.env` is undefined and remove optional chaining so bundlers can inline the values at build time.
## 3.0.13
- Show a loading dialog while resuming a session from history so the TUI no longer appears frozen during the load.
- Speed up the `/clear` command by deferring new session creation until you send the next prompt, so clearing no longer blocks on spinning up an empty session.
## 3.0.12
- Show a loading dialog while the config screen switches provider or model so the transition no longer looks frozen.
- Render the ask question tool prompt inline with the conversation so the question and suggested answers stay attached to the assistant turn that asked them, instead of appearing in a separate modal.
- Allow manual `cline update` runs to install the latest published version immediately, bypassing the release age gate that delays automatic updates.
- Refresh the bundled SDK to 0.0.42, updating the model catalog.
## 3.0.11
- Fix a regression in the ChatGPT OAuth provider where requests failed with `max_output_tokens not supported`, by restoring the full output token budget instead of applying an implicit cap.
- Hide the `Space toggle` hint in the config footer when the highlighted row is not toggleable (rules, agents, hooks).
- Authenticate Vertex Gemini through Google auth when `gcp.projectId` is configured, and surface the full Vertex model list instead of only Claude models.
- Include tool names in tool result content blocks so message logs and session history consistently track which tool produced each result.
## 3.0.10
- Install plugins from `file://` URLs in addition to npm and git sources.
- Show Ollama API key note in TUI settings so users know when to provide an API key.
- Keep interactive sessions alive when idle or awaiting approval instead of treating them as ended, and stop reading message files for every session when `hydrate: false`.
- Add Poolside as a provider.
- Add Gemini 3.5 Flash to the Gemini provider model list.
- Auto-detect Telegram bot username from the bot token so the Telegram connector no longer requires it to be configured separately.
- Notify connectors when a scheduled execution fails, not just when it succeeds.
- Bake OTEL telemetry variables into the CLI at build time so telemetry works in nightly and production builds.
- Preserve model output token limits from the SDK model catalog so context window math matches the upstream provider.
- Soften the visual treatment of rejected tool calls in the TUI.
- Hide the skills tool from the system prompt when skills are disabled, and refresh slash commands after toggling a skill.
- Restore AWS Bedrock profile-based auth during legacy config migration so profiles set via `awsAuthentication: "profile"` are preserved without `awsUseProfile`.
- Cache global settings reads keyed by file mtime so repeated reads skip the JSON parse and zod validation on the hot path.
## 3.0.9
- Speed up CLI startup with plugins by loading sandboxed plugins concurrently and caching plugin tool descriptors per plugin, provider, and model.
- Speed up plugin and tool config toggles by updating the TUI optimistically and persisting changes without reloading the full config or reimporting plugins.
- Restore fuzzy ranking for the @-mention file picker so the most relevant files appear first.
- Keep the interactive CLI session alive after cancelling a task instead of tearing the session down.
- Accept dash-prefixed prompts when passed after `--`, so prompts starting with `-` are no longer parsed as flags.
- Recover from hub abort cleanup failures so a cancel that hits an error no longer crashes the runtime host.
- Route GLM thinking through provider metadata so thinking-enabled GLM models behave correctly through the gateway.
## 3.0.8
- Use Telegram numeric participant ids so renamed users stay linked to the same participant in the Telegram connector.
- Keep failed plugins visible in the config UI with their load/setup phase and error details so broken plugin definitions are easier to diagnose.
- Move the Create Session Fork shortcut from Opt+F to Opt+R so terminal word-right navigation works again.
- Fix AWS Bedrock region and profile detection in the CLI onboarding, and surface bearer-token and additional Bedrock config fields in the provider config screens.
- Fix inflated token usage counts caused by AgentRuntime.execute() not resetting usage between calls, which the local runtime host was then double-counting on top of the session baseline.
## 3.0.7
- Skip the ChatGPT OAuth model refresh on session startup so the CLI launches without the extra network round-trip.
- Align the ChatGPT OAuth model catalog with the Codex provider list so the available models match the subscription tier.
## 3.0.6
- Fix ChatGPT provider model list to include the codex variants and the gpt-5.2, gpt-5.4, and gpt-5.4-mini subscription models.
## 3.0.5
- Show plugin-provided tools and slash commands in the CLI settings dialog by hydrating them through the sandbox.
- Preserve hydrated plugin tools and config reload options when toggling settings, so they no longer disappear after a toggle.
## 3.0.4
- Improve light theme TUI colors so chat, status bar, tool output, and syntax highlighting render with better contrast on light terminals.
- Fix plugin tools failing in the production npm build by bundling the SDK deps plugins import at runtime.
## 3.0.3
- Add `--worktree` flag that auto-creates a fresh git worktree under `~/.cline/worktrees/` and runs the task there. Works with `--taskId` and `--continue` so you can resume a task in an isolated worktree to try a different approach.
- Show session status in the CLI history view and refresh status rows in place while the standalone history TUI is open.
- Restore the OpenAI compatible provider in the auth flow and preserve stored model metadata when configuring or migrating OpenAI-compatible providers.
- Fix dropped macOS screenshots when pasting them into the TUI or asking the agent to read them: paths containing U+202F (narrow no-break space) and other Unicode variants now resolve to the real file instead of failing with ENOENT.
- Accept bearer token auth for AWS Bedrock and map AWS profiles correctly when configuring the Bedrock gateway.
- Honor `--thinking none` for Ollama models that ship with reasoning enabled by default.
- Recover from detached hub event errors instead of crashing the session.
- Refine the shared system prompt with clearer guidance on tool output formatting, unsupported file reads, long-running shell commands, and final verification before completing a task.
## 3.0.2
- Fix token count display showing inflated numbers in the TUI.
## 3.0.1
- Fix CLI release cleanup scripts so they work correctly on Windows.
- Fix the kanban migration notice wording in the TUI.
## 3.0.0
Introducing our new Cline CLI built on our new SDK and comes with a snappy new TUI.
Install:
```sh
npm install -g cline
```
For nightly builds:
```sh
npm install -g cline@nightly
```
## 0.0.13
- Detect prompt-cache support from cache write pricing so providers with write-only caching are represented correctly in the model catalog
- Dual-publish `@clinebot/cli` mirror wrapper so existing users who installed via `npm i -g @clinebot/cli` continue receiving updates
- Fix response truncation for OpenAI Codex model responses
## 0.0.12
- Fix markdown rendering in the published binary: headers, inline code, blockquotes, bold, italic, and lists now render with proper syntax highlighting (tables were the only element working before)
- Add keyboard shortcuts for scrolling through the chat transcript (Page Up/Down, Home/End)
- Preserve typed input when selecting slash command skills instead of clearing the prompt
- Fix `--thinking none` being ignored when persisted reasoning settings existed, which caused DeepSeek API errors
- Fix terminal cleanup on exit so the summary prints cleanly
- Fix onboarding provider model resolution
- Hide ChatGPT subscription provider usage costs
- Handle file index prewarm timeouts gracefully instead of hanging
## 0.0.11
- Add `/skills` slash command for browsing and toggling available skills interactively
- System prompts from AI SDK are now passed via the dedicated `system` option instead of being embedded in message history
- Context compaction can now be triggered manually and runs more reliably
- Disable the search tool in yolo mode so the model uses bash for searching instead
- Fix `submit_and_exit` completion policy not being wired through to the runtime
- Fix resumed sessions losing tool results when an abort interrupted tool execution mid-turn
- Fix interactive sessions becoming unusable after aborting a running turn
- Fix strict JSON schema mode rejecting valid tool schemas with unions, optional fields, and nullable types
- Fix stray log output appearing over the TUI when the log file fallback wrote directly to the stderr file descriptor, bypassing the TUI's stdio capture
- Refresh the built-in model catalog with the latest available models and pricing
## 0.0.10
- Improve local provider onboarding: setting up Ollama, LM Studio, or other local providers now prompts for the endpoint URL directly, supports typing a model ID manually when the provider returns no models, and correctly discovers models from your saved endpoint
- Ctrl+C no longer cancels a running turn -- it now clears the input field or exits the CLI, matching standard terminal behavior. Use Escape to cancel a running turn instead
- Thinking level chosen in the model picker now persists across CLI restarts instead of resetting to off
- The context bar now shows visible progress as tokens are used, instead of appearing empty on some terminal themes
- The status bar token count now shows actual context window usage instead of over-counting across multiple model calls in a turn
- Resuming a saved session now correctly displays the accumulated cost
- Sessions are now saved to disk after each assistant response, so conversation progress survives crashes or unexpected exits
- Auto-compaction now runs inline during model requests, keeping long conversations within the context window automatically
- The home screen robot now follows the cursor while you type
- Hub websocket connections now automatically reconnect after going idle, so sessions no longer silently lose their connection to the hub daemon
- MCP stdio servers on Windows no longer spawn visible console windows
- Tool input schemas containing `allOf` clauses are now handled correctly instead of being rejected
- Login now uses device auth exclusively
- Fix chat input and chat view text losing its indent on wrapped lines
## 0.0.9
- Fix stray text appearing over the TUI when background operations (like hub restart messages) write directly to stdout/stderr during interactive sessions
- Fix hub connection recovery: when a newer CLI instance restarts the shared hub daemon, already-running CLI sessions now automatically reconnect to the new hub endpoint instead of failing with transport errors
## 0.0.8
- Fix crash when pressing Escape to cancel a running turn
- Add plugin and SDK tool toggles to the settings panel
- Add `@cline/sdk` as a user-facing alias for `@cline/core`
- Improve hub recovery with better error handling, logging, and recovery timeouts
- Show session summary (ID, model, cost, resume command) on exit
- Fix OAuth browser-launch failure
- Fix compact no-op being reported indistinctly
- Fix CLI history resume being non-transactional (could leave blank UI or corrupt session on disk)
- Fix cross-client session history not loading Code/VS Code sessions, and fix interactive turn status showing stale state
- Fix configuration file paths for hooks and rules (now resolve from `~/.cline/hooks` and `~/.cline/rules`)
- Fix Telegram connector: honor `--no-tools` flag, lock tool-disabled mode across state changes, post replies as raw text to avoid markdown parse failures, add `/help` and `/start` commands
- Clean up CLI program description and compact slash command descriptions
- Clean up CLI flags
## 0.0.7
- Fix graceful recovery when the model returns malformed tool call inputs, preventing crashes mid-conversation
- Add settings toggles for core skills (enable/disable individual skills from the settings panel)
- Secure the local hub daemon with a discovery auth token, preventing unauthorized local access
- Fix auto-approve tool policies being incorrectly reset after session restore
- Fix npm wrapper detection for auto updates, so self-update works when the CLI is invoked through npm/npx shims
- Improve fork session UX with clearer prompts and smoother flow
- Fix manual thinking budget not being applied when using Anthropic models directly
- Improve account onboarding flow with better error messages and step sequencing
- Add enable/disable controls for individual tools and plugins
- Fix abort handling so the public run promise resolves correctly when a run is cancelled
- Fix markdown token styling in chat output
- Fix chat auto-scrolling to bottom on message submit
- Fix hub tool capabilities being routed to the wrong session
- Revert loading extension-created sessions from history (was causing issues)
## 0.0.6
- Add checkpoint restore: press Esc twice or type `/undo` to rewind to a previous checkpoint, with options to restore chat only or chat + workspace
- Fix clipboard: fall back to system clipboard (pbcopy, PowerShell, wl-copy, xclip) when OSC 52 fails, fixing copy for longer text selections
- Fix prompt focus: restore focus to the prompt input after dialogs close, preventing the input from becoming unresponsive after using `/settings`
## 0.0.5
- The input field has been completely redesigned -- the old bordered box is replaced with a clean chevron-prompt style that adapts its background color to any terminal theme using perceptual OKLAB color math. Light terminals are fully supported now.
- Pasting 5+ lines into the input shows a compact preview marker instead of flooding the textarea. The full content is still submitted.
- Arrow-key history navigation respects cursor position so you don't lose your place when scrolling through previous prompts.
- The TUI renders immediately instead of blocking while the hub daemon boots. Hub readiness and session hydration happen in the background.
- Listing previous sessions no longer hydrates every full session, making `cline history` and the history picker snappy even with hundreds of sessions.
- Updating the CLI no longer leaves you connected to a stale hub daemon. Incompatible versions are detected and replaced automatically, eliminating the "Unsupported hub schedule command" class of errors.
- Schedules can now trigger on external events (webhooks, GitHub events, plugin-emitted signals) in addition to cron intervals, with deduplication, filtering, and retry policies.
- Plugins can register automation event types that feed into the scheduling system, enabling custom triggers from any source.
- Resuming a session automatically picks up any in-flight team runs without needing to remember or pass `--team-name`.
- `providers.json` (which stores API keys and OAuth tokens) is now written with 0600 permissions, preventing other processes on the machine from reading it.
- Models that emit `command` or `cmd` instead of `commands` (or `paths` instead of `path`) no longer fail. Common aliases are normalized before execution.
## 0.0.4
- Fix compiled binary spawning infinite hub daemon recursion loop
## 0.0.3
- Rewritten TUI from Ink to OpenTUI with streaming markdown, syntax-highlighted diffs, scrollable chat, and mouse support
- Dialog system for model picker, tool approval, settings browser, session history, and onboarding
- Interactive setup wizards: `cline connect`, `cline schedule`, `cline mcp`
- Plan/Act mode toggle with system prompt and tool rebuilding on switch
- Input autocomplete for slash commands and file mentions
- Message queuing and steer messages during running turns
- Platform-specific compiled binaries for macOS, Linux, and Windows (arm64 and x64)
- npm trusted publishing via GitHub Actions OIDC
-334
View File
@@ -1,334 +0,0 @@
# Cline CLI
<p align="center">
<img src="https://github.com/user-attachments/assets/7123f9d1-afeb-48d5-93fa-e750dec0ebba" width="70%" />
</p>
<div align="center">
<table>
<tbody>
<td align="center">
<a href="https://www.npmjs.com/package/cline" target="_blank">NPM</a>
</td>
<td align="center">
<a href="https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev" target="_blank">VS Code Extension</a>
</td>
<td align="center">
<a href="https://discord.gg/cline" target="_blank">Discord</a>
</td>
<td align="center">
<a href="https://www.reddit.com/r/cline/" target="_blank">r/cline</a>
</td>
<td align="center">
<a href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop" target="_blank">Feature Requests</a>
</td>
<td align="center">
<a href="https://docs.cline.bot" target="_blank">Docs</a>
</td>
</tbody>
</table>
</div>
Run Cline in your terminal. Interactive chat for paired sessions, or fully headless for CI/CD and scripting. The CLI shares its agent core with the [Cline VS Code extension](https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev), JetBrains plugin, and SDK, so plan/act modes, MCP servers, checkpoints, rules, skills, and provider configuration all behave the same across surfaces.
## Install
```sh
npm install -g cline
```
For nightly builds:
```sh
npm install -g cline@nightly
```
Platform binaries are published for macOS, Linux, and Windows on `arm64` and `x64`. The `cline` package resolves the correct binary for your platform via optional dependencies, so no Node, Bun, or Zig runtime is required at install time.
## Quick start
Run interactively:
```sh
cline
```
Run a single prompt:
```sh
cline "Audit this package and propose fixes"
```
Pipe input:
```sh
cat file.txt | cline "Summarize this"
```
See `cline --help` for the full flag reference.
## Use any provider
Cline supports the same providers as the VS Code extension. You can sign in to Cline directly, use your ChatGPT Subscription through `openai-codex`, or bring an API key from Anthropic, OpenAI, Google Gemini, OpenRouter, AWS Bedrock, GCP Vertex, Cerebras, Groq, and any OpenAI-compatible endpoint.
```sh
cline auth # interactive sign-in
cline auth cline # OAuth sign-in
cline auth --provider anthropic --apikey sk-... --modelid claude-sonnet-4-6
```
`cline auth` without a provider opens the interactive auth setup TUI with the same options as the old CLI flow (Sign in with Cline, Sign in with ChatGPT Subscription, Sign in with OCA, or use your own API key).
OAuth-supported providers (`cline`, `openai-codex`, `oca`) do not auto-launch a browser on normal startup. Authenticate explicitly first with `cline auth <provider>`. For non-interactive runs, if an OAuth provider is selected and no saved credentials are available, `cline` fails fast with an authentication message instead of launching a hidden browser flow.
## Modes
Cline CLI runs in a few different shapes depending on what you need:
- Interactive TUI: `cline` or `cline -i` opens a full terminal UI with plan/act toggle, slash commands, file mentions, and live tool approvals
- One-shot: `cline "your prompt"` runs a single turn and exits
- JSON: `cline --json "..."` streams NDJSON events for piping into other tools
- Yolo: `cline --yolo "..."` skips approval prompts and exits when the turn finishes
- Zen: `cline --zen "..."` fires the task to the background hub daemon and exits immediately (see below)
## Headless mode for CI/CD
Run Cline with zero interaction for scripting and automation. Pipe input, get JSON output, chain commands, integrate into CI/CD pipelines.
```sh
# One-shot prompt, auto-approve all tools
cline --yolo "Run tests and fix any failures"
# Pipe a diff in for review
git diff origin/main | cline "Review these changes for issues"
# NDJSON output for downstream tooling
cline --json "List all TODO comments" | jq -r 'select(.type == "agent_event" and .event.text) | .event.text'
```
## Features
- Streaming TUI built on [OpenTUI](https://github.com/sst/opentui) with markdown rendering, syntax-highlighted diffs, scrollable chat, and mouse support
- Plan/Act mode toggle for switching between planning and execution
- Native MCP support for connecting custom tools
- Checkpoints with `/undo` to rewind workspace state
- Sub-agent spawning and agent teams for parallel work
- OAuth login for Cline, ChatGPT Subscription (`openai-codex`), and OCA
- Configurable thinking budgets per run
- Cron and event-driven schedules for recurring agent work
- Chat connectors for Telegram, Google Chat, and WhatsApp
## Usage
```sh
# Start Cline CLI without a prompt to enter interactive mode
cline
# Single prompt (one-shot) - includes tools, spawn, and teams
cline "Audit this package and propose fixes"
# Interactive mode with a starting prompt
cline -i "Let's work on this together. First, analyze the current state."
# With a custom system prompt
cline -i -s "You are a pirate" "Tell me about the sea"
# Require approval before each tool call
cline --auto-approve false "Inspect and modify this repository"
# Explicit yolo: enables submit_and_exit and disables spawn/team tools by default
cline --yolo --retries 5 "Refactor this package"
# Override consecutive internal mistake (retry) limit (default: 3)
cline --retries 5 "Fix failing tests"
# Team workflow with persistent name
cline --team-name my-team "Plan, implement, and verify release checklist"
cline --team-name my-team "Continue yesterday's team workflow"
# Show verbose run stats (elapsed time, tokens, estimated cost when available)
cline -v "Explain quantum computing"
# Use a specific provider, model, and access token for a single prompt
cline -P openrouter -m google/gemini-3-pro -k sk-... "Set up a storybook"
# Use a different model with the last used provider
cline -m anthropic/claude-opus-4-6 "Explain string theory"
# Stream structured NDJSON output
cline --json "Summarize this repository"
# Quick provider setup
cline auth --provider anthropic --apikey sk-... --modelid claude-sonnet-4-6
cline auth --provider openai-native --apikey sk-... --modelid gpt-5 --baseurl https://api.example.com/v1
```
### Connectors
Bridge a chat surface into RPC-backed Cline sessions. Each conversation thread maps to a session with full context. Supported platforms: Telegram, Slack, Google Chat, WhatsApp, and Linear.
```sh
# Telegram (polling mode)
cline connect telegram -k 123456:ABCDEF...
# Slack (webhook mode)
cline connect slack --bot-token $SLACK_BOT_TOKEN --signing-secret $SLACK_SIGNING_SECRET --base-url https://your-domain.com
# Slack (socket mode)
cline connect slack --bot-token $SLACK_BOT_TOKEN --app-token $SLACK_APP_TOKEN
# Google Chat (webhook mode)
cline connect gchat --base-url https://your-domain.com
# WhatsApp (webhook mode)
cline connect whatsapp --base-url https://your-domain.com
# Linear (webhook mode)
cline connect linear --api-key $LINEAR_API_KEY --base-url https://your-domain.com
# Stop connector bridges and delete their sessions
cline connect --stop
cline connect --stop telegram
```
In chat surfaces, connector slash commands include `/help`, `/start`, `/new`, `/clear`, `/whereami`, `/tools`, `/yolo`, `/cwd <path>`, `/schedule`, `/abort`, and `/exit`. Run `cline connect <adapter> --help` to see the full flag list for any adapter.
### Schedules
Schedule agents on cron-like intervals or external events.
```sh
cline schedule create "Daily code review" \
--cron "0 9 * * MON-FRI" \
--prompt "Review PRs opened yesterday and summarize issues." \
--workspace /path/to/repo \
--provider cline \
--model openai/gpt-5.3-codex \
--timeout 3600 \
--tags automation,review
cline schedule list
cline schedule get <schedule-id>
cline schedule trigger <schedule-id>
cline schedule history <schedule-id> --limit 20
cline schedule export <schedule-id> > daily-review.yaml
cline schedule import ./daily-review.yaml
```
Schedules can route results back to chat surfaces with `--delivery-adapter`, `--delivery-bot`, and `--delivery-thread`.
## Options
| Flag | Description |
|------|-------------|
| `-s, --system <prompt>` | Override the system prompt |
| `-P, --provider <id>` | Provider id (default: `cline`) |
| `-m, --model <id>` | Model id (default: `anthropic/claude-sonnet-4.6`) |
| `-k, --key <api-key>` | API key override for this run |
| `-p, --plan` | Run in plan mode (default is act mode) |
| `-i, --tui` | Interactive TUI multi-turn mode |
| `-t, --timeout <seconds>` | Optional run timeout in seconds |
| `-c, --cwd <path>` | Working directory for tools |
| `--config <path>` | Configuration directory (used for CLI home resolution) |
| `--hooks-dir <path>` | Additional hooks directory hint for runtime hook injection |
| `--acp` | ACP (Agent Client Protocol) mode |
| `--thinking [none\|low\|medium\|high\|xhigh]` | Model thinking level when supported. Defaults to `medium` when the flag is provided without a level; thinking is off when the flag is omitted. |
| `--compaction <agentic\|basic\|off>` | Context compaction mode. Defaults to `basic`; use `agentic` for LLM compaction or `off` to disable. |
| `--retries <count>` | Maximum consecutive mistakes (retries) before halting (default: `3`) |
| `--json` | Output NDJSON instead of styled text |
| `--data-dir <path>` | Use isolated local state at `<path>` instead of `~/.cline` (enables sandbox mode automatically) |
| `--auto-approve [true\|false]` | Set tool auto-approval for all tools |
| `--kanban` | Run the external `kanban` app |
| `-y, --yolo` | Skip tool approval prompts, enable `submit_and_exit`, and disable spawn/team tools by default |
| `-z, --zen` | Dispatch the task to the background hub and exit the CLI immediately |
| `--team-name <name>` | Override the runtime team state name |
| `-h, --help` | Show help and exit |
| `-v, --verbose` | Show verbose runtime diagnostics |
| `-V, --version` | Show version and exit |
`--json` is non-interactive and requires either a prompt argument or piped stdin. `--key` takes precedence over environment variables.
## Top-level commands
- `cline config` - Open the interactive config view
- `cline history|h [options]` - List session history or manage saved sessions
- `cline version` - Show CLI version
- `cline update [options]` - Check for CLI and kanban updates
- `cline auth <provider>` - Authenticate or seed provider credentials
- `cline connect <adapter>` - Run a chat connector bridge (`telegram`, `gchat`, `whatsapp`)
- `cline connect --stop [adapter]` - Stop connector bridge processes and their sessions
- `cline schedule <command>` - Create and manage scheduled runs
- `cline doctor` - Inspect local CLI health and stale processes
- `cline doctor fix` - Kill stale local RPC listeners and old CLI processes
- `cline doctor log` - Open the CLI runtime log file
- `cline hook` - Handle a hook payload from stdin
- `cline hub` - Manage the local hub daemon
- `cline kanban` - Run the external `kanban` app, installing it first when needed
## Zen mode
`--zen` (alias `-z`) runs a task in the background hub daemon and exits the CLI immediately. It is intended for long-running tasks you want to fire off and walk away from.
```sh
cline --zen "Refactor the authentication module and add unit tests"
```
Behavior:
- The CLI starts (or reuses) the local hub daemon, submits the task, then exits. It does not stream output or stay attached to the session.
- Because there is no human in the loop once the CLI exits, zen sessions run with full tool auto-approval (same semantics as `--yolo`). `spawn`/`team` tools are disabled by default for safety, consistent with yolo-mode defaults.
- If the Cline menubar app is running, it subscribes to hub `ui.notify` events and will surface a system notification when the task completes.
- If the menubar app is not running, there is no live UI for the task. Use `cline history` later to find the session and inspect the result.
- `--zen` is incompatible with `--data-dir` (the implicit sandbox requires a local backend that exits with the CLI) and with `--tui` (there is no terminal UI to render into).
## Tool approval
Tool calls are auto-approved by default. Use `--auto-approve false` to require review before tool execution.
```sh
cline --auto-approve false "Inspect and modify this repository"
```
When approval is required, the CLI prompts in TTY mode:
```text
Approve tool "<tool_name>" with input <preview>? [y/N]
```
- Enter `y` or `yes` to approve.
- Enter anything else (or press Enter) to reject.
- If stdin/stdout is not a TTY, required-approval calls are denied in terminal mode.
Desktop-integrated approval mode is also supported via env wiring (`CLINE_TOOL_APPROVAL_MODE=desktop` and `CLINE_TOOL_APPROVAL_DIR=<path>`). In desktop mode, CLI writes a request JSON file and waits for a matching decision JSON file.
## Environment variables
- `ANTHROPIC_API_KEY` - API key for Anthropic
- `CLINE_API_KEY` - API key for Cline (when using `-P cline`)
- `OPENAI_API_KEY` - API key for OpenAI (when using `-P openai`)
- `OPENROUTER_API_KEY` - API key for OpenRouter (when using `-P openrouter`)
- `AI_GATEWAY_API_KEY` - API key for Vercel AI Gateway (when using `-P vercel-ai-gateway`)
- `V0_API_KEY` - API key for v0 (when using `-P v0`)
- `CLINE_DATA_DIR` - Base data directory for sessions/settings/teams/hooks
- `CLINE_SANDBOX` - Set to `1` to force sandbox mode
- `CLINE_SANDBOX_DATA_DIR` - Override sandbox state directory
- `CLINE_TEAM_DATA_DIR` - Override team persistence directory
- `CLINE_BUILD_ENV` - Runtime build mode for SDK-owned subprocess launches
- `CLINE_DEBUG_HOST` - Host for development inspector listeners (default `127.0.0.1`)
- `CLINE_DEBUG_PORT_BASE` - Base inspector port for development child processes
- `CLINE_TOOL_APPROVAL_MODE` - Approval mode (`desktop` uses file IPC; unset uses terminal prompt)
- `CLINE_TOOL_APPROVAL_DIR` - Directory for desktop approval request/decision files
- `CLINE_LOG_ENABLED` - Set to `0`/`false` to disable runtime file logging
- `CLINE_LOG_LEVEL` - Runtime log level (`trace|debug|info|warn|error|fatal|silent`, default `info`)
- `CLINE_LOG_PATH` - Runtime log file path (default `<CLINE_DATA_DIR>/logs/cline.log`)
- `CLINE_LOG_NAME` - Logger name embedded in runtime log records
`--key` takes precedence over environment variables.
## Contributing
See [DEVELOPMENT.md](./DEVELOPMENT.md) for local development setup, monorepo structure, and TUI architecture. See [DISTRIBUTION.md](./DISTRIBUTION.md) for how the CLI is packaged and distributed.
## License
[Apache 2.0 © Cline Bot Inc.](https://github.com/cline/cline/blob/main/LICENSE)
-36
View File
@@ -1,36 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
describe("runAcpMode", () => {
afterEach(() => {
vi.doUnmock("@agentclientprotocol/sdk");
vi.doUnmock("./acpAgent");
vi.restoreAllMocks();
});
it("writes the startup diagnostic without labeling it as an error", async () => {
const stderrWrite = vi
.spyOn(process.stderr, "write")
.mockImplementation(() => true);
vi.doMock("@agentclientprotocol/sdk", () => ({
ndJsonStream: vi.fn(() => ({})),
AgentSideConnection: class {
closed = Promise.resolve();
},
}));
vi.doMock("./acpAgent", () => ({
AcpAgent: class {},
}));
const { runAcpMode } = await import("./index");
await runAcpMode();
expect(stderrWrite).toHaveBeenCalledWith(
"[acp] starting ACP mode over stdio…\n",
);
expect(stderrWrite).not.toHaveBeenCalledWith(
expect.stringContaining("error:"),
);
});
});
-184
View File
@@ -1,184 +0,0 @@
import { mkdirSync, mkdtempSync } from "node:fs";
import { arch, platform, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { runDashboardCommand, waitForProcessShutdown } from "./dashboard";
const ENV_KEYS = [
"WORKSPACE_ROOT",
"HOST",
"CLINE_HUB_DASHBOARD_PORT",
"PUBLIC_URL",
"ROOM_SECRET",
"CLINE_HUB_WEBVIEW_DIST_DIR",
"CLINE_WRAPPER_PATH",
] as const;
const originalEnv = Object.fromEntries(
ENV_KEYS.map((key) => [key, process.env[key]]),
);
afterEach(() => {
for (const key of ENV_KEYS) {
const value = originalEnv[key];
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
});
describe("runDashboardCommand", () => {
it("starts the dashboard server, opens the invite URL, and waits for shutdown", async () => {
const output: string[] = [];
const errors: string[] = [];
const opened: string[] = [];
const stop = vi.fn();
let observedEnv:
| {
workspaceRoot: string | undefined;
host: string | undefined;
port: string | undefined;
publicUrl: string | undefined;
roomSecret: string | undefined;
webviewDistDir: string | undefined;
}
| undefined;
const webviewDistDir = mkdtempSync(join(tmpdir(), "cline-webview-dist-"));
mkdirSync(webviewDistDir, { recursive: true });
process.env.CLINE_HUB_WEBVIEW_DIST_DIR = webviewDistDir;
const exitCode = await runDashboardCommand({
cwd: "sdk",
host: "127.0.0.1",
port: "9090",
publicUrl: "http://127.0.0.1:9090",
roomSecret: "secret",
io: {
writeln: (text) => output.push(text ?? ""),
writeErr: (text) => errors.push(text),
},
startServer: async () => {
observedEnv = {
workspaceRoot: process.env.WORKSPACE_ROOT,
host: process.env.HOST,
port: process.env.CLINE_HUB_DASHBOARD_PORT,
publicUrl: process.env.PUBLIC_URL,
roomSecret: process.env.ROOM_SECRET,
webviewDistDir: process.env.CLINE_HUB_WEBVIEW_DIST_DIR,
};
return {
listenUrl: "http://127.0.0.1:9090/",
publicUrl: "http://127.0.0.1:9090",
inviteUrl: "http://127.0.0.1:9090/?roomSecret=secret",
hubUrl: "ws://127.0.0.1:25463/hub",
stop,
};
},
openUrl: async (url) => {
opened.push(url);
},
waitForShutdown: async (server) => {
await server.stop();
},
});
expect(exitCode).toBe(0);
expect(observedEnv).toEqual({
workspaceRoot: resolve("sdk"),
host: "127.0.0.1",
port: "9090",
publicUrl: "http://127.0.0.1:9090",
roomSecret: "secret",
webviewDistDir,
});
expect(opened).toEqual(["http://127.0.0.1:9090/?roomSecret=secret"]);
expect(stop).toHaveBeenCalledTimes(1);
expect(output.join("\n")).toContain("Cline dashboard listening at");
expect(output.join("\n")).toContain("ws://127.0.0.1:25463/hub");
expect(errors).toEqual([]);
expect(process.env.WORKSPACE_ROOT).toBe(originalEnv.WORKSPACE_ROOT);
expect(process.env.CLINE_HUB_WEBVIEW_DIST_DIR).toBe(webviewDistDir);
});
it("honors --no-open behavior", async () => {
const openUrl = vi.fn();
const exitCode = await runDashboardCommand({
openBrowser: false,
io: {
writeln: () => {},
writeErr: () => {},
},
startServer: async () => ({
listenUrl: "http://127.0.0.1:8787/",
publicUrl: "http://127.0.0.1:8787",
inviteUrl: "http://127.0.0.1:8787",
stop: vi.fn(),
}),
openUrl,
waitForShutdown: async () => {},
});
expect(exitCode).toBe(0);
expect(openUrl).not.toHaveBeenCalled();
});
it("finds webview assets from the published wrapper package layout", async () => {
const root = mkdtempSync(join(tmpdir(), "cline-wrapper-layout-"));
const wrapperPath = join(root, "node_modules", "cline", "bin", "cline");
const platformName = platform() === "win32" ? "windows" : platform();
const webviewDistDir = join(
root,
"node_modules",
"cline",
"node_modules",
"@cline",
`cli-${platformName}-${arch()}`,
"cline-hub",
"webview",
);
mkdirSync(join(wrapperPath, ".."), { recursive: true });
mkdirSync(webviewDistDir, { recursive: true });
process.env.CLINE_WRAPPER_PATH = wrapperPath;
delete process.env.CLINE_HUB_WEBVIEW_DIST_DIR;
let observedWebviewDistDir: string | undefined;
const exitCode = await runDashboardCommand({
openBrowser: false,
io: {
writeln: () => {},
writeErr: () => {},
},
startServer: async () => {
observedWebviewDistDir = process.env.CLINE_HUB_WEBVIEW_DIST_DIR;
return {
listenUrl: "http://127.0.0.1:8787/",
publicUrl: "http://127.0.0.1:8787",
inviteUrl: "http://127.0.0.1:8787",
stop: vi.fn(),
};
},
waitForShutdown: async () => {},
});
expect(exitCode).toBe(0);
expect(observedWebviewDistDir).toBe(webviewDistDir);
});
it("settles shutdown when server stop rejects", async () => {
const shutdown = waitForProcessShutdown({
listenUrl: "http://127.0.0.1:8787/",
publicUrl: "http://127.0.0.1:8787",
inviteUrl: "http://127.0.0.1:8787",
stop: vi.fn(async () => {
throw new Error("stop failed");
}),
});
process.emit("SIGINT", "SIGINT");
await expect(shutdown).rejects.toThrow("stop failed");
});
});
-195
View File
@@ -1,195 +0,0 @@
import { existsSync } from "node:fs";
import { arch, platform } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import open from "open";
import { c } from "../utils/output";
export interface DashboardServerHandle {
listenUrl: string;
publicUrl: string;
inviteUrl: string;
hubUrl?: string;
stop: () => void | Promise<void>;
}
interface DashboardCommandIo {
writeln: (text?: string) => void;
writeErr: (text: string) => void;
}
export interface RunDashboardCommandOptions {
cwd?: string;
host?: string;
port?: string;
publicUrl?: string;
roomSecret?: string;
openBrowser?: boolean;
io: DashboardCommandIo;
startServer?: () => Promise<DashboardServerHandle>;
openUrl?: (url: string) => Promise<void>;
waitForShutdown?: (server: DashboardServerHandle) => Promise<void>;
}
const DASHBOARD_PORT_ENV = "CLINE_HUB_DASHBOARD_PORT";
const WEBVIEW_DIST_ENV = "CLINE_HUB_WEBVIEW_DIST_DIR";
function setEnvValue(name: string, value: string | undefined): () => void {
const previous = process.env[name];
if (value === undefined) {
return () => {};
}
process.env[name] = value;
return () => {
if (previous === undefined) {
delete process.env[name];
} else {
process.env[name] = previous;
}
};
}
async function withDashboardEnvironment<T>(
options: RunDashboardCommandOptions,
fn: () => Promise<T>,
): Promise<T> {
const restore = [
setEnvValue(
"WORKSPACE_ROOT",
options.cwd ? resolve(options.cwd) : undefined,
),
setEnvValue("HOST", options.host),
setEnvValue(DASHBOARD_PORT_ENV, options.port),
setEnvValue("PUBLIC_URL", options.publicUrl),
setEnvValue("ROOM_SECRET", options.roomSecret),
setEnvValue(WEBVIEW_DIST_ENV, resolveDefaultWebviewDistDir()),
];
try {
return await fn();
} finally {
for (let i = restore.length - 1; i >= 0; i--) {
restore[i]?.();
}
}
}
function resolveDefaultWebviewDistDir(): string | undefined {
if (process.env[WEBVIEW_DIST_ENV]?.trim()) {
return undefined;
}
const moduleDir = dirname(fileURLToPath(import.meta.url));
const candidates = [
...resolveInstalledPlatformPackageWebviewCandidates(),
// Source checkout: apps/cli/src/commands/dashboard.ts
join(moduleDir, "../../../cline-hub/dist/webview"),
// Node bundle: apps/cli/dist/index.js
join(moduleDir, "cline-hub/webview"),
// Compiled platform package: apps/cli/dist/<platform>/bin/cline
join(dirname(process.execPath), "../cline-hub/webview"),
];
return candidates.find((candidate) => existsSync(candidate));
}
function resolveInstalledPlatformPackageWebviewCandidates(): string[] {
const packageName = resolvePlatformPackageName();
const starts = [
process.env.CLINE_WRAPPER_PATH
? dirname(process.env.CLINE_WRAPPER_PATH)
: undefined,
dirname(process.execPath),
].filter((value): value is string => !!value?.trim());
const candidates: string[] = [];
for (const start of starts) {
let current = start;
for (;;) {
candidates.push(
join(current, "node_modules", packageName, "cline-hub/webview"),
);
const parent = dirname(current);
if (parent === current) break;
current = parent;
}
}
return candidates;
}
function resolvePlatformPackageName(): string {
const platformName = platform() === "win32" ? "windows" : platform();
return `@cline/cli-${platformName}-${arch()}`;
}
async function startDefaultDashboardServer(): Promise<DashboardServerHandle> {
const { startClineHubDashboardServer } = await import("@cline/cline-hub");
return await startClineHubDashboardServer();
}
async function openDefaultUrl(url: string): Promise<void> {
await open(url, { wait: false });
}
export function waitForProcessShutdown(
server: DashboardServerHandle,
): Promise<void> {
return new Promise<void>((resolveShutdown, rejectShutdown) => {
let settled = false;
const cleanup = () => {
process.off("SIGINT", handleSignal);
process.off("SIGTERM", handleSignal);
};
const stop = async () => {
if (settled) return;
settled = true;
cleanup();
try {
await server.stop();
resolveShutdown();
} catch (error) {
rejectShutdown(error);
}
};
function handleSignal() {
void stop();
}
process.on("SIGINT", handleSignal);
process.on("SIGTERM", handleSignal);
});
}
export async function runDashboardCommand(
options: RunDashboardCommandOptions,
): Promise<number> {
try {
const server = await withDashboardEnvironment(options, () =>
(options.startServer ?? startDefaultDashboardServer)(),
);
const dashboardUrl =
server.inviteUrl || server.publicUrl || server.listenUrl;
options.io.writeln(
`${c.green}Cline dashboard listening at${c.reset} ${dashboardUrl}`,
);
if (server.hubUrl) {
options.io.writeln(`${c.dim}Hub endpoint: ${server.hubUrl}${c.reset}`);
}
if (options.openBrowser !== false) {
try {
await (options.openUrl ?? openDefaultUrl)(dashboardUrl);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
options.io.writeErr(`Failed to open browser: ${message}`);
}
}
await (options.waitForShutdown ?? waitForProcessShutdown)(server);
return 0;
} catch (error) {
options.io.writeErr(error instanceof Error ? error.message : String(error));
return 1;
}
}
-738
View File
@@ -1,738 +0,0 @@
import { execFileSync } from "node:child_process";
import {
existsSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
discoverPluginModulePaths,
resolvePluginConfigSearchPaths,
setClineDir,
setHomeDir,
} from "@cline/shared/storage";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
installPlugin,
isOfficialPluginSlug,
parsePluginSource,
runPluginInstallCommand,
runPluginUninstallCommand,
} from "./plugin";
type FetchCall = (
...args: Parameters<typeof fetch>
) => ReturnType<typeof fetch>;
describe("plugin install command", () => {
let root = "";
let home = "";
let workspace = "";
let originalHome: string | undefined;
let originalClineDir: string | undefined;
let originalClineDataDir: string | undefined;
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), "cli-plugin-install-"));
home = join(root, "home");
workspace = join(root, "workspace");
originalHome = process.env.HOME;
originalClineDir = process.env.CLINE_DIR;
originalClineDataDir = process.env.CLINE_DATA_DIR;
process.env.HOME = home;
process.env.CLINE_DIR = join(home, ".cline");
process.env.CLINE_DATA_DIR = join(home, ".cline", "data");
setHomeDir(home);
setClineDir(process.env.CLINE_DIR);
});
function runGitCommand(cwd: string, args: string[]): void {
execFileSync("git", args, { cwd, stdio: "ignore" });
}
async function createOfficialPluginsRepo(
plugins: Record<string, Record<string, string>>,
): Promise<string> {
const repo = mkdtempSync(join(root, "official-plugins-"));
for (const [slug, files] of Object.entries(plugins)) {
const pluginRoot = join(repo, "plugins", slug);
await mkdir(pluginRoot, { recursive: true });
for (const [filename, content] of Object.entries(files)) {
await writeFile(join(pluginRoot, filename), content, "utf8");
}
}
runGitCommand(repo, ["init"]);
runGitCommand(repo, ["config", "user.email", "test@example.com"]);
runGitCommand(repo, ["config", "user.name", "Cline Test"]);
runGitCommand(repo, ["add", "."]);
runGitCommand(repo, ["commit", "-m", "seed plugins"]);
return repo;
}
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
if (originalHome === undefined) {
delete process.env.HOME;
} else {
process.env.HOME = originalHome;
}
if (originalClineDir === undefined) {
delete process.env.CLINE_DIR;
} else {
process.env.CLINE_DIR = originalClineDir;
}
if (originalClineDataDir === undefined) {
delete process.env.CLINE_DATA_DIR;
} else {
process.env.CLINE_DATA_DIR = originalClineDataDir;
}
rmSync(root, { recursive: true, force: true });
});
it("parses explicit npm source type without the npm prefix", () => {
expect(parsePluginSource("@scope/plugin@1.2.3", "npm")).toEqual({
type: "npm",
spec: "@scope/plugin@1.2.3",
name: "@scope/plugin",
});
});
it("parses explicit git source type without the git prefix", () => {
expect(parsePluginSource("github.com/acme/plugin", "git")).toMatchObject({
type: "git",
repo: "https://github.com/acme/plugin",
host: "github.com",
path: "acme/plugin",
});
});
it("parses bare official keywords as official plugin slugs", () => {
expect(isOfficialPluginSlug("clickhouse")).toBe(true);
expect(isOfficialPluginSlug("web-search")).toBe(true);
expect(isOfficialPluginSlug("WebSearch")).toBe(false);
expect(parsePluginSource("clickhouse")).toEqual({
type: "official",
slug: "clickhouse",
});
expect(parsePluginSource("web-search")).toEqual({
type: "official",
slug: "web-search",
});
expect(parsePluginSource("web-search", "npm")).toEqual({
type: "npm",
spec: "web-search",
name: "web-search",
});
});
it("rejects hostname-style sources without --git guidance", () => {
expect(() => parsePluginSource("github.com/acme/plugin")).toThrow(
/Use --git/,
);
});
it("parses GitHub plugin file URLs as remote sources", () => {
expect(
parsePluginSource(
"https://github.com/cline/cline/blob/main/sdk/examples/plugins/weather-metrics.ts",
),
).toEqual({
type: "remote",
url: "https://raw.githubusercontent.com/cline/cline/main/sdk/examples/plugins/weather-metrics.ts",
filename: "weather-metrics.ts",
});
});
it("parses raw plugin file URLs as remote sources", () => {
expect(
parsePluginSource(
"https://raw.githubusercontent.com/cline/cline/main/sdk/examples/plugins/weather-metrics.ts",
),
).toEqual({
type: "remote",
url: "https://raw.githubusercontent.com/cline/cline/main/sdk/examples/plugins/weather-metrics.ts",
filename: "weather-metrics.ts",
});
});
it("rejects HTTP plugin file URLs", () => {
expect(() =>
parsePluginSource("http://example.com/plugins/weather-metrics.ts"),
).toThrow(/must use https/);
});
it("installs a local plugin file into the global plugin root", async () => {
const source = join(root, "weather.ts");
writeFileSync(
source,
"export const plugin = { name: 'weather', manifest: { capabilities: ['tools'] } };",
"utf8",
);
const result = await installPlugin({ source });
expect(result.installPath).toContain(join(home, ".cline", "plugins"));
expect(result.entryPaths).toHaveLength(1);
expect(existsSync(result.entryPaths[0] ?? "")).toBe(true);
const discovered = discoverPluginModulePaths(
join(home, ".cline", "plugins"),
);
expect(discovered).toEqual(result.entryPaths);
});
it("installs a remote plugin file into the workspace plugin root", async () => {
const source =
"https://github.com/acme/plugins/blob/main/weather-metrics.ts";
const fetchMock = vi.fn<FetchCall>(async (input) => {
expect(String(input)).toBe(
"https://raw.githubusercontent.com/acme/plugins/main/weather-metrics.ts",
);
return new Response(
"export default { name: 'remote-weather', manifest: { capabilities: ['tools'] } };",
);
});
vi.stubGlobal("fetch", fetchMock);
const result = await installPlugin({ source, cwd: workspace });
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(result.installPath).toContain(
join(workspace, ".cline", "plugins", "_installed", "remote"),
);
expect(result.entryPaths).toHaveLength(1);
expect(existsSync(result.entryPaths[0] ?? "")).toBe(true);
expect(readFileSync(result.entryPaths[0] ?? "", "utf8")).toContain(
"remote-weather",
);
expect(
discoverPluginModulePaths(join(workspace, ".cline", "plugins")),
).toEqual(result.entryPaths);
});
it("installs an official plugin slug from the configured collection repo", async () => {
const officialPluginsRepo = await createOfficialPluginsRepo({
"web-search": {
"index.ts":
"export default { name: 'official-web-search', manifest: { capabilities: ['tools'] } };",
},
"other-plugin": {
"index.ts":
"export default { name: 'other-plugin', manifest: { capabilities: ['tools'] } };",
},
});
const result = await installPlugin({
source: "web-search",
cwd: workspace,
officialPluginsRepo,
});
expect(result.installPath).toContain(
join(workspace, ".cline", "plugins", "_installed", "official"),
);
expect(result.entryPaths).toHaveLength(1);
expect(readFileSync(result.entryPaths[0] ?? "", "utf8")).toContain(
"official-web-search",
);
const wrapperManifest = JSON.parse(
readFileSync(join(result.installPath, "package.json"), "utf8"),
) as { name?: string };
expect(wrapperManifest.name).toBe("web-search");
expect(existsSync(join(result.installPath, "repo"))).toBe(false);
expect(
existsSync(join(result.installPath, "package", "other-plugin")),
).toBe(false);
expect(
discoverPluginModulePaths(join(workspace, ".cline", "plugins")),
).toEqual(result.entryPaths);
});
it("installs an official package plugin and runs package dependency install", async () => {
const officialPluginsRepo = await createOfficialPluginsRepo({
"package-plugin": {
"package.json": JSON.stringify(
{
name: "package-plugin",
type: "module",
cline: {
plugins: [{ paths: ["./index.ts"] }],
},
dependencies: {
yaml: "^2.8.1",
},
},
null,
2,
),
"index.ts":
"export default { name: 'package-plugin', manifest: { capabilities: ['tools'] } };",
},
});
const npmLogPath = join(root, "official-npm-install.log");
const npmCommandPath = join(root, "official-fake-npm.sh");
writeFileSync(
npmCommandPath,
`#!/bin/sh\nprintf '%s\\n' "$PWD $*" >> "${npmLogPath}"\nexit 0\n`,
{ encoding: "utf8", mode: 0o755 },
);
const result = await installPlugin({
source: "package-plugin",
cwd: workspace,
officialPluginsRepo,
npmCommand: npmCommandPath,
});
const npmLog = readFileSync(npmLogPath, "utf8");
expect(npmLog).toContain("package install --omit=dev --omit=peer");
expect(result.entryPaths).toHaveLength(1);
expect(readFileSync(result.entryPaths[0] ?? "", "utf8")).toContain(
"package-plugin",
);
});
it("reports a clear error when an official plugin slug is missing", async () => {
const officialPluginsRepo = await createOfficialPluginsRepo({
"known-plugin": {
"index.ts":
"export default { name: 'known-plugin', manifest: { capabilities: ['tools'] } };",
},
});
await expect(
installPlugin({
source: "missing-plugin",
cwd: workspace,
officialPluginsRepo,
}),
).rejects.toThrow(
/Official Cline plugin "missing-plugin" was not found at plugins\/missing-plugin/,
);
});
it("keeps explicit relative paths as local plugin installs", async () => {
const localPluginRoot = join(workspace, "web-search");
await mkdir(localPluginRoot, { recursive: true });
await writeFile(
join(localPluginRoot, "index.ts"),
"export default { name: 'local-web-search', manifest: { capabilities: ['tools'] } };",
"utf8",
);
const result = await installPlugin({
source: "./web-search",
cwd: workspace,
});
expect(result.installPath).toContain(
join(workspace, ".cline", "plugins", "_installed", "local"),
);
const wrapperManifest = JSON.parse(
readFileSync(join(result.installPath, "package.json"), "utf8"),
) as { name?: string };
expect(wrapperManifest.name).toBe("web-search");
expect(readFileSync(result.entryPaths[0] ?? "", "utf8")).toContain(
"local-web-search",
);
});
it("times out stalled remote plugin downloads", async () => {
vi.useFakeTimers();
const source =
"https://github.com/acme/plugins/blob/main/weather-metrics.ts";
const fetchMock = vi.fn<FetchCall>((_input, init) => {
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => {
const error = new Error("Aborted");
error.name = "AbortError";
reject(error);
});
});
});
vi.stubGlobal("fetch", fetchMock);
const install = installPlugin({ source, cwd: workspace });
const rejection = expect(install).rejects.toThrow(/Timed out downloading/);
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
await vi.advanceTimersByTimeAsync(30_000);
await rejection;
});
it("rejects remote plugin files with oversized content length", async () => {
const source =
"https://github.com/acme/plugins/blob/main/weather-metrics.ts";
const fetchMock = vi.fn<FetchCall>(async () => {
return new Response(
"export default { name: 'remote-weather', manifest: { capabilities: ['tools'] } };",
{
headers: {
"content-length": String(10 * 1024 * 1024 + 1),
},
},
);
});
vi.stubGlobal("fetch", fetchMock);
await expect(installPlugin({ source, cwd: workspace })).rejects.toThrow(
/exceeds the 10485760 byte limit/,
);
});
it("rejects remote plugin files that stream past the size limit", async () => {
const source =
"https://github.com/acme/plugins/blob/main/weather-metrics.ts";
const fetchMock = vi.fn<FetchCall>(async () => {
return new Response(
new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(10 * 1024 * 1024 + 1));
controller.close();
},
}),
);
});
vi.stubGlobal("fetch", fetchMock);
await expect(installPlugin({ source, cwd: workspace })).rejects.toThrow(
/exceeds the 10485760 byte limit/,
);
});
it("installs into cwd plugin root when cwd is provided", async () => {
const source = join(root, "plugin-package");
const npmLogPath = join(root, "npm-install.log");
const npmCommandPath = join(root, "fake-npm.sh");
writeFileSync(
npmCommandPath,
`#!/bin/sh\nprintf '%s\\n' "$PWD $*" >> "${npmLogPath}"\nexit 0\n`,
{ encoding: "utf8", mode: 0o755 },
);
await mkdir(join(source, "node_modules", "dependency"), {
recursive: true,
});
await writeFile(
join(source, "package.json"),
JSON.stringify(
{
name: "plugin-package",
cline: {
plugins: [{ paths: ["./index.ts"], capabilities: ["tools"] }],
},
dependencies: {
"@cline/core": "latest",
yaml: "^2.8.1",
},
peerDependencies: {
"@cline/shared": "*",
bun: ">=1.0.0",
},
peerDependenciesMeta: {
"@cline/shared": {
optional: true,
},
},
},
null,
2,
),
"utf8",
);
await writeFile(
join(source, "index.ts"),
"export default { name: 'plugin-package', manifest: { capabilities: ['tools'] } };",
"utf8",
);
await writeFile(
join(source, "node_modules", "dependency", "noise.ts"),
"export default { name: 'noise', manifest: { capabilities: ['tools'] } };",
"utf8",
);
await mkdir(join(source, ".git", "objects"), { recursive: true });
await writeFile(join(source, ".git", "HEAD"), "ref: refs/heads/main\n");
const result = await installPlugin({
source,
cwd: workspace,
npmCommand: npmCommandPath,
});
const wrapperManifest = JSON.parse(
readFileSync(join(result.installPath, "package.json"), "utf8"),
) as { name?: string; cline?: { plugins?: Array<{ paths?: string[] }> } };
expect(wrapperManifest.name).toBe("plugin-package");
expect(wrapperManifest.cline?.plugins?.[0]?.paths).toHaveLength(1);
expect(wrapperManifest.cline?.plugins?.[0]?.paths?.[0]).toContain(
"package/index.ts",
);
const packageManifest = JSON.parse(
readFileSync(join(result.installPath, "package", "package.json"), "utf8"),
) as {
dependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
peerDependenciesMeta?: Record<string, unknown>;
};
expect(packageManifest.dependencies).toEqual({ yaml: "^2.8.1" });
expect(packageManifest.peerDependencies).toEqual({ bun: ">=1.0.0" });
expect(packageManifest.peerDependenciesMeta).toBeUndefined();
const npmLog = readFileSync(npmLogPath, "utf8");
expect(npmLog).toContain(`${join(".tmp")}/`);
expect(npmLog).toContain(
"package install --omit=dev --omit=peer --legacy-peer-deps --no-audit --no-fund --package-lock=false",
);
expect(existsSync(join(result.installPath, "package", ".git"))).toBe(false);
expect(
existsSync(join(result.installPath, "package", "node_modules")),
).toBe(false);
const discovered = discoverPluginModulePaths(
join(workspace, ".cline", "plugins"),
);
expect(discovered).toEqual(result.entryPaths);
expect(discovered.some((path) => path.includes("noise.ts"))).toBe(false);
});
it("omits and removes host SDK packages from npm-sourced installs", async () => {
const npmLogPath = join(root, "npm-source-install.log");
const npmCommandPath = join(root, "fake-npm-source.sh");
writeFileSync(
npmCommandPath,
[
"#!/bin/sh",
`printf '%s\\n' "$*" >> "${npmLogPath}"`,
"prefix=''",
"while [ $# -gt 0 ]; do",
" if [ \"$1\" = '--prefix' ]; then",
" shift",
' prefix="$1"',
" fi",
" shift",
"done",
'mkdir -p "$prefix/node_modules/published-plugin"',
'mkdir -p "$prefix/node_modules/@cline/core"',
'printf \'%s\\n\' \'{"name":"published-plugin","type":"module","cline":{"plugins":["index.ts"]}}\' > "$prefix/node_modules/published-plugin/package.json"',
"printf '%s\\n' \"export default { name: 'published-plugin', manifest: { capabilities: ['tools'] } };\" > \"$prefix/node_modules/published-plugin/index.ts\"",
'printf \'%s\\n\' \'{"name":"@cline/core"}\' > "$prefix/node_modules/@cline/core/package.json"',
"exit 0",
].join("\n"),
{ encoding: "utf8", mode: 0o755 },
);
const result = await installPlugin({
source: "npm:published-plugin@1.0.0",
npmCommand: npmCommandPath,
});
const npmLog = readFileSync(npmLogPath, "utf8");
expect(npmLog).toContain("install published-plugin@1.0.0");
expect(npmLog).toContain("--omit=peer");
expect(npmLog).toContain("--legacy-peer-deps");
expect(
existsSync(
join(result.installPath, "package", "node_modules", "@cline", "core"),
),
).toBe(false);
expect(existsSync(result.entryPaths[0] ?? "")).toBe(true);
});
it("requires --force before replacing an existing install", async () => {
const source = join(root, "replace.ts");
writeFileSync(
source,
"export default { name: 'replace', manifest: { capabilities: ['tools'] } };",
"utf8",
);
const first = await installPlugin({ source });
await expect(installPlugin({ source })).rejects.toThrow(/Use --force/);
const second = await installPlugin({ source, force: true });
expect(second.installPath).toBe(first.installPath);
});
it("keeps an existing install when a forced replacement fails during staging", async () => {
const source = join(root, "replace-package");
const npmCommandPath = join(root, "fake-npm.sh");
await mkdir(source, { recursive: true });
await writeFile(
join(source, "package.json"),
JSON.stringify(
{
name: "replace-package",
cline: {
plugins: [{ paths: ["./index.ts"], capabilities: ["tools"] }],
},
},
null,
2,
),
"utf8",
);
await writeFile(
join(source, "index.ts"),
"export default { name: 'installed-v1', manifest: { capabilities: ['tools'] } };",
"utf8",
);
writeFileSync(npmCommandPath, "#!/bin/sh\nexit 0\n", {
encoding: "utf8",
mode: 0o755,
});
const first = await installPlugin({ source, npmCommand: npmCommandPath });
await writeFile(
join(source, "index.ts"),
"export default { name: 'installed-v2', manifest: { capabilities: ['tools'] } };",
"utf8",
);
writeFileSync(npmCommandPath, "#!/bin/sh\nprintf 'offline' >&2\nexit 1\n", {
encoding: "utf8",
mode: 0o755,
});
await expect(
installPlugin({ source, force: true, npmCommand: npmCommandPath }),
).rejects.toThrow(/offline/);
expect(existsSync(first.installPath)).toBe(true);
expect(
readFileSync(join(first.installPath, "package", "index.ts"), "utf8"),
).toContain("installed-v1");
});
it("uninstalls a package plugin by package name", async () => {
const source = join(root, "uninstall-package");
const npmCommandPath = join(root, "fake-npm.sh");
await mkdir(source, { recursive: true });
await writeFile(
join(source, "package.json"),
JSON.stringify(
{
name: "cli-uninstall-plugin",
cline: {
plugins: [{ paths: ["./index.ts"], capabilities: ["tools"] }],
},
},
null,
2,
),
"utf8",
);
await writeFile(
join(source, "index.ts"),
"export default { name: 'cli-uninstall-plugin', manifest: { capabilities: ['tools'] } };",
"utf8",
);
writeFileSync(npmCommandPath, "#!/bin/sh\nexit 0\n", {
encoding: "utf8",
mode: 0o755,
});
const installed = await installPlugin({
source,
npmCommand: npmCommandPath,
});
const output: string[] = [];
const code = await runPluginUninstallCommand({
name: "cli-uninstall-plugin",
io: {
writeln: (text = "") => output.push(text),
writeErr: (text) => output.push(text),
},
});
expect(code).toBe(0);
expect(existsSync(installed.installPath)).toBe(false);
expect(output.join("\n")).toContain(
"Uninstalled plugin cli-uninstall-plugin",
);
});
it("prints JSON output for command callers", async () => {
const source = join(root, "json.ts");
writeFileSync(
source,
"export default { name: 'json', manifest: { capabilities: ['tools'] } };",
"utf8",
);
const stdout: string[] = [];
const originalWrite = process.stdout.write;
process.stdout.write = ((chunk: string | Uint8Array) => {
stdout.push(String(chunk));
return true;
}) as typeof process.stdout.write;
try {
const code = await runPluginInstallCommand({
source,
json: true,
io: {
writeln: () => {},
writeErr: () => {},
},
});
expect(code).toBe(0);
const parsed = JSON.parse(stdout.join("")) as { installPath: string };
expect(parsed.installPath).toContain(join(home, ".cline", "plugins"));
} finally {
process.stdout.write = originalWrite;
}
});
it("prints JSON output for official plugin installs", async () => {
const officialPluginsRepo = await createOfficialPluginsRepo({
"json-plugin": {
"index.ts":
"export default { name: 'json-plugin', manifest: { capabilities: ['tools'] } };",
},
});
const stdout: string[] = [];
const originalWrite = process.stdout.write;
process.stdout.write = ((chunk: string | Uint8Array) => {
stdout.push(String(chunk));
return true;
}) as typeof process.stdout.write;
try {
const code = await runPluginInstallCommand({
source: "json-plugin",
cwd: workspace,
officialPluginsRepo,
json: true,
io: {
writeln: () => {},
writeErr: () => {},
},
});
expect(code).toBe(0);
const parsed = JSON.parse(stdout.join("")) as { installPath: string };
expect(parsed.installPath).toContain(
join(workspace, ".cline", "plugins", "_installed", "official"),
);
} finally {
process.stdout.write = originalWrite;
}
});
it("uses shared search paths for cwd installs", async () => {
const source = join(root, "workspace.ts");
writeFileSync(
source,
"export default { name: 'workspace', manifest: { capabilities: ['tools'] } };",
"utf8",
);
await installPlugin({
source,
cwd: workspace,
});
expect(resolvePluginConfigSearchPaths(workspace)[0]).toBe(
join(workspace, ".cline", "plugins"),
);
expect(
discoverPluginModulePaths(join(workspace, ".cline", "plugins")),
).toHaveLength(1);
});
});
@@ -1,626 +0,0 @@
import { writeFileSync } from "node:fs";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ConnectDiscordOptions } from "@cline/shared";
import type { Thread } from "chat";
import { afterEach, describe, expect, it, vi } from "vitest";
import { readBindings, writeBindings } from "../thread-bindings";
import { __test__, discordConnector } from "./discord";
const parseDiscordArgs = (rawArgs: string[]): ConnectDiscordOptions =>
(
discordConnector as unknown as {
parseArgs(rawArgs: string[]): ConnectDiscordOptions;
}
).parseArgs(rawArgs);
type TestDiscordState = {
sessionId?: string;
enableTools?: boolean;
autoApproveTools?: boolean;
cwd?: string;
workspaceRoot?: string;
systemPrompt?: string;
participantKey?: string;
participantLabel?: string;
welcomeSentAt?: string;
};
function createThread(
initialState: TestDiscordState,
): Thread<TestDiscordState> {
let state = { ...initialState };
return {
id: "discord:guild:channel:thread",
channelId: "discord:guild:channel",
isDM: false,
get state() {
return Promise.resolve(state);
},
async setState(nextState: TestDiscordState) {
state = { ...nextState };
},
toJSON() {
return {
id: "discord:guild:channel:thread",
channelId: "discord:guild:channel",
isDM: false,
state,
};
},
} as unknown as Thread<TestDiscordState>;
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe("discordConnector", () => {
it("accepts the documented app id and token aliases", () => {
const options = parseDiscordArgs([
"--app-id",
"app-123",
"--token",
"bot-token",
"--public-key",
"public-key",
"--base-url",
"https://example.test",
]);
expect(options.applicationId).toBe("app-123");
expect(options.botToken).toBe("bot-token");
expect(options.publicKey).toBe("public-key");
expect(options.baseUrl).toBe("https://example.test");
});
it("keeps accepting the explicit application id and bot token options", () => {
const options = parseDiscordArgs([
"--application-id",
"app-456",
"--bot-token",
"other-token",
"--public-key",
"public-key",
"--owner-user-id",
"owner-123",
]);
expect(options.applicationId).toBe("app-456");
expect(options.botToken).toBe("other-token");
expect(options.ownerUserId).toBe("owner-123");
expect(options.allowBotAuthors).toBe(true);
});
it("can explicitly ignore bot-authored Discord messages", () => {
const options = parseDiscordArgs([
"--application-id",
"app-456",
"--bot-token",
"other-token",
"--public-key",
"public-key",
"--ignore-bot-authors",
]);
expect(options.allowBotAuthors).toBe(false);
});
it("builds empty-runtime fallback replies from the current Discord turn", async () => {
const priorMessages = [
{
role: "user",
content: [{ type: "text", text: "previous question" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Previous reply." }],
},
];
const currentMessages = [
...priorMessages,
{
role: "user",
content: [{ type: "text", text: "read README.md" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Summary from saved session." }],
},
];
const client = {
readMessages: vi
.fn()
.mockResolvedValueOnce(priorMessages)
.mockResolvedValueOnce(currentMessages),
};
const resolveFallbackText =
await __test__.createDiscordEmptyRuntimeReplyResolver({
client: client as never,
sessionId: "session-1",
});
await expect(resolveFallbackText?.()).resolves.toBe(
"Summary from saved session.",
);
expect(client.readMessages).toHaveBeenCalledTimes(2);
});
it("does not reuse prior Discord replies as empty-runtime fallback text", async () => {
const priorMessages = [
{
role: "user",
content: [{ type: "text", text: "previous question" }],
},
{
role: "assistant",
content: [{ type: "text", text: "Previous reply." }],
},
];
const currentMessages = [
...priorMessages,
{
role: "user",
content: [{ type: "text", text: "run ls /tmp" }],
},
{
role: "tool",
content: [{ type: "text", text: "tool output" }],
},
];
const client = {
readMessages: vi
.fn()
.mockResolvedValueOnce(priorMessages)
.mockResolvedValueOnce(currentMessages),
};
const resolveFallbackText =
await __test__.createDiscordEmptyRuntimeReplyResolver({
client: client as never,
sessionId: "session-1",
});
await expect(resolveFallbackText?.()).resolves.toBeUndefined();
expect(client.readMessages).toHaveBeenCalledTimes(2);
});
it("resolves Discord participants from normalized gateway message authors", () => {
expect(
__test__.resolveDiscordParticipant(
{
content: "<@1509620637721821224> Heyo",
author: {
id: "bot-message-author-should-not-win",
username: "beebot",
},
},
{
userId: "850213762576810065",
userName: "alice",
fullName: "Alice Example",
},
),
).toEqual({
key: "discord:user:850213762576810065",
label: "Alice Example",
});
});
it("resolves Discord interaction users even when raw.data is command data", () => {
expect(
__test__.resolveDiscordParticipant({
id: "interaction-1",
data: { name: "ask" },
member: {
user: {
id: "488220547356950529",
username: "bob",
global_name: "Bob Example",
},
},
}),
).toEqual({
key: "discord:user:488220547356950529",
label: "Bob Example",
});
});
it("switches Discord thread state to the incoming participant without reusing the previous participant session", async () => {
const dir = await mkdtemp(join(tmpdir(), "discord-participants-"));
const bindingsPath = join(dir, "threads.json");
const thread = createThread({
sessionId: "session-alice",
participantKey: "discord:user:alice",
participantLabel: "Alice",
});
writeBindings<TestDiscordState>(bindingsPath, {
"discord:user:alice": {
channelId: thread.channelId,
isDM: thread.isDM,
participantKey: "discord:user:alice",
participantLabel: "Alice",
serializedThread: JSON.stringify(thread.toJSON()),
sessionId: "session-alice",
state: {
sessionId: "session-alice",
participantKey: "discord:user:alice",
participantLabel: "Alice",
},
updatedAt: "2026-05-26T00:00:00.000Z",
},
});
await __test__.persistDiscordThreadContext({
thread,
bindingsPath,
baseStartRequest: {
enableTools: false,
autoApproveTools: false,
cwd: "/tmp/work",
workspaceRoot: "/tmp/work",
systemPrompt: "system",
provider: "cline",
model: "test-model",
mode: "act",
},
message: {
raw: {
author: {
id: "bob",
username: "bob",
global_name: "Bob",
},
},
},
errorLabel: "Discord",
});
const bob =
readBindings<TestDiscordState>(bindingsPath)["discord:user:bob"];
expect(bob?.state?.participantKey).toBe("discord:user:bob");
expect(bob?.state?.participantLabel).toBe("Bob");
expect(bob?.state?.sessionId).toBeUndefined();
expect(
readBindings<TestDiscordState>(bindingsPath)["discord:user:alice"]?.state
?.sessionId,
).toBe("session-alice");
});
it("adds Discord author context to runtime turns", () => {
expect(
__test__.formatDiscordRuntimeText(
"Heyo",
{
key: "discord:user:850213762576810065",
label: "Alice Example",
},
{
ownerUserId: "850213762576810065",
isDirectMention: false,
isSubscribedThreadMessage: true,
},
),
).toContain("authorId: 850213762576810065");
expect(
__test__.formatDiscordRuntimeText(
"Heyo",
{
key: "discord:user:850213762576810065",
label: "Alice Example",
},
{ ownerUserId: "850213762576810065" },
),
).toContain("isOwner: true");
expect(
__test__.formatDiscordRuntimeText(
"Heyo",
{
key: "discord:user:850213762576810065",
label: "Alice Example",
},
{
isDirectMention: false,
isSubscribedThreadMessage: true,
},
),
).toContain("isDirectMention: false");
expect(
__test__.formatDiscordRuntimeText(
"Heyo",
{
key: "discord:user:850213762576810065",
label: "Alice Example",
},
{
isDirectMention: false,
isSubscribedThreadMessage: true,
},
),
).toContain("isSubscribedThreadMessage: true");
});
it("instructs Discord agents to use /idle for unrelated subscribed thread messages", () => {
expect(__test__.DISCORD_SYSTEM_RULES).toContain("reply exactly /idle");
expect(__test__.DISCORD_SYSTEM_RULES).toContain("isDirectMention is false");
expect(__test__.DISCORD_SYSTEM_RULES).toContain("send /mute@BotName");
expect(__test__.DISCORD_SYSTEM_RULES).toContain("send /unmute@BotName");
expect(__test__.DISCORD_SYSTEM_RULES).toContain(
"/mute@BotName @user-or-bot",
);
expect(__test__.DISCORD_SYSTEM_RULES).toContain(
"/unmute@BotName @user-or-bot",
);
});
it("resolves Discord mute targets from user mentions and ids", () => {
expect(__test__.resolveDiscordMuteTarget("<@123456789012345678>")).toEqual({
participantKey: "discord:user:123456789012345678",
participantLabel: "<@123456789012345678>",
});
expect(__test__.resolveDiscordMuteTarget("<@!123456789012345678>")).toEqual(
{
participantKey: "discord:user:123456789012345678",
participantLabel: "<@123456789012345678>",
},
);
expect(__test__.resolveDiscordMuteTarget("@123456789012345678")).toEqual({
participantKey: "discord:user:123456789012345678",
participantLabel: "<@123456789012345678>",
});
expect(__test__.resolveDiscordMuteTarget("@not-a-user-id")).toBeUndefined();
});
it("resolves outbound Discord mention names to user mention ids", async () => {
const fetchMock = vi.fn(async (url: string | URL) => {
expect(String(url)).toContain(
"/guilds/guild-123/members/search?query=cline-test-bot&limit=10",
);
return new Response(
JSON.stringify([
{
nick: "cline-test-bot",
user: {
id: "1509620637721821224",
username: "clinetestbot",
bot: true,
},
},
]),
{ status: 200 },
);
});
vi.stubGlobal("fetch", fetchMock);
await expect(
__test__.resolveDiscordOutboundMentions({
botToken: "token",
threadId: "discord:guild-123:channel-123:thread-123",
text: "@cline-test-bot how is your day?",
}),
).resolves.toBe("<@1509620637721821224> how is your day?");
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it("repairs adapter-split hyphenated Discord mention names before resolving", async () => {
const fetchMock = vi.fn(async (url: string | URL) => {
expect(String(url)).toContain("query=cline-test-bot");
return new Response(
JSON.stringify([
{
nick: "cline-test-bot",
user: {
id: "1509620637721821224",
username: "clinetestbot",
bot: true,
},
},
]),
{ status: 200 },
);
});
vi.stubGlobal("fetch", fetchMock);
await expect(
__test__.resolveDiscordOutboundMentions({
botToken: "token",
threadId: "discord:guild-123:channel-123:thread-123",
text: "<@cline>-test-bot how is your day?",
}),
).resolves.toBe("<@1509620637721821224> how is your day?");
});
it("does not resolve outbound mentions from non-exact Discord member search results", async () => {
const fetchMock = vi.fn(async () => {
return new Response(
JSON.stringify([
{
nick: "team-alice-bot",
user: {
id: "wrong-user",
username: "team-alice-bot",
bot: true,
},
},
]),
{ status: 200 },
);
});
vi.stubGlobal("fetch", fetchMock);
await expect(
__test__.resolveDiscordOutboundMentions({
botToken: "token",
threadId: "discord:guild-123:channel-123:thread-123",
text: "@alice can you check this?",
}),
).resolves.toBe("@alice can you check this?");
});
it("normalizes forwarded bot-role mentions as Discord mentions", async () => {
const fetchMock = vi.fn(async (url: string | URL) => {
expect(String(url)).toContain("/guilds/guild-role-test/members/app-123");
return new Response(JSON.stringify({ roles: ["role-123"] }), {
status: 200,
});
});
vi.stubGlobal("fetch", fetchMock);
const request = new Request("https://example.test/api/webhooks/discord", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "GATEWAY_MESSAGE_CREATE",
data: {
id: "message-1",
guild_id: "guild-role-test",
channel_id: "channel-1",
content: "<@&role-123> hello",
mention_roles: ["role-123"],
mentions: [],
author: {
id: "user-1",
username: "alice",
bot: false,
},
},
}),
});
const normalized = await __test__.normalizeDiscordForwardedGatewayRequest({
request,
botToken: "token",
applicationId: "app-123",
});
const event = (await normalized.json()) as {
data: { is_mention?: boolean };
};
expect(event.data.is_mention).toBe(true);
});
it("retries bot role lookups after transient Discord API failures", async () => {
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response("temporary", { status: 500 }))
.mockResolvedValueOnce(
new Response(JSON.stringify({ roles: ["role-123"] }), {
status: 200,
}),
);
vi.stubGlobal("fetch", fetchMock);
const buildRequest = () =>
new Request("https://example.test/api/webhooks/discord", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
type: "GATEWAY_MESSAGE_CREATE",
data: {
id: "message-1",
guild_id: "guild-retry-test",
channel_id: "channel-1",
content: "<@&role-123> hello",
mention_roles: ["role-123"],
mentions: [],
author: {
id: "user-1",
username: "alice",
bot: false,
},
},
}),
});
const failed = await __test__.normalizeDiscordForwardedGatewayRequest({
request: buildRequest(),
botToken: "token",
applicationId: "app-retry",
});
const failedEvent = (await failed.json()) as {
data: { is_mention?: boolean };
};
expect(failedEvent.data.is_mention).toBeUndefined();
const retried = await __test__.normalizeDiscordForwardedGatewayRequest({
request: buildRequest(),
botToken: "token",
applicationId: "app-retry",
});
const retriedEvent = (await retried.json()) as {
data: { is_mention?: boolean };
};
expect(retriedEvent.data.is_mention).toBe(true);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("restores persisted thread subscriptions once on startup", async () => {
const dir = await mkdtemp(join(tmpdir(), "discord-bindings-"));
const bindingsPath = join(dir, "threads.json");
const subscribe = vi.fn(async () => undefined);
const threads = new Map([
[
"thread-1",
{
id: "thread-1",
subscribe,
},
],
]);
const bot = {
reviver: () => (_key: string, value: unknown) => {
if (
value &&
typeof value === "object" &&
(value as { _type?: string })._type === "chat:Thread"
) {
return threads.get((value as { id: string }).id) ?? value;
}
return value;
},
};
const logger = {
core: { log: vi.fn() },
} as unknown as Parameters<
typeof __test__.restoreDiscordThreadSubscriptions
>[0]["logger"];
writeFileSync(
bindingsPath,
JSON.stringify({
"discord:user:1": {
channelId: "discord:g:c",
isDM: false,
participantKey: "discord:user:1",
serializedThread: JSON.stringify({
_type: "chat:Thread",
id: "thread-1",
}),
updatedAt: "2026-05-26T00:00:00.000Z",
},
duplicate: {
channelId: "discord:g:c",
isDM: false,
serializedThread: JSON.stringify({
_type: "chat:Thread",
id: "thread-1",
}),
updatedAt: "2026-05-26T00:00:00.000Z",
},
}),
);
const restored = await __test__.restoreDiscordThreadSubscriptions({
bot,
bindingsPath,
logger,
});
expect(restored).toBe(1);
expect(subscribe).toHaveBeenCalledTimes(1);
expect(logger.core.log).not.toHaveBeenCalled();
});
});
@@ -1,395 +0,0 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { ConnectTelegramOptions } from "@cline/shared";
import { afterEach, describe, expect, it, vi } from "vitest";
import { __test__, telegramConnector } from "./telegram";
const parseTelegramArgs = (rawArgs: string[]): ConnectTelegramOptions =>
(
telegramConnector as unknown as {
parseArgs(rawArgs: string[]): ConnectTelegramOptions;
}
).parseArgs(rawArgs);
const originalClineDataDir = process.env.CLINE_DATA_DIR;
const tempDataDirs: string[] = [];
function useTempClineDataDir(): string {
const dataDir = mkdtempSync(join(tmpdir(), "cline-telegram-test-"));
tempDataDirs.push(dataDir);
process.env.CLINE_DATA_DIR = dataDir;
return dataDir;
}
afterEach(() => {
vi.unstubAllGlobals();
if (originalClineDataDir === undefined) {
delete process.env.CLINE_DATA_DIR;
} else {
process.env.CLINE_DATA_DIR = originalClineDataDir;
}
for (const dir of tempDataDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("telegramConnector", () => {
it("honors --no-tools", () => {
const options = parseTelegramArgs([
"--bot-username",
"test_bot",
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
"--no-tools",
]);
expect(options.enableTools).toBe(false);
});
it("enables tools by default", () => {
const options = parseTelegramArgs([
"--bot-username",
"test_bot",
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
]);
expect(options.enableTools).toBe(true);
});
it("builds an authorization hook from --allowed-user-id", () => {
const options = parseTelegramArgs([
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
"--allowed-user-id",
"1201547643",
]);
expect(options.hookCommand).toBe(
`jq -r ".payload.actor.participantKey" | grep -qx "telegram:id:1201547643" && echo '{"action":"allow"}' || echo '{"action":"deny","message":"unauthorized","reason":"not_on_allowlist"}'`,
);
});
it("rejects unsafe --allowed-user-id values", () => {
expect(() =>
parseTelegramArgs([
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
"--allowed-user-id",
"123; rm -rf /",
]),
).toThrow("digits only");
});
it("rejects mixing --allowed-user-id with --hook-command", () => {
expect(() =>
parseTelegramArgs([
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
"--allowed-user-id",
"1201547643",
"--hook-command",
"echo noop",
]),
).toThrow("either --allowed-user-id or --hook-command");
});
it("rejects mixing --allowed-user-id with the hook command env var", () => {
const originalHookCommand = process.env.CLINE_CONNECT_HOOK_COMMAND;
process.env.CLINE_CONNECT_HOOK_COMMAND = "echo noop";
try {
expect(() =>
parseTelegramArgs([
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
"--allowed-user-id",
"1201547643",
]),
).toThrow("either --allowed-user-id or --hook-command");
} finally {
if (originalHookCommand === undefined) {
delete process.env.CLINE_CONNECT_HOOK_COMMAND;
} else {
process.env.CLINE_CONNECT_HOOK_COMMAND = originalHookCommand;
}
}
});
it("does not require the bot username", () => {
const options = parseTelegramArgs([
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
]);
expect(options.botUsername).toBeUndefined();
expect(options.botToken).toBe("123:test");
});
it("normalizes an explicit bot username", () => {
const options = parseTelegramArgs([
"--bot-username",
" @test_bot ",
"--bot-token",
"123:test",
"--cwd",
"/tmp/work",
]);
expect(options.botUsername).toBe("test_bot");
});
it("does not call getMe when the token-only connector is already running", async () => {
const dataDir = useTempClineDataDir();
const connectorDir = join(dataDir, "connectors", "telegram");
mkdirSync(connectorDir, { recursive: true });
writeFileSync(
join(connectorDir, "resolved_bot.json"),
JSON.stringify({
botUsername: "resolved_bot",
botId: "123",
pid: process.pid,
rpcAddress: "127.0.0.1:54321",
startedAt: new Date().toISOString(),
}),
);
const fetchImpl = vi.fn(async () => {
throw new Error("unexpected getMe call");
});
vi.stubGlobal("fetch", fetchImpl);
const output: string[] = [];
const errors: string[] = [];
await expect(
telegramConnector.run(["--bot-token", "123:test", "--cwd", "/tmp/work"], {
writeln: (text = "") => output.push(text),
writeErr: (text) => errors.push(text),
}),
).resolves.toBe(0);
expect(fetchImpl).not.toHaveBeenCalled();
expect(errors).toEqual([]);
expect(output).toEqual([
`[telegram] connector already running pid=${process.pid} rpc=127.0.0.1:54321`,
]);
});
});
describe("telegram bot username resolution", () => {
it("reads the public Telegram bot id from a token", () => {
expect(__test__.readTelegramBotId("123456:secret")).toBe("123456");
expect(__test__.readTelegramBotId("not-a-token")).toBeUndefined();
});
it("uses the configured username without calling Telegram", async () => {
const fetchImpl = vi.fn(async () => {
throw new Error("unexpected fetch");
});
await expect(
__test__.resolveTelegramBotUsername(
{
botToken: "123:test",
botUsername: "@configured_bot",
cwd: "/tmp/work",
mode: "act",
interactive: true,
enableTools: true,
rpcAddress: "127.0.0.1:0",
},
fetchImpl,
),
).resolves.toBe("configured_bot");
expect(fetchImpl).not.toHaveBeenCalled();
});
it("fetches the username from Telegram getMe when omitted", async () => {
const fetchImpl = vi.fn(async () => {
return new Response(
JSON.stringify({
ok: true,
result: { username: "resolved_bot" },
}),
);
});
await expect(
__test__.fetchTelegramBotUsername("123:test", fetchImpl),
).resolves.toBe("resolved_bot");
expect(fetchImpl).toHaveBeenCalledWith(
"https://api.telegram.org/bot123:test/getMe",
);
});
it("surfaces Telegram getMe failures", async () => {
const fetchImpl = vi.fn(async () => {
return new Response(
JSON.stringify({
ok: false,
description: "Unauthorized",
}),
{ status: 401, statusText: "Unauthorized" },
);
});
await expect(
__test__.fetchTelegramBotUsername("bad-token", fetchImpl),
).rejects.toThrow("Telegram getMe failed");
});
});
describe("telegram participant resolution", () => {
it("uses the stable numeric Telegram user id when username is also present", () => {
const result = __test__.resolveTelegramParticipant({
message: {
from: {
id: 1201547643,
username: "AraFatKatze",
first_name: "Ara",
},
},
});
expect(result).toEqual({
key: "telegram:id:1201547643",
label: "arafatkatze",
});
});
it("falls back to username when Telegram does not provide a numeric user id", () => {
const result = __test__.resolveTelegramParticipant({
message: {
from: {
username: "Alice",
},
},
});
expect(result).toEqual({
key: "telegram:user:alice",
label: "alice",
});
});
it("accepts string numeric user ids from raw Telegram payloads", () => {
const result = __test__.resolveTelegramParticipant({
message: {
from: {
id: "1201547643",
username: "arafatkatze",
},
},
});
expect(result?.key).toBe("telegram:id:1201547643");
});
});
describe("telegram binding lookup", () => {
it("falls back to channel identity when a restarted connector gets a new thread id", () => {
const result = __test__.findBindingForThread(
{
legacy_thread_id: {
channelId: "chat-123",
isDM: true,
serializedThread: "{}",
sessionId: "sess-1",
state: { sessionId: "sess-1", cwd: "/tmp/work" },
updatedAt: "2026-03-17T00:00:00.000Z",
},
},
{
id: "new_thread_id",
channelId: "chat-123",
isDM: true,
},
);
expect(result).toEqual({
key: "legacy_thread_id",
binding: {
channelId: "chat-123",
isDM: true,
serializedThread: "{}",
sessionId: "sess-1",
state: { sessionId: "sess-1", cwd: "/tmp/work" },
updatedAt: "2026-03-17T00:00:00.000Z",
},
});
});
it("prefers an exact thread id match over a channel fallback", () => {
const result = __test__.findBindingForThread(
{
current_thread_id: {
channelId: "chat-123",
isDM: true,
serializedThread: "{}",
sessionId: "sess-2",
state: { sessionId: "sess-2" },
updatedAt: "2026-03-17T00:00:00.000Z",
},
legacy_thread_id: {
channelId: "chat-123",
isDM: true,
serializedThread: "{}",
sessionId: "sess-1",
state: { sessionId: "sess-1" },
updatedAt: "2026-03-17T00:00:00.000Z",
},
},
{
id: "current_thread_id",
channelId: "chat-123",
isDM: true,
},
);
expect(result?.key).toBe("current_thread_id");
expect(result?.binding.sessionId).toBe("sess-2");
});
it("reuses a binding by participant key across different chats", () => {
const result = __test__.findBindingForThread(
{
"telegram:user:alice": {
channelId: "chat-123",
isDM: true,
participantKey: "telegram:user:alice",
participantLabel: "alice",
serializedThread: "{}",
sessionId: "sess-1",
state: {
sessionId: "sess-1",
participantKey: "telegram:user:alice",
participantLabel: "alice",
},
updatedAt: "2026-03-17T00:00:00.000Z",
},
},
{
id: "new_thread_id",
channelId: "chat-999",
isDM: true,
participantKey: "telegram:user:alice",
},
);
expect(result?.key).toBe("telegram:user:alice");
expect(result?.binding.sessionId).toBe("sess-1");
});
});
-36
View File
@@ -1,36 +0,0 @@
export type ConnectorCatalogEntry = {
name: string;
description: string;
};
export const CONNECTOR_CATALOG: ConnectorCatalogEntry[] = [
{
name: "discord",
description:
"Discord interactions and gateway bridge backed by RPC runtime sessions",
},
{
name: "gchat",
description: "Google Chat webhook bridge backed by RPC runtime sessions",
},
{
name: "linear",
description: "Linear webhook bridge backed by RPC runtime sessions",
},
{
name: "slack",
description: "Slack webhook/socket bridge backed by RPC runtime sessions",
},
{
name: "telegram",
description: "Bridge Telegram bot messages into RPC chat sessions",
},
{
name: "whatsapp",
description: "Bridge WhatsApp webhook messages into RPC chat sessions",
},
];
export function listConnectorCatalog(): ConnectorCatalogEntry[] {
return CONNECTOR_CATALOG.map((entry) => ({ ...entry }));
}
File diff suppressed because it is too large Load Diff
-14
View File
@@ -1,14 +0,0 @@
import { describe, expect, it } from "vitest";
import { getConnector, listConnectors } from "./registry";
describe("connector registry", () => {
it("registers the Discord connector", async () => {
expect(listConnectors().map((connector) => connector.name)).toContain(
"discord",
);
await expect(getConnector("discord")).resolves.toMatchObject({
name: "discord",
});
});
});
-196
View File
@@ -1,196 +0,0 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { resolveClineDataDir } from "@cline/core";
function isProcessRunning(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) {
return false;
}
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
export type ActiveConnectorRecord = {
id: string;
type: string;
pid: number;
hubUrl: string;
startedAt?: string;
applicationId?: string;
botUsername?: string;
userName?: string;
phoneNumberId?: string;
port?: number;
baseUrl?: string;
connectionMode?: string;
};
function listConnectorStatePaths(
type: ActiveConnectorRecord["type"],
): string[] {
const dir = join(resolveClineDataDir(), "connectors", type);
if (!existsSync(dir)) {
return [];
}
return readdirSync(dir)
.filter((name) => name.endsWith(".json") && !name.endsWith(".threads.json"))
.map((name) => join(dir, name));
}
function readJsonRecord(path: string): Record<string, unknown> | undefined {
if (!existsSync(path)) {
return undefined;
}
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw) as unknown;
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
} catch {
// Ignore malformed connector state.
}
return undefined;
}
type ConnectorFieldKey = keyof Omit<
ActiveConnectorRecord,
"id" | "type" | "pid" | "hubUrl"
>;
const connectorFieldExtractors: Record<
ConnectorFieldKey,
(p: Record<string, unknown>) => string | number | undefined
> = {
startedAt: (p) => (typeof p.startedAt === "string" ? p.startedAt : undefined),
port: (p) => (typeof p.port === "number" ? p.port : undefined),
baseUrl: (p) => (typeof p.baseUrl === "string" ? p.baseUrl : undefined),
connectionMode: (p) =>
typeof p.connectionMode === "string" ? p.connectionMode : undefined,
userName: (p) => (typeof p.userName === "string" ? p.userName : undefined),
botUsername: (p) =>
typeof p.botUsername === "string" ? p.botUsername : undefined,
applicationId: (p) =>
typeof p.applicationId === "string" ? p.applicationId : undefined,
phoneNumberId: (p) =>
typeof p.phoneNumberId === "string" ? p.phoneNumberId : undefined,
};
const connectorConfigs: Record<
string,
{ required: ConnectorFieldKey[]; optional: ConnectorFieldKey[] }
> = {
discord: {
required: ["userName", "applicationId"],
optional: ["startedAt", "port", "baseUrl"],
},
telegram: { required: ["botUsername"], optional: ["startedAt"] },
gchat: { required: ["userName"], optional: ["startedAt", "port", "baseUrl"] },
linear: {
required: ["userName"],
optional: ["startedAt", "port", "baseUrl"],
},
slack: {
required: ["userName"],
optional: ["startedAt", "connectionMode", "port", "baseUrl"],
},
whatsapp: {
required: ["userName"],
optional: ["startedAt", "phoneNumberId", "port", "baseUrl"],
},
};
function connectorRecordId(
type: ActiveConnectorRecord["type"],
fields: Partial<
Omit<ActiveConnectorRecord, "id" | "type" | "pid" | "hubUrl">
>,
pid: number,
): string {
const identity =
fields.botUsername ??
fields.userName ??
fields.applicationId ??
fields.phoneNumberId ??
String(pid);
return `${type}:${identity}`;
}
function readActiveConnectorRecord(
type: ActiveConnectorRecord["type"],
statePath: string,
): ActiveConnectorRecord | undefined {
const parsed = readJsonRecord(statePath);
if (!parsed) {
return undefined;
}
const pid = typeof parsed.pid === "number" ? parsed.pid : undefined;
const hubUrl =
typeof parsed.hubUrl === "string"
? parsed.hubUrl
: typeof parsed.rpcAddress === "string"
? parsed.rpcAddress
: undefined;
if (!pid || !hubUrl || !isProcessRunning(pid)) {
return undefined;
}
const config = connectorConfigs[type];
if (!config) {
return undefined;
}
const fields: Partial<
Omit<ActiveConnectorRecord, "id" | "type" | "pid" | "hubUrl">
> = {};
for (const key of config.required) {
const value = connectorFieldExtractors[key](parsed);
if (!value || (typeof value === "string" && !value.trim())) {
return undefined;
}
(fields as Record<string, unknown>)[key] = value;
}
for (const key of config.optional) {
const value = connectorFieldExtractors[key](parsed);
if (value !== undefined) {
(fields as Record<string, unknown>)[key] = value;
}
}
return {
id: connectorRecordId(type, fields, pid),
type,
pid,
hubUrl,
...fields,
} as ActiveConnectorRecord;
}
export function listActiveConnectors(): ActiveConnectorRecord[] {
const connectorTypes: ActiveConnectorRecord["type"][] = [
"discord",
"telegram",
"gchat",
"linear",
"slack",
"whatsapp",
];
const records: ActiveConnectorRecord[] = [];
for (const type of connectorTypes) {
for (const statePath of listConnectorStatePaths(type)) {
const record = readActiveConnectorRecord(type, statePath);
if (record) {
records.push(record);
}
}
}
return records.sort((left, right) => {
if (left.type !== right.type) {
return left.type.localeCompare(right.type);
}
const leftName = left.botUsername ?? left.userName ?? "";
const rightName = right.botUsername ?? right.userName ?? "";
return leftName.localeCompare(rightName);
});
}
@@ -1,252 +0,0 @@
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Thread } from "chat";
import { afterEach, describe, expect, it } from "vitest";
import {
type ConnectorThreadState,
clearBindingSessionIds,
isParticipantMuted,
isThreadMuted,
readBindingForThread,
readBindings,
setParticipantMuted,
setThreadMuted,
writeBindings,
} from "./thread-bindings";
type TestState = ConnectorThreadState & {
teamId?: string;
};
const tempDirs: string[] = [];
function createBindingsPath(): string {
const dir = mkdtempSync(join(tmpdir(), "thread-bindings-"));
tempDirs.push(dir);
return join(dir, "bindings.json");
}
function createThread(input: {
id: string;
channelId: string;
isDM: boolean;
participantKey?: string;
}): Thread<TestState> {
return {
id: input.id,
channelId: input.channelId,
isDM: input.isDM,
toJSON: () => ({
id: input.id,
channelId: input.channelId,
isDM: input.isDM,
}),
} as unknown as Thread<TestState>;
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("thread binding refresh", () => {
it("refreshes the serialized thread immediately when channel fallback rebinds a thread id", () => {
const path = createBindingsPath();
writeBindings<TestState>(path, {
legacy_thread_id: {
channelId: "slack:C123",
isDM: false,
serializedThread: JSON.stringify({
id: "legacy_thread_id",
channelId: "slack:C123",
isDM: false,
}),
sessionId: "sess-1",
state: { sessionId: "sess-1", teamId: "T123" },
updatedAt: "2026-03-17T00:00:00.000Z",
},
});
const binding = readBindingForThread<TestState>(
path,
createThread({
id: "new_thread_id",
channelId: "slack:C123",
isDM: false,
}),
"Slack",
);
expect(binding?.serializedThread).toContain("new_thread_id");
const bindings = readBindings<TestState>(path);
expect(bindings.legacy_thread_id).toBeUndefined();
expect(bindings.new_thread_id?.serializedThread).toContain("new_thread_id");
});
it("refreshes the serialized thread when a participant-key binding matches a new thread id", () => {
const path = createBindingsPath();
const participantKey = "slack:team:T123:user:U123";
writeBindings<TestState>(path, {
[participantKey]: {
channelId: "slack:C123",
isDM: false,
participantKey,
serializedThread: JSON.stringify({
id: "legacy_thread_id",
channelId: "slack:C123",
isDM: false,
}),
sessionId: "sess-1",
state: {
sessionId: "sess-1",
teamId: "T123",
participantKey,
},
updatedAt: "2026-03-17T00:00:00.000Z",
},
});
const binding = readBindingForThread<TestState>(
path,
createThread({
id: "new_thread_id",
channelId: "slack:C123",
isDM: false,
}),
"Slack",
participantKey,
);
expect(binding?.serializedThread).toContain("new_thread_id");
expect(
readBindings<TestState>(path)[participantKey]?.serializedThread,
).toContain("new_thread_id");
});
it("stores mute state at thread scope instead of participant scope", () => {
const path = createBindingsPath();
const thread = createThread({
id: "thread-1",
channelId: "discord:guild:channel",
isDM: false,
participantKey: "discord:user:alice",
});
setThreadMuted(path, thread, true, "Discord");
expect(
isThreadMuted(
path,
createThread({
id: "thread-1",
channelId: "discord:guild:channel",
isDM: false,
participantKey: "discord:user:bob",
}),
),
).toBe(true);
const binding = readBindingForThread<TestState>(
path,
thread,
"Discord",
"discord:user:alice",
);
expect(binding).toBeUndefined();
setThreadMuted(path, thread, false, "Discord");
expect(isThreadMuted(path, thread)).toBe(false);
});
it("stores participant mute state scoped to the current thread", () => {
const path = createBindingsPath();
const thread = createThread({
id: "thread-1",
channelId: "discord:guild:channel",
isDM: false,
});
const otherThread = createThread({
id: "thread-2",
channelId: "discord:guild:channel",
isDM: false,
});
setParticipantMuted(
path,
thread,
{
participantKey: "discord:user:bob",
participantLabel: "Bob",
},
true,
"Discord",
);
expect(isParticipantMuted(path, thread, "discord:user:bob")).toBe(true);
expect(isParticipantMuted(path, thread, "discord:user:alice")).toBe(false);
expect(isParticipantMuted(path, otherThread, "discord:user:bob")).toBe(
false,
);
expect(
readBindingForThread<TestState>(
path,
thread,
"Discord",
"discord:user:bob",
),
).toBeUndefined();
setParticipantMuted(
path,
thread,
{ participantKey: "discord:user:bob" },
false,
"Discord",
);
expect(isParticipantMuted(path, thread, "discord:user:bob")).toBe(false);
});
});
describe("clearBindingSessionIds", () => {
it("clears session ids from bindings and serialized thread state", () => {
const path = createBindingsPath();
writeBindings<TestState>(path, {
thread_1: {
channelId: "discord:C123",
isDM: false,
serializedThread: JSON.stringify({
id: "thread_1",
channelId: "discord:C123",
isDM: false,
sessionId: "legacy-root-session",
state: {
sessionId: "sess-1",
cwd: "/tmp/work",
teamId: "T123",
},
}),
sessionId: "sess-1",
state: { sessionId: "sess-1", cwd: "/tmp/work", teamId: "T123" },
updatedAt: "2026-03-17T00:00:00.000Z",
},
});
clearBindingSessionIds<TestState>(path);
const binding = readBindings<TestState>(path).thread_1;
expect(binding?.sessionId).toBeUndefined();
expect(binding?.state?.sessionId).toBeUndefined();
expect(binding?.state?.cwd).toBe("/tmp/work");
const serializedThread = JSON.parse(binding?.serializedThread ?? "{}") as {
sessionId?: string;
state?: TestState;
};
expect(serializedThread.sessionId).toBeUndefined();
expect(serializedThread.state?.sessionId).toBeUndefined();
expect(serializedThread.state?.cwd).toBe("/tmp/work");
});
});
@@ -1,825 +0,0 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { UserInstructionConfigService } from "@cline/core";
import { afterEach, describe, expect, it } from "vitest";
import {
buildSlashCommandRegistry,
expandUserCommandPrompt,
} from "../../tui/commands/slash-command-registry";
import {
applyPluginFailures,
type InteractiveConfigItem,
} from "../../tui/interactive-config";
import type { Config } from "../../utils/types";
import { createInteractiveConfigDataLoader } from "./config-data";
function createConfig(cwd: string): Config {
return {
apiKey: "test-key",
cwd,
workspaceRoot: cwd,
systemPrompt: "",
modelId: "test-model",
providerId: "test-provider",
mode: "act",
verbose: false,
sandbox: false,
thinking: false,
outputMode: "text",
defaultToolAutoApprove: false,
toolPolicies: { "*": { autoApprove: false } },
enableTools: true,
enableSpawnAgent: true,
enableAgentTeams: true,
};
}
describe("interactive config data loader", () => {
const tempRoots: string[] = [];
const envSnapshot = {
CLINE_GLOBAL_SETTINGS_PATH: process.env.CLINE_GLOBAL_SETTINGS_PATH,
CLINE_MCP_SETTINGS_PATH: process.env.CLINE_MCP_SETTINGS_PATH,
};
afterEach(async () => {
process.env.CLINE_GLOBAL_SETTINGS_PATH =
envSnapshot.CLINE_GLOBAL_SETTINGS_PATH;
process.env.CLINE_MCP_SETTINGS_PATH = envSnapshot.CLINE_MCP_SETTINGS_PATH;
await Promise.all(
tempRoots.map((dir) => rm(dir, { recursive: true, force: true })),
);
tempRoots.length = 0;
});
async function writeSettingsPlugin(tempRoot: string): Promise<string> {
const pluginsDir = join(tempRoot, ".cline", "plugins");
await mkdir(pluginsDir, { recursive: true });
const pluginPath = join(pluginsDir, "settings-plugin.js");
await writeFile(
pluginPath,
[
"export default {",
" name: 'settings-plugin',",
" manifest: { capabilities: ['tools'] },",
" setup(api) {",
" api.registerTool({",
" name: 'settings_plugin_tool',",
" description: 'Settings plugin tool',",
" inputSchema: { type: 'object', properties: {} },",
" execute: async () => 'ok',",
" });",
" },",
"};",
].join("\n"),
);
return pluginPath;
}
it("toggles a skill item to the opposite enabled state and refreshes before reload", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const skillPath = join(tempRoot, "SKILL.md");
await writeFile(
skillPath,
`---
name: skill-one
---
Use this skill.`,
);
const calls: string[] = [];
let refreshed = false;
const userInstructionService = {
async refreshType(type: string) {
calls.push(`refreshType:${type}`);
refreshed = true;
},
listRuntimeCommands() {
calls.push("listRuntimeCommands");
return refreshed
? []
: [
{
name: "skill-one",
instructions: "Use this skill.",
description: "Skill one",
kind: "skill",
},
];
},
listRecords(type: string) {
calls.push(`listRecords:${type}`);
if (type !== "skill") {
return [];
}
return [
{
id: "skill-one",
type: "skill",
filePath: skillPath,
item: {
name: "skill-one",
disabled: refreshed,
description: "Skill one",
instructions: "Use this skill.",
frontmatter: {},
},
},
];
},
} as unknown as UserInstructionConfigService;
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
userInstructionService,
});
const item: InteractiveConfigItem = {
id: "skill-one",
name: "skill-one",
path: skillPath,
enabled: true,
source: "workspace",
kind: "skill",
};
const data = await loader.onToggleConfigItem(item);
const written = await readFile(skillPath, "utf8");
expect(written).toContain("disabled: true");
expect(data?.skills[0]?.enabled).toBe(false);
expect(
data?.workflowSlashCommands.map((command) => command.name),
).not.toContain("skill-one");
expect(calls).toContain("refreshType:skill");
expect(calls.lastIndexOf("listRecords:skill")).toBeGreaterThan(
calls.indexOf("refreshType:skill"),
);
});
it("returns refreshed slash commands so disabled skills stop expanding before submit", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const skillPath = join(tempRoot, "SKILL.md");
await writeFile(
skillPath,
`---
name: find-skills
---
Find installable skills.`,
);
let refreshed = false;
const userInstructionService = {
async refreshType() {
refreshed = true;
},
listRuntimeCommands() {
return refreshed
? []
: [
{
name: "find-skills",
instructions: "Find installable skills.",
description: "Find skills",
kind: "skill",
},
];
},
listRecords(type: string) {
if (type !== "skill") {
return [];
}
return [
{
id: "find-skills",
type: "skill",
filePath: skillPath,
item: {
name: "find-skills",
disabled: refreshed,
description: "Find skills",
instructions: "Find installable skills.",
frontmatter: {},
},
},
];
},
} as unknown as UserInstructionConfigService;
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
userInstructionService,
});
const initialData = await loader.loadConfigData();
const initialRegistry = buildSlashCommandRegistry({
workflowSlashCommands: initialData.workflowSlashCommands,
});
expect(
expandUserCommandPrompt("/find-skills what can u do?", initialRegistry),
).toContain("<user_command");
const nextData = await loader.onToggleConfigItem({
id: "find-skills",
name: "find-skills",
path: skillPath,
enabled: true,
source: "workspace",
kind: "skill",
});
const refreshedRegistry = buildSlashCommandRegistry({
workflowSlashCommands: nextData?.workflowSlashCommands,
});
expect(
nextData?.workflowSlashCommands.map((command) => command.name),
).not.toContain("find-skills");
expect(
expandUserCommandPrompt("/find-skills what can u do?", refreshedRegistry),
).toBe("/find-skills what can u do?");
});
it("keeps plugin tool toggle behavior", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
const pluginToolPath = join(tempRoot, "plugin-tool.js");
await writeFile(pluginToolPath, "export {};\n");
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const item: InteractiveConfigItem = {
id: "plugin:tool:path",
name: "plugin-tool",
path: pluginToolPath,
enabled: true,
source: "workspace-plugin",
kind: "tool",
};
const data = await loader.onToggleConfigItem(item);
const settings = JSON.parse(
await readFile(process.env.CLINE_GLOBAL_SETTINGS_PATH, "utf8"),
) as { disabledTools?: string[] };
expect(settings.disabledTools).toEqual(["plugin-tool"]);
expect(data).toBeUndefined();
});
it("can skip plugin tool imports for fast settings open", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
const pluginPath = await writeSettingsPlugin(tempRoot);
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData({ includePluginTools: false });
expect(data.plugins.some((item) => item.path === pluginPath)).toBe(true);
expect(
data.tools.some((item) => item.pluginName === "settings-plugin"),
).toBe(false);
});
it("loads plugin tools when requested", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
await writeSettingsPlugin(tempRoot);
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData({ includePluginTools: true });
expect(
data.tools.some(
(item) =>
item.pluginName === "settings-plugin" &&
item.name === "settings_plugin_tool",
),
).toBe(true);
});
it("keeps failed plugins visible with their load error", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
const pluginsDir = join(tempRoot, ".cline", "plugins");
await mkdir(pluginsDir, { recursive: true });
const pluginPath = join(pluginsDir, "broken-plugin.js");
const invalidPluginPath = join(pluginsDir, "invalid-plugin.js");
await writeFile(
pluginPath,
[
"export default {",
" name: 'broken-plugin',",
" manifest: { capabilities: ['tools'] },",
" setup() {",
" throw new Error('setup exploded');",
" },",
"};",
].join("\n"),
);
await writeFile(invalidPluginPath, "export default {};\n", "utf8");
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData({ includePluginTools: true });
const plugin = data.plugins.find((item) => item.path === pluginPath);
expect(plugin?.name).toBe("broken-plugin");
expect(plugin?.loadErrorPhase).toBe("setup");
expect(plugin?.loadError).toContain("setup failed: setup exploded");
const invalidPlugin = data.plugins.find(
(item) => item.path === invalidPluginPath,
);
expect(invalidPlugin?.name).toBe("invalid-plugin");
expect(invalidPlugin?.loadErrorPhase).toBe("load");
expect(invalidPlugin?.loadError).toContain("load failed:");
});
it("preserves multiple load failures for the same plugin path", () => {
const plugin: InteractiveConfigItem = {
id: "/tmp/plugin.js",
name: "plugin",
path: "/tmp/plugin.js",
enabled: true,
kind: "plugin",
source: "workspace-plugin",
};
applyPluginFailures(
[plugin],
[
{
pluginPath: "/tmp/plugin.js",
pluginName: "plugin",
phase: "setup",
message: "first failure",
},
{
pluginPath: "/tmp/plugin.js",
phase: "setup",
message: "second failure",
},
],
);
expect(plugin.loadError).toBe(
"setup failed: first failure\nsetup failed: second failure",
);
expect(plugin.loadErrorPhase).toBeUndefined();
});
it("toggles every SDK tool name for a displayed built-in tool", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const item: InteractiveConfigItem = {
id: "editor",
name: "editor",
path: "editor, apply_patch",
enabled: true,
source: "builtin",
kind: "tool",
configKind: "tool",
toolNames: ["editor", "apply_patch"],
};
await loader.onToggleConfigItem(item);
const settings = JSON.parse(
await readFile(process.env.CLINE_GLOBAL_SETTINGS_PATH, "utf8"),
) as { disabledTools?: string[] };
expect(settings.disabledTools).toEqual(["apply_patch", "editor"]);
});
it("loads and toggles plugin enabled state from global settings", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
const pluginsDir = join(tempRoot, ".cline", "plugins");
await mkdir(pluginsDir, { recursive: true });
const pluginPath = join(pluginsDir, "workspace-plugin.js");
await writeFile(pluginPath, "export default {};\n");
await writeFile(
process.env.CLINE_GLOBAL_SETTINGS_PATH,
JSON.stringify({ disabledPlugins: [pluginPath] }, null, 2),
);
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData();
const plugin = data.plugins.find((item) => item.path === pluginPath);
expect(plugin?.enabled).toBe(false);
if (!plugin) {
throw new Error("Expected workspace plugin to be listed");
}
const nextData = await loader.onToggleConfigItem(plugin);
const refreshedData = await loader.loadConfigData();
const settings = JSON.parse(
await readFile(process.env.CLINE_GLOBAL_SETTINGS_PATH, "utf8"),
) as { disabledPlugins?: string[] };
expect(settings.disabledPlugins).toBeUndefined();
expect(nextData).toBeUndefined();
expect(
refreshedData.plugins.find((item) => item.path === pluginPath)?.enabled,
).toBe(true);
});
it("deletes a package-backed plugin and refreshes bundled slash commands", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
process.env.CLINE_GLOBAL_SETTINGS_PATH = join(
tempRoot,
"global-settings.json",
);
const packageDir = join(tempRoot, ".cline", "plugins", "delete-plugin");
const pluginPath = join(packageDir, "index.ts");
const skillPath = join(packageDir, "skills", "erase", "SKILL.md");
await mkdir(join(packageDir, "skills", "erase"), { recursive: true });
await writeFile(
join(packageDir, "package.json"),
JSON.stringify(
{
name: "delete-plugin",
cline: {
plugins: [{ paths: ["./index.ts"] }],
},
},
null,
2,
),
);
await writeFile(pluginPath, "export default {};\n");
await writeFile(
skillPath,
`---
name: erase
---
Erase stale plugin commands.`,
);
await writeFile(
process.env.CLINE_GLOBAL_SETTINGS_PATH,
JSON.stringify({ disabledPlugins: [pluginPath] }, null, 2),
);
const refreshCalls: string[] = [];
let refreshed = false;
const userInstructionService = {
async refreshType(type: string) {
refreshCalls.push(type);
refreshed = true;
},
listRuntimeCommands() {
return refreshed
? []
: [
{
name: "erase",
instructions: "Erase stale plugin commands.",
description: "Erase",
kind: "skill",
},
];
},
listRecords(type: string) {
if (type !== "skill") {
return [];
}
return [
{
id: "erase",
type: "skill",
filePath: skillPath,
item: {
name: "erase",
disabled: false,
description: "Erase",
instructions: "Erase stale plugin commands.",
frontmatter: {},
},
},
];
},
} as unknown as UserInstructionConfigService;
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
userInstructionService,
});
const data = await loader.loadConfigData({ includePluginTools: false });
const plugin = data.plugins.find((item) => item.path === pluginPath);
if (!plugin) {
throw new Error("Expected package plugin to be listed");
}
const nextData = await loader.onDeleteConfigItem(plugin, {
includePluginTools: false,
});
const settings = JSON.parse(
await readFile(process.env.CLINE_GLOBAL_SETTINGS_PATH, "utf8"),
) as { disabledPlugins?: string[] };
await expect(readFile(pluginPath, "utf8")).rejects.toThrow();
await expect(readFile(skillPath, "utf8")).rejects.toThrow();
expect(settings.disabledPlugins).toBeUndefined();
expect(refreshCalls).toEqual(
expect.arrayContaining(["workflow", "rule", "skill"]),
);
expect(nextData?.plugins.some((item) => item.path === pluginPath)).toBe(
false,
);
expect(
nextData?.workflowSlashCommands.map((command) => command.name),
).not.toContain("erase");
});
it("uses the package name for package-backed plugin entries", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const packageDir = join(
tempRoot,
".cline",
"plugins",
"_installed",
"git",
"github.com",
"demo",
"package",
);
await mkdir(packageDir, { recursive: true });
const pluginPath = join(packageDir, "index.ts");
await writeFile(
join(packageDir, "package.json"),
JSON.stringify(
{
name: "cline-sdk-portable-agents",
cline: {
plugins: [{ paths: ["./index.ts"] }],
},
},
null,
2,
),
);
await writeFile(pluginPath, "export default {};\n");
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData();
const plugin = data.plugins.find((item) => item.path === pluginPath);
expect(plugin?.name).toBe("cline-sdk-portable-agents");
});
it("marks bundled package skills with their plugin owner", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const installRoot = join(
tempRoot,
".cline",
"plugins",
"_installed",
"git",
"github.com",
"demo",
);
const packageDir = join(installRoot, "package");
const skillPath = join(packageDir, "skills", "review", "SKILL.md");
const pluginPath = join(packageDir, "index.ts");
await mkdir(join(packageDir, "skills", "review"), { recursive: true });
await writeFile(
join(installRoot, "package.json"),
JSON.stringify(
{
name: "cline-installed-plugin-demo",
cline: {
plugins: [{ paths: ["./package/index.ts"] }],
},
},
null,
2,
),
);
await writeFile(
join(packageDir, "package.json"),
JSON.stringify(
{
name: "cline-sdk-portable-agents",
},
null,
2,
),
);
await writeFile(pluginPath, "export default {};\n");
await writeFile(
skillPath,
`---
name: review
---
Review with the bundled skill.`,
);
const userInstructionService = {
listRuntimeCommands() {
return [];
},
listRecords(type: string) {
if (type !== "skill") {
return [];
}
return [
{
id: "review",
type: "skill",
filePath: skillPath,
item: {
name: "review",
disabled: false,
description: "Review code",
instructions: "Review with the bundled skill.",
frontmatter: {},
},
},
];
},
} as unknown as UserInstructionConfigService;
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
userInstructionService,
});
const data = await loader.loadConfigData({ includePluginTools: false });
const skill = data.skills.find((item) => item.path === skillPath);
expect(skill).toMatchObject({
name: "review",
pluginName: "cline-sdk-portable-agents",
pluginPath,
source: "workspace-plugin",
});
});
it("toggles MCP server enabled state through core settings", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const settingsPath = join(tempRoot, "cline_mcp_settings.json");
process.env.CLINE_MCP_SETTINGS_PATH = settingsPath;
await writeFile(
settingsPath,
`${JSON.stringify(
{
otherSetting: true,
mcpServers: {
docs: {
transport: {
type: "stdio",
command: "node",
},
},
},
},
null,
2,
)}\n`,
);
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData();
const item = data.mcp.find((candidate) => candidate.name === "docs");
expect(item?.enabled).toBe(true);
const nextData = item ? await loader.onToggleConfigItem(item) : undefined;
const settings = JSON.parse(await readFile(settingsPath, "utf8")) as {
otherSetting?: boolean;
mcpServers?: Record<string, { disabled?: boolean }>;
};
expect(settings.otherSetting).toBe(true);
expect(settings.mcpServers?.docs?.disabled).toBe(true);
expect(
nextData?.mcp.find((candidate) => candidate.name === "docs")?.enabled,
).toBe(false);
});
it("surfaces MCP OAuth status and errors", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const settingsPath = join(tempRoot, "cline_mcp_settings.json");
process.env.CLINE_MCP_SETTINGS_PATH = settingsPath;
await writeFile(
settingsPath,
`${JSON.stringify(
{
mcpServers: {
linear: {
transport: {
type: "streamableHttp",
url: "https://mcp.linear.app/mcp",
},
oauth: {
lastError: "OAuth authorization failed",
},
},
docs: {
transport: {
type: "sse",
url: "https://mcp.example.com/sse",
},
oauth: {
tokens: {
access_token: "token",
},
},
},
},
},
null,
2,
)}\n`,
);
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const data = await loader.loadConfigData();
const linear = data.mcp.find((item) => item.name === "linear");
const docs = data.mcp.find((item) => item.name === "docs");
expect(linear?.description).toBe("streamableHttp, oauth error");
expect(linear?.loadError).toBe("OAuth authorization failed");
expect(docs?.description).toBe("sse, oauth authorized");
expect(docs?.loadError).toBeUndefined();
});
it("does not toggle workflow items", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
const workflowPath = join(tempRoot, "workflow.md");
await writeFile(workflowPath, "Run this workflow.");
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const item: InteractiveConfigItem = {
id: "workflow-one",
name: "workflow-one",
path: workflowPath,
enabled: true,
source: "workspace",
kind: "workflow",
};
await expect(loader.onToggleConfigItem(item)).resolves.toBeUndefined();
expect(await readFile(workflowPath, "utf8")).toBe("Run this workflow.");
});
it("returns undefined for non-toggleable items", async () => {
const tempRoot = await mkdtemp(join(tmpdir(), "cli-config-data-"));
tempRoots.push(tempRoot);
await mkdir(join(tempRoot, "hooks"));
const hookPath = join(tempRoot, "hooks", "hook.json");
await writeFile(hookPath, "{}");
const loader = createInteractiveConfigDataLoader({
config: createConfig(tempRoot),
});
const item: InteractiveConfigItem = {
id: hookPath,
name: "hook.json",
path: hookPath,
enabled: true,
source: "workspace",
kind: "hook",
};
await expect(loader.onToggleConfigItem(item)).resolves.toBeUndefined();
});
});
@@ -1,340 +0,0 @@
import type {
AgentEvent,
ProviderSettingsManager,
TeamEvent,
ToolApprovalRequest,
ToolApprovalResult,
} from "@cline/core";
import { SessionNotFoundError } from "@cline/core";
import type { AgentTool, Message } from "@cline/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ChatCommandState } from "../../utils/chat-commands";
import type { Config } from "../../utils/types";
const {
mockCreateCliCore,
mockCreateRuntimeHooks,
mockLoadInteractiveResumeMessages,
mockSetActiveCliSession,
} = vi.hoisted(() => ({
mockCreateCliCore: vi.fn(),
mockCreateRuntimeHooks: vi.fn(),
mockLoadInteractiveResumeMessages: vi.fn(),
mockSetActiveCliSession: vi.fn(),
}));
vi.mock("../../session/session", () => ({
createCliCore: mockCreateCliCore,
}));
vi.mock("../../utils/hooks", () => ({
createRuntimeHooks: mockCreateRuntimeHooks,
}));
vi.mock("../../utils/output", () => ({
setActiveCliSession: mockSetActiveCliSession,
}));
vi.mock("../../utils/resume", () => ({
loadInteractiveResumeMessages: mockLoadInteractiveResumeMessages,
}));
vi.mock("../../utils/approval", () => ({
submitAndExitInTerminal: vi.fn(),
}));
vi.mock("../active-runtime", () => ({
markAbortInProgress: vi.fn(),
}));
vi.mock("../session-events", () => ({
subscribeToAgentEvents: vi.fn(() => vi.fn()),
subscribeToPendingPromptEvents: vi.fn(() => vi.fn()),
}));
import { createInteractiveSessionRuntime } from "./session-runtime";
function makeConfig(): Config {
return {
apiKey: "",
providerId: "cline",
modelId: "openai/gpt-5.3-codex",
verbose: false,
sandbox: false,
thinking: false,
outputMode: "text",
mode: "act",
systemPrompt: "",
enableTools: true,
enableSpawnAgent: true,
enableAgentTeams: false,
defaultToolAutoApprove: false,
toolPolicies: {},
cwd: "/tmp/work",
workspaceRoot: "/tmp/work",
};
}
function makeChatCommandState(config: Config): ChatCommandState {
return {
enableTools: config.enableTools,
autoApproveTools: config.defaultToolAutoApprove,
cwd: config.cwd,
workspaceRoot: config.workspaceRoot?.trim() || config.cwd,
};
}
function makeSwitchToActModeTool(): AgentTool {
return {
name: "switch_to_act_mode",
description: "Switch to act mode",
inputSchema: { type: "object", properties: {} },
execute: () => ({ ok: true }),
};
}
function makeManager() {
let startCount = 0;
const start = vi.fn(async (_input?: unknown) => {
startCount += 1;
const sessionId = `session-${startCount}`;
return {
sessionId,
manifest: {
session_id: sessionId,
},
};
});
return {
start,
stop: vi.fn(async () => {}),
send: vi.fn(),
getAccumulatedUsage: vi.fn(),
abort: vi.fn(),
dispose: vi.fn(),
get: vi.fn(),
readMessages: vi.fn(async (): Promise<Message[]> => []),
readTranscript: vi.fn(),
ingestHookEvent: vi.fn(),
subscribe: vi.fn(),
updateSessionModel: vi.fn(),
pendingPrompts: {
update: vi.fn(),
},
restore: vi.fn(),
};
}
function makeTurnResult() {
return {
text: "ok",
usage: { inputTokens: 0, outputTokens: 0 },
messages: [],
toolCalls: [],
iterations: 1,
finishReason: "completed" as const,
model: { id: "openai/gpt-5.3-codex", provider: "cline" },
startedAt: new Date("2026-01-01T00:00:00.000Z"),
endedAt: new Date("2026-01-01T00:00:00.100Z"),
durationMs: 100,
};
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
function makeRuntime(
manager: ReturnType<typeof makeManager>,
options: { resumeSessionId?: string } = {},
) {
mockCreateCliCore.mockResolvedValue(manager);
const config = makeConfig();
return createInteractiveSessionRuntime({
config,
providerSettingsManager: {} as ProviderSettingsManager,
resumeSessionId: options.resumeSessionId,
chatCommandState: makeChatCommandState(config),
requestToolApproval: async (
_request: ToolApprovalRequest,
): Promise<ToolApprovalResult> => ({ approved: true }),
askQuestionRef: { current: null },
resolveMistakeLimitDecision: undefined,
switchToActModeTool: makeSwitchToActModeTool(),
onAgentEvent: (_event: AgentEvent) => {},
onTeamEvent: (_event: TeamEvent) => {},
onPendingPrompts: () => {},
onPendingPromptSubmitted: () => {},
});
}
describe("createInteractiveSessionRuntime", () => {
beforeEach(() => {
vi.clearAllMocks();
mockCreateRuntimeHooks.mockReturnValue({
hooks: undefined,
shutdown: vi.fn(async () => {}),
});
mockLoadInteractiveResumeMessages.mockResolvedValue([]);
});
it("defers creating the replacement session after a new-session reset", async () => {
const manager = makeManager();
const runtime = makeRuntime(manager);
await runtime.ensureReady();
expect(manager.start).toHaveBeenCalledOnce();
expect(runtime.getActiveSessionId()).toBe("session-1");
await runtime.resetForNewSession();
expect(manager.stop).toHaveBeenCalledWith("session-1");
expect(manager.start).toHaveBeenCalledOnce();
expect(runtime.getActiveSessionId()).toBe("");
expect(mockSetActiveCliSession).toHaveBeenLastCalledWith(undefined);
await runtime.ensureReady();
expect(manager.start).toHaveBeenCalledTimes(2);
expect(runtime.getActiveSessionId()).toBe("session-2");
});
it("starts fresh after resetting an initially resumed session", async () => {
const manager = makeManager();
const runtime = makeRuntime(manager, {
resumeSessionId: "resumed-session",
});
await runtime.ensureReady();
expect(mockLoadInteractiveResumeMessages).toHaveBeenNthCalledWith(
1,
manager,
"resumed-session",
);
expect(manager.start).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
config: expect.objectContaining({
sessionId: "resumed-session",
}),
}),
);
await runtime.resetForNewSession();
await runtime.ensureReady();
expect(mockLoadInteractiveResumeMessages).toHaveBeenNthCalledWith(
2,
manager,
undefined,
);
expect(manager.start).toHaveBeenCalledTimes(2);
expect(manager.start).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
config: expect.not.objectContaining({
sessionId: "resumed-session",
}),
}),
);
});
it("keeps explicit empty restarts eager for config-driven restarts", async () => {
const manager = makeManager();
const runtime = makeRuntime(manager);
await runtime.ensureReady();
await runtime.restartEmpty();
expect(manager.stop).toHaveBeenCalledWith("session-1");
expect(manager.start).toHaveBeenCalledTimes(2);
expect(runtime.getActiveSessionId()).toBe("session-2");
});
it("recovers and retries when the active interactive session disappeared", async () => {
const manager = makeManager();
const messages = [
{
role: "user" as const,
content: [{ type: "text" as const, text: "hi" }],
},
];
manager.readMessages.mockResolvedValue(messages);
manager.send
.mockRejectedValueOnce(new SessionNotFoundError("session-1"))
.mockResolvedValueOnce(makeTurnResult());
const runtime = makeRuntime(manager);
await runtime.ensureReady();
const result = await runtime.sendCurrentTurn({
prompt: "second hi",
mode: "act",
});
expect(result?.finishReason).toBe("completed");
expect(manager.readMessages).toHaveBeenCalledWith("session-1");
expect(manager.start).toHaveBeenCalledTimes(2);
expect(manager.start).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
initialMessages: messages,
}),
);
expect(manager.send).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ sessionId: "session-1" }),
);
expect(manager.send).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ sessionId: "session-2" }),
);
expect(runtime.getActiveSessionId()).toBe("session-2");
});
it("waits for missing-session recovery before cleanup disposes the manager", async () => {
const manager = makeManager();
const recoveryRead = deferred<Message[]>();
manager.readMessages
.mockImplementationOnce(() => recoveryRead.promise)
.mockResolvedValue([]);
manager.get.mockResolvedValue(undefined);
manager.getAccumulatedUsage.mockResolvedValue(undefined);
manager.send.mockRejectedValueOnce(new SessionNotFoundError("session-1"));
const runtime = makeRuntime(manager);
await runtime.ensureReady();
const sendPromise = runtime
.sendCurrentTurn({
prompt: "second hi",
mode: "act",
})
.catch((error) => error);
await vi.waitFor(() => {
expect(manager.readMessages).toHaveBeenCalledWith("session-1");
});
let cleanupSettled = false;
const cleanupPromise = runtime.cleanup().finally(() => {
cleanupSettled = true;
});
await new Promise((resolve) => setTimeout(resolve, 0));
expect(cleanupSettled).toBe(false);
expect(manager.get).not.toHaveBeenCalled();
expect(manager.dispose).not.toHaveBeenCalled();
recoveryRead.resolve([]);
await cleanupPromise;
const sendError = await sendPromise;
expect(sendError).toBeInstanceOf(SessionNotFoundError);
expect(manager.dispose).toHaveBeenCalledWith("cli_interactive_shutdown");
});
});
@@ -1,18 +0,0 @@
import type { DialogActions, DialogId } from "@opentui-ui/dialog/react";
export type LoadingDialogActions = Pick<DialogActions, "show" | "close">;
export async function withShownDialog<T>(
dialog: Pick<DialogActions, "close">,
show: () => DialogId,
run: () => Promise<T>,
): Promise<T> {
const loadingDialogId = show();
// Give OpenTUI a microtask to mount the loading dialog before work starts.
await Promise.resolve();
try {
return await run();
} finally {
dialog.close(loadingDialogId);
}
}
@@ -1,66 +0,0 @@
import type { DialogActions, DialogId } from "@opentui-ui/dialog/react";
import { describe, expect, it } from "vitest";
import { withShownDialog } from "./loading-dialog-lifecycle";
type LoadingDialogCall =
| {
name: "show";
}
| {
name: "close";
id: DialogId | undefined;
};
function createDialog(calls: LoadingDialogCall[]) {
return {
close: (id?: DialogId): DialogId | undefined => {
calls.push({ name: "close", id });
return id;
},
} satisfies Pick<DialogActions, "close">;
}
function showLoading(calls: LoadingDialogCall[]): DialogId {
calls.push({ name: "show" });
return "loading-dialog";
}
describe("withShownDialog", () => {
it("shows a loading dialog while work runs", async () => {
const calls: LoadingDialogCall[] = [];
const events: string[] = [];
const dialog = createDialog(calls);
const result = await withShownDialog(
dialog,
() => showLoading(calls),
async () => {
events.push("run");
return 42;
},
);
expect(result).toBe(42);
expect(events).toEqual(["run"]);
expect(calls.map((call) => call.name)).toEqual(["show", "close"]);
expect(calls[1]).toEqual({ name: "close", id: "loading-dialog" });
});
it("closes the loading dialog when work fails", async () => {
const calls: LoadingDialogCall[] = [];
const dialog = createDialog(calls);
await expect(
withShownDialog(
dialog,
() => showLoading(calls),
async () => {
throw new Error("failed");
},
),
).rejects.toThrow("failed");
expect(calls.map((call) => call.name)).toEqual(["show", "close"]);
expect(calls[1]).toEqual({ name: "close", id: "loading-dialog" });
});
});
@@ -1,56 +0,0 @@
// @jsxImportSource @opentui/react
import type {
DialogId,
DialogSize,
DialogStyle,
} from "@opentui-ui/dialog/react";
import "opentui-spinner/react";
import {
type LoadingDialogActions,
withShownDialog,
} from "./loading-dialog-lifecycle";
export interface LoadingDialogContentProps {
message: string;
}
export function LoadingDialogContent(props: LoadingDialogContentProps) {
return (
<box flexDirection="row" gap={1} paddingX={1}>
<spinner name="dots" color="gray" />
<text fg="gray">{props.message}</text>
</box>
);
}
export interface LoadingDialogOptions {
size?: DialogSize;
style?: DialogStyle;
}
export function showLoadingDialog(
dialog: LoadingDialogActions,
message: string,
options?: LoadingDialogOptions,
): DialogId {
return dialog.show({
size: options?.size ?? "small",
style: options?.style,
closeOnEscape: false,
closeOnClickOutside: false,
content: () => <LoadingDialogContent message={message} />,
});
}
export async function withLoadingDialog<T>(
dialog: LoadingDialogActions,
message: string,
run: () => Promise<T>,
options?: LoadingDialogOptions,
): Promise<T> {
return await withShownDialog(
dialog,
() => showLoadingDialog(dialog, message, options),
run,
);
}
@@ -1,332 +0,0 @@
import { useKeyboard, useTerminalDimensions } from "@opentui/react";
import { useCallback, useRef, useState } from "react";
import { palette } from "../palette";
import type { RuntimeToolInteraction } from "../types";
import { formatApprovalParams } from "./dialogs/tool-approval";
export interface InlineToolResponseProps {
interaction: RuntimeToolInteraction;
accent: string;
inputBackground: string;
inputForeground: string;
inputPlaceholder: string;
onResolveToolApproval: (id: number, approved: boolean) => void;
onResolveAskQuestion: (id: number, answer: string | null) => void;
}
function isPrintableKey(name: string): boolean {
return name.length === 1 || name === "space";
}
function keyToText(name: string): string {
return name === "space" ? " " : name;
}
function Shell(
props: Pick<
InlineToolResponseProps,
"accent" | "inputBackground" | "inputForeground"
> & {
title: string;
children: React.ReactNode;
},
) {
const { height } = useTerminalDimensions();
const maxHeight = Math.max(7, Math.min(14, Math.floor(height * 0.38)));
return (
<box
flexDirection="column"
width="100%"
maxHeight={maxHeight}
backgroundColor={props.inputBackground}
paddingX={1}
paddingY={1}
gap={1}
>
<box flexDirection="row" gap={1}>
<text fg={palette.act}>{props.title}</text>
</box>
{props.children}
</box>
);
}
function ChoiceButton(props: {
label: string;
selected: boolean;
selectedFg?: string;
onPress: () => void;
}) {
return (
<box
paddingX={1}
backgroundColor={props.selected ? palette.selection : undefined}
onMouseDown={props.onPress}
>
<text
fg={
props.selected
? (props.selectedFg ?? palette.textOnSelection)
: undefined
}
>
{props.label}
</text>
</box>
);
}
function ToolApprovalResponse(
props: InlineToolResponseProps & {
interaction: Extract<RuntimeToolInteraction, { kind: "tool_approval" }>;
},
) {
const [selected, setSelected] = useState<"approve" | "deny">("approve");
const selectedRef = useRef(selected);
selectedRef.current = selected;
const request = props.interaction.request;
const interactionId = props.interaction.id;
const onResolveToolApproval = props.onResolveToolApproval;
const params = formatApprovalParams(request.toolName, request.input);
const resolve = useCallback(
(approved: boolean) => {
onResolveToolApproval(interactionId, approved);
},
[interactionId, onResolveToolApproval],
);
useKeyboard((key) => {
if (key.name === "y") {
resolve(true);
return;
}
if (key.name === "n" || key.name === "escape") {
resolve(false);
return;
}
if (key.name === "left" || key.name === "right" || key.name === "tab") {
setSelected((current) => (current === "approve" ? "deny" : "approve"));
return;
}
if (key.name === "return" || key.name === "enter") {
resolve(selectedRef.current === "approve");
}
});
return (
<Shell
title="Cline needs permission"
accent={props.accent}
inputBackground={props.inputBackground}
inputForeground={props.inputForeground}
>
<box flexDirection="column" gap={1}>
<text fg="yellow">Approve tool call?</text>
<text fg={props.accent} selectable>
{request.toolName}
</text>
{params && (
<box flexDirection="column" overflow="hidden">
{params}
</box>
)}
</box>
<box flexDirection="row" gap={1}>
<ChoiceButton
label="[y] Approve"
selected={selected === "approve"}
onPress={() => resolve(true)}
/>
<ChoiceButton
label="[n] Deny"
selected={selected === "deny"}
onPress={() => resolve(false)}
/>
</box>
</Shell>
);
}
function AskQuestionResponse(
props: InlineToolResponseProps & {
interaction: Extract<RuntimeToolInteraction, { kind: "ask_question" }>;
},
) {
const { interaction } = props;
const [selected, setSelected] = useState(0);
const [customValue, setCustomValue] = useState("");
const [customEmptyAttempted, setCustomEmptyAttempted] = useState(false);
const selectedRef = useRef(0);
const customValueRef = useRef("");
const interactionId = interaction.id;
const onResolveAskQuestion = props.onResolveAskQuestion;
const customIndex = interaction.options.length;
const isTyping = selected === customIndex;
const totalChoices = interaction.options.length + 1;
const selectIndex = useCallback(
(index: number) => {
selectedRef.current = index;
setSelected(index);
if (index !== customIndex) {
setCustomEmptyAttempted(false);
}
},
[customIndex],
);
const setCustomText = useCallback((value: string) => {
customValueRef.current = value;
setCustomValue(value);
if (value.trim()) {
setCustomEmptyAttempted(false);
}
}, []);
const resolveAnswer = useCallback(
(answer: string | null) => {
onResolveAskQuestion(interactionId, answer);
},
[interactionId, onResolveAskQuestion],
);
useKeyboard((key) => {
const typing = selectedRef.current === customIndex;
if (key.name === "escape") {
if (typing && customValueRef.current) {
setCustomText("");
return;
}
resolveAnswer(null);
return;
}
if (typing && key.name === "backspace") {
setCustomText(customValueRef.current.slice(0, -1));
return;
}
if (typing && key.name === "delete") {
setCustomText("");
return;
}
if (key.name === "return" || key.name === "enter") {
if (typing) {
const answer = customValueRef.current.trim();
if (answer) {
resolveAnswer(answer);
return;
}
setCustomEmptyAttempted(true);
return;
}
resolveAnswer(interaction.options[selectedRef.current] ?? "");
return;
}
if (key.name === "up" || (key.ctrl && key.name === "p")) {
const next =
selectedRef.current <= 0 ? totalChoices - 1 : selectedRef.current - 1;
selectIndex(next);
return;
}
if (key.name === "down" || (key.ctrl && key.name === "n")) {
const next =
selectedRef.current >= totalChoices - 1 ? 0 : selectedRef.current + 1;
selectIndex(next);
return;
}
if (!typing && key.name >= "1" && key.name <= "9") {
const index = Number.parseInt(key.name, 10) - 1;
const option = interaction.options[index];
if (option) {
resolveAnswer(option);
return;
}
}
if (typing && !key.ctrl && !key.meta && isPrintableKey(key.name)) {
const value = keyToText(key.name);
setCustomText(`${customValueRef.current}${value}`);
return;
}
if (!key.ctrl && !key.meta && isPrintableKey(key.name)) {
const value = keyToText(key.name);
setCustomText(value);
selectIndex(customIndex);
}
});
return (
<Shell
title="Cline is asking a question"
accent={props.accent}
inputBackground={props.inputBackground}
inputForeground={props.inputForeground}
>
<text fg={props.inputForeground} selectable>
{interaction.question}
</text>
<box flexDirection="column">
{interaction.options.map((option, index) => {
const optionSelected = !isTyping && selected === index;
return (
<box
key={`${index.toString()}:${option}`}
paddingX={1}
flexDirection="row"
gap={1}
backgroundColor={optionSelected ? palette.selection : undefined}
onMouseDown={() => resolveAnswer(option)}
>
<text
fg={optionSelected ? palette.textOnSelection : "gray"}
flexShrink={0}
>
{optionSelected ? ">" : " "}
</text>
<text
fg={
optionSelected
? palette.textOnSelection
: props.inputForeground
}
>
{option}
</text>
</box>
);
})}
<box
paddingX={1}
flexDirection="row"
gap={1}
backgroundColor={isTyping ? palette.selection : undefined}
onMouseDown={() => selectIndex(customIndex)}
>
<text fg={isTyping ? palette.textOnSelection : "gray"} flexShrink={0}>
{isTyping ? ">" : " "}
</text>
{isTyping ? (
<text fg={palette.textOnSelection} flexGrow={1}>
{customValue
? `${customValue}|`
: customEmptyAttempted
? "Type a response first..."
: "Type a response..."}
</text>
) : (
<text fg={props.inputPlaceholder}>Type a response...</text>
)}
</box>
</box>
</Shell>
);
}
export function InlineToolResponse(props: InlineToolResponseProps) {
if (props.interaction.kind === "tool_approval") {
return <ToolApprovalResponse {...props} interaction={props.interaction} />;
}
return <AskQuestionResponse {...props} interaction={props.interaction} />;
}
@@ -1,27 +0,0 @@
import { describe, expect, it } from "vitest";
import { nextUsageTokenDisplay } from "./session-context";
describe("nextUsageTokenDisplay", () => {
it("uses streaming input tokens as an absolute context size", () => {
let displayedTokens = 0;
displayedTokens = nextUsageTokenDisplay(displayedTokens, {
inputTokens: 633_000,
outputTokens: 31_000,
});
displayedTokens = nextUsageTokenDisplay(displayedTokens, {
inputTokens: 934_000,
outputTokens: 266_000,
});
expect(displayedTokens).toBe(934_000);
});
it("ignores output-only usage events for the context size display", () => {
expect(
nextUsageTokenDisplay(633_000, {
outputTokens: 31_000,
}),
).toBe(633_000);
});
});
-180
View File
@@ -1,180 +0,0 @@
import { Llms } from "@cline/core";
import type { ChoiceContext } from "@opentui-ui/dialog";
import type { DialogActions } from "@opentui-ui/dialog/react";
import { useCallback, useMemo } from "react";
import type {
InteractiveConfigData,
InteractiveConfigItem,
InteractiveConfigTab,
LoadInteractiveConfigDataOptions,
} from "../../tui/interactive-config";
import type { CliCompactionMode, Config } from "../../utils/types";
import {
ConfigErrorContent,
DeleteConfigItemConfirmContent,
ExtDetailContent,
} from "../components/dialogs/config-dialogs";
import { withLoadingDialog } from "../components/dialogs/loading-dialog";
import { ConfigPanelContent } from "../views/config-view";
import type { ConfigAction } from "../views/config-view-helpers";
import type { OpenModelSelectorOptions } from "./use-model-selector";
export interface OpenConfigOptions {
initialTab?: InteractiveConfigTab;
}
export function useConfigPanel(opts: {
dialog: DialogActions;
config: Config;
sessionUiMode: string;
compactionMode: CliCompactionMode;
toggleMode: () => void;
toggleAutoApprove: () => void;
setCompactionMode: (mode: CliCompactionMode) => void;
termHeight: number;
loadConfigData: (
options?: LoadInteractiveConfigDataOptions,
) => Promise<InteractiveConfigData>;
onToggleConfigItem?: (
item: InteractiveConfigItem,
options?: LoadInteractiveConfigDataOptions,
) => Promise<InteractiveConfigData | undefined>;
onDeleteConfigItem?: (
item: InteractiveConfigItem,
options?: LoadInteractiveConfigDataOptions,
) => Promise<InteractiveConfigData | undefined>;
openModelSelector: (options?: OpenModelSelectorOptions) => Promise<void>;
openMcpManager: (options?: { refocus?: boolean }) => Promise<boolean>;
refocusTextarea: () => void;
}) {
const emptyConfigData = useMemo(
() => ({
workflows: [] as InteractiveConfigItem[],
rules: [] as InteractiveConfigItem[],
skills: [] as InteractiveConfigItem[],
hooks: [] as InteractiveConfigItem[],
agents: [] as InteractiveConfigItem[],
plugins: [] as InteractiveConfigItem[],
mcp: [] as InteractiveConfigItem[],
tools: [] as InteractiveConfigItem[],
workflowSlashCommands: [],
}),
[],
);
const openConfig = useCallback(
async (options: OpenConfigOptions = {}) => {
let keepOpen = true;
let activeTab = options.initialTab;
while (keepOpen) {
const [data, providerInfo] = await withLoadingDialog(
opts.dialog,
"Loading settings...",
async () =>
await Promise.all([
opts
.loadConfigData({ includePluginTools: false })
.catch(() => emptyConfigData),
Llms.getProvider(opts.config.providerId).catch(() => undefined),
]),
);
const providerDisplayName =
providerInfo?.name ?? opts.config.providerId;
const action = await opts.dialog.choice<ConfigAction>({
size: "large",
style: { maxHeight: opts.termHeight - 2 },
closeOnEscape: false,
content: (ctx: ChoiceContext<ConfigAction>) => (
<ConfigPanelContent
{...ctx}
config={opts.config}
configData={data}
loadConfigData={opts.loadConfigData}
providerDisplayName={providerDisplayName}
currentMode={opts.sessionUiMode}
currentCompactionMode={opts.compactionMode}
initialTab={activeTab}
onActiveTabChange={(tab) => {
activeTab = tab;
}}
onToggleConfigItem={opts.onToggleConfigItem}
onDeleteConfigItem={opts.onDeleteConfigItem}
onToggleMode={opts.toggleMode}
onToggleAutoApprove={opts.toggleAutoApprove}
onSetCompactionMode={opts.setCompactionMode}
/>
),
});
if (!action) {
keepOpen = false;
continue;
}
if (action.kind === "open-provider") {
await opts.openModelSelector({
startWithProviderChange: true,
onCancel: () => {},
});
} else if (action.kind === "open-model") {
await opts.openModelSelector({ onCancel: () => {} });
} else if (action.kind === "toggle-item") {
await opts.onToggleConfigItem?.(action.item);
} else if (action.kind === "delete-item") {
const confirmed = await opts.dialog.choice<boolean>({
closeOnEscape: true,
content: (ctx: ChoiceContext<boolean>) => (
<DeleteConfigItemConfirmContent {...ctx} item={action.item} />
),
});
if (confirmed && opts.onDeleteConfigItem) {
try {
await withLoadingDialog(
opts.dialog,
`Deleting ${action.item.name}...`,
async () =>
await opts.onDeleteConfigItem?.(action.item, {
includePluginTools: false,
}),
);
} catch (error) {
await opts.dialog.choice<void>({
closeOnEscape: true,
content: (ctx: ChoiceContext<void>) => (
<ConfigErrorContent
{...ctx}
title="Plugin delete failed"
message={
error instanceof Error ? error.message : String(error)
}
/>
),
});
}
}
} else if (action.kind === "ext-detail") {
await opts.dialog.choice<void>({
style: { maxHeight: opts.termHeight - 2 },
closeOnEscape: false,
content: (ctx: ChoiceContext<void>) => (
<ExtDetailContent
{...ctx}
item={action.item}
onToggleConfigItem={opts.onToggleConfigItem}
/>
),
});
} else if (action.kind === "open-mcp") {
const changed = await opts.openMcpManager({ refocus: false });
if (changed) {
keepOpen = false;
}
}
}
opts.refocusTextarea();
},
[opts, emptyConfigData],
);
return openConfig;
}
@@ -1,203 +0,0 @@
import type { AgentMode } from "@cline/core";
import type { ToolApprovalRequest, ToolApprovalResult } from "@cline/shared";
import { useCallback, useEffect, useRef, useState } from "react";
import type { RuntimeToolInteraction, TuiProps } from "../types";
type PendingRuntimeToolInteraction =
| {
id: number;
kind: "tool_approval";
request: ToolApprovalRequest;
resolve: (result: ToolApprovalResult) => void;
}
| {
id: number;
kind: "ask_question";
question: string;
options: string[];
resolve: (answer: string) => void;
};
function toRuntimeToolInteraction(
pending: PendingRuntimeToolInteraction,
): RuntimeToolInteraction {
if (pending.kind === "tool_approval") {
return {
id: pending.id,
kind: pending.kind,
request: pending.request,
};
}
return {
id: pending.id,
kind: pending.kind,
question: pending.question,
options: pending.options,
};
}
function deniedToolResult(request: ToolApprovalRequest): ToolApprovalResult {
return {
approved: false,
reason: `Tool "${request.toolName}" was denied by user`,
};
}
function dismissPendingInteraction(pending: PendingRuntimeToolInteraction) {
if (pending.kind === "tool_approval") {
pending.resolve(deniedToolResult(pending.request));
return;
}
pending.resolve("[User dismissed the question]");
}
export function useRuntimeDialogBridge(input: {
setToolApprover: TuiProps["setToolApprover"];
setAskQuestion: TuiProps["setAskQuestion"];
setModeChangeNotifier: TuiProps["setModeChangeNotifier"];
setUiMode: (mode: AgentMode) => void;
refocusTextarea: () => void;
}) {
const {
setToolApprover,
setAskQuestion,
setModeChangeNotifier,
setUiMode,
refocusTextarea,
} = input;
const [interaction, setInteraction] = useState<RuntimeToolInteraction | null>(
null,
);
const activeRef = useRef<PendingRuntimeToolInteraction | null>(null);
const queueRef = useRef<PendingRuntimeToolInteraction[]>([]);
const nextIdRef = useRef(1);
const activate = useCallback((pending: PendingRuntimeToolInteraction) => {
activeRef.current = pending;
setInteraction(toRuntimeToolInteraction(pending));
}, []);
const enqueue = useCallback(
(pending: PendingRuntimeToolInteraction) => {
if (activeRef.current) {
queueRef.current.push(pending);
return;
}
activate(pending);
},
[activate],
);
const finishActive = useCallback(
(id: number) => {
if (activeRef.current?.id !== id) {
return false;
}
const next = queueRef.current.shift() ?? null;
if (next) {
activate(next);
return true;
}
activeRef.current = null;
setInteraction(null);
return false;
},
[activate],
);
const resolveToolApproval = useCallback(
(id: number, approved: boolean) => {
const pending = activeRef.current;
if (!pending || pending.id !== id || pending.kind !== "tool_approval") {
return;
}
pending.resolve(
approved ? { approved: true } : deniedToolResult(pending.request),
);
const hasNext = finishActive(id);
if (!hasNext) {
refocusTextarea();
}
},
[finishActive, refocusTextarea],
);
const resolveAskQuestion = useCallback(
(id: number, answer: string | null) => {
const pending = activeRef.current;
if (!pending || pending.id !== id || pending.kind !== "ask_question") {
return;
}
pending.resolve(
answer === null ? "[User dismissed the question]" : answer,
);
const hasNext = finishActive(id);
if (!hasNext) {
refocusTextarea();
}
},
[finishActive, refocusTextarea],
);
const dismissAll = useCallback(() => {
if (activeRef.current) {
dismissPendingInteraction(activeRef.current);
activeRef.current = null;
}
for (const pending of queueRef.current) {
dismissPendingInteraction(pending);
}
queueRef.current = [];
setInteraction(null);
}, []);
useEffect(() => {
setToolApprover(
(request) =>
new Promise<ToolApprovalResult>((resolve) => {
enqueue({
id: nextIdRef.current,
kind: "tool_approval",
request,
resolve,
});
nextIdRef.current += 1;
}),
);
setAskQuestion(
(question, options) =>
new Promise<string>((resolve) => {
enqueue({
id: nextIdRef.current,
kind: "ask_question",
question,
options,
resolve,
});
nextIdRef.current += 1;
}),
);
setModeChangeNotifier((mode) => {
setUiMode(mode);
});
return () => {
setToolApprover(null);
setAskQuestion(null);
setModeChangeNotifier(null);
dismissAll();
};
}, [
dismissAll,
enqueue,
setAskQuestion,
setModeChangeNotifier,
setToolApprover,
setUiMode,
]);
return {
interaction,
resolveToolApproval,
resolveAskQuestion,
};
}
@@ -1,48 +0,0 @@
import { describe, expect, it } from "vitest";
import { rankMentionPaths } from "./interactive-welcome";
describe("TUI file mention search ranking", () => {
it("keeps initialism matches for compact and hyphenated input", () => {
const paths = [
"src/components/Button.tsx",
"src/domain/MyAmazingClassDefinition.ts",
"docs/MACD.md",
"packages/core/src/runtime/manager.ts",
];
expect(rankMentionPaths(paths, "MACD", 10)).toEqual([
"docs/MACD.md",
"src/domain/MyAmazingClassDefinition.ts",
]);
expect(rankMentionPaths(paths, "M-A-C-D", 10)).toEqual([
"docs/MACD.md",
"src/domain/MyAmazingClassDefinition.ts",
]);
});
it("normalizes common mention prefixes before matching workspace paths", () => {
const paths = [
"docs/architecture.md",
"src/tui/interactive-welcome.ts",
"src/tui/hooks/use-autocomplete.ts",
];
expect(rankMentionPaths(paths, "./src/tui", 10)).toEqual([
"src/tui/hooks/use-autocomplete.ts",
"src/tui/interactive-welcome.ts",
]);
expect(rankMentionPaths(paths, "/docs", 10)).toEqual([
"docs/architecture.md",
]);
});
it("ranks filename matches ahead of path-only fuzzy matches", () => {
const paths = [
"src/migrations/add-column.ts",
"src/domain/MyAmazingClassDefinition.ts",
"docs/classes.md",
];
expect(rankMentionPaths(paths, "class", 10)[0]).toBe("docs/classes.md");
});
});
-37
View File
@@ -1,37 +0,0 @@
import { describe, expect, it } from "vitest";
import { getModeAccent, getSuccessColor, getTerminalTheme } from "./palette";
describe("getTerminalTheme", () => {
it("detects light terminals from the default background", () => {
expect(getTerminalTheme("#ffffff")).toBe("light");
expect(getTerminalTheme("#fdf6e3")).toBe("light");
});
it("detects dark terminals from the default background", () => {
expect(getTerminalTheme("#000000")).toBe("dark");
expect(getTerminalTheme("#002b36")).toBe("dark");
});
it("uses the foreground as a fallback when background is unavailable", () => {
expect(getTerminalTheme(null, "#1a1a1a")).toBe("light");
expect(getTerminalTheme(null, "#f0f0f0")).toBe("dark");
});
it("defaults to the existing dark theme when detection is unavailable", () => {
expect(getTerminalTheme(null, null)).toBe("dark");
});
});
describe("theme-aware palette helpers", () => {
it("preserves the existing named ANSI colors for dark terminals", () => {
expect(getModeAccent("act", "dark")).toBe("cyan");
expect(getModeAccent("plan", "dark")).toBe("yellow");
expect(getSuccessColor("dark")).toBe("brightGreen");
});
it("uses darker accents on light terminals", () => {
expect(getModeAccent("act", "light")).toBe("#0969da");
expect(getModeAccent("plan", "light")).toBe("#9a6700");
expect(getSuccessColor("light")).toBe("#116329");
});
});
@@ -1,83 +0,0 @@
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { describe, expect, it } from "vitest";
import {
readImageDataUrlFromPastedText,
readImmediateImagePasteAttachment,
resolvePastedImagePath,
} from "./image-paste";
describe("image paste helpers", () => {
it("loads pasted image file paths as data urls", () => {
const dir = mkdtempSync(join(tmpdir(), "cli image paste "));
const imagePath = join(dir, "hero.png");
writeFileSync(imagePath, Buffer.from("hello"));
const result = readImageDataUrlFromPastedText(`"${imagePath}"`);
expect(result).toEqual({
dataUrl: "data:image/png;base64,aGVsbG8=",
source: "path",
});
});
it("resolves file url paste paths", () => {
const dir = mkdtempSync(join(tmpdir(), "cli-image-paste-"));
const imagePath = join(dir, "hero.png");
expect(resolvePastedImagePath(pathToFileURL(imagePath).href)).toBe(
imagePath,
);
});
it("decodes direct image paste bytes when metadata is available", () => {
const event = {
bytes: Buffer.from("hello"),
metadata: { mimeType: "image/png" },
};
expect(readImmediateImagePasteAttachment(event)).toEqual({
dataUrl: "data:image/png;base64,aGVsbG8=",
source: "paste",
});
});
it("loads macOS screenshot paths when narrow no-break space is normalized to a regular space", () => {
// macOS Sonoma+ embeds U+202F (NARROW NO-BREAK SPACE) before AM/PM
// in screenshot filenames. When the path travels through clipboards,
// terminals, or anything that normalizes whitespace, U+202F can be
// collapsed to a regular space (U+0020) -- but the on-disk filename
// still contains U+202F, so a literal readFileSync fails with ENOENT.
const dir = mkdtempSync(join(tmpdir(), "cli-image-paste-nnbsp-"));
const onDiskName = "Screenshot 2026-05-12 at 4.42.48\u202FPM.png";
const pastedName = "Screenshot 2026-05-12 at 4.42.48 PM.png";
const onDiskPath = join(dir, onDiskName);
writeFileSync(onDiskPath, Buffer.from("hello"));
const result = readImageDataUrlFromPastedText(join(dir, pastedName));
expect(result).toEqual({
dataUrl: "data:image/png;base64,aGVsbG8=",
source: "path",
});
});
it("loads paths when an arbitrary Unicode space differs from the on-disk filename", () => {
// Generalized variant: any exotic space (here U+00A0 NBSP) in the
// actual filename should still resolve when the pasted text uses a
// regular space.
const dir = mkdtempSync(join(tmpdir(), "cli-image-paste-nbsp-"));
const onDiskName = "weird\u00a0name.png";
const pastedName = "weird name.png";
writeFileSync(join(dir, onDiskName), Buffer.from("hello"));
const result = readImageDataUrlFromPastedText(join(dir, pastedName));
expect(result).toEqual({
dataUrl: "data:image/png;base64,aGVsbG8=",
source: "path",
});
});
});
@@ -1,86 +0,0 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
getDefaultAwsRegion,
resolveProviderConfigAwsRegion,
resolveProviderConfigSap,
updateProviderConfigValue,
} from "./provider-config-values";
const originalEnv = { ...process.env };
afterEach(() => {
process.env = { ...originalEnv };
});
describe("provider config values", () => {
it("updates an auto-filled AWS region when the profile changes", () => {
delete process.env.AWS_REGION;
delete process.env.AWS_DEFAULT_REGION;
const dir = mkdtempSync(join(tmpdir(), "cline-provider-config-"));
try {
const configPath = join(dir, "config");
writeFileSync(
configPath,
[
"[default]",
"region = us-east-1",
"[profile dev]",
"region = ap-southeast-2",
].join("\n"),
);
process.env.AWS_CONFIG_FILE = configPath;
const result = updateProviderConfigValue(
{ awsProfile: "", awsRegion: getDefaultAwsRegion("") },
"awsProfile",
"dev",
);
expect(result.awsRegion).toBe("ap-southeast-2");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
it("preserves a manually entered AWS region when the profile changes", () => {
const result = updateProviderConfigValue(
{ awsProfile: "", awsRegion: "eu-central-1" },
"awsProfile",
"dev",
);
expect(result.awsRegion).toBe("eu-central-1");
});
it("resolves AWS region from the saved profile when region is blank", () => {
process.env.AWS_REGION = "us-west-2";
expect(
resolveProviderConfigAwsRegion({
awsProfile: "dev",
awsRegion: "",
}),
).toBe("us-west-2");
});
it("resolves SAP AI Core field values into SAP settings", () => {
expect(
resolveProviderConfigSap({
sapClientId: " client ",
sapClientSecret: " secret ",
sapTokenUrl: " https://auth.example ",
sapResourceGroup: " default ",
sapDeploymentId: " deployment ",
}),
).toEqual({
clientId: "client",
clientSecret: "secret",
tokenUrl: "https://auth.example",
resourceGroup: "default",
deploymentId: "deployment",
});
});
});
@@ -1,61 +0,0 @@
import type { ProviderConfigFieldKey } from "@cline/core";
import { resolveAwsRegion } from "../../utils/aws-region";
export type ProviderConfigValues = Partial<
Record<ProviderConfigFieldKey, string>
>;
const DEFAULT_AWS_REGION = "us-east-1";
export function getDefaultAwsRegion(profile?: string): string {
return (
resolveAwsRegion({ profile: profile?.trim() || undefined }) ??
DEFAULT_AWS_REGION
);
}
export function resolveProviderConfigAwsRegion(
values: ProviderConfigValues,
): string {
return values.awsRegion?.trim() || getDefaultAwsRegion(values.awsProfile);
}
export function resolveProviderConfigSap(values: ProviderConfigValues):
| {
clientId?: string;
clientSecret?: string;
tokenUrl?: string;
resourceGroup?: string;
deploymentId?: string;
}
| undefined {
const sap = {
clientId: values.sapClientId?.trim() || undefined,
clientSecret: values.sapClientSecret?.trim() || undefined,
tokenUrl: values.sapTokenUrl?.trim() || undefined,
resourceGroup: values.sapResourceGroup?.trim() || undefined,
deploymentId: values.sapDeploymentId?.trim() || undefined,
};
return Object.values(sap).some((value) => value !== undefined)
? sap
: undefined;
}
export function updateProviderConfigValue(
previous: ProviderConfigValues,
field: ProviderConfigFieldKey,
value: string,
): ProviderConfigValues {
const next: ProviderConfigValues = { ...previous, [field]: value };
if (field !== "awsProfile") {
return next;
}
const previousRegion = previous.awsRegion?.trim();
const previousProfileRegion = getDefaultAwsRegion(previous.awsProfile);
if (!previousRegion || previousRegion === previousProfileRegion) {
next.awsRegion = getDefaultAwsRegion(value);
}
return next;
}
@@ -1,52 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { getSyntaxStyle } from "./syntax-style";
const { MockRGBA, MockSyntaxStyle } = vi.hoisted(() => {
class MockRGBA {
private constructor(private readonly hex: string) {}
static fromHex(hex: string): MockRGBA {
return new MockRGBA(hex.toLowerCase());
}
toInts(): [number, number, number, number] {
return [
Number.parseInt(this.hex.slice(1, 3), 16),
Number.parseInt(this.hex.slice(3, 5), 16),
Number.parseInt(this.hex.slice(5, 7), 16),
255,
];
}
}
class MockSyntaxStyle {
private constructor(private readonly styles: Map<string, unknown>) {}
static fromStyles(styles: Record<string, unknown>): MockSyntaxStyle {
return new MockSyntaxStyle(new Map(Object.entries(styles)));
}
getStyle(name: string): unknown {
return this.styles.get(name);
}
}
return { MockRGBA, MockSyntaxStyle };
});
vi.mock("@opentui/core", () => ({
RGBA: MockRGBA,
SyntaxStyle: MockSyntaxStyle,
}));
describe("getSyntaxStyle", () => {
it("keeps dark markdown prose on the terminal default foreground", () => {
expect(getSyntaxStyle("dark").getStyle("default")).toBeUndefined();
});
it("uses a dark default foreground for light markdown content", () => {
const style = getSyntaxStyle("light").getStyle("default");
expect(style?.fg?.toInts()).toEqual([26, 26, 26, 255]);
});
});
-154
View File
@@ -1,154 +0,0 @@
import { RGBA, type StyleDefinition, SyntaxStyle } from "@opentui/core";
import type { TerminalTheme } from "../palette";
const instances: Record<TerminalTheme, SyntaxStyle | null> = {
dark: null,
light: null,
};
interface SyntaxColors {
keyword: string;
operator: string;
type: string;
functionName: string;
variable: string;
string: string;
number: string;
comment: string;
punctuation: string;
property: string;
constant: string;
tag: string;
attribute: string;
escape: string;
markdownCode: string;
markdownHeading: string;
markdownMuted: string;
markdownLink: string;
markdownItalic: string;
markdownDefault?: string;
}
const syntaxColors: Record<TerminalTheme, SyntaxColors> = {
dark: {
keyword: "#c678dd",
operator: "#56b6c2",
type: "#e5c07b",
functionName: "#61afef",
variable: "#e06c75",
string: "#98c379",
number: "#d19a66",
comment: "#5c6370",
punctuation: "#abb2bf",
property: "#e06c75",
constant: "#d19a66",
tag: "#e06c75",
attribute: "#d19a66",
escape: "#56b6c2",
markdownCode: "#98c379",
markdownHeading: "#56b6c2",
markdownMuted: "#808080",
markdownLink: "#56b6c2",
markdownItalic: "#e5c07b",
},
light: {
keyword: "#cf222e",
operator: "#0550ae",
type: "#953800",
functionName: "#8250df",
variable: "#953800",
string: "#0a3069",
number: "#0550ae",
comment: "#6e7781",
punctuation: "#57606a",
property: "#0550ae",
constant: "#0550ae",
tag: "#116329",
attribute: "#0550ae",
escape: "#0550ae",
markdownCode: "#116329",
markdownHeading: "#0969da",
markdownMuted: "#6e7781",
markdownLink: "#0969da",
markdownItalic: "#8250df",
markdownDefault: "#1a1a1a",
},
};
function color(hex: string): RGBA {
return RGBA.fromHex(hex);
}
function fg(hex: string): StyleDefinition {
return { fg: color(hex) };
}
function bold(hex: string): StyleDefinition {
return { fg: color(hex), bold: true };
}
function italic(hex: string): StyleDefinition {
return { fg: color(hex), italic: true };
}
function underline(hex: string): StyleDefinition {
return { fg: color(hex), underline: true };
}
function buildSyntaxStyle(theme: TerminalTheme): SyntaxStyle {
const colors = syntaxColors[theme];
const markdownHeading = color(colors.markdownHeading);
const markdownCode = color(colors.markdownCode);
const markdownMuted = color(colors.markdownMuted);
const markdownLink = color(colors.markdownLink);
return SyntaxStyle.fromStyles({
...(colors.markdownDefault ? { default: fg(colors.markdownDefault) } : {}),
keyword: bold(colors.keyword),
"keyword.control": bold(colors.keyword),
"keyword.operator": fg(colors.operator),
type: fg(colors.type),
"type.builtin": fg(colors.type),
function: fg(colors.functionName),
"function.method": fg(colors.functionName),
variable: fg(colors.variable),
"variable.parameter": fg(colors.variable),
"variable.builtin": fg(colors.type),
string: fg(colors.string),
"string.special": fg(colors.string),
number: fg(colors.number),
comment: italic(colors.comment),
operator: fg(colors.operator),
punctuation: fg(colors.punctuation),
property: fg(colors.property),
constant: fg(colors.constant),
tag: fg(colors.tag),
attribute: fg(colors.attribute),
escape: fg(colors.escape),
"markup.heading": { fg: markdownHeading, bold: true },
"markup.heading.1": { fg: markdownHeading, bold: true },
"markup.heading.2": { fg: markdownHeading, bold: true },
"markup.heading.3": { fg: markdownHeading, bold: true },
"markup.heading.4": { fg: markdownHeading, bold: true },
"markup.heading.5": { fg: markdownHeading, bold: true },
"markup.heading.6": { fg: markdownHeading, bold: true },
"markup.raw": { fg: markdownCode },
"markup.raw.inline": { fg: markdownCode },
"markup.raw.block": { fg: markdownCode },
"markup.strong": { fg: markdownHeading, bold: true },
"markup.bold": { fg: markdownHeading, bold: true },
"markup.italic": italic(colors.markdownItalic),
"markup.quote": { fg: markdownMuted, italic: true },
"markup.list": { fg: markdownHeading },
"markup.link": { fg: markdownLink, underline: true },
"markup.link.label": { fg: markdownLink, underline: true },
"markup.link.url": { fg: markdownLink, underline: true },
label: { fg: markdownLink },
conceal: { fg: markdownMuted },
"string.special.url": underline(colors.markdownLink),
});
}
export function getSyntaxStyle(theme: TerminalTheme = "dark"): SyntaxStyle {
return (instances[theme] ??= buildSyntaxStyle(theme));
}
@@ -1,88 +0,0 @@
import { describe, expect, it } from "vitest";
import {
getToolErrorPresentation,
isWarningToolError,
unwrapToolError,
} from "./tool-errors";
describe("tool error presentation", () => {
it("unwraps JSON-encoded tool errors", () => {
const raw = JSON.stringify({
error: "Tool call run_commands was rejected before execution: nope",
});
expect(unwrapToolError(raw)).toBe(
"Tool call run_commands was rejected before execution: nope",
);
});
it("summarizes invalid tool input as a warning", () => {
const raw = JSON.stringify({
error:
'Tool call run_commands was rejected before execution: Invalid input for tool run_commands: Type validation failed: Value: {"commands":[{"command":"cat file"}]}.\nError message: []',
});
expect(getToolErrorPresentation(raw)).toMatchObject({
severity: "warning",
summary: "Invalid run_commands input; tool call skipped.",
});
expect(isWarningToolError(raw)).toBe(true);
});
it("summarizes generic pre-execution rejections as warnings", () => {
expect(
getToolErrorPresentation(
"Tool call editor was rejected before execution: approval request failed",
),
).toMatchObject({
severity: "warning",
summary: "editor call was skipped before execution.",
});
});
it("keeps non-rejection failures as errors", () => {
const presentation = getToolErrorPresentation("command failed with exit 1");
expect(presentation).toEqual({
severity: "error",
summary: "command failed with exit 1",
detail: "command failed with exit 1",
});
});
it("summarizes JSON-wrapped hard errors without dumping stacks", () => {
const raw = JSON.stringify({
error:
"Error: command failed with exit 1\n at runTool (/tmp/tool.ts:10:1)\n at async main (/tmp/main.ts:5:1)",
});
expect(getToolErrorPresentation(raw)).toEqual({
severity: "error",
summary: "command failed with exit 1",
detail:
"Error: command failed with exit 1\n at runTool (/tmp/tool.ts:10:1)\n at async main (/tmp/main.ts:5:1)",
});
});
it("collapses long one-line hard errors", () => {
const detail = `Validation failed: ${"x".repeat(180)}`;
const presentation = getToolErrorPresentation(detail);
expect(presentation.severity).toBe("error");
expect(presentation.detail).toBe(detail);
expect(presentation.summary.length).toBeLessThanOrEqual(140);
expect(presentation.summary.endsWith("...")).toBe(true);
});
it("uses a generic summary when no string error can be extracted", () => {
const presentation = getToolErrorPresentation(
JSON.stringify({ code: "E_TOOL", data: { value: 1 } }),
);
expect(presentation).toEqual({
severity: "error",
summary: "Tool returned a structured error.",
detail: JSON.stringify({ code: "E_TOOL", data: { value: 1 } }),
});
});
});
-118
View File
@@ -1,118 +0,0 @@
export interface ToolErrorPresentation {
severity: "warning" | "error";
summary: string;
detail: string;
}
const MAX_ERROR_SUMMARY_LENGTH = 140;
function extractStringError(value: unknown): string | undefined {
if (typeof value === "string") {
return value.trim() || undefined;
}
if (!value || typeof value !== "object" || Array.isArray(value)) {
return undefined;
}
const record = value as Record<string, unknown>;
return (
extractStringError(record.error) ??
extractStringError(record.message) ??
undefined
);
}
export function unwrapToolError(error: string): string {
let current = error.trim();
for (let i = 0; i < 3; i += 1) {
if (!current.startsWith("{") && !current.startsWith("[")) break;
try {
const parsed = JSON.parse(current) as unknown;
const next = extractStringError(parsed);
if (!next || next === current) break;
current = next.trim();
} catch {
break;
}
}
return current;
}
function summarizeInvalidInput(message: string): string | undefined {
const rejected = message.match(
/^Tool call\s+([A-Za-z0-9_-]+)\s+was rejected before execution:\s+Invalid input for tool\s+([A-Za-z0-9_-]+):\s*([^.\n]+)(?:\.|\n|$)/,
);
if (rejected) {
return `Invalid ${rejected[2]} input; tool call skipped.`;
}
const invalid = message.match(
/^Invalid input for tool\s+([A-Za-z0-9_-]+):\s*([^.\n]+)(?:\.|\n|$)/,
);
if (invalid) {
return `Invalid ${invalid[1]} input; tool call skipped.`;
}
return undefined;
}
function truncateSummary(text: string): string {
const trimmed = text.trim();
if (trimmed.length <= MAX_ERROR_SUMMARY_LENGTH) {
return trimmed;
}
return `${trimmed.slice(0, MAX_ERROR_SUMMARY_LENGTH - 3).trimEnd()}...`;
}
function summarizeErrorDetail(detail: string): string {
const trimmed = detail.trim();
if (!trimmed) {
return "Tool failed.";
}
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
return "Tool returned a structured error.";
}
const firstLine =
trimmed
.replace(/\r\n/g, "\n")
.split("\n")
.map((line) => line.trim())
.find(Boolean) ?? "Tool failed.";
const withoutGenericPrefix = firstLine.replace(/^Error:\s+/i, "");
return truncateSummary(withoutGenericPrefix.replace(/\s+/g, " "));
}
export function getToolErrorPresentation(error: string): ToolErrorPresentation {
const detail = unwrapToolError(error);
const inputSummary = summarizeInvalidInput(detail);
if (inputSummary) {
return {
severity: "warning",
summary: inputSummary,
detail,
};
}
const rejected = detail.match(
/^Tool call\s+([A-Za-z0-9_-]+)\s+was rejected before execution:/,
);
if (rejected) {
return {
severity: "warning",
summary: `${rejected[1]} call was skipped before execution.`,
detail,
};
}
return {
severity: "error",
summary: summarizeErrorDetail(detail),
detail,
};
}
export function isWarningToolError(error: string | undefined): boolean {
return error ? getToolErrorPresentation(error).severity === "warning" : false;
}
@@ -1,150 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const hoisted = vi.hoisted(() => ({
loginLocalProvider: vi.fn(),
startClineDeviceAuth: vi.fn(),
completeClineDeviceAuth: vi.fn(),
saveLocalProviderOAuthCredentials: vi.fn(),
openMock: vi.fn(() => Promise.resolve()),
}));
vi.mock("@cline/core", () => ({
loginLocalProvider: hoisted.loginLocalProvider,
startClineDeviceAuth: hoisted.startClineDeviceAuth,
completeClineDeviceAuth: hoisted.completeClineDeviceAuth,
saveLocalProviderOAuthCredentials: hoisted.saveLocalProviderOAuthCredentials,
ProviderSettingsManager: class {},
}));
vi.mock("@cline/shared", () => ({
getClineEnvironmentConfig: () => ({ apiBaseUrl: "https://api.example" }),
}));
vi.mock("open", () => ({ default: hoisted.openMock }));
import { runDeviceCodeAuthFlow, runOAuthAuthFlow } from "./auth";
// Minimal stand-in for a telemetry service. The auth helpers must forward this
// reference verbatim into core; we only need referential equality, so the
// concrete shape doesn't matter for these tests.
const fakeTelemetry = { __id: "fake-telemetry" } as unknown as Parameters<
typeof runOAuthAuthFlow
>[0]["telemetry"];
function makeManager() {
return {
getProviderSettings: vi.fn(() => undefined),
} as unknown as Parameters<
typeof runOAuthAuthFlow
>[0]["providerSettingsManager"];
}
describe("onboarding auth telemetry forwarding", () => {
beforeEach(() => {
hoisted.loginLocalProvider.mockReset();
hoisted.startClineDeviceAuth.mockReset();
hoisted.completeClineDeviceAuth.mockReset();
hoisted.saveLocalProviderOAuthCredentials.mockReset();
hoisted.openMock.mockReset();
hoisted.openMock.mockResolvedValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
it("forwards the CLI telemetry service into loginLocalProvider", async () => {
// Resolve the credentials promise so the onComplete branch fires, but the
// test's assertion is on the telemetry argument passed to core.
hoisted.loginLocalProvider.mockResolvedValueOnce({
access: "a",
refresh: "r",
expires: 0,
});
const onComplete = vi.fn();
runOAuthAuthFlow({
providerId: "openai-codex",
providerSettingsManager: makeManager(),
isAborted: () => false,
setStatus: vi.fn(),
setAuthUrl: vi.fn(),
setError: vi.fn(),
onComplete,
telemetry: fakeTelemetry,
});
// Flush the .then chain so we can assert on the post-login callbacks too.
await Promise.resolve();
await Promise.resolve();
expect(hoisted.loginLocalProvider).toHaveBeenCalledTimes(1);
const [providerArg, , , telemetryArg] =
hoisted.loginLocalProvider.mock.calls[0];
expect(providerArg).toBe("openai-codex");
// Identity, not deep-equal — we are validating the exact reference flows
// through so opt-out / common metadata stays consistent.
expect(telemetryArg).toBe(fakeTelemetry);
});
it("does not pass telemetry when none is provided (back-compat)", () => {
hoisted.loginLocalProvider.mockResolvedValueOnce({
access: "a",
refresh: "r",
expires: 0,
});
runOAuthAuthFlow({
providerId: "openai-codex",
providerSettingsManager: makeManager(),
isAborted: () => false,
setStatus: vi.fn(),
setAuthUrl: vi.fn(),
setError: vi.fn(),
onComplete: vi.fn(),
});
const [, , , telemetryArg] = hoisted.loginLocalProvider.mock.calls[0];
expect(telemetryArg).toBeUndefined();
});
it("forwards telemetry into completeClineDeviceAuth for the device-code flow", async () => {
hoisted.startClineDeviceAuth.mockResolvedValueOnce({
deviceCode: "dc",
userCode: "uc",
verificationUri: "https://verify",
verificationUriComplete: "https://verify?user_code=uc",
expiresInSeconds: 600,
pollIntervalSeconds: 5,
});
hoisted.completeClineDeviceAuth.mockResolvedValueOnce({
access: "a",
refresh: "r",
expires: 0,
});
runDeviceCodeAuthFlow({
providerId: "cline",
providerSettingsManager: makeManager(),
isAborted: () => false,
setUserCode: vi.fn(),
setVerifyUrl: vi.fn(),
setStatus: vi.fn(),
setError: vi.fn(),
onComplete: vi.fn(),
telemetry: fakeTelemetry,
});
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(hoisted.completeClineDeviceAuth).toHaveBeenCalledTimes(1);
const [opts] = hoisted.completeClineDeviceAuth.mock.calls[0];
expect(opts.telemetry).toBe(fakeTelemetry);
// We do NOT forward telemetry to startClineDeviceAuth — auth_started is
// emitted by completeClineDeviceAuth, so passing telemetry to the start
// helper would double-emit the event.
expect(hoisted.startClineDeviceAuth).toHaveBeenCalledWith();
});
});
@@ -1,14 +0,0 @@
import type { ProviderConfigFieldKey } from "@cline/core";
/** Render order for provider config fields and Tab cycling. */
export const FIELD_ORDER: ProviderConfigFieldKey[] = [
"awsRegion",
"baseUrl",
"apiKey",
"awsProfile",
"sapClientId",
"sapClientSecret",
"sapTokenUrl",
"sapResourceGroup",
"sapDeploymentId",
];
-47
View File
@@ -1,47 +0,0 @@
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { resolveAwsRegion } from "./aws-region";
const originalEnv = { ...process.env };
afterEach(() => {
process.env = { ...originalEnv };
});
describe("resolveAwsRegion", () => {
it("prefers explicit region", () => {
process.env.AWS_REGION = "us-east-1";
expect(resolveAwsRegion({ explicitRegion: "us-west-2" })).toBe("us-west-2");
});
it("uses AWS_REGION before AWS_DEFAULT_REGION", () => {
process.env.AWS_REGION = "eu-west-1";
process.env.AWS_DEFAULT_REGION = "us-east-2";
expect(resolveAwsRegion()).toBe("eu-west-1");
});
it("reads selected profile region from AWS config", () => {
delete process.env.AWS_REGION;
delete process.env.AWS_DEFAULT_REGION;
const dir = mkdtempSync(join(tmpdir(), "cline-aws-config-"));
try {
const configPath = join(dir, "config");
writeFileSync(
configPath,
[
"[default]",
"region = us-east-1",
"[profile dev]",
"region = ap-southeast-2",
].join("\n"),
);
process.env.AWS_CONFIG_FILE = configPath;
expect(resolveAwsRegion({ profile: "dev" })).toBe("ap-southeast-2");
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
-65
View File
@@ -1,65 +0,0 @@
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
function parseAwsConfigProfiles(
content: string,
): Record<string, Record<string, string>> {
const profiles: Record<string, Record<string, string>> = {};
let currentProfile: string | undefined;
for (const rawLine of content.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith("#") || line.startsWith(";")) continue;
const sectionMatch = line.match(/^\[([^\]]+)]$/);
if (sectionMatch) {
const section = sectionMatch[1]?.trim() ?? "";
currentProfile = section.startsWith("profile ")
? section.slice("profile ".length).trim()
: section;
profiles[currentProfile] ??= {};
continue;
}
if (!currentProfile) continue;
const separatorIndex = line.indexOf("=");
if (separatorIndex === -1) continue;
const key = line.slice(0, separatorIndex).trim();
const value = line.slice(separatorIndex + 1).trim();
profiles[currentProfile][key] = value;
}
return profiles;
}
function readAwsConfigRegion(profile: string): string | undefined {
const configPath =
process.env.AWS_CONFIG_FILE?.trim() || join(homedir(), ".aws", "config");
if (!existsSync(configPath)) return undefined;
try {
const profiles = parseAwsConfigProfiles(readFileSync(configPath, "utf8"));
return profiles[profile]?.region?.trim() || undefined;
} catch {
return undefined;
}
}
export function resolveAwsRegion(
input: { explicitRegion?: string; profile?: string } = {},
): string | undefined {
const explicitRegion = input.explicitRegion?.trim();
if (explicitRegion) return explicitRegion;
const envRegion =
process.env.AWS_REGION?.trim() || process.env.AWS_DEFAULT_REGION?.trim();
if (envRegion) return envRegion;
const profile =
input.profile?.trim() || process.env.AWS_PROFILE?.trim() || "default";
return (
readAwsConfigRegion(profile) ??
(profile !== "default" ? readAwsConfigRegion("default") : undefined)
);
}
-166
View File
@@ -1,166 +0,0 @@
import { execFileSync } from "node:child_process";
import {
access,
mkdir,
mkdtemp,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import * as path from "node:path";
import { setClineDir } from "@cline/shared/storage";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createTaskWorktree, getTaskWorktreesHomePath } from "./worktree";
function git(cwd: string, args: string[]): string {
return execFileSync("git", ["-C", cwd, ...args], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
}).trim();
}
async function pathExists(targetPath: string): Promise<boolean> {
try {
await access(targetPath);
return true;
} catch {
return false;
}
}
describe("createTaskWorktree", () => {
let sandboxRoot: string;
let clineDir: string;
let repoPath: string;
let nonRepoPath: string;
let originalClineDir: string | undefined;
beforeEach(async () => {
sandboxRoot = await mkdtemp(path.join(tmpdir(), "cline-sdk-worktree-"));
clineDir = path.join(sandboxRoot, ".cline");
repoPath = path.join(sandboxRoot, "myrepo");
nonRepoPath = path.join(sandboxRoot, "not-a-repo");
originalClineDir = process.env.CLINE_DIR;
process.env.CLINE_DIR = clineDir;
setClineDir(clineDir);
await writeFile(path.join(sandboxRoot, ".keep"), "");
await rm(repoPath, { recursive: true, force: true });
await rm(nonRepoPath, { recursive: true, force: true });
await mkdir(repoPath, { recursive: true });
await mkdir(nonRepoPath, { recursive: true });
git(repoPath, ["init", "-q", "-b", "main"]);
await writeFile(path.join(repoPath, "file.txt"), "hello");
git(repoPath, ["add", "."]);
git(repoPath, [
"-c",
"user.email=test@example.com",
"-c",
"user.name=Test",
"commit",
"-q",
"-m",
"init",
]);
});
afterEach(async () => {
if (originalClineDir === undefined) {
delete process.env.CLINE_DIR;
} else {
process.env.CLINE_DIR = originalClineDir;
}
setClineDir(originalClineDir ?? path.join("~", ".cline"));
await rm(sandboxRoot, { recursive: true, force: true });
});
it("places worktrees under ~/.cline/worktrees", () => {
expect(getTaskWorktreesHomePath()).toBe(path.join(clineDir, "worktrees"));
});
it("creates a detached worktree at ~/.cline/worktrees/<taskId>/<repoName>", async () => {
const result = await createTaskWorktree({
cwd: repoPath,
taskId: "my-task",
});
expect(result.success).toBe(true);
expect(result.taskId).toBe("my-task");
expect(result.repoRoot).toBeDefined();
expect(result.path).toBeDefined();
if (!result.repoRoot || !result.path) {
throw new Error("Expected worktree result to include repoRoot and path.");
}
const worktreePath = result.path;
expect(await realpath(result.repoRoot)).toBe(await realpath(repoPath));
expect(result.path).toBe(
path.join(clineDir, "worktrees", "my-task", "myrepo"),
);
expect(git(worktreePath, ["rev-parse", "--is-inside-work-tree"])).toBe(
"true",
);
expect(git(worktreePath, ["rev-parse", "HEAD"])).toBe(
git(repoPath, ["rev-parse", "HEAD"]),
);
expect(git(worktreePath, ["rev-parse", "--abbrev-ref", "HEAD"])).toBe(
"HEAD",
);
});
it("generates a Kanban-style short taskId when none is provided", async () => {
const result = await createTaskWorktree({ cwd: repoPath });
expect(result.success).toBe(true);
expect(result.taskId).toMatch(/^[0-9a-f]{5}$/i);
expect(result.taskId).toBeDefined();
if (!result.taskId) {
throw new Error("Expected generated taskId.");
}
expect(result.path).toBe(
path.join(clineDir, "worktrees", result.taskId, "myrepo"),
);
});
it("rejects when cwd is not a git repository", async () => {
const result = await createTaskWorktree({ cwd: nonRepoPath });
expect(result.success).toBe(false);
expect(result.message).toMatch(/Not a git repository/);
});
it("cleans up the task directory when git worktree add fails", async () => {
const emptyRepoPath = path.join(sandboxRoot, "empty-repo");
await mkdir(emptyRepoPath, { recursive: true });
git(emptyRepoPath, ["init", "-q", "-b", "main"]);
const result = await createTaskWorktree({
cwd: emptyRepoPath,
taskId: "empty",
});
expect(result.success).toBe(false);
expect(result.message).toMatch(/Failed to create worktree/);
expect(await pathExists(path.join(clineDir, "worktrees", "empty"))).toBe(
false,
);
});
it("rejects unsafe taskIds", async () => {
const traversal = await createTaskWorktree({
cwd: repoPath,
taskId: "../escape",
});
const nullByte = await createTaskWorktree({
cwd: repoPath,
taskId: "safe\0../escape",
});
expect(traversal.success).toBe(false);
expect(traversal.message).toMatch(/Invalid worktree id/);
expect(nullByte.success).toBe(false);
expect(nullByte.message).toMatch(/Invalid worktree id/);
});
});
-147
View File
@@ -1,147 +0,0 @@
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import { access, mkdir, rm } from "node:fs/promises";
import * as path from "node:path";
import { promisify } from "node:util";
import { resolveClineDir } from "@cline/shared/storage";
const execFileAsync = promisify(execFile);
const TASK_ID_LENGTH = 5;
export interface CreateTaskWorktreeResult {
success: boolean;
message: string;
path?: string;
taskId?: string;
repoRoot?: string;
}
export function getTaskWorktreesHomePath(): string {
return path.join(resolveClineDir(), "worktrees");
}
function getWorkspaceFolderLabelForWorktreePath(repoPath: string): string {
const folder = path.basename(repoPath.replace(/[\\/]+$/g, "")) || "workspace";
const cleaned = [...folder]
.filter((char) => {
const code = char.charCodeAt(0);
return code >= 32 && code !== 127;
})
.join("")
.trim();
return cleaned || "workspace";
}
function createShortTaskId(): string {
return randomUUID().replaceAll("-", "").slice(0, TASK_ID_LENGTH);
}
async function pathExists(targetPath: string): Promise<boolean> {
try {
await access(targetPath);
return true;
} catch {
return false;
}
}
async function checkGitInstalled(): Promise<boolean> {
try {
await execFileAsync("git", ["--version"], { windowsHide: true });
return true;
} catch {
return false;
}
}
async function getGitRootPath(cwd: string): Promise<string | null> {
try {
const { stdout } = await execFileAsync(
"git",
["-C", cwd, "rev-parse", "--show-toplevel"],
{ windowsHide: true },
);
const root = stdout.trim();
return root || null;
} catch {
return null;
}
}
export async function createTaskWorktree(options: {
cwd: string;
taskId?: string;
}): Promise<CreateTaskWorktreeResult> {
if (!(await checkGitInstalled())) {
return {
success: false,
message: "Git is not installed. --worktree requires git on PATH.",
};
}
const repoRoot = await getGitRootPath(options.cwd);
if (!repoRoot) {
return {
success: false,
message: `Not a git repository: ${options.cwd}. --worktree requires a git repo.`,
};
}
let taskId = options.taskId?.trim() || createShortTaskId();
if (
taskId.includes("/") ||
taskId.includes("\\") ||
taskId.includes("..") ||
taskId.includes("\0")
) {
return { success: false, message: `Invalid worktree id: ${taskId}` };
}
const workspaceLabel = getWorkspaceFolderLabelForWorktreePath(repoRoot);
let worktreePath = path.join(
getTaskWorktreesHomePath(),
taskId,
workspaceLabel,
);
if (!options.taskId) {
for (
let attempt = 0;
attempt < 16 && (await pathExists(worktreePath));
attempt += 1
) {
taskId = createShortTaskId();
worktreePath = path.join(
getTaskWorktreesHomePath(),
taskId,
workspaceLabel,
);
}
}
const parentDir = path.dirname(worktreePath);
const parentDirExisted = await pathExists(parentDir);
try {
await mkdir(parentDir, { recursive: true });
await execFileAsync(
"git",
["-C", repoRoot, "worktree", "add", "--detach", worktreePath, "HEAD"],
{ windowsHide: true },
);
return {
success: true,
message: `Worktree created at ${worktreePath}`,
path: worktreePath,
taskId,
repoRoot,
};
} catch (error) {
if (!parentDirExisted) {
await rm(parentDir, { recursive: true, force: true }).catch(() => {});
}
return {
success: false,
message: `Failed to create worktree: ${error instanceof Error ? error.message : String(error)}`,
};
}
}
@@ -1,81 +0,0 @@
import { describe, expect, it } from "vitest";
import { PLATFORMS, shouldIncludeField } from "./platforms";
describe("connect wizard platform security fields", () => {
it("does not ask Telegram users to re-enter the bot username", () => {
const telegram = PLATFORMS.find((platform) => platform.id === "telegram");
expect(telegram?.fields.map((field) => field.label)).toEqual(["Bot token"]);
expect(telegram?.fields.map((field) => field.flag)).toEqual(["-k"]);
});
it("rejects unsafe Telegram and Slack access restriction identifiers", () => {
const telegram = PLATFORMS.find((platform) => platform.id === "telegram");
const slack = PLATFORMS.find((platform) => platform.id === "slack");
const telegramUser = telegram?.security?.fields.find(
(field) => field.key === "userId",
);
const slackTeam = slack?.security?.fields.find(
(field) => field.key === "teamId",
);
const slackUser = slack?.security?.fields.find(
(field) => field.key === "userId",
);
expect(telegramUser?.validate?.("123456")).toBeUndefined();
expect(telegramUser?.validate?.("123; rm -rf /")).toContain("digits");
expect(slackTeam?.validate?.("T01ABC123")).toBeUndefined();
expect(slackTeam?.validate?.("T01;bad")).toContain("Slack workspace");
expect(slackUser?.validate?.("U01ABC123")).toBeUndefined();
expect(slackUser?.validate?.("U01$(bad)")).toContain("Slack member");
});
it("uses the Telegram allowed user ID flag for wizard security", () => {
const telegram = PLATFORMS.find((platform) => platform.id === "telegram");
const args = telegram?.security?.buildArgs({
userId: "123456",
});
expect(args).toEqual(["--allowed-user-id", "123456"]);
});
it("builds an exact-match Slack authorization hook", () => {
const slack = PLATFORMS.find((platform) => platform.id === "slack");
const args = slack?.security?.buildArgs({
teamId: "T01ABC123",
userId: "U01ABC123",
});
expect(args).toEqual([
"--hook-command",
`jq -r ".payload.actor.participantKey" | grep -qx "slack:team:T01ABC123:user:U01ABC123" && echo '{"action":"allow"}' || echo '{"action":"deny"}'`,
]);
});
it("asks Slack users for mode-specific setup fields", () => {
const slack = PLATFORMS.find((platform) => platform.id === "slack");
const fields = slack?.fields ?? [];
const webhookValues = { "--base-url": "https://example.test" };
const socketValues = { "--base-url": "" };
expect(fields.map((field) => field.flag)).toEqual([
"--bot-token",
"--base-url",
"--signing-secret",
"--app-token",
]);
expect(
fields
.filter((field) => shouldIncludeField(field, webhookValues))
.map((field) => field.flag),
).toEqual(["--bot-token", "--base-url", "--signing-secret"]);
expect(
fields
.filter((field) => shouldIncludeField(field, socketValues))
.map((field) => field.flag),
).toEqual(["--bot-token", "--base-url", "--app-token"]);
});
});

Some files were not shown because too many files have changed in this diff Show More