├── .clinerules
├── c#-guide.md
├── cline-architecture.md
├── cline-continuous-improvement-protocol.md
├── cline-for-research.md
├── cline-for-slides.md
├── cline-for-webdev-ui.md
├── comprehensive-slide-dev-guide.md
├── gemini-comprehensive-software-engineering-guide.md
├── mcp-development-protocol.md
├── memory-bank.md
├── new-task-automation
├── next-js-supabase.md
├── self-improving-cline.md
├── sequential-thinking.md
├── uv-python-usage-guide.md
└── writing-effective-clinerules.md
├── README.md
└── workflows
└── pr-review-cline.md
/.clinerules/cline-architecture.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: Defines Cline's extension architecture, components, data flow, and development guidelines.
3 | author: https://github.com/cline
4 | version: 1.0
5 | tags: ["architecture", "development-guide", "extension", "vscode", "core-behavior"]
6 | globs: ["*"]
7 | ---
8 | # Cline Extension Architecture & Development Guide
9 |
10 | ## Project Overview
11 |
12 | Cline is a VSCode extension that provides AI assistance through a combination of a core extension backend and a React-based webview frontend. The extension is built with TypeScript and follows a modular architecture pattern.
13 |
14 | ## Architecture Overview
15 |
16 | ```mermaid
17 | graph TB
18 | subgraph VSCodeExtensionHost[VSCode Extension Host]
19 | subgraph CoreExtension[Core Extension]
20 | ExtensionEntry[Extension Entry
src/extension.ts]
21 | WebviewProvider[WebviewProvider
src/core/webview/index.ts]
22 | Controller[Controller
src/core/controller/index.ts]
23 | Task[Task
src/core/task/index.ts]
24 | GlobalState[VSCode Global State]
25 | SecretsStorage[VSCode Secrets Storage]
26 | McpHub[McpHub
src/services/mcp/McpHub.ts]
27 | end
28 |
29 | subgraph WebviewUI[Webview UI]
30 | WebviewApp[React App
webview-ui/src/App.tsx]
31 | ExtStateContext[ExtensionStateContext
webview-ui/src/context/ExtensionStateContext.tsx]
32 | ReactComponents[React Components]
33 | end
34 |
35 | subgraph Storage
36 | TaskStorage[Task Storage
Per-Task Files & History]
37 | CheckpointSystem[Git-based Checkpoints]
38 | end
39 |
40 | subgraph apiProviders[API Providers]
41 | AnthropicAPI[Anthropic]
42 | OpenRouterAPI[OpenRouter]
43 | BedrockAPI[AWS Bedrock]
44 | OtherAPIs[Other Providers]
45 | end
46 |
47 | subgraph MCPServers[MCP Servers]
48 | ExternalMcpServers[External MCP Servers]
49 | end
50 | end
51 |
52 | %% Core Extension Data Flow
53 | ExtensionEntry --> WebviewProvider
54 | WebviewProvider --> Controller
55 | Controller --> Task
56 | Controller --> McpHub
57 | Task --> GlobalState
58 | Task --> SecretsStorage
59 | Task --> TaskStorage
60 | Task --> CheckpointSystem
61 | Task --> |API Requests| apiProviders
62 | McpHub --> |Connects to| ExternalMcpServers
63 | Task --> |Uses| McpHub
64 |
65 | %% Webview Data Flow
66 | WebviewApp --> ExtStateContext
67 | ExtStateContext --> ReactComponents
68 |
69 | %% Bidirectional Communication
70 | WebviewProvider <-->|postMessage| ExtStateContext
71 |
72 | style GlobalState fill:#f9f,stroke:#333,stroke-width:2px
73 | style SecretsStorage fill:#f9f,stroke:#333,stroke-width:2px
74 | style ExtStateContext fill:#bbf,stroke:#333,stroke-width:2px
75 | style WebviewProvider fill:#bfb,stroke:#333,stroke-width:2px
76 | style McpHub fill:#bfb,stroke:#333,stroke-width:2px
77 | style apiProviders fill:#fdb,stroke:#333,stroke-width:2px
78 | ```
79 |
80 | ## Definitions
81 |
82 | - **Core Extension**: Anything inside the src folder, organized into modular components
83 | - **Core Extension State**: Managed by the Controller class in src/core/controller/index.ts, which serves as the single source of truth for the extension's state. It manages multiple types of persistent storage (global state, workspace state, and secrets), handles state distribution to both the core extension and webview components, and coordinates state across multiple extension instances. This includes managing API configurations, task history, settings, and MCP configurations.
84 | - **Webview**: Anything inside the webview-ui. All the react or view's seen by the user and user interaction components
85 | - **Webview State**: Managed by ExtensionStateContext in webview-ui/src/context/ExtensionStateContext.tsx, which provides React components with access to the extension's state through a context provider pattern. It maintains local state for UI components, handles real-time updates through message events, manages partial message updates, and provides methods for state modifications. The context includes extension version, messages, task history, theme, API configurations, MCP servers, marketplace catalog, and workspace file paths. It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to state through a custom hook (useExtensionState).
86 |
87 | ### Core Extension Architecture
88 |
89 | The core extension follows a clear hierarchical structure:
90 |
91 | 1. **WebviewProvider** (src/core/webview/index.ts): Manages the webview lifecycle and communication
92 | 2. **Controller** (src/core/controller/index.ts): Handles webview messages and task management
93 | 3. **Task** (src/core/task/index.ts): Executes API requests and tool operations
94 |
95 | This architecture provides clear separation of concerns:
96 | - WebviewProvider focuses on VSCode webview integration
97 | - Controller manages state and coordinates tasks
98 | - Task handles the execution of AI requests and tool operations
99 |
100 | ### WebviewProvider Implementation
101 |
102 | The WebviewProvider class in `src/core/webview/index.ts` is responsible for:
103 |
104 | - Managing multiple active instances through a static set (`activeInstances`)
105 | - Handling webview lifecycle events (creation, visibility changes, disposal)
106 | - Implementing HTML content generation with proper CSP headers
107 | - Supporting Hot Module Replacement (HMR) for development
108 | - Setting up message listeners between the webview and extension
109 |
110 | The WebviewProvider maintains a reference to the Controller and delegates message handling to it. It also handles the creation of both sidebar and tab panel webviews, allowing Cline to be used in different contexts within VSCode.
111 |
112 | ### Core Extension State
113 |
114 | The `Controller` class manages multiple types of persistent storage:
115 |
116 | - **Global State:** Stored across all VSCode instances. Used for settings and data that should persist globally.
117 | - **Workspace State:** Specific to the current workspace. Used for task-specific data and settings.
118 | - **Secrets:** Secure storage for sensitive information like API keys.
119 |
120 | The `Controller` handles the distribution of state to both the core extension and webview components. It also coordinates state across multiple extension instances, ensuring consistency.
121 |
122 | State synchronization between instances is handled through:
123 | - File-based storage for task history and conversation data
124 | - VSCode's global state API for settings and configuration
125 | - Secrets storage for sensitive information
126 | - Event listeners for file changes and configuration updates
127 |
128 | The Controller implements methods for:
129 | - Saving and loading task state
130 | - Managing API configurations
131 | - Handling user authentication
132 | - Coordinating MCP server connections
133 | - Managing task history and checkpoints
134 |
135 | ### Webview State
136 |
137 | The `ExtensionStateContext` in `webview-ui/src/context/ExtensionStateContext.tsx` provides React components with access to the extension's state. It uses a context provider pattern and maintains local state for UI components. The context includes:
138 |
139 | - Extension version
140 | - Messages
141 | - Task history
142 | - Theme
143 | - API configurations
144 | - MCP servers
145 | - Marketplace catalog
146 | - Workspace file paths
147 |
148 | It synchronizes with the core extension through VSCode's message passing system and provides type-safe access to the state via a custom hook (`useExtensionState`).
149 |
150 | The ExtensionStateContext handles:
151 | - Real-time updates through message events
152 | - Partial message updates for streaming content
153 | - State modifications through setter methods
154 | - Type-safe access to state through a custom hook
155 |
156 | ## API Provider System
157 |
158 | Cline supports multiple AI providers through a modular API provider system. Each provider is implemented as a separate module in the `src/api/providers/` directory and follows a common interface.
159 |
160 | ### API Provider Architecture
161 |
162 | The API system consists of:
163 |
164 | 1. **API Handlers**: Provider-specific implementations in `src/api/providers/`
165 | 2. **API Transformers**: Stream transformation utilities in `src/api/transform/`
166 | 3. **API Configuration**: User settings for API keys and endpoints
167 | 4. **API Factory**: Builder function to create the appropriate handler
168 |
169 | Key providers include:
170 | - **Anthropic**: Direct integration with Claude models
171 | - **OpenRouter**: Meta-provider supporting multiple model providers
172 | - **AWS Bedrock**: Integration with Amazon's AI services
173 | - **Gemini**: Google's AI models
174 | - **Ollama**: Local model hosting
175 | - **LM Studio**: Local model hosting
176 | - **VSCode LM**: VSCode's built-in language models
177 |
178 | ### API Configuration Management
179 |
180 | API configurations are stored securely:
181 | - API keys are stored in VSCode's secrets storage
182 | - Model selections and non-sensitive settings are stored in global state
183 | - The Controller manages switching between providers and updating configurations
184 |
185 | The system supports:
186 | - Secure storage of API keys
187 | - Model selection and configuration
188 | - Automatic retry and error handling
189 | - Token usage tracking and cost calculation
190 | - Context window management
191 |
192 | ### Plan/Act Mode API Configuration
193 |
194 | Cline supports separate model configurations for Plan and Act modes:
195 | - Different models can be used for planning vs. execution
196 | - The system preserves model selections when switching modes
197 | - The Controller handles the transition between modes and updates the API configuration accordingly
198 |
199 | ## Task Execution System
200 |
201 | The Task class is responsible for executing AI requests and tool operations. Each task runs in its own instance of the Task class, ensuring isolation and proper state management.
202 |
203 | ### Task Execution Loop
204 |
205 | The core task execution loop follows this pattern:
206 |
207 | ```typescript
208 | class Task {
209 | async initiateTaskLoop(userContent: UserContent, isNewTask: boolean) {
210 | while (!this.abort) {
211 | // 1. Make API request and stream response
212 | const stream = this.attemptApiRequest()
213 |
214 | // 2. Parse and present content blocks
215 | for await (const chunk of stream) {
216 | switch (chunk.type) {
217 | case "text":
218 | // Parse into content blocks
219 | this.assistantMessageContent = parseAssistantMessage(chunk.text)
220 | // Present blocks to user
221 | await this.presentAssistantMessage()
222 | break
223 | }
224 | }
225 |
226 | // 3. Wait for tool execution to complete
227 | await pWaitFor(() => this.userMessageContentReady)
228 |
229 | // 4. Continue loop with tool result
230 | const recDidEndLoop = await this.recursivelyMakeClineRequests(
231 | this.userMessageContent
232 | )
233 | }
234 | }
235 | }
236 | ```
237 |
238 | ### Message Streaming System
239 |
240 | The streaming system handles real-time updates and partial content:
241 |
242 | ```typescript
243 | class Task {
244 | async presentAssistantMessage() {
245 | // Handle streaming locks to prevent race conditions
246 | if (this.presentAssistantMessageLocked) {
247 | this.presentAssistantMessageHasPendingUpdates = true
248 | return
249 | }
250 | this.presentAssistantMessageLocked = true
251 |
252 | // Present current content block
253 | const block = this.assistantMessageContent[this.currentStreamingContentIndex]
254 |
255 | // Handle different types of content
256 | switch (block.type) {
257 | case "text":
258 | await this.say("text", content, undefined, block.partial)
259 | break
260 | case "tool_use":
261 | // Handle tool execution
262 | break
263 | }
264 |
265 | // Move to next block if complete
266 | if (!block.partial) {
267 | this.currentStreamingContentIndex++
268 | }
269 | }
270 | }
271 | ```
272 |
273 | ### Tool Execution Flow
274 |
275 | Tools follow a strict execution pattern:
276 |
277 | ```typescript
278 | class Task {
279 | async executeToolWithApproval(block: ToolBlock) {
280 | // 1. Check auto-approval settings
281 | if (this.shouldAutoApproveTool(block.name)) {
282 | await this.say("tool", message)
283 | this.consecutiveAutoApprovedRequestsCount++
284 | } else {
285 | // 2. Request user approval
286 | const didApprove = await askApproval("tool", message)
287 | if (!didApprove) {
288 | this.didRejectTool = true
289 | return
290 | }
291 | }
292 |
293 | // 3. Execute tool
294 | const result = await this.executeTool(block)
295 |
296 | // 4. Save checkpoint
297 | await this.saveCheckpoint()
298 |
299 | // 5. Return result to API
300 | return result
301 | }
302 | }
303 | ```
304 |
305 | ### Error Handling & Recovery
306 |
307 | The system includes robust error handling:
308 |
309 | ```typescript
310 | class Task {
311 | async handleError(action: string, error: Error) {
312 | // 1. Check if task was abandoned
313 | if (this.abandoned) return
314 |
315 | // 2. Format error message
316 | const errorString = `Error ${action}: ${error.message}`
317 |
318 | // 3. Present error to user
319 | await this.say("error", errorString)
320 |
321 | // 4. Add error to tool results
322 | pushToolResult(formatResponse.toolError(errorString))
323 |
324 | // 5. Cleanup resources
325 | await this.diffViewProvider.revertChanges()
326 | await this.browserSession.closeBrowser()
327 | }
328 | }
329 | ```
330 |
331 | ### API Request & Token Management
332 |
333 | The Task class handles API requests with built-in retry, streaming, and token management:
334 |
335 | ```typescript
336 | class Task {
337 | async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
338 | // 1. Wait for MCP servers to connect
339 | await pWaitFor(() => this.controllerRef.deref()?.mcpHub?.isConnecting !== true)
340 |
341 | // 2. Manage context window
342 | const previousRequest = this.clineMessages[previousApiReqIndex]
343 | if (previousRequest?.text) {
344 | const { tokensIn, tokensOut } = JSON.parse(previousRequest.text || "{}")
345 | const totalTokens = (tokensIn || 0) + (tokensOut || 0)
346 |
347 | // Truncate conversation if approaching context limit
348 | if (totalTokens >= maxAllowedSize) {
349 | this.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange(
350 | this.apiConversationHistory,
351 | this.conversationHistoryDeletedRange,
352 | totalTokens / 2 > maxAllowedSize ? "quarter" : "half"
353 | )
354 | }
355 | }
356 |
357 | // 3. Handle streaming with automatic retry
358 | try {
359 | this.isWaitingForFirstChunk = true
360 | const firstChunk = await iterator.next()
361 | yield firstChunk.value
362 | this.isWaitingForFirstChunk = false
363 |
364 | // Stream remaining chunks
365 | yield* iterator
366 | } catch (error) {
367 | // 4. Error handling with retry
368 | if (isOpenRouter && !this.didAutomaticallyRetryFailedApiRequest) {
369 | await setTimeoutPromise(1000)
370 | this.didAutomaticallyRetryFailedApiRequest = true
371 | yield* this.attemptApiRequest(previousApiReqIndex)
372 | return
373 | }
374 |
375 | // 5. Ask user to retry if automatic retry failed
376 | const { response } = await this.ask(
377 | "api_req_failed",
378 | this.formatErrorWithStatusCode(error)
379 | )
380 | if (response === "yesButtonClicked") {
381 | await this.say("api_req_retried")
382 | yield* this.attemptApiRequest(previousApiReqIndex)
383 | return
384 | }
385 | }
386 | }
387 | }
388 | ```
389 |
390 | Key features:
391 |
392 | 1. **Context Window Management**
393 | - Tracks token usage across requests
394 | - Automatically truncates conversation when needed
395 | - Preserves important context while freeing space
396 | - Handles different model context sizes
397 |
398 | 2. **Streaming Architecture**
399 | - Real-time chunk processing
400 | - Partial content handling
401 | - Race condition prevention
402 | - Error recovery during streaming
403 |
404 | 3. **Error Handling**
405 | - Automatic retry for transient failures
406 | - User-prompted retry for persistent issues
407 | - Detailed error reporting
408 | - State cleanup on failure
409 |
410 | 4. **Token Tracking**
411 | - Per-request token counting
412 | - Cumulative usage tracking
413 | - Cost calculation
414 | - Cache hit monitoring
415 |
416 | ### Context Management System
417 |
418 | The Context Management System handles conversation history truncation to prevent context window overflow errors. Implemented in the `ContextManager` class, it ensures long-running conversations remain within model context limits while preserving critical context.
419 |
420 | Key features:
421 |
422 | 1. **Model-Aware Sizing**: Dynamically adjusts based on different model context windows (64K for DeepSeek, 128K for most models, 200K for Claude).
423 |
424 | 2. **Proactive Truncation**: Monitors token usage and preemptively truncates conversations when approaching limits, maintaining buffers of 27K-40K tokens depending on the model.
425 |
426 | 3. **Intelligent Preservation**: Always preserves the original task message and maintains the user-assistant conversation structure when truncating.
427 |
428 | 4. **Adaptive Strategies**: Uses different truncation strategies based on context pressure - removing half of the conversation for moderate pressure or three-quarters for severe pressure.
429 |
430 | 5. **Error Recovery**: Includes specialized detection for context window errors from different providers with automatic retry and more aggressive truncation when needed.
431 |
432 | ### Task State & Resumption
433 |
434 | The Task class provides robust task state management and resumption capabilities:
435 |
436 | ```typescript
437 | class Task {
438 | async resumeTaskFromHistory() {
439 | // 1. Load saved state
440 | this.clineMessages = await getSavedClineMessages(this.getContext(), this.taskId)
441 | this.apiConversationHistory = await getSavedApiConversationHistory(this.getContext(), this.taskId)
442 |
443 | // 2. Handle interrupted tool executions
444 | const lastMessage = this.apiConversationHistory[this.apiConversationHistory.length - 1]
445 | if (lastMessage.role === "assistant") {
446 | const toolUseBlocks = content.filter(block => block.type === "tool_use")
447 | if (toolUseBlocks.length > 0) {
448 | // Add interrupted tool responses
449 | const toolResponses = toolUseBlocks.map(block => ({
450 | type: "tool_result",
451 | tool_use_id: block.id,
452 | content: "Task was interrupted before this tool call could be completed."
453 | }))
454 | modifiedOldUserContent = [...toolResponses]
455 | }
456 | }
457 |
458 | // 3. Notify about interruption
459 | const agoText = this.getTimeAgoText(lastMessage?.ts)
460 | newUserContent.push({
461 | type: "text",
462 | text: `[TASK RESUMPTION] This task was interrupted ${agoText}. It may or may not be complete, so please reassess the task context.`
463 | })
464 |
465 | // 4. Resume task execution
466 | await this.initiateTaskLoop(newUserContent, false)
467 | }
468 |
469 | private async saveTaskState() {
470 | // Save conversation history
471 | await saveApiConversationHistory(this.getContext(), this.taskId, this.apiConversationHistory)
472 | await saveClineMessages(this.getContext(), this.taskId, this.clineMessages)
473 |
474 | // Create checkpoint
475 | const commitHash = await this.checkpointTracker?.commit()
476 |
477 | // Update task history
478 | await this.controllerRef.deref()?.updateTaskHistory({
479 | id: this.taskId,
480 | ts: lastMessage.ts,
481 | task: taskMessage.text,
482 | // ... other metadata
483 | })
484 | }
485 | }
486 | ```
487 |
488 | Key aspects of task state management:
489 |
490 | 1. **Task Persistence**
491 | - Each task has a unique ID and dedicated storage directory
492 | - Conversation history is saved after each message
493 | - File changes are tracked through Git-based checkpoints
494 | - Terminal output and browser state are preserved
495 |
496 | 2. **State Recovery**
497 | - Tasks can be resumed from any point
498 | - Interrupted tool executions are handled gracefully
499 | - File changes can be restored from checkpoints
500 | - Context is preserved across VSCode sessions
501 |
502 | 3. **Workspace Synchronization**
503 | - File changes are tracked through Git
504 | - Checkpoints are created after tool executions
505 | - State can be restored to any checkpoint
506 | - Changes can be compared between checkpoints
507 |
508 | 4. **Error Recovery**
509 | - Failed API requests can be retried
510 | - Interrupted tool executions are marked
511 | - Resources are cleaned up properly
512 | - User is notified of state changes
513 |
514 | ## Plan/Act Mode System
515 |
516 | Cline implements a dual-mode system that separates planning from execution:
517 |
518 | ### Mode Architecture
519 |
520 | The Plan/Act mode system consists of:
521 |
522 | 1. **Mode State**: Stored in `chatSettings.mode` in the Controller's state
523 | 2. **Mode Switching**: Handled by `togglePlanActModeWithChatSettings` in the Controller
524 | 3. **Mode-specific Models**: Optional configuration to use different models for each mode
525 | 4. **Mode-specific Prompting**: Different system prompts for planning vs. execution
526 |
527 | ### Mode Switching Process
528 |
529 | When switching between modes:
530 |
531 | 1. The current model configuration is saved to mode-specific state
532 | 2. The previous mode's model configuration is restored
533 | 3. The Task instance is updated with the new mode
534 | 4. The webview is notified of the mode change
535 | 5. Telemetry events are captured for analytics
536 |
537 | ### Plan Mode
538 |
539 | Plan mode is designed for:
540 | - Information gathering and context building
541 | - Asking clarifying questions
542 | - Creating detailed execution plans
543 | - Discussing approaches with the user
544 |
545 | In Plan mode, the AI uses the `plan_mode_respond` tool to engage in conversational planning without executing actions.
546 |
547 | ### Act Mode
548 |
549 | Act mode is designed for:
550 | - Executing the planned actions
551 | - Using tools to modify files, run commands, etc.
552 | - Implementing the solution
553 | - Providing results and completion feedback
554 |
555 | In Act mode, the AI has access to all tools except `plan_mode_respond` and focuses on implementation rather than discussion.
556 |
557 | ## Data Flow & State Management
558 |
559 | ### Core Extension Role
560 |
561 | The Controller acts as the single source of truth for all persistent state. It:
562 | - Manages VSCode global state and secrets storage
563 | - Coordinates state updates between components
564 | - Ensures state consistency across webview reloads
565 | - Handles task-specific state persistence
566 | - Manages checkpoint creation and restoration
567 |
568 | ### Terminal Management
569 |
570 | The Task class manages terminal instances and command execution:
571 |
572 | ```typescript
573 | class Task {
574 | async executeCommandTool(command: string): Promise<[boolean, ToolResponse]> {
575 | // 1. Get or create terminal
576 | const terminalInfo = await this.terminalManager.getOrCreateTerminal(cwd)
577 | terminalInfo.terminal.show()
578 |
579 | // 2. Execute command with output streaming
580 | const process = this.terminalManager.runCommand(terminalInfo, command)
581 |
582 | // 3. Handle real-time output
583 | let result = ""
584 | process.on("line", (line) => {
585 | result += line + "\n"
586 | if (!didContinue) {
587 | sendCommandOutput(line)
588 | } else {
589 | this.say("command_output", line)
590 | }
591 | })
592 |
593 | // 4. Wait for completion or user feedback
594 | let completed = false
595 | process.once("completed", () => {
596 | completed = true
597 | })
598 |
599 | await process
600 |
601 | // 5. Return result
602 | if (completed) {
603 | return [false, `Command executed.\n${result}`]
604 | } else {
605 | return [
606 | false,
607 | `Command is still running in the user's terminal.\n${result}\n\nYou will be updated on the terminal status and new output in the future.`
608 | ]
609 | }
610 | }
611 | }
612 | ```
613 |
614 | Key features:
615 | 1. **Terminal Instance Management**
616 | - Multiple terminal support
617 | - Terminal state tracking (busy/inactive)
618 | - Process cooldown monitoring
619 | - Output history per terminal
620 |
621 | 2. **Command Execution**
622 | - Real-time output streaming
623 | - User feedback handling
624 | - Process state monitoring
625 | - Error recovery
626 |
627 | ### Browser Session Management
628 |
629 | The Task class handles browser automation through Puppeteer:
630 |
631 | ```typescript
632 | class Task {
633 | async executeBrowserAction(action: BrowserAction): Promise {
634 | switch (action) {
635 | case "launch":
636 | // 1. Launch browser with fixed resolution
637 | await this.browserSession.launchBrowser()
638 | return await this.browserSession.navigateToUrl(url)
639 |
640 | case "click":
641 | // 2. Handle click actions with coordinates
642 | return await this.browserSession.click(coordinate)
643 |
644 | case "type":
645 | // 3. Handle keyboard input
646 | return await this.browserSession.type(text)
647 |
648 | case "close":
649 | // 4. Clean up resources
650 | return await this.browserSession.closeBrowser()
651 | }
652 | }
653 | }
654 | ```
655 |
656 | Key aspects:
657 | 1. **Browser Control**
658 | - Fixed 900x600 resolution window
659 | - Single instance per task lifecycle
660 | - Automatic cleanup on task completion
661 | - Console log capture
662 |
663 | 2. **Interaction Handling**
664 | - Coordinate-based clicking
665 | - Keyboard input simulation
666 | - Screenshot capture
667 | - Error recovery
668 |
669 | ## MCP (Model Context Protocol) Integration
670 |
671 | ### MCP Architecture
672 |
673 | The MCP system consists of:
674 |
675 | 1. **McpHub Class**: Central manager in `src/services/mcp/McpHub.ts`
676 | 2. **MCP Connections**: Manages connections to external MCP servers
677 | 3. **MCP Settings**: Configuration stored in a JSON file
678 | 4. **MCP Marketplace**: Online catalog of available MCP servers
679 | 5. **MCP Tools & Resources**: Capabilities exposed by connected servers
680 |
681 | The McpHub class:
682 | - Manages the lifecycle of MCP server connections
683 | - Handles server configuration through a settings file
684 | - Provides methods for calling tools and accessing resources
685 | - Implements auto-approval settings for MCP tools
686 | - Monitors server health and handles reconnection
687 |
688 | ### MCP Server Types
689 |
690 | Cline supports two types of MCP server connections:
691 | - **Stdio**: Command-line based servers that communicate via standard I/O
692 | - **SSE**: HTTP-based servers that communicate via Server-Sent Events
693 |
694 | ### MCP Server Management
695 |
696 | The McpHub class provides methods for:
697 | - Discovering and connecting to MCP servers
698 | - Monitoring server health and status
699 | - Restarting servers when needed
700 | - Managing server configurations
701 | - Setting timeouts and auto-approval rules
702 |
703 | ### MCP Tool Integration
704 |
705 | MCP tools are integrated into the Task execution system:
706 | - Tools are discovered and registered at connection time
707 | - The Task class can call MCP tools through the McpHub
708 | - Tool results are streamed back to the AI
709 | - Auto-approval settings can be configured per tool
710 |
711 | ### MCP Marketplace
712 |
713 | The MCP Marketplace provides:
714 | - A catalog of available MCP servers
715 | - One-click installation
716 | - README previews
717 | - Server status monitoring
718 |
719 | The Controller class manages MCP servers through the McpHub service:
720 |
721 | ```typescript
722 | class Controller {
723 | mcpHub?: McpHub
724 |
725 | constructor(context: vscode.ExtensionContext, outputChannel: vscode.OutputChannel, webviewProvider: WebviewProvider) {
726 | this.mcpHub = new McpHub(this)
727 | }
728 |
729 | async downloadMcp(mcpId: string) {
730 | // Fetch server details from marketplace
731 | const response = await axios.post(
732 | "https://api.cline.bot/v1/mcp/download",
733 | { mcpId },
734 | {
735 | headers: { "Content-Type": "application/json" },
736 | timeout: 10000,
737 | }
738 | )
739 |
740 | // Create task with context from README
741 | const task = `Set up the MCP server from ${mcpDetails.githubUrl}...`
742 |
743 | // Initialize task and show chat view
744 | await this.initClineWithTask(task)
745 | }
746 | }
747 | ```
748 |
749 | ## Conclusion
750 |
751 | This guide provides a comprehensive overview of the Cline extension architecture, with special focus on state management, data persistence, and code organization. Following these patterns ensures robust feature implementation with proper state handling across the extension's components.
752 |
753 | Remember:
754 | - Always persist important state in the extension
755 | - The core extension follows a WebviewProvider -> Controller -> Task flow
756 | - Use proper typing for all state and messages
757 | - Handle errors and edge cases
758 | - Test state persistence across webview reloads
759 | - Follow the established patterns for consistency
760 | - Place new code in appropriate directories
761 | - Maintain clear separation of concerns
762 | - Install dependencies in correct package.json
763 |
764 | ## Contributing
765 |
766 | Contributions to the Cline extension are welcome! Please follow these guidelines:
767 |
768 | When adding new tools or API providers, follow the existing patterns in the `src/integrations/` and `src/api/providers/` directories, respectively. Ensure that your code is well-documented and includes appropriate error handling.
769 |
770 | The `.clineignore` file allows users to specify files and directories that Cline should not access. When implementing new features, respect the `.clineignore` rules and ensure that your code does not attempt to read or modify ignored files.
771 |
--------------------------------------------------------------------------------
/.clinerules/cline-continuous-improvement-protocol.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: Defines Cline's mandatory protocol for self-reflection, persistent knowledge capture using dedicated logs, and continuous improvement of its operational knowledge before task completion.
3 | author: https://github.com/jeanibarz
4 | version: 1.0
5 | tags: ["protocol", "meta", "learning", "reflection", "knowledge-management", "core-behavior"]
6 | globs: ["*"] # This core protocol is always active and applies to all Cline operations.
7 | ---
8 | # Cline Continuous Improvement Protocol
9 |
10 | **Objective:** Ensure Cline proactively learns from tasks, captures knowledge in a structured way, **distills fundamental insights,** refines understanding, and improves efficiency and reliability. This protocol maintains two key files: `memory-bank/raw_reflection_log.md` for initial detailed logging, and `memory-bank/consolidated_learnings.md` for pruned, actionable, long-term knowledge. This is vital for optimal performance and avoiding redundant effort.
11 |
12 | **Core Principle:** Continuous learning and adaptation are **mandatory**. This protocol **must be executed before `attempt_completion`** for tasks with new learning, problem-solving, user feedback, or multiple steps. Trivial mechanical tasks *may* be exempt per higher-level rules; otherwise, execution is default.
13 |
14 | **Key Knowledge Files:**
15 | * **`memory-bank/raw_reflection_log.md`**: Contains detailed, timestamped, and task-referenced raw entries from the "Task Review & Analysis" phase. This is the initial dump of all observations.
16 | * **`memory-bank/consolidated_learnings.md`**: Contains curated, summarized, and actionable insights derived from `raw_reflection_log.md`. This is the primary, refined knowledge base for long-term use. It should be kept concise and highly relevant.
17 |
18 | ---
19 |
20 | ## 1. Mandatory Pre-Completion Reflection & Raw Knowledge Capture
21 |
22 | Before signaling task completion (e.g., via `attempt_completion`), Cline **must** perform the following internal steps:
23 |
24 | ### 1.1. Task Review & Analysis:
25 | * Review the completed task (conversation, logs, artifacts).
26 | * **Identify Learnings:** What new information, techniques, **underlying patterns,** API behaviors, project-specific commands (e.g., test, build, run flags), environment variables, setup quirks, or successful outcomes were discovered? **What core principles can be extracted?**
27 | * **Identify Difficulties & Mistakes (as Learning Opportunities):** What challenges were faced? Were there any errors, misunderstandings, or inefficiencies? **How can these experiences refine future approaches (resilience & adaptation)?** Did user feedback indicate a misstep?
28 | * **Identify Successes:** What went particularly well? What strategies or tools were notably effective? **What were the key contributing factors?**
29 |
30 | ### 1.2. Logging to `memory-bank/raw_reflection_log.md`:
31 | * Based on Task Review & Analysis (1.1), create a timestamped, task-referenced entry in `memory-bank/raw_reflection_log.md` detailing all learnings, difficulties (and their resolutions/learnings), and successes (and contributing factors).
32 | * This file serves as the initial, detailed record. Its entries are candidates for later consolidation.
33 | * *Example Entry in `memory-bank/raw_reflection_log.md`:*
34 | ```markdown
35 | ---
36 | Date: {{CURRENT_DATE_YYYY_MM_DD}}
37 | TaskRef: "Implement JWT refresh logic for Project Alpha"
38 |
39 | Learnings:
40 | - Discovered `jose` library's `createRemoteJWKSet` is highly effective for dynamic key fetching for Project Alpha's auth.
41 | - Confirmed that a 401 error with `X-Reason: token-signature-invalid` from the auth provider requires re-fetching JWKS.
42 | - Project Alpha's integration tests: `cd services/auth && poetry run pytest -m integration --maxfail=1`
43 | - Required ENV for local testing of Project Alpha auth: `AUTH_API_KEY="test_key_alpha"`
44 |
45 | Difficulties:
46 | - Initial confusion about JWKS caching led to intermittent validation failures. Resolved by implementing a 5-minute cache.
47 |
48 | Successes:
49 | - The 5-minute JWKS cache with explicit bust mechanism proved effective.
50 |
51 | Improvements_Identified_For_Consolidation:
52 | - General pattern: JWKS caching strategy (5-min cache, explicit bust).
53 | - Project Alpha: Specific commands and ENV vars.
54 | ---
55 | ```
56 |
57 | ---
58 |
59 | ## 2. Knowledge Consolidation & Refinement Process (Periodic)
60 |
61 | This outlines refining knowledge from `memory-bank/raw_reflection_log.md` into `memory-bank/consolidated_learnings.md`. This occurs periodically or when `raw_reflection_log.md` grows significantly, not necessarily after each task.
62 |
63 | ### 2.1. Review and Identify for Consolidation:
64 | * Periodically, or when prompted by the user or significant new raw entries, review `memory-bank/raw_reflection_log.md`.
65 | * Identify entries/parts representing durable, actionable, or broadly applicable knowledge (e.g., reusable patterns, critical configurations, effective strategies, resolved errors).
66 |
67 | ### 2.2. Synthesize and Transfer to `memory-bank/consolidated_learnings.md`:
68 | * For identified insights:
69 | * Concisely synthesize, summarize, and **distill into generalizable principles or actionable patterns.**
70 | * Add refined knowledge to `memory-bank/consolidated_learnings.md`, organizing logically (by topic, project, tech) for easy retrieval.
71 | * Ensure `consolidated_learnings.md` content is actionable, **generalizable,** and non-redundant.
72 | * *Example Entry in `memory-bank/consolidated_learnings.md` (derived from above raw log example):*
73 | ```markdown
74 | ## JWT Handling & JWKS
75 | **Pattern: JWKS Caching Strategy**
76 | - For systems using JWKS for token validation, implement a short-lived cache (e.g., 5 minutes) for fetched JWKS.
77 | - Include an explicit cache-bust mechanism if immediate key rotation needs to be handled.
78 | - *Rationale:* Balances performance by reducing frequent JWKS re-fetching against timely key updates. Mitigates intermittent validation failures due to stale keys.
79 |
80 | ## Project Alpha - Specifics
81 | **Auth Module:**
82 | - **Integration Tests:** `cd services/auth && poetry run pytest -m integration --maxfail=1`
83 | - **Local Testing ENV:** `AUTH_API_KEY="test_key_alpha"`
84 | ```
85 |
86 | ### 2.3. Prune `memory-bank/raw_reflection_log.md`:
87 | * **Crucially, once information has been successfully transferred and consolidated into `memory-bank/consolidated_learnings.md`, the corresponding original entries or processed parts **must be removed** from `memory-bank/raw_reflection_log.md`.**
88 | * This keeps `raw_reflection_log.md` focused on recent, unprocessed reflections and prevents it from growing indefinitely with redundant information.
89 |
90 | ### 2.4. Proposing `.clinerule` Enhancements (Exceptional):
91 | * The primary focus of this protocol is the maintenance of `raw_reflection_log.md` and `consolidated_learnings.md`.
92 | * If a significant, broadly applicable insight in `consolidated_learnings.md` strongly suggests modifying *another active `.clinerule`* (e.g., core workflow, tech guidance), Cline MAY propose this change after user confirmation. This is exceptional.
93 |
94 | ---
95 |
96 | ## 3. Guidelines for Knowledge Content
97 |
98 | These guidelines apply to entries in `memory-bank/raw_reflection_log.md` (initial capture) and especially to `memory-bank/consolidated_learnings.md` (refined, long-term knowledge).
99 |
100 | * **Prioritize High-Value Insights:** Focus on lessons that significantly impact future performance, **lead to more robust or generalizable understanding,** or detail critical errors and their resolutions, major time-saving discoveries, fundamental shifts in understanding, and essential project-specific configurations.
101 | * **Be Concise & Actionable (especially for `consolidated_learnings.md`):** Information should be clear, to the point, and useful when revisited. What can be *done* differently or leveraged next time?
102 | * **Strive for Clarity and Future Usability:** Document insights in a way that is clear and easily understandable for future review, facilitating effective knowledge retrieval and application (akin to self-explainability).
103 | * **Document Persistently, Refine & Prune Continuously:** Capture raw insights immediately. Systematically refine, consolidate, and prune this knowledge as per Section 2.
104 | * **Organize for Retrieval:** Structure `consolidated_learnings.md` logically. Use clear headings and Markdown formatting.
105 | * **Avoid Low-Utility Information in `consolidated_learnings.md`:** This file should not contain trivial statements. Raw, verbose thoughts belong in `raw_reflection_log.md` before pruning.
106 | * **Support Continuous Improvement:** The ultimate goal is to avoid repeating mistakes, accelerate future tasks, and make Cline's operations more robust and reliable. Frame all knowledge with this in mind.
107 | * **Manage Information Density:** Actively work to keep `consolidated_learnings.md` dense with high-value information and free of outdated or overly verbose content. The pruning of `raw_reflection_log.md` is key to this.
108 |
--------------------------------------------------------------------------------
/.clinerules/cline-for-research.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: Guides the user through a research process using available MCP tools, offering choices for refinement, method, and output.
3 | author: https://github.com/nickbaumann98
4 | version: 1.0
5 | tags: ["research", "mcp", "workflow", "assistant-behavior"]
6 | globs: ["*"]
7 | ---
8 | # Cline for Research Assistant
9 |
10 | **Objective:** Guide the user through a research process using available MCP tools, offering choices for refinement, method, and output.
11 |
12 | **Workflow:**
13 |
14 | 1. **Initiation:** This rule activates automatically when it is toggled "on" and the user asks a question that appears to be a research request. It then takes the user's initial question as the starting `research_topic`.
15 | 2. **Topic Confirmation/Refinement:**
16 | * Confirm the inferred topic: "Okay, I can research `research_topic`. Would you like to refine this query first?"
17 | * Provide selectable options: ["Yes, help refine", "No, proceed with this topic"]
18 | * If "Yes": Engage in a brief dialogue to refine `research_topic`.
19 | * If "No": Proceed.
20 | 3. **Research Method Selection:**
21 | * Ask the user: "Which research method should I use?"
22 | * Provide options:
23 | * "Quick Web Search (Serper MCP)"
24 | * "AI-Powered Search (Perplexity MCP)"
25 | * "Deep Research (Firecrawl MCP)"
26 | * Store the choice as `research_method`.
27 | 4. **Output Format Selection:**
28 | * Ask the user: "How should I deliver the results?"
29 | * Provide options:
30 | * "Summarize in chat"
31 | * "Create a Markdown file"
32 | * "Create a raw data file (JSON)"
33 | * Store the choice as `output_format`.
34 | * If a file format is chosen, ask: "What filename should I use? (e.g., `topic_results.md` or `topic_data.json`)" Store as `output_filename`. Default to `research_results.md` or `research_data.json` if no name is provided.
35 | 5. **Execution:**
36 | * Based on `research_method`:
37 | * If "Quick Web Search":
38 | * Use `use_mcp_tool` with a placeholder for the Serper MCP `search` tool, passing `research_topic`.
39 | * Inform the user: "Executing Quick Web Search via Serper MCP..."
40 | * If "AI-Powered Search":
41 | * Use `use_mcp_tool` for `github.com/pashpashpash/perplexity-mcp` -> `search` tool, passing `research_topic`.
42 | * Inform the user: "Executing AI-Powered Search via Perplexity MCP..."
43 | * If "Deep Research":
44 | * Use `use_mcp_tool` for `github.com/mendableai/firecrawl-mcp-server` -> `firecrawl_deep_research` tool, passing `research_topic`.
45 | * Inform the user: "Executing Deep Research via Firecrawl MCP... (This may take a few minutes)"
46 | * Store the raw result as `raw_research_data`.
47 | 6. **Output Delivery:**
48 | * Based on `output_format`:
49 | * If "Summarize in chat":
50 | * Analyze `raw_research_data` and provide a concise summary in the chat.
51 | * If "Create a Markdown file":
52 | * Determine filename (use `output_filename` or default).
53 | * Format `raw_research_data` into Markdown and use `write_to_file` to save it.
54 | * Inform the user: "Research results saved to ``."
55 | * If "Create a raw data file":
56 | * Determine filename (use `output_filename` or default).
57 | * Use `write_to_file` to save `raw_research_data` (likely JSON).
58 | * Inform the user: "Raw research data saved to ``."
59 | 7. **Completion:** End the rule execution.
60 |
61 | ---
62 | **Notes:**
63 |
64 | * This rule relies on the user having the Perplexity Firecrawl, and Serper MCP servers connected and running.
65 | * The "Quick Web Search" option is currently hypothetical and would require a Serper MCP server to be implemented and connected.
66 | * Error handling (e.g., if an MCP tool fails) is omitted for brevity but should be considered for a production rule.
67 |
--------------------------------------------------------------------------------
/.clinerules/cline-for-slides.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: Provides guidelines and best practices for creating and working with Slidev presentation projects.
3 | author: https://github.com/nickbaumann98
4 | version: 1.0
5 | tags: ["slidev", "slides", "markdown", "vue", "vite", "guide"]
6 | globs: ["slides.md", "**/slides.md", "*.vue", "layouts/**/*.vue", "components/**/*.vue"]
7 | ---
8 | # Slidev Project Instructions
9 |
10 | This document provides guidelines for working with Slidev projects. Slidev is a Markdown-based presentation tool powered by Vue and Vite.
11 |
12 | ## Core Concepts & Structure
13 |
14 | 1. **Entry Point**: The main presentation content is typically in `http://slides.md`.
15 | 2. **Slide Separation**: Slides are separated by `---` on a new line.
16 | 3. **Frontmatter/Headmatter**:
17 | * YAML blocks at the beginning of the file (`--- ... ---`) configure the deck (headmatter) or individual slides (frontmatter).
18 | * Headmatter (first block) applies globally (e.g., `theme`, `title`, `addons`).
19 | * Frontmatter configures specific slides (e.g., `layout`, `background`, `class`, `transition`, `clicks`).
20 | * **YAML Quoting:** Prefer double quotes (`"..."`) for strings containing single quotes (`'`) to avoid parsing errors (e.g., `title: "My Deck's Title"`).
21 | 4. **Layouts**:
22 | * Define the structure of slides. Specified via `layout:` in frontmatter.
23 | * Default layout for the first slide is `cover`, others are `default`.
24 | * Custom layouts are placed in the `layouts/` directory as `.vue` files. Use `` for default content and named slots (``) for specific sections.
25 | 5. **Components**:
26 | * Vue components can be used directly in Markdown (e.g., ``).
27 | * Components are auto-imported from:
28 | * Slidev built-ins (`@slidev/client/builtin/`).
29 | * The active theme.
30 | * Installed addons.
31 | * The local `components/` directory.
32 | * Custom components go in the `components/` directory as `.vue` files.
33 | 6. **Styles**:
34 | * [UnoCSS](https://unocss.dev) is built-in for utility-first styling. Apply classes directly in Markdown or components.
35 | * Global styles can be added in the `styles/` directory (e.g., `styles/index.css`).
36 | * Scoped styles for a specific slide can be added using `` within the slide's Markdown.
37 | 7. **Assets**:
38 | * Static assets (images, videos) can be placed in the `public/` directory and referenced with absolute paths starting with `/` (e.g., `background: /my-image.png`).
39 | * Relative paths (e.g., `./image.png`) work for standard Markdown image syntax (``) but might break in frontmatter or components after building. Prefer the `public/` directory method for reliability.
40 | 8. **Notes**:
41 | * Presenter notes are added as HTML comments (``) at the *very end* of a slide's Markdown content.
42 | * Notes support Markdown formatting.
43 |
44 | ## Key Features & Syntax
45 |
46 | 1. **Code Blocks**:
47 | * Use standard Markdown fenced code blocks (e.g., ` ```ts ... ``` `).
48 | * Syntax highlighting is provided by Shiki.
49 | * Supports line highlighting (`{1,3-5}`), line numbers (`{lines:true}`), Monaco editor (`{monaco}`), diffs (`{monaco-diff}`), code imports (`<<< @/path/to/file.js#region {lines=...}`). Refer to the Syntax Guide for details.
50 | 2. **Animations (Clicks)**:
51 | * Use `` component or `v-click` directive to reveal elements step-by-step.
52 | * `v-after` reveals elements simultaneously with the previous `v-click`.
53 | * `.hide` modifier (e.g., `v-click.hide`) hides elements instead of showing them.
54 | * `` component applies `v-click` to its children (useful for lists).
55 | * Control timing with `at="..."` (e.g., `v-click="3"` for absolute click 3, `v-click="'+2'"` for 2 clicks after the previous relative element).
56 | * Specify enter/leave ranges: `v-click="[2, 5]"` (visible from click 2 up to, but not including, 5).
57 | * Override total clicks per slide with `clicks: N` in frontmatter.
58 | 3. **Motion (VueUse Motion)**:
59 | * Use the `v-motion` directive for element transitions (e.g., `:initial="{ x: -80 }" :enter="{ x: 0 }"`).
60 | * Can be triggered by clicks using `:click-N` attributes (e.g., `:click-1="{ y: 30 }"`).
61 | 4. **Slide Transitions**:
62 | * Set in headmatter (`transition: slide-left`) for global effect or frontmatter for specific slides.
63 | * Built-in transitions: `fade`, `fade-out`, `slide-left`, `slide-right`, `slide-up`, `slide-down`, `view-transition`.
64 | * Specify different forward/backward transitions: `transition: slide-left | slide-right`.
65 | 5. **Diagrams**: Supports Mermaid (` ```mermaid ... ``` `) and PlantUML (` ```plantuml ... ``` `).
66 | 6. **LaTeX**: Use `$` for inline math (`$a^2+b^2=c^2$`) and `$$` for block math.
67 | 7. **Global Context**: Access runtime info like `$nav` (navigation controls), `$clicks` (current click count), `$page` (current slide number), `$frontmatter`, `$slidev.configs` within components or directly in Markdown using `{{ }}`. Use composables like `useNav()` from `@slidev/client` in `