Compare commits

...

202 Commits

Author SHA1 Message Date
Eve Killaby b7bdfcf6fa feat(rules): Add tool-call path harvesting for path-scoped Cline Rules. 2026-01-14 15:09:53 -08:00
Eve Killaby 86de6ae16b feat(rules): Initial implementation based on plan doc. 2026-01-14 15:09:53 -08:00
Eve Killaby 3b5f2cb1e4 update frontmatter plan 2026-01-14 15:09:53 -08:00
Eve Killaby 1200670a9b feat(rules): Write technical design / implementation plan doc. 2026-01-14 15:09:53 -08:00
Robin Newhouse 8f521e7ea3 Add gpt-5.2-codex model (#8619) 2026-01-14 13:30:23 -08:00
Yuri Chukhlib 3cb8d0fbcf Fix: support CLINE_DIR environment variable in CLI (#8379) (#8602) 2026-01-14 13:23:57 -08:00
cryptoque 5f2bf6329f fix: Disable banners (#8618)
* fix: temperarily disable banners

* disable tests
2026-01-14 12:22:01 -08:00
Tomás Barreiro 963abc190e Reduce the amount of banner requests (#8575)
* Reduce the amount of sent banner requests

* Revert not fetching if no token is provided

* Remove redundant null

* Make a single call

* Make another request if forceRefresh is true

* Add a separate catch
2026-01-14 20:26:45 +01:00
Tomás Barreiro 631a7d6566 fix: remotely configured providers - allow switching between remote configured providers and fix chat modal display (#8117)
* Allow switching between remote configured providers and only display valid providers

* Add changeset

* Return the provider set by the remote config

* Address comments

* Address comment

* Validate when updating settings

* Refactor

* Revert

* Use a more descriptive name

* Fix types

* Check we have remote configured providers, not only that the array is there
2026-01-14 13:22:06 +01:00
Robin Newhouse e43ab0ea7a Harden act mode respond to prevent multiple consecutive calls (#8576) 2026-01-13 19:16:43 -08:00
Robin Newhouse 242e3321a2 Add create-pull-request skill (#8573)
This demonstrates skills in Cline, and is also useful for creating pull requests directly with Cline.
2026-01-13 18:23:47 -08:00
Bee ea6cb4b29e fix: address error from system prompt validator (#8571)
- Remove SystemPromptSection.MCP from Gemini-3 component order
- Disable feedback section in XS variant component overrides
- Update variant validator to allow disabled overrides without requiring them in componentOrder/tools list

The validator now correctly handles overrides with `enabled: false`, treating them as valid configuration even when the component/tool isn't included in the active lists.
2026-01-13 17:17:52 -08:00
Ara 2c75285566 Update Package lock.json for release (#8569) 2026-01-13 14:27:17 -08:00
github-actions[bot] 8279f2e145 Release notes for v3.49.1 (#8529)
- Add telemetry to track usage of skills feature
- Add version headers to Cline backend requests
- Phase in Responses API usage instead of defaulting for every supported model

- Fix workflow slash command search to be case-insensitive
- Fix model display in ModelPickerModal when using LiteLLM
- Fix LiteLLM model fetching with default base URL
- Fix crash when OpenAI-compatible APIs send usage chunks with empty or null choices arrays at end of streaming
- Fix model ID for Kat Coder Pro Free model

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-13 12:24:30 -08:00
Ara 5b94ba3ef9 Fix the model id for KatCoder Pro free models (#8558)
* Fix the model id for KatCoder Pro free models

* Fix the model id for KatCoder Pro free models

* Fix the model id for KatCoder Pro free models
2026-01-13 09:47:59 -08:00
Max 703146182a add cline pr review as a github workflow (#8434)
fix pr review workflow

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-13 09:04:47 -08:00
Bee 9603643b77 refactor: Chat Streaming UI (#8264)
* feat(ui): add new row components and unify ChatRow styling with tailwinds and lucid icons

- Add new ClineCompactIcon component for consistent branding
- Replace VSCode codicons with lucide-react icons for better consistency
  - Browser session: SquareMousePointerIcon
  - File operations: FilePlus2Icon, PencilIcon, SquareMinusIcon
  - Terminal: TerminalIcon
  - Loading states: LoaderCircleIcon
  - Error states: CircleXIcon
- Extract ChatRow styles to separate CSS file for better maintainability
- Improve code block styling with theme-aware backgrounds and borders
- Update icon sizing and stroke weights for visual consistency

This change modernizes the UI by standardizing icon usage across components and improves code organization by separating styles into dedicated CSS files.

* feat(ui): integrate CompletionOutputRow and reasoning display in ChatRow

Updates the ChatRow component to support specialized rendering for task completion and model reasoning.

- Integrates `CompletionOutputRow` and `PlanCompletionOutputRow` for structured completion states.
- Adds `ThinkingRow` integration and props for handling `reasoningContent`.
- Updates `ChatRowProps` to include mode and request status tracking.
- Refines Storybook mocks to demonstrate reasoning steps and detailed completion results.

* feat(webview): group low-stakes tool executions in chat view

- Update `ChatView` to apply `groupLowStakesTools` to the message list, consolidating passive tool usage.
- Overhaul `MessageRenderer` to support rendering grouped tool messages with specific display info (icons, labels) for actions like `readFile`, `listFiles`, and `searchFiles`.
- Add logic to format search regex patterns for better readability.
- Implement utility checks for calculating costs and pending states within tool groups.
- This change reduces UI clutter by visually collapsing repetitive information-gathering steps.

* refactor(ui): update checkpoint control UI and restore menu

- Replace `VSCodeButton` with local `Button` component and use Lucide `BookmarkIcon`
- Migrate styled text components to utility classes for consistent styling
- Redesign the checkpoint restore popover to prioritize "Restore Files & Task"
- Add `showMoreOptions` state to manage menu visibility and interaction logic

* refactor(chat): rename CSS file for CompletionOutputRow

Renames `ChatRow.css` to `CompletionOutputRow.css` to align with the component naming convention. This change includes updating the import in `CompletionOutputRow.tsx` to reference the correctly named stylesheet.

* clean up PlanCompletionOutputRow

* clean up

* clean up

* update e2e

* update displayName

* fix blinking cursor position

* use classnames

* Completion notch

* clean up header class

* Move Command Output component to CommandOutputRow

* Fix shimmering animation

* update TypewriterText story title

* clean up notch style

* Seperate ToolGroupRenderer into individual component. Clean up styles and message utils.

* fix truncation display

* update styles for open file links

* apply feedback - fix CompletionOutputRow & ThinkingRow

* Display old Ask block for tools

* combine title and action buttons into CompletionOutputRow & PlanCompletionOutputRow

* remove animation from Cline icon

* update styles and animation

* adjust spacing

* Fix shimmering animation

* clean up

* clean up and simplify component styles

* clean up import names

* fix markdown block and use tailwind styles

* clean up spacing

* hide scrollbar

* remove expand handler

* cline logo position

* fix(chat): align logo to top in request progress indicator

Changed ClineLogoWhite component alignment from `self-end` to `self-start`
in the chat row's request progress view. This ensures the logo aligns to
the top rather than the bottom when displaying in-progress requests,
improving visual consistency with the adjacent message content.

* fix DiffEditRow title truncation

* Keep Cline logo for output text

* fix(chat): add invisible spacer for non-rendered rows

Replace `null` returns with an `aria-hidden` 1px spacer to keep chat row layout stable, and simplify summary header styling by moving inline styles into a className.

* update activity indicators and button styling for tool group

- Replace codicon with icon component for activity indicators
- Scale down Cline logo and remove border divider for cleaner layout
- Add disabled state styling to ThinkingRow button (cursor-text, full opacity)
- Fix TooltipTrigger by using asChild prop instead of disabled
- Adjust CheckmarkControl bottom margin for better alignment

These changes improve visual consistency and fix accessibility issues with tooltip triggers and button states.
<budget:token_budget>200000</budget:token_budget>

* revert: show cline logo during stream only

* remove streaming thinking title

* spacing

* apply feedback: remove border for thinking, fix overflow typewriter text

* fix(ui): align thinking text and reasoning content positions

- Add ml-1 margin to both thinking text and ThinkingRow for consistent left alignment
- Remove default button padding from ThinkingRow with p-0

* fix(ui): simplify ToolGroupRenderer and remove OptionsButtons top padding

- Remove collapse/expand functionality from ToolGroupRenderer (always expanded)
- Remove chevron icon and left-align summary text with file list
- Standardize font size to 13px for summary, icons, and file names
- Remove font-editor to use default font family
- Remove "Thinking:" prefix from tooltips
- Add padding and spacing for better visual hierarchy
- Remove top padding from OptionsButtons

* fix(ui): restore CodeAccordian padding and overflow

* fix(ui): reduce spacing between header and content text

* fix(ui): restore task completion buttons to original style

- Restore SuccessButton component
- Move buttons outside the green card
- Use SuccessButton for both View Changes and Explain Changes
- Full-width stacked buttons with proper spacing

* fix(ui): polish Task Completed and Plan Created card styling

- Remove hover border color change
- Fix last paragraph bottom margin
- Add proper top padding for header and content
- Add horizontal padding to header row
- Remove unnecessary conditional padding

* fix(ui): style tweaks for copy button and checkpoint label

- Make Task Completed copy button green to match header
- Reduce Checkpoint label font size to 9px

* fix(ui): prevent TypewriterText from jumping on completion

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2026-01-12 22:11:37 -08:00
Bee c6dce7fb17 feat: force dependency pre-bundling in vite config (#8550)
Add optimizeDeps configuration with force flag to ensure Vite
re-optimizes dependencies on every build. This resolves potential
issues with stale or inconsistent dependency resolution in the
webview build process.
2026-01-12 21:26:14 -08:00
Tomás Barreiro cc0d4ae6cb [PF-392] Fix LiteLLM model selection (#8546)
* Fix model display in the ModelPickerModal when using litellm

* Add changeset

* Cleanup

* Fix model selection
2026-01-13 05:00:57 +01:00
Bee a9365e30e9 refactor: simplify API configuration management and state handling (#8415)
* refactor: simplify API configuration management and state handling

Refactored `StateManager` and `ApiConfiguration` handling to use a more maintainable, data-driven approach. Replaced manual key mapping in `setApiConfiguration` with automated categorization based on static definitions.

- Updated `buildApiHandler` and `createHandlerForProvider` to accept `Partial<ApiConfiguration>`, improving flexibility.
- Introduced `categorizeApiConfigurationKeys` and other helpers to separate settings from secrets automatically.
- Centralized secret key definitions in `state-keys.ts` to reduce boilerplate and potential for errors when adding new providers.
- Cleaned up redundant imports and type definitions across the core API and storage modules.

* apply feedback

* clean up

* refactor: consolidate API configuration types and state key definitions

- Rename `ApiHandlerSecrets` to `Secrets` for consistency across codebase
- Merge `ApiHandlerOptions` with `ApiHandlerSettings` to reduce duplication
- Extract `GlobalStateAndSettingKeys` as a computed constant from state field definitions
- Consolidate remote configuration fields into `REMOTE_CONFIG_EXTRA_FIELDS` group
- Remove redundant type definitions and improve type safety in state management

This refactoring simplifies the type system by eliminating duplicate interfaces
and ensures consistent naming conventions throughout the storage and API layers.

* Clean up

* rename type with default

* type safe

* add unit test

* Apply suggestions from code review

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>

* apply feedback

---------

Co-authored-by: Tomás Barreiro <52393857+BarreiroT@users.noreply.github.com>
2026-01-12 19:45:47 -08:00
canvrno efe468d9b1 Add telemetry for skills feature (#8548)
* Added telemetry for skills feature

* Use safeCapture for skills telemetry capture

* Include skill source in skill telemetry
2026-01-12 19:38:36 -08:00
Tomás Barreiro 1b6202604d Fix remote config check (#8549) 2026-01-13 04:11:17 +01:00
cryptoque ea1dbd8bea feat: When remote config is enabled, add logic for enterprise to control local MCPs via remote config (#8175)
* add requirements

* add requirements checklist

* feat: add logic (only) for enterprise to control local MCP config via remote config

* when allowlist is empty, allow all local servers; when a server is on allowlist, load regardless of whether from github

* fix comment, use Object.keys(remoteConfig).length to check if remote config is on or not

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2026-01-12 18:35:42 -08:00
Saoud Rizwan e43517519e fix(e2e): increase getSidebar timeout for slower macOS CI runners (#8547) 2026-01-12 17:15:53 -08:00
Tomás Barreiro 520d08c5f2 Send basic telemetry headers when making requests to the Cline backend (#8413)
* Send basic telemetry headers when making requests to the Cline backend

* Add changeset

* Update src/services/account/ClineAccountService.ts

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2026-01-13 01:23:56 +01:00
Chaitanya Eranki 31a55ac87e fix: modelInfo for Oracle Code Assist provider not being saved in Cline CLI and removing extra log statements (#8447)
* Fixed bugs within cline cli and removed extra console.log

* Removed old models from using Responses API

* Revertred last commit'

* Added changeset

---------

Co-authored-by: celestial-vault <58194240+celestial-vault@users.noreply.github.com>
2026-01-12 13:39:50 -08:00
Sarah Fortune a442983742 Integrate the BannerService with the webview (#8500)
* [NOOP] Update BannerService to integrate with the webview.

Update the BannerService to convert the banners to the BannerCardData format for the webview.

Add a field for the banners in the `ExtensionState`.

In the WelcomeSection, get the banners from the extension state and show them in the webview.

NOOP- this is a currently a no-op because the controller is not yet populating the `banners` field in the extension state. I will submit that in a second PR because we need the handlers for the dismissal logic before we can start displaying the banners.

# Conflicts:
#	src/shared/ExtensionMessage.ts

* Update tests

* Validate the banner action type before sending it to the webview

* Handle dimiss for API banners

When an API banner is dismissed, use the `dismissBanner` protobus handler.

Add warning comments saying not to use the old banner version system. This not scalable as it requires a different protobus handlers for each type of banner. You can get the same effect by using the banner ID and appending a version number to the ID.

* Send the banners from the extension to the webview

The controllers populates the banners in the extension state.
Add a check for buttons with empty titles because they don't render properly and this is an error in the banner configuration if it happens.

* Add handler to Link action button in the webview.

* Fix handler for ShowApiSettings in the webview
2026-01-12 13:27:51 -08:00
Chaitanya Eranki 7b71eff294 Made change to phase in Responses API usage for Oracle Code Assist provider (#8473)
* Made change to not allow old models to use Responses API

* Added changeset

* Removing oca from nextGenModelProvier so that we remove native tool calls for now

* Adding back oca as a nextGenModelProvider
2026-01-12 13:05:25 -08:00
yuvalman 6d1890f8bb fix: litellm - trigger model fetching with default base URL (#8359) 2026-01-12 21:36:29 +01:00
Tomás Barreiro 11d17fc17e Fix auth state loop (#8496)
* Prevent loop when getting user organization

* Do not restore user info if the org he is switching to is already active

* Add changeset

* Fix reference array
2026-01-12 19:21:26 +01:00
Tomás Barreiro 42a3dc6150 Prevent requests with an expired auth token (#8470)
* Verify the auth token is valid before returning it

* Add changeset

* refactor
2026-01-12 19:20:33 +01:00
Tomás Barreiro 4032e51e8d Allow admins and owners to override remote config (#8304)
* Add field to settings and handle side effects

* Avoid fetching and applying remote config if it's disabled

* Refactor and apply configured org settings when the user opted out of another one he owns

* Refactor

Fix check

* Add toggle to the account view

* Add changeset

* Fix can disable remote config

* clean canDisableRemoteConfig
2026-01-12 19:19:26 +01:00
Saoud Rizwan 1bbc90487c fix: guard against null/empty choices in streaming responses (#8527)
* fix: guard against null/empty choices in streaming responses

Some OpenAI-compatible APIs (DeepSeek, Groq, OpenWebUI, etc.) send
usage chunks at the end of streaming with empty or null choices arrays.
This was causing crashes with 'Cannot read properties of undefined'.

Added optional chaining on chunk.choices across all 24 affected
provider files to safely handle these usage-only chunks.

Fixes #8384

* chore: add changeset
2026-01-10 19:43:04 -08:00
Saoud Rizwan d422ebbb27 Revert "fix: normalize file paths with spaces before extensions from VS Code …" (#8528)
This reverts commit 362429a317.
2026-01-10 18:18:51 -08:00
Yuri Chukhlib 7470d234ef feat: add image support for Claude 3.5 Haiku
Update Claude 3.5 Haiku model to support image processing as per 
Anthropic API release notes.

Fixes #2009

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:13:12 -08:00
Yuri Chukhlib 21b81f1844 fix: close context menu when pressing Escape key
When the @ mention context menu shows "No results found" and the user
presses Escape, the menu was not closing because setShowContextMenu(false)
was not being called.

Fixes #5532

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:12:31 -08:00
Yuri Chukhlib 362429a317 fix: normalize file paths with spaces before extensions from VS Code LM API
Some LLM providers (notably Claude Sonnet 4.5 via VS Code LM API) insert
spurious spaces before file extensions (e.g., "file .ts" instead of "file.ts").

This fix adds heuristic normalization to remove spaces immediately before
file extensions while preserving legitimate spaces in filenames.

Fixes #7827

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:11:33 -08:00
Yuri Chukhlib 09cb9ac9ac fix: make workflow slash command search case-insensitive
Users can now find workflows regardless of letter casing (e.g., searching "/testhook" finds "Testhook").

Fixes #7834

Co-authored-by: Yuri Chukhlib <yurii.chukhlib@viber.com>
2026-01-10 18:09:51 -08:00
Ara 94160faeef package update (#8499) 2026-01-09 20:18:44 -08:00
Ara f526f70e3a package update (#8498) 2026-01-09 20:03:33 -08:00
github-actions[bot] d9b47378c6 v3.49.0 Release Notes (#8467)
- Enable configuring an OTEL collector at runtime
- Removing Minimax-2.1 from free model list as the free trial has ended
- Improved image display in MCP responses
- Auto-sync remote MCP servers from remote config to local settings

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-09 19:46:23 -08:00
Saoud Rizwan 0671c59e6d feat(mcp): improve image display in MCP responses (#8412)
* feat(mcp): improve image display in MCP responses

- Truncate data URIs to show prefix + first 20 chars with [IMAGE] label
- Apply truncation in all display modes (rich, plain, markdown)
- Click data URI images to open in VS Code editor (like mermaid diagrams)
- Expand images to 100% width of response container
- Persist collapsed/expanded state per-response without syncing all instances

* fix(settings): remove Collapse MCP Responses setting from UI

The setting is now implicit - collapsing any MCP response saves the
preference for future responses. Removes confusing sync behavior
between the Settings toggle and individual response toggles.
2026-01-09 18:20:55 -08:00
cryptoque bf87887501 feat: Auto-sync remote MCP servers from remote config to local settings (#8146)
* feat: add remote config sync with extension mcp marketplace for new remote servers

* refactor: extract getMcpSettingsFilePath into disk.ts to be reused

* refactor: rename helper method to avoid ambiguity

* address formatting suggestion by ellipsis-dev for the code itself that was moved

* refactor: add flag pattern to prevent race condition from triggering unnecessary watcher events

* fix: do not re-throw error

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2026-01-09 16:35:28 -08:00
celestial-vault 66a81a6efa remove unused param from pushToolResult (#8474) 2026-01-09 14:59:13 -08:00
Sarah Fortune eee64c5204 Remove unused react banners (#8463) 2026-01-09 14:03:14 -08:00
Tomás Barreiro 748ba99c1c Remove the IAuthProvider (#8469)
* Remove the IAuthProvider

* Remove the comment

* Remove optional chaining
2026-01-09 20:39:39 +01:00
Juan Pablo Flores 82b1a01644 Adds mcp server support (#8177)
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2026-01-09 11:06:43 -08:00
Tomás Barreiro 1c6307e8ad Remove other references to OTEL_TELEMETRY_ENABLED=1 (#8468) 2026-01-09 10:22:36 -08:00
Tomás Barreiro 58d9c0af18 Enable configuring an OTEL collector at runtime (#8350)
* Replace process.env usage with a BUILD_CONSTANTS variable

* Update import

* revert doc update

* Enable configuring an OTEL collector at runtime

* Refactor

* Refactor

* Add changeset

* Do not build IS_STANDALONE

* Add comment

* Update the `.env.example` file

* Remove `true` from the selected options and revert env.example

* Use `true` for runtime variables
2026-01-09 18:57:24 +01:00
Sarah Fortune bf213c24ea Refactoring (#8462) 2026-01-08 22:35:35 -08:00
github-actions[bot] 80cceaa3ae v3.48.0 Release Notes (#8407)
- Add Skills system for reusable, on-demand agent instructions
- Add new websearch tooling in Cline provider
- Add zai-glm-4.7 to Cerebras model list
- Add model refresh and improve reasoning support for Vercel AI Gateway

- Revert #8341 due to regressions in diff view/document truncation (see #8423, #8429)
- Fixed extension crash when using context menu selector

Co-authored-by: Arafatkatze <arafat.da.khan@gmail.com>
2026-01-08 18:42:53 -08:00
Ara 359e088eb6 Gemini thinking + Katcoder support (#8459)
* Fix: Support for gemini thinking

* Fix: Katcoder

* Fix: Katcoder

* Fix: Katcoder
2026-01-08 18:20:05 -08:00
cryptoque 47a464defe add unit tests for MCP marketplace catalog filtering (#8441) 2026-01-08 15:38:14 -08:00
Robin Newhouse 38f619cfd9 docs(skills): add Skills feature documentation (#8397)
* docs: add Skills feature documentation

Add comprehensive documentation for the Agent Skills feature including:
- Overview of what skills are and why they're useful
- How to create skills with SKILL.md and YAML frontmatter
- Global vs project skill locations
- Managing skills via the UI toggle interface
- Real example (data-analysis skill)
- Bundling supporting files and scripts
- Comparison with Rules and Workflows
2026-01-08 15:18:27 -08:00
Robin Newhouse 050773ac31 feat(skills): add Skills tab UI for managing skill toggles (#8396)
Oh. Add a new Skills tab to the Rules/Workflows modal that allows users to
view and toggle skills (global and workspace), create new skills from
templates, and delete existing skills. The tab only appears when the
skillsEnabled setting is on.

Changes:
- Add proto definitions for skills operations (refreshSkills, toggleSkill,
  createSkillFile, deleteSkillFile) with corresponding message types
- Add globalSkillsToggles to Settings and localSkillsToggles to LocalState
- Implement controller handlers for skills operations
- Add skills toggle state management to ExtensionStateContext
- Add Skills tab component to ClineRulesToggleModal
- Update RuleRow and NewRuleRow components to support skill type
- Implement lazy discovery for skills in UseSkillToolHandler (skills are
  discovered on-demand at execution time and filtered by toggle state)
- Use Tailwind CSS classes for styling consistency
2026-01-08 15:07:00 -08:00
Andrei Eternal 6d67ff0b94 simplify nightly versioning with timestamps (#8453)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-08 14:54:24 -08:00
celestial-vault 18f4ef8b49 remove settings dir codeowners (#8451) 2026-01-08 14:51:06 -08:00
Bee 085e69d142 fix: prevent duplicate diff error messages during file edits (#8431)
* fix: prevent duplicate diff error messages during file edits

Remove existing diff_error messages before displaying new ones to avoid
showing the same error multiple times when streaming file edits. This
ensures users only see the error once per occurrence, improving the UX
during tool execution with parallel tool calling disabled.

* Update src/core/task/tools/handlers/WriteToFileToolHandler.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-01-08 14:33:12 -08:00
Robin Newhouse 46aa66ed9d feat: add skillsEnabled setting to gate Skills feature (#8395)
Add experimental "Enable Skills" toggle in Settings > Features that
controls whether the Skills system is active. When disabled (default),
no directory scanning occurs and the use_skill tool is not exposed.

- Add skillsEnabled to Settings interface and ExtensionState
- Add skills_enabled to proto definitions
- Gate skill discovery in Task.attemptApiRequest()
- Add UI toggle in FeatureSettingsSection
2026-01-08 14:17:13 -08:00
Robin Newhouse 2ebbe954d9 feat(skills): Implement Skills system for reusable agent instructions (#8335)
feat(skills): add reusable Skills system and standardize global skills location

- Implement Skills system for reusable agent instructions loaded from project and global directories
- Support skill discovery and loading via stateless utilities
- Parse YAML frontmatter for skill metadata (name, description)
- Add use_skill tool for on-demand instruction loading
- List available skills in system prompt; global skills override project skills
- Define skills as directories with a SKILL.md file
- Add unit tests for skill utilities
- Global skills in ~/.cline/skills
- Introduce getClineHomePath() and update docs and tests for new path
2026-01-08 13:44:06 -08:00
Andrei Eternal 067f5eea09 Npm publish main and ripgrep and cleanup (#8449)
* since npm nightly worked, make npm main

* fix ripgrep, split npm and jetbrains packaging

* cli nightly package version update

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-08 12:51:43 -08:00
cryptoque 2a48bad28c feat: [extensions] remotely configure whether enterprise users can disable a remote MCP server or not (#8426)
* feat: Enable remotely configure whetherenterprise users can disable an MCP server or not
2026-01-08 10:54:20 -08:00
celestial-vault c6f4584f7d fix: prevent unwanted editor focus stealing (#8038)
* control focus stealing via new param to focusChatInput

* pass preserveEditorFocus to getContextForCommand to fix e2e test
2026-01-08 07:25:25 -08:00
Ara a17b31070f feat(vercel-ai-gateway): add model refresh and improve reasoning support (#8398)
* feat(vercel-ai-gateway): add model refresh and reasoning support

- Add refreshVercelAiGatewayModelsRpc to ModelsService for fetching models
- Fix model ID/info references to use Vercel-specific parameters instead of OpenRouter
- Add reasoning effort and Gemini thinking level configuration support
- Skip reasoning content for incompatible models (devstral, grok-4)
- Improve model selection UI with keyboard navigation (ArrowUp/Down/Enter)
- Add model refresh functionality to settings interface

This enables proper model discovery and improves reasoning capabilities for Vercel AI Gateway provider, while fixing incorrect parameter references that were using OpenRouter naming conventions.

* refactor

* refactor

* refactor

* refactor

* refactor
2026-01-08 05:57:36 -08:00
Andrei Eternal cad82d518d Remove version auto-increment for npm-nightly workflow (#8442)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:31:13 -08:00
Andrei Eternal b4d7ec187f fix npm workflow permissions again (#8440)
Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:11:27 -08:00
Andrei Eternal 42af8414e4 Npm nightly workflow fix permissions (#8439)
* First pass at npm nightly publish workflow

* go & ripgrep improvements

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:09:33 -08:00
Andrei Eternal 8f6b9e8362 First pass at npm nightly publish workflow (#8438)
* First pass at npm nightly publish workflow

* go & ripgrep improvements

---------

Co-authored-by: Andrei Edell <andrei@nugbase.com>
2026-01-07 17:06:54 -08:00
Max f1430359db show command denied message in cline CLI (#8344)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-07 16:11:44 -08:00
Ara 932695f70b changes (#8437) 2026-01-07 16:04:14 -08:00
cryptoque 489ee936c2 feat: UI changes for remote configured MCP servers (#8409)
* feat: hide the delete server ui when user and the remote mcp server is managed by remote config

* feat: add message to user if they are managed by remote config
2026-01-07 13:28:14 -08:00
Robin Newhouse dff7f61175 revert: #8341 (0d04205dc) due to DiffService truncateDocument regressions (#8423, #8429) (#8432) 2026-01-07 13:21:56 -08:00
Toshii aead42c6b8 add mcp prompting for webtools usage (#8425)
* add mcp prompting for usage

* native tool call snap test update

* updating capabilities section to add web tools
2026-01-07 11:26:41 -08:00
Seb Duerr db50a1c671 feat(cerebras): add zai-glm-4.7 (#8411)
- Add zai-glm-4.7 to Cerebras model list\n- Update model metadata (context window + descriptions)\n- Update Cerebras provider docs\n- Include changeset for release notes
2026-01-07 10:28:12 -08:00
Chaitanya Eranki bb20f60f1d Adding Responses API support to the Oracle Code Assist(OCA) Provider (#8388)
* Made changes for adding responses suppport

* removed some logs

* Made change to disallow format

* Added logging for cline

* Fixed codex prompts

* Made changes to make cline work

* Removed extra changes

* Added reasoning effort also to chat completions

* Made changes to fix issues with cline based on bugbash

* removed extra console.log statements

* Added extra changes to make reasoningEffortOptions working properly(outputs undefined)

* Made changes to code that make it cleaner

* created utility function for responses

* Removed extra console.log lines

* Fixed issues with tests not working

* Added changeset

* Update webview-ui/src/components/settings/providers/OcaModelPicker.tsx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* removing openai-native changes

* Switched to using api format instead of supportsResponsesApi and supportChatApi

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2026-01-06 22:35:40 -08:00
Tomás Barreiro a7333b7177 Remove remote OTEL config type casting (#8351) 2026-01-07 06:04:08 +01:00
Tomás Barreiro f30837a850 Do not request /users/me when fetching other data (#8410)
* Do not use /users/me when fetching other data

* Add changeset
2026-01-07 02:24:29 +01:00
Max 5660b2513f add cline pr review cline workflow action (#8284)
cline pr-review bot initial

cline permission system

Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2026-01-06 17:20:05 -08:00
Tomás Barreiro 64e7e5fa4c Replace process.env usage with a BUILD_CONSTANTS variable (#8349)
* Replace process.env usage with a BUILD_CONSTANTS variable

* Update import

* revert doc update

* Do not build IS_STANDALONE
2026-01-07 01:07:28 +01:00
Toshii b34166e99a add web tool docs (#8408) 2026-01-06 14:54:43 -08:00
Ara cd2d8f98a7 feat: remove kwaipilot/kat-coder-pro from free models list (#8406)
* feat: remove kwaipilot/kat-coder-pro from free models list

Remove the KwaiPilot KAT-Coder Pro model from the OpenRouter
free models picker, likely due to availability changes or
model deprecation.

* changes
2026-01-06 12:47:31 -08:00
github-actions[bot] 333468c9b6 v3.47.0 Release Notes (#8286)
- Added experimental support for Background Edits (allows editing files in background without opening the diff view)
- Updated free model to MiniMax M2.1 (replacing MiniMax M2)
- Added support for Azure based identity authentication in OpenAI Compatible provider and Azure OpenAI
- Add `supportsReasoning` property to Baseten models

- Prevent expired token usage in authenticated requests
- Exclude binary files without extensions from diffs
- Preserve file endings and trailing newlines
- Fix Cerebras rate limiting
- Fix Auto Compact for Claude Code provider
- Make Workspace and Favorites history filters independent
- Fix remote MCP server connection failures (404 response handling)
- Disable native tool calling for Deepseek 3.2 speciale
- Show notification instead of opening sidebar on update
- Fix Baseten model selector

- Modify prompts for parallel tool usage in Claude and Gemini 3 models

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-01-06 12:00:52 -08:00
Juan Pablo Flores 0da6ddc001 feat: Add Background Edit feature to enhance workflow efficiency (#8405)
* Introduced a new feature, Background Edit, allowing file changes without opening the diff editor.
* Updated documentation to explain how to enable and use Background Edit, including its benefits and relationship with other features.
2026-01-06 11:48:35 -08:00
Tomás Barreiro 612130366f fix: Verify selected index is not -1 when checking if an option is selectable in the context menu (#8404)
* Verify selected index is not -1 when checking if an option is selectable

* Add changeset
2026-01-06 18:59:53 +01:00
Ara 85206cfded fix: update Minimax model ID to m2.1 in picker and cost logic (#8402)
Updates the Minimax model identifier from `minimax/minimax-m2` to `minimax/minimax-m2.1` in the OpenRouter model picker configuration. Additionally, updates the Cline provider to ensure the new model version is correctly recognized as a free model for cost calculation purposes.
2026-01-06 09:48:48 -08:00
CandiedUniverse 6f8ed7aa56 Display simple indicator for hooks in the CLI [ENG-1376] (#8269)
* feat(hooks): Initial implementation of UI output in the CLI

* feat(hooks): Display hooks UI output in the CLI nicely

* feat(hooks): Improvements to the hooks CLI implementation

* feat(hooks): Changes as per Cline's code review of hooks CLI PR

* feat(hooks): Make comments more concise and to the point

* feat(hooks): Minor improvements to code complexity

* feat(cli): polish hook status output (headers, paths, spacing)

- Align hook headings with ToolRenderer-style language
- Prefer workspace-relative paths for hook scripts
- Document hook_output_stream suppression + future grouping
- Add unit tests for rendering + path formatting

* feat(hooks): Isolate hook handlers and harden path handling

- Move hook-specific SAY handling into say_handlers_hooks.go
- Use os.UserHomeDir + filepath.Rel for more portable hook path shortening
- Document why hooks render from state stream (ordering/reordering)
- Standardize on filepath for filesystem paths in cline-clients
- Avoid silently ignoring os.Getwd() errors in dev fallback resolution

* feat(hooks): Add pendingToolInfo to hook status in the CLI

* feat(hooks): Fix verbose output to CLI

* feat(hooks): Add changeset commit.

* feat(hooks): code review feedback - make paths OS-agnostic

* feat(hooks): code review feedback - use strings.Builder

* feat(hooks): code review feedback - no need to normalize say type

* feat(hooks): code review feedback - define HookOutputStreamMeta type

* feat(hooks): code review feedback - remove dynamic import

* feat(hooks): code review feedback - turn repetitive logic into helper function and make say type names reflect proto field names

* feat(hooks): code review feedback - remove unrelated changes

* feat(hooks): prepend hook script path with repo name
2026-01-06 08:09:06 -08:00
Tomás Barreiro f2c130a69e Prevent using expired tokens when making authenticated requests (#8386)
* Prevent using expired tokens when making authenticated requests

* Add changeset

* refactor

* Update AuthService.ts

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2026-01-06 02:52:18 +01:00
Bee c870bfb454 refactor: migrate HistoryView & ServerRow UI to use shadcn Button (#8387)
* refactor: migrate HistoryView & ServerRow UI to use shadcn Button and Tailwind classes

- Replace VSCodeButton with shadcn Button component
- Convert inline styles to Tailwind CSS utility classes
- Replace DangerButton with Button variant="destructive"
- Add custom Tailwind color classes for VS Code theme variables
- Simplify JSX structure by removing redundant style objects
- Improve code readability and maintainability

* fix typo
2026-01-05 17:12:28 -08:00
valquaint 436bfdb535 Do not use native tool calling when using Deepseek 3.2 speciale (#8390)
* Do not use native tool calling when using Deepseek 3.2 speciale

* Add changeset
2026-01-05 17:00:22 -08:00
yuvalman e2a3652d26 fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode (#7099)
* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode

* fix: sap provider - support replace credentials in orchestration mode without the need to reload vscode
2026-01-05 13:04:43 -08:00
wenwolf 632aca225c feat: Support Azure Identity DefaultCredential for AzureOpenAI (OpenAI Compatible provider) (#8385)
* feat: support azure identity authentication

Signed-off-by: patst <patrick.steinig@googlemail.com>

* feat: support azure identity authentication

Signed-off-by: patst <patrick.steinig@googlemail.com>

* chore: format changes

* set azureIdentity in state

* ADD Openai Compat Azure AD managed identity support: added proto messages def for azure identity, updated OpenAI APi key missing if azure identity is checked, ...

* feat: Support Azure Identity DefaultCredential for AzureOpenAI (OpenAI Compatible provider)

* fixed azure identity version and missing state setting in proto

* added missing state setting in proto

---------

Signed-off-by: patst <patrick.steinig@googlemail.com>
Co-authored-by: patst <patrick.steinig@googlemail.com>
Co-authored-by: Wenceslas Wolfersperger <wenceslas.wolfersperger@idorsia.com>
2026-01-05 13:03:42 -08:00
yuvalman a1eaccdaef fix: sap provider - use messages_history field instead of messages which doesn't validate user input based on template syntax (#8280)
* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error

* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error

* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error

* fix: sap provider - use messages_history field instead of messages because of placeholder_values usage templating error
2026-01-05 10:26:01 -08:00
Ara f7e76f9bee feat: add MiniMax model support for OpenRouter and Vercel AI Gateway (#8376)
* feat: add MiniMax model support for OpenRouter and Vercel AI Gateway

Add MiniMax M2, M2.1, and M2.1-lightning models to the list of models
that require special system prompt handling in OpenRouter stream.
Also extend Vercel AI Gateway to apply the same system prompt format
for MiniMax models as used for Anthropic models.

* adding changes with debug logs
2026-01-04 17:18:07 -08:00
Robin Newhouse 0d04205dc4 fix: preserve file endings and trailing newlines across all edit tools (#8341) 2026-01-03 10:12:25 -08:00
Bee 4b9dbf11a0 feat: add Select UI component and Storybook story (#8355)
* feat: add Select UI component and Storybook story

Add @radix-ui/react-select dependency and introduce a Select Storybook
story to document and validate the new dropdown UI component.

* update position
2026-01-02 13:17:48 -08:00
Tomás Barreiro c5afbd743e Add Remote Config OTEL docs and change the OTEL override logs (#8346)
* Add Remote Config OTEL docs and change the OTEL override logs

* Add the new page to the sidebar

* Update docs/enterprise-solutions/monitoring/opentelemetry.mdx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Update docs/enterprise-solutions/monitoring/opentelemetry_override.mdx

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>

* Fix inconsistent casing

---------

Co-authored-by: ellipsis-dev[bot] <65095814+ellipsis-dev[bot]@users.noreply.github.com>
2025-12-31 21:05:26 +01:00
Robin Newhouse 6d1bfc3a1b feat(prompts): enable parallel tool usage for claude and gemini 3 models (#8331)
* feat(prompts): enable parallel tool usage for claude and gemini 3 models

- Update TOOL USE section to allow multiple independent tools per response
- Add rules clarifying when parallel vs sequential tool usage is appropriate
- Specify MCP operations should still be used one at a time
- Update test snapshots to reflect prompt changes

* Change prompts based on whether parallel tool calling is enabled

- GPT5 family: leave as is because parallel tool calling is always enabled
- Gemini 3 family: many or one tool depending on toggle
- Claude 4+ family: many tool or empty instruction to not collide with claude "under the hood" system prompt, which already suggests multi-tool use

* Revert non-parallel behavior to use working prompt.

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>

* feat: add MCP server checks with utility function

Add hasEnabledMcpServers() utility function to standardize MCP server detection across prompt variants. Conditionally include MCP-specific instructions only when MCP servers are enabled, avoiding unnecessary prompts when no servers are configured.

* Update prompt test snapshots

---------

Co-authored-by: Bee <68532117+abeatrix@users.noreply.github.com>
2025-12-30 22:15:56 -08:00
Bee d18486a199 chore: import codicons to storybook (#8345)
- Import @vscode/codicons CSS and font files in StorybookDecorator to ensure icons render correctly in the Storybook environment.
- Move the global `index.css` import from `preview.ts` to `StorybookDecorator.tsx` to consolidate style initialization.
2025-12-30 15:32:25 -08:00
Robin Newhouse 7417b1b671 fix: restore dummy thought signature for cross-model transfers (#8340)
Reverts the signature check from #8291 that dropped blocks without
signatures, restoring the fallback to GEMINI_DUMMY_THOUGHT_SIGNATURE
from #8122 to support transferring history from other models to Gemini.
2025-12-30 11:19:58 -08:00
Tony Loehr e4fbe331f4 sso docs (#8169)
* sso docs

* sso UI first approach

* added screenshot

* removed keycloak mention
2025-12-30 10:16:03 -08:00
Bee d122683e91 fix: Baseten model selector issue in ModelPickerModal (#8330)
* fix: Baseten model selector issue in ModelPickerModal

Fixed an issue where Baseten model cannot be selected when running in ModelPickerModal.
Refactor ModelPickerModal to reuse ThinkingBudgetSlider component
- Remove duplicated thinking budget slider UI components and logic
- Replace with shared ThinkingBudgetSlider component for consistency
- Clean up unused constants and helper functions
- Simplify provider-specific configuration handling

* clean up styled spans

* fix
2025-12-29 14:48:14 -08:00
Bee fdc96d0545 fix: add supportsReasoning property to Baseten models (#8329)
* fix: add supportsReasoning property to Baseten models

- Add supportsReasoning field to model configurations in basetenModels
- Implement detection logic for reasoning support via supported_parameters
- Mark reasoning-capable models (DeepSeek-R1, Qwen3, etc.) with supportsReasoning: true
- Update model refresh logic to populate supportsReasoning based on static config or parameter detection

This fixes issues where Baseten models are showing Thinking not supported in the UI.

* add changeset

* simplify

* clean up

* typo
2025-12-29 13:53:00 -08:00
canvrno c0241f4060 Fix: Exclude files without extensions (and dotfiles) from getDiffSet results (#8328)
* Exclude files without extensions (and dotfiles) from getDiffSet results

* More robust binary detection for explain changes feature
2025-12-29 13:44:45 -08:00
Seb Duerr c3f523427b fix(cerebras): use conservative max_tokens to avoid premature rate limiting
Cerebras rate limiter estimates token consumption using max_completion_tokens upfront, so requesting the model maximum (e.g., 64K) reserves that quota even if actual usage is low. This causes users to hit rate limits prematurely during agentic workflows with many short tool-use responses.

Uses 16K as default which is sufficient for most agentic tool use while preserving rate limit headroom.

Co-authored-by: Seb Duerr <sebastian.duerr@cerebras.net>
2025-12-29 13:33:27 -08:00
Ara 428e465d4d feat(api): add MiniMax M2.1 and M2.1-lightning models (#8327)
- Add MiniMax-M2.1 model with 192K context window and prompt caching
- Add MiniMax-M2.1-lightning variant with higher output pricing
- Update default model from MiniMax-M2 to MiniMax-M2.1
2025-12-29 11:18:38 -08:00
Saoud Rizwan 46ab08c9f8 fix(mcp): handle 404 responses from streamableHttp servers (#8321)
* fix(mcp): handle 404 responses from streamableHttp servers

The MCP SDK sends a GET request to check for SSE stream support when
connecting to streamableHttp servers. Per the MCP spec, servers that
don't support SSE should return 405 (Method Not Allowed), but many
servers incorrectly return 404 (Not Found).

The SDK only gracefully handles 405 responses, so servers returning 404
cause connection failures with "Failed to open SSE stream: Not Found".

This was exposed by the SDK upgrade from 1.22.0 to 1.25.1 in v3.46.0,
which added stricter SSE stream initialization checks.

This fix wraps the fetch function to normalize 404 -> 405 for GET
requests, allowing Cline to work with non-compliant servers while
they update to return proper 405 responses.

Fixes #8320
Fixes #7577

* chore: add changeset
2025-12-29 10:23:51 -08:00
Saoud Rizwan 0fd30e0d20 fix: stop auto-opening sidebar on extension update (#8322)
Only show a notification when the extension updates, instead of
automatically focusing the Cline sidebar. This prevents the extension
from stealing focus on VS Code launch.
2025-12-29 10:11:00 -08:00
Saoud Rizwan e87a765773 fix: recognize Claude Code short model aliases as Claude 4+ (#8324) 2025-12-29 10:07:23 -08:00
Ara e80c3d3cd8 fix: report correct shell in system prompt for background exec mode
When using background exec mode, commands run in the system default shell
(cmd.exe on Windows, /bin/bash on Unix) rather than the VS Code configured
shell. This ensures the system prompt accurately reflects which shell will
be used for command execution.

- Add getEffectiveShell() function to determine actual shell used
- Pass terminalExecutionMode through SystemPromptContext
- Use system default shell info when backgroundExec mode is active

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-12-29 08:29:23 -08:00
Ara 80b6ab6046 fix: resolve 'ask promise was ignored' error on background command cancel
Update command cancellation to modify existing message instead of sending new say() to avoid interfering with pending ask() dialogs.

- Extend updateClineMessage to support text updates
- Find last command_output message and append cancellation notice
- Add missing cleanupFileBased() calls for background tracking paths
- Use shared findLastIndex utility

Co-authored-by: Ara <arafat.da.khan@gmail.com>
2025-12-29 08:03:29 -08:00
Saoud Rizwan 5155123b80 docs: add changeset guidance 2025-12-29 04:58:36 -08:00
Juan Pablo Flores 30af711d5e Update documentation link in AboutSection (#8317) 2025-12-28 19:30:14 -08:00
Saoud Rizwan b218b25e0b Revert "feat: add stale PR detection to PR review workflow"
This reverts commit bf27aa53ef.
2025-12-28 13:18:17 -08:00
Saoud Rizwan bf27aa53ef feat: add stale PR detection to PR review workflow 2025-12-28 12:54:11 -08:00
Saoud Rizwan 4644a7159a feat: add For Maintainers section to PR review workflow 2025-12-28 12:12:14 -08:00
Saoud Rizwan 63c63f38f5 fix: skip draft PRs, trigger on ready_for_review 2025-12-28 12:01:13 -08:00
Saoud Rizwan f1d8ca423d fix: make PR review one-time response with comprehensive explanation 2025-12-28 10:45:47 -08:00
Saoud Rizwan 16b8ce7e44 fix: make review comment freeform with warm intro, remove Claude branding 2025-12-28 10:13:47 -08:00
Saoud Rizwan 0bbb4299ba fix: only auto-run PR review on opened, manual re-runs for updates 2025-12-28 09:56:51 -08:00
Saoud Rizwan 197b17b3bd fix: simplify PR review contributing guidelines checks 2025-12-28 09:42:35 -08:00
Saoud Rizwan 591b840531 feat: add automated PR review workflow 2025-12-28 09:37:33 -08:00
chenxue c35ba37402 Update aihubmix.ts (#8311) 2025-12-28 07:44:09 -08:00
Robin Newhouse 850a6ab841 Fix Gemini/OpenRouter failures from corrupted reasoning details and missing thought signatures (#8291)
* fix(api): filter Gemini reasoning details by tool call ID

Filter reasoning details in the OpenAI format transformer to ensure they
only include entries matching the specific tool call ID. This prevents
"Function call is missing a thought_signature" errors when using Gemini
models, where mismatched reasoning details would cause API validation
failures.

* fix(gemini): drop invalid thought signatures and corrupted reasoning_details

- Gemini direct: drop tool_use/thinking blocks when signature is missing
- OpenRouter: keep only tool reasoning_details matching tool id
- Skip reasoning.encrypted entries missing data to avoid 400s (#8214)

* fix(core): sanitize Gemini tool calls in OpenRouter stream

Gemini models require thought signatures for tool calls. When switching providers mid-conversation, historical tool calls may lack these reasoning details, causing subsequent requests to fail.

This change implements a filter for Gemini models that:
- Identifies assistant messages with tool calls but no reasoning details.
- Drops those tool calls while preserving textual content.
- Removes the corresponding tool response messages to maintain conversation integrity.
2025-12-26 13:10:22 -08:00
Saoud Rizwan 99c85710e9 fix: make Workspace and Favorites history filters independent (#8292)
* fix: make Workspace and Favorites history filters independent

Move Workspace and Favorites filters out of the VSCodeRadioGroup into
their own container. This fixes the regression where selecting one filter
would prevent selecting the other, since VSCodeRadioGroup enforces mutual
exclusivity. The filters now work as independent toggles while maintaining
visual continuity with the sort options above.

Fixes #8289

* add changeset
2025-12-24 21:44:51 -08:00
Saoud Rizwan 9fc9785aa2 chore: add .worktrees to gitignore 2025-12-24 20:21:26 -08:00
Tony Loehr 5c02f6eb13 deep planning demo (#8263)
* deep planning demo

* deep-planning-demo cleanup

* Update docs/features/slash-commands/deep-planning.mdx

Co-authored-by: Juan Pablo Flores  <juan@cline.bot>

* Update docs/features/slash-commands/deep-planning.mdx

Co-authored-by: Juan Pablo Flores  <juan@cline.bot>

---------

Co-authored-by: Juan Pablo Flores <juan@cline.bot>
2025-12-23 15:33:17 -08:00
yuvalman ac01e69555 fix: sap provider - regression in claude models in native api mode (#8278)
* fix: regression in claude models in native api mode for sap provider
2025-12-23 14:05:19 -08:00
Saoud Rizwan dbc18a8fce fix: add .husky/_/ to gitignore for worktree compatibility 2025-12-23 00:33:51 -08:00
Ara b77398390b docs: recommend background execution mode for terminal issues (#8271)
Update terminal troubleshooting docs to prominently recommend
Background Execution Mode as the primary solution for terminal
integration problems. This provides a simpler fix for most users
before diving into more complex troubleshooting steps.

- Add tip boxes with step-by-step instructions for enabling
  Background Exec mode in both terminal guide documents
- Clarify that detailed troubleshooting is for users who
  specifically need VSCode's integrated terminal
2025-12-22 19:36:31 -08:00
Ara c20052de00 feat(telemetry): add terminal type tracking to telemetry events (#8265)
* feat(telemetry): add terminal type tracking to telemetry events

Add terminalType parameter to terminal telemetry methods to differentiate
between VSCode and standalone terminal execution contexts. This enables
better analysis of terminal output capture success rates across different
environments.

- Add TerminalType, VscodeOutputMethod, and StandaloneOutputMethod types
- Update captureTerminalExecution to require terminalType parameter
- Update captureTerminalOutputFailure to require terminalType parameter
- Add terminalType option to OrchestrationOptions interface
- Update all call sites in VscodeTerminalProcess with "vscode" type

* feat(terminal): add terminal type tracking to telemetry events

Pass terminal type (standalone vs vscode) to telemetry capture calls
for terminal hang and user intervention events. This enables better
analysis of terminal behavior differences between execution modes.

* feat: add telemetry tracking for standalone terminal execution

Add telemetry capture for terminal process completion and errors in
StandaloneTerminalProcess to track execution success/failure metrics.

- Track successful completions (exit code 0 or null) and failures
- Capture error events separately with child_process_error identifier
- Use "standalone" terminal type for metric categorization
2025-12-22 16:44:12 -08:00
Ara 1dac507b63 feat: remove z-ai/glm-4.6 from free models list (#8260)
* feat: remove z-ai/glm-4.6 from free models list

Remove the Zhipu AI GLM-4.6 model from the free models selection in the OpenRouter model picker component. This change updates the available free model options for users.

* update changelog
2025-12-22 13:46:51 -08:00
github-actions[bot] e5aa48c2b5 v3.46.0 Release Notes (#8242)
- Added GLM 4.7 model
- Enhanced background terminal execution with command tracking, log file output, zombie process prevention (10-minute timeout), and clickable log paths in UI
- Apply Patch tool for GPT-5+ models (replacing current diff edit tools)

- Duplicate error messages during streaming for Diff Edit tool when Parallel Tool Calling is not enabled
- Banner carousel styling and dismiss functionality
- Typos in Gemini system prompt overrides
- Model picker favorites ordering, star toggle, and keyboard navigation for OpenRouter and Vercel AI Gateway providers
- Fetch remote config values from the cache

- Anthropic handler to use metadata for reasoning support
- Bedrock provider to use metadata for reasoning support

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-12-22 12:59:30 -08:00
Saoud Rizwan 63efb4aa5d fix: clarify label instructions in issue triage workflow 2025-12-22 12:24:16 -08:00
Saoud Rizwan 5fcf83b627 feat: add Regression label for issues caused by recent changes
When the triage bot identifies a likely regression from a recent PR or
commit, it will now apply the "Regression" label to help the team
prioritize and route these issues to the responsible developer.
2025-12-22 12:18:56 -08:00
Ara 0b308d610e feat(api): add GLM-4.7 model and update ZAi defaults (#8258)
- Add glm-4.7 model configuration for both international and mainland ZAi
- Update default model from glm-4.5 to glm-4.7
- Add missing cacheReadsPrice property to glm-4.6 model configs
2025-12-22 12:01:46 -08:00
Ara 60d3048aa0 feat(terminal): add background command tracking and bug fixes for terminals (#8085)
* refactor(terminal): centralize constants and implement output capping

- Move terminal-related constants (timeouts, compiling markers, and size limits) to a centralized constants file.
- Implement output capping in VscodeTerminalProcess to prevent memory exhaustion by truncating fullOutput when it exceeds MAX_FULL_OUTPUT_SIZE.
- Update terminal process logic to use centralized constants for consistency across VS Code and standalone terminal implementations.
- Clean up imports and formatting in the task core.

* update pricing

* fix(terminal): improve compilation marker detection accuracy

Extract compilation detection logic into isCompilingOutput() function
that checks markers at the START of lines only, rather than anywhere
in the output. This prevents false positives from file names, error
messages, or code snippets that happen to contain marker words.

* update pricing

* refactor(chat): simplify log file link display to show filename only

- Extract filename from full path for cleaner display
- Change from banner-style div to compact ghost button
- Add full path as tooltip for reference
- Improve styling with smaller text and border-based separator

* feat: add graceful process termination with SIGKILL fallback

Extract process termination logic into a reusable utility that handles
graceful shutdown:

- Send SIGTERM first to allow processes to clean up
- Wait for configurable timeout (default 2 seconds)
- Fall back to SIGKILL if process doesn't exit gracefully
- Support cross-platform termination via tree-kill

Update StandaloneTerminalProcess to use the new async terminate method
and update ITerminalProcess interface to allow async termination.

* feat(terminal): simplify compilation output detection to match markers anywhere

Change isCompilingOutput to use simple string includes() instead of
line-by-line startsWith() matching. This allows detecting compilation
markers anywhere in the output rather than only at the start of lines,
making detection more permissive and the code simpler.

* update pricing

* fix(ui): use theme-aware colors for shell integration warning banner

* fix(ui): improve log file path banner styling and wrapping

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-22 09:56:27 -08:00
Sarah Fortune aed3ac6597 Use the same font for the auth handler redirect as the dashboard (#8224)
The dashboard has switch to use Azaret san-serif instead of mono.
2025-12-22 09:21:53 -08:00
reneehuang1 86e2a3e7ce clean up writeups docs (#8195)
Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-22 00:13:35 -08:00
Saoud Rizwan 47856c70d2 chore: update workflow comment 2025-12-22 00:06:32 -08:00
Saoud Rizwan f1a84ddbde feat: add Claude Code web session setup with gh CLI and worktree support (#8249)
* feat: add SessionStart hook for Claude Code on the web

Adds a session-start hook that runs in remote environments to:
- Install all dependencies (npm run install:all)
- Generate gRPC/protobuf types (npm run protos)

This enables Claude Code web sessions to properly run tests and linters.

* feat: add .worktreeinclude for Claude Code worktrees

Ensures environment files and local settings are copied to new worktrees:
- .env files
- .clineignore
- Local Claude settings

* fix: include node_modules and generated files in worktreeinclude

Copying these to worktrees saves significant setup time:
- node_modules: skips npm install (~1-2 min)
- src/generated/, src/shared/proto/: skips proto generation

* feat: install gh CLI and add GITHUB_TOKEN support in session hook

- Rename session-start.sh to claude-code-for-web-setup.sh
- Install latest gh CLI from GitHub releases
- Check for GITHUB_TOKEN and inform Claude about gh availability
- Enables using `gh issue`, `gh pr` commands when token is configured

* refactor: make .worktreeinclude a symlink to .gitignore
2025-12-21 22:22:35 -08:00
Saoud Rizwan ebcc927cc7 fix(ui): ensure scroll-to-top reaches true top with virtual rendering (#8232)
When scrolled to bottom, the up button wasn't reliably scrolling all
the way to the top because Virtuoso's virtual rendering doesn't have
all items rendered. Added a delayed follow-up scroll to ensure we
reach the actual top after items render.
2025-12-21 18:58:44 -08:00
Saoud Rizwan 1e108d87e0 fix(ui): History page UI improvements (#8228)
* fix(ui): center View All button under task history list

* fix(ui): use VSCodeRadio for workspace and favorites filters on history page

* fix(ui): move Select All/None buttons to bottom of history page with secondary style
2025-12-21 18:58:16 -08:00
Saoud Rizwan 7b62d7786e fix(ui): MCP server UI improvements (#8227)
* fix(ui): prevent MCP server toggle from triggering row expand/collapse

* fix(ui): show connecting status when enabling MCP server

* fix(ui): show connecting status during MCP server restart

* fix(ui): add cursor pointer on hover for expandable MCP server rows
2025-12-21 17:04:00 -08:00
Saoud Rizwan 042f5c9823 chore(deps): update mintlify to fix security vulnerabilities (#8240) 2025-12-21 09:49:02 -08:00
aikido-autofix[bot] 2f8a4525a4 chore(deps): bump streamlit from 1.28.0 to 1.43.2 in evals
Co-authored-by: aikido-autofix[bot] <119856028+aikido-autofix[bot]@users.noreply.github.com>
2025-12-21 07:54:56 -08:00
aikido-autofix[bot] 20774a4187 chore(deps): fix security issues in jws, jsonwebtoken, @modelcontextprotocol/sdk
Co-authored-by: aikido-autofix[bot] <119856028+aikido-autofix[bot]@users.noreply.github.com>
2025-12-21 07:54:39 -08:00
dependabot[bot] be5bda2740 chore(deps-dev): bump storybook from 9.1.7 to 9.1.17
Bumps [storybook](https://github.com/storybookjs/storybook/tree/HEAD/code/core) from 9.1.7 to 9.1.17.
- [Release notes](https://github.com/storybookjs/storybook/releases)
- [Changelog](https://github.com/storybookjs/storybook/blob/next/CHANGELOG.md)
- [Commits](https://github.com/storybookjs/storybook/commits/v9.1.17/code/core)

---
updated-dependencies:
- dependency-name: storybook
  dependency-version: 9.1.17
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-21 07:48:54 -08:00
dependabot[bot] 261fd9036f chore(deps): bump @modelcontextprotocol/sdk from 1.22.0 to 1.25.1
Bumps [@modelcontextprotocol/sdk](https://github.com/modelcontextprotocol/typescript-sdk) from 1.22.0 to 1.25.1.
- [Release notes](https://github.com/modelcontextprotocol/typescript-sdk/releases)
- [Commits](https://github.com/modelcontextprotocol/typescript-sdk/compare/1.22.0...1.25.1)

---
updated-dependencies:
- dependency-name: "@modelcontextprotocol/sdk"
  dependency-version: 1.25.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-21 07:48:50 -08:00
Nick Baumann 2334d4d531 fix: model picker favorites ordering, star toggle, and keyboard nav
Co-authored-by: Nick Baumann <nickbaumann98@gmail.com>
2025-12-21 06:54:13 -08:00
Prithvi Singh Chohan 6390d854f7 fix: sync Plan/Act mode settings when switching tabs in OpenAI compatible provider
Co-authored-by: Prithvi Singh Chohan <pv11messi@gmail.com>
2025-12-21 06:38:01 -08:00
Saoud Rizwan 7d5c56a55a chore: add CLAUDE.local.md to gitignore 2025-12-21 06:14:32 -08:00
Saoud Rizwan 0dc760ac03 fix: rename Bot Triaged label to Bot Responded, apply after comment 2025-12-21 04:41:05 -08:00
Saoud Rizwan 8c1241c8cd feat: use Opus 4.5 model for issue triage 2025-12-21 04:11:06 -08:00
Saoud Rizwan 17686ae3d9 feat: add Bot Triaged label to issue triage workflow 2025-12-21 03:59:58 -08:00
Saoud Rizwan 97460d2952 fix: fetch label descriptions for better triage 2025-12-21 03:24:28 -08:00
Saoud Rizwan e629ed0ef6 fix: always include Possible Duplicates section 2025-12-21 02:29:24 -08:00
Saoud Rizwan 96788e9127 fix: clarify one-time response - no follow-up language 2025-12-21 02:18:28 -08:00
Saoud Rizwan d7716a514d fix: improve triage prompt - always report on recent changes analysis 2025-12-21 02:08:56 -08:00
Saoud Rizwan 7aaa5966d6 fix: allow all tools for issue triage 2025-12-21 01:31:39 -08:00
Saoud Rizwan bb1d068139 feat: add Claude issue triage workflow for automatic issue response 2025-12-21 01:14:54 -08:00
Saoud Rizwan 450945ae0e fix(ci): fetch tags for previous tag lookup and add line break in release body 2025-12-20 07:30:13 -08:00
Saoud Rizwan 191e9635bd fix(ci): use CHANGELOG.md content for GitHub release notes
Instead of auto-generating release notes from PRs, extract the
changelog entry for the version being released and append the
Full Changelog comparison link.
2025-12-20 06:59:36 -08:00
Saoud Rizwan c13a7a80b3 v3.45.1 Release Notes (hotfix)
Hotfix release including:
- 8a9e03c8f: fix(mcp): resolve race condition when updating Cline-specific MCP settings
2025-12-20 06:41:28 -08:00
Saoud Rizwan d4a4adfa5f fix(ui): Misc UI improvements (markdown + home page) (#8229)
* fix(ui): add margin styling for ordered lists in markdown

* fix(ui): prevent info icon from shrinking and add padding on home page
2025-12-20 01:46:59 -08:00
Saoud Rizwan 557e20224e fix(checkpoints): don't show checkpoint message when initialization fails (#8230)
When starting a task in a location that can't use checkpoints (e.g., Desktop,
Documents, Downloads, or home directory), the checkpoint message was still
appearing in the chat without a SHA. This happened because the code added
the message before checking if initialization had failed.

Now we check for `checkpointManagerErrorMessage` before showing the checkpoint
message, so users in unsupported locations won't see a broken checkpoint element.
2025-12-20 01:44:06 -08:00
Saoud Rizwan 0e9a326a6a fix(test): update banner carousel pagination format in e2e test
The banner carousel format changed from '1/3' to '1 / 3' (with spaces)
in commit 8f1405b88. Update the test regex patterns to match.
2025-12-20 00:47:38 -08:00
Saoud Rizwan f5ecb6db0c feat(ui): add green styling to task completed row (#8226)
* Revert "feat: enhanced compact task complete ui (#8025)"

This reverts commit cc36c67fc9.

* feat(ui): add green styling to task completed row

- Add green border and tinted green background to task completion container
- Add copyButtonStyle prop to WithCopyButton for custom positioning
- Revert previous compact task UI changes in favor of simpler styling
2025-12-19 23:01:55 -08:00
Saoud Rizwan 8f1405b881 fix(ui): improve banner carousel styling and dismiss functionality (#8225)
* fix(ui): improve banner carousel styling and dismiss functionality

- Fix dismiss button not working by adding version-based filtering
- Use CSS Grid stack technique to auto-size carousel to tallest card
- Fix spacing issues on narrow widths with reduced margins/padding
- Add hover underline for links in banner descriptions
- Prevent header icon from shrinking on narrow screens
- Remove bottom margin from markdown paragraphs
- Clean up navigation footer styling

* chore: add changeset
2025-12-19 22:18:44 -08:00
Saoud Rizwan 8a9e03c8ff fix(mcp): resolve race condition when updating Cline-specific MCP settings (#8222)
* fix(mcp): resolve race condition when updating Cline-specific MCP settings

Fixes a bug where toggling auto-approve for MCP tools or changing timeout
settings would cause the UI to flash and revert, making the toggles appear
unresponsive.

The root cause was a race condition between two state update mechanisms:
1. RPC Response: Returns updated servers immediately to the webview
2. File Watcher: Detects the settings file change and triggers a second
   update ~100ms later, potentially overwriting the first

Additionally, the file watcher was triggering full server restarts even
for settings changes that don't affect the MCP transport connection.

Changes:
- Add `isUpdatingClineSettings` flag to skip file watcher processing
  when we're making internal settings changes
- Add `configsRequireRestart()` method to distinguish between settings
  that require server restart vs Cline-specific UI settings
- Only notify webview when actual connection changes occur
- Update in-memory state for timeout changes without server restart
- Add comprehensive documentation for future Cline-specific settings

* chore: add changeset

* fix: update comments and sync all Cline-specific settings in-memory
2025-12-19 21:35:06 -08:00
Bee edba02b45e feat: add background edit mode with webview diff display (#8205)
* feat: add background edit mode with webview diff display

- Replace editor-based diff preview with webview DiffEditRow component
- Remove unused partialPreviewState and related methods from ApplyPatchHandler
- Integrate FileEditProvider in Task for background file edits when enabled
- Add comprehensive Storybook stories for diff edit row states

Test Plan:

1. Go to Features Setting to turn on `Background Edit`
2. Start a task that would perform file edits
3. Verify the diff edits will be performed in the background instead of stealing focus from your editor
4. Verify the new stories in Storybook for the new DiffEditRow components

* backgroundEditEnabled

* changeset

* clean up

* clear time out

* fix storybook
2025-12-19 16:23:13 -08:00
Jose R. Perez cc36c67fc9 feat: enhanced compact task complete ui (#8025)
* feat: enhanced task completed response ui

* feat: enhanced task completed response ui

* feature: adjusted embed component styling

* fix: minor adjustments

* fix: made last task completed expanded by default

* fix: restore api request and thinking

* feat: copy button fix
2025-12-19 15:46:20 -08:00
CandiedUniverse d77032bc8a fix(hooks): Fix edge case for hooks-enabled schema in the CLI (#8134)
* fix(hooks): Fix edge case for hooks-enabled schema in the CLI

* fix(hooks): Change as per PR feedback to simplify verbose logic
2025-12-19 14:25:15 -08:00
Max 608dde94b3 bump go version (#8216)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 14:14:21 -08:00
Max 47ff7c1620 fix security vulnerability with sapaicore provider (#8215)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 13:37:15 -08:00
Bee 1b7f971c34 refactor: banner system with data-driven architecture [ENG-1426] (#8140)
* refactor: banner system with data-driven architecture

Add new banner data structures and types to support a flexible, backend-driven
banner system. This enables dynamic banner management while maintaining
consistent UI rendering.

Changes:
- Add BannerCardData interface for banner configuration with support for icons,
  severity levels, actions, and platform/user filtering
- Add BannerActionType enum defining action handlers (link, settings, CLI
  install, model selection)
- Add BannerAction interface for button/link definitions
- Refactor banner rendering logic to use data-driven approach instead of
  hardcoded implementations
- Update BannerCarousel component to handle new action types dynamically

This allows the backend to construct banner JSON that the frontend renders
consistently through the BannerCarousel component when ready.

* apply feedback

* update e2e test

* Add BackendBanner struct with converter

* clean up types

* clean up
2025-12-19 12:58:36 -08:00
Max 12eadd3378 fix bedrock byo problem (#8191)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 12:22:51 -08:00
Max b3e0ef9ed7 multi-root workspace support for cli (#8163)
Co-authored-by: Max Paulus 🥪 <max@cline.bot>
2025-12-19 12:21:22 -08:00
Bee fb94d8d3d4 fix: expose process.platform in webview build configuration (#8201)
* fix(webview): expose process.platform in build configuration

Add process.platform to Vite and Storybook define configs to make
platform detection available in the webview UI code.

* Add changeset

* Update webview-ui/vite.config.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* revert copilot suggestion

* revert package-lock.json

* remove unknown

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-19 11:19:22 -08:00
Robin Newhouse d11bd15d60 Refactor Bedrock provider to use metadata for reasoning support (#8196)
- Remove hardcoded shouldEnableReasoning check in AwsBedrockHandler

- Use modelInfo.supportsReasoning from metadata to determine if reasoning should be enabled

- Update src/shared/api.ts to include supportsReasoning: true for all relevant Bedrock models (Claude 3.7, 3.5 Sonnet/Haiku, Opus, and 1m variants)

- Ensure consistency with other providers by keeping model capabilities in metadata
2025-12-19 11:08:35 -08:00
celestial-vault 31c48898a6 Update litellm case in normalizeApiConfiguration to check stored modelinfo (#8202) 2025-12-19 10:46:22 -08:00
Zhongying Qiao 5c9901d68a feat: Make banner providers filtering determined by what is selected instead of existing provider keys (#8119)
* feat: make banner providers filtering determined by what is selected instead of existing provider keys

* refactor: address feedback, use default case for string comparison
2025-12-19 10:01:19 -08:00
Bee 45b79dc3d7 feat: add background edit mode setting (#7146)
Add backgroundEditEnabled setting to global state and settings infrastructure.
This includes:
- Proto definition for the update settings request
- State management in controller and state helpers
- Extension state interface updates
- Default value of false in webview context

Building block for ENG-1367. Setting is not yet used in the UI or anywhere in the app yet. It will be done in the follow-up PR where the feature is implemented.
2025-12-18 22:03:25 -08:00
Bee 26b6c7bdb6 refactor: move vscode config access to hostbridge layer (#7843)
- Add error_level field to telemetry proto messages
- Move getConfiguration usage from core services to vscode hostbridge provider
- Remove migrateDisableBrowserToolSetting and migrateChromeExecutablePathSetting methods
- Remove direct vscode imports from core/task and services/browser
- Update getTelemetrySettings to retrieve and return telemetryLevel from vscode config

This refactoring centralizes vscode-specific configuration access in the hostbridge provider layer, improving separation of concerns and making core services less coupled to the vscode API. Plus the cline configurations has already been set to be empty in the package.json for vs code extension.
2025-12-18 19:43:50 -08:00
Sarah Fortune d0678a2ad1 Add another codeowner for the settings directory (#8165)
* Add more codeowners for the settings directory

* Update CODEOWNERS
2025-12-18 19:11:14 -08:00
Bee 09276ebf43 fix: prevent duplicate error messages during streamed edit tool failures (#8200)
Add early return in WriteToFileToolHandler catch block when tool has
already failed once during streaming when enableParallelToolCalling is not enabled. This prevents the same error
message from being repeatedly added to userMessages array on each
new streaming chunk received.
2025-12-18 18:17:48 -08:00
CandiedUniverse af8b51b189 Revert "fix(hooks): Fix the underlying Windows detection logic [#8703] (#8168)" (#8197)
This reverts commit 3e6b3f252b.
2025-12-18 15:12:34 -08:00
CandiedUniverse 3e6b3f252b fix(hooks): Fix the underlying Windows detection logic [#8703] (#8168)
* fix(hooks): Fix the underlying Windows detection logic

* fix(hooks): Rename isMacOSOrLinux() to useIsMacOSOrLinux() per review feedback
2025-12-18 13:57:24 -08:00
Robin Newhouse f019c365a6 Refactor Anthropic handler to use metadata for reasoning support and cache_control behavior (#8170)
* Refactor Anthropic handler to use metadata for cache_control behavior

Replace hardcoded switch statement with model.info.supportsPromptCache check, following the same pattern as OpenAI Native and Vertex providers.

* Refactor Anthropic handler to use metadata for reasoning support

Replace modelId substring checks with model.info.supportsReasoning flag, and add supportsReasoning: true to all models that support extended thinking (3-7, 4-, 4-5).
2025-12-18 13:54:38 -08:00
Ara f6fe843cfb feat: auto-fail task in YOLO mode on consecutive mistakes (#8189)
When YOLO mode is enabled and the maximum consecutive mistakes
threshold is reached, automatically fail the task instead of
waiting for user input. This prevents the task from hanging
indefinitely in automated/unattended scenarios.

Displays an error message suggesting to use a more capable model
and ends the task loop with a failure signal.
2025-12-18 13:04:45 -08:00
Ara 01f26c21ae fix: handle yolo mode in AskFollowupQuestionToolHandler (#8188)
- Add check for yoloModeToggled flag to prevent waiting for user input
- Auto-respond with tool usage instructions when in yolo mode
- Log the auto-response action for transparency
- Maintain existing functionality for non-yolo mode operations
2025-12-18 12:40:52 -08:00
Robin Newhouse 031c2f5b05 fix: correct typos in gemini system prompt overrides (#8183)
Co-authored-by: CandiedUniverse <132302818+candieduniverse@users.noreply.github.com>
2025-12-18 12:18:23 -08:00
Juan Pablo Flores c999e269db docs: add .clineignore file guidance to reduce noise in multi-root workspaces (#8162)
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-18 11:15:18 -08:00
Juan Pablo Flores 032c1bf792 DEVREL-61 docs: enhance Auto Approve feature documentation with detailed permis… (#8097)
* docs: enhance Auto Approve feature documentation with detailed permissions and usage examples

* Update docs/features/auto-approve.mdx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix: replace image with video in Auto Approve documentation for better clarity

* Update docs/features/auto-approve.mdx

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-18 11:14:23 -08:00
Nick Baumann fa73d60b7a Improve Model Picker Modal UI and provider persistence (#8131)
* Improve Model Picker Modal UI and provider persistence

* Replace fuzzy search with multi-word substring matching in model picker

* feat(model-picker): add thinking slider, provider dropdown portal, and UI improvements

- Add thinking budget slider with min/max constraints
- Render provider dropdown via portal with flip logic for positioning
- Add getProviderInfo helper for settings-only providers
- Use ArrowLeftRight icon for plan/act split toggle
- Close provider list when typing in search
- Fix selection backgrounds with linear-gradient layering
- Improve row heights and icon positioning

* refactor(model-picker): replace Fuse.js with multi-word substring search

---------

Co-authored-by: Saoud Rizwan <7799382+saoudrizwan@users.noreply.github.com>
2025-12-17 21:22:32 -08:00
Robin Newhouse 841bb7f1d7 Disable specifically the Cline extensions in launch.json (#8176)
Replaced the global `--disable-extensions` flag with specific
`--disable-extension` flags for `saoudrizwan.claude-dev` and
`saoudrizwan.claude-dev-nightly`. This allows testing the extension
under development alongside other installed extensions while
preventing conflicts with production or nightly versions of Cline.
2025-12-17 18:01:51 -08:00
Bee f01428884d feat: replace diff edit tools with APPLY_PATCH tool for gpt-5+ native tools (#8167)
* feat: replace diff edit tools with APPLY_PATCH tool for gpt-5+ with native tool calling

Replace FILE_NEW and FILE_EDIT tools with APPLY_PATCH in the native-gpt-5-1 variant configuratiob as that's the format the GPT 5 models are trained on.

* update snapshot

* Update ApplyPatchHandler UI and new line bug
2025-12-17 16:07:47 -08:00
Tomás Barreiro 2ce5548250 [PF-207] Remotely configured OTEL (#8056)
* Remote configured OTEL

* Configure the OpenTelemetryTelemetryProvider for Remote Config and remove it when resetting the confiig

* Address comments

* Fix tests

* Refactor

* Address comments

* Refactor openTelemetryOtlpHeaders and add comment

---------

Co-authored-by: Sarah Fortune <sarah.fortune@gmail.com>
2025-12-17 21:36:35 +01:00
Tomás Barreiro 9f32cd247f fix: Fetch values available in the remote config (#8070)
* Update the StateManager with the new fields

* Add comment

* Add changeset
2025-12-17 21:09:08 +01:00
Max ace48198cc Add slash command auto-complete dropdown to cline cli (#8026) 2025-12-17 11:53:13 -08:00
Tony Loehr 9f0240dfd7 fixed keyboard shortcuts docs (#8116)
* fixed keyboard shortcuts docs

* improved flow of keyboard shortcuts docs

* fixed keyboard shortcuts relevance

* fixed terminal integration keyboard shortcuts relevance
2025-12-17 11:02:55 -08:00
Juan Pablo Flores 5530cfe375 DEVREL-69 docs: update multi-root workspace documentation for clarity and consi… (#8121)
* docs: update multi-root workspace documentation for clarity and consistency

* docs: remove experimental label from multi-root workspace feature

Update documentation to reflect that multi-root workspaces are no
longer considered experimental while still noting the existing
limitations with Cline rules and checkpoints.

* docs: update multi-root workspace examples to clarify workspace config file locations

* docs: add guidance on using VSCode's files.exclude to manage generated folders in multi-root workspaces

---------

Co-authored-by: Tony Loehr <turingxo@gmail.com>
2025-12-17 10:11:22 -08:00
Juan Pablo Flores af4d99e0bc docs: add JSON output section and ClineMessage schema to CLI reference (#8151)
* docs: add JSON output section and ClineMessage schema to CLI reference

* docs: enhance JSON output section with ClineMessage schema details
2025-12-17 10:04:11 -08:00
403 changed files with 24238 additions and 10126 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add gpt-5.2-codex OpenAI model support
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Support CLINE_DIR environment variable in CLI (#8379)
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add create-pull-request skill
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix the selection of remotely configured providers
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Harden act_mode_respond to prevent consecutive calls
+51
View File
@@ -0,0 +1,51 @@
#!/bin/bash
set -euo pipefail
# Only run in Claude Code remote environments
if [ "${CLAUDE_CODE_REMOTE:-}" != "true" ]; then
exit 0
fi
cd "$CLAUDE_PROJECT_DIR"
echo "=== Claude Code for Web Setup ==="
echo ""
# Install latest gh CLI tool
echo "Installing GitHub CLI..."
GH_VERSION=$(curl -s https://api.github.com/repos/cli/cli/releases/latest | grep '"tag_name"' | cut -d'"' -f4 | sed 's/^v//')
curl -sL "https://github.com/cli/cli/releases/download/v${GH_VERSION}/gh_${GH_VERSION}_linux_amd64.tar.gz" -o /tmp/gh.tar.gz
tar -xzf /tmp/gh.tar.gz -C /tmp
sudo mv "/tmp/gh_${GH_VERSION}_linux_amd64/bin/gh" /usr/local/bin/gh
rm -rf /tmp/gh.tar.gz /tmp/gh_${GH_VERSION}_linux_amd64
echo "Installed gh version: $(gh --version | head -1)"
echo ""
# Check if GITHUB_TOKEN is set and configure gh
if [ -n "${GITHUB_TOKEN:-}" ]; then
echo "GITHUB_TOKEN is configured - gh CLI is ready to use"
echo ""
echo "You can use gh commands directly, for example:"
echo " gh issue list --repo cline/cline --limit 5"
echo " gh pr list --repo cline/cline --state open"
echo " gh issue view 123 --repo cline/cline"
echo ""
else
echo "GITHUB_TOKEN is not set - gh CLI will have limited functionality"
echo ""
echo "To enable full GitHub API access:"
echo "1. Create a Fine-grained Personal Access Token at https://github.com/settings/tokens?type=beta"
echo "2. Add it as GITHUB_TOKEN in your Claude Code environment settings"
echo ""
fi
# Install project dependencies
echo "Installing dependencies..."
npm run install:all
# Generate gRPC/protobuf types (required for TypeScript)
echo "Generating proto types..."
npm run protos
echo ""
echo "Session setup complete!"
+14
View File
@@ -0,0 +1,14 @@
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/claude-code-for-web-setup.sh"
}
]
}
]
}
}
+196
View File
@@ -0,0 +1,196 @@
---
name: create-pull-request
description: Create a GitHub pull request following project conventions. Use when the user asks to create a PR, submit changes for review, or open a pull request. Handles commit analysis, branch management, and PR creation using the gh CLI tool.
---
# Create Pull Request
This skill guides you through creating a well-structured GitHub pull request that follows project conventions and best practices.
## Prerequisites Check
Before proceeding, verify the following:
### 1. Check if `gh` CLI is installed
```bash
gh --version
```
If not installed, inform the user:
> The GitHub CLI (`gh`) is required but not installed. Please install it:
> - macOS: `brew install gh`
> - Other: https://cli.github.com/
### 2. Check if authenticated with GitHub
```bash
gh auth status
```
If not authenticated, guide the user to run `gh auth login`.
### 3. Verify clean working directory
```bash
git status
```
If there are uncommitted changes, ask the user whether to:
- Commit them as part of this PR
- Stash them temporarily
- Discard them (with caution)
## Gather Context
### 1. Identify the current branch
```bash
git branch --show-current
```
Ensure you're not on `main` or `master`. If so, ask the user to create or switch to a feature branch.
### 2. Find the base branch
```bash
git remote show origin | grep "HEAD branch"
```
This is typically `main` or `master`.
### 3. Analyze recent commits relevant to this PR
```bash
git log origin/main..HEAD --oneline --no-decorate
```
Review these commits to understand:
- What changes are being introduced
- The scope of the PR (single feature/fix or multiple changes)
- Whether commits should be squashed or reorganized
### 4. Review the diff
```bash
git diff origin/main..HEAD --stat
```
This shows which files changed and helps identify the type of change.
## Information Gathering
Before creating the PR, you need the following information. Check if it can be inferred from:
- Commit messages
- Branch name (e.g., `fix/issue-123`, `feature/new-login`)
- Changed files and their content
If any critical information is missing, use `ask_followup_question` to ask the user:
### Required Information
1. **Related Issue Number**: Look for patterns like `#123`, `fixes #123`, or `closes #123` in commit messages
2. **Description**: What problem does this solve? Why were these changes made?
3. **Type of Change**: Bug fix, new feature, breaking change, refactor, cosmetic, documentation, or workflow
4. **Test Procedure**: How was this tested? What could break?
### Example clarifying question
If the issue number is not found:
> I couldn't find a related issue number in the commit messages or branch name. What GitHub issue does this PR address? (Enter the issue number, e.g., "123" or "N/A" for small fixes)
## Git Best Practices
Before creating the PR, consider these best practices:
### Commit Hygiene
1. **Atomic commits**: Each commit should represent a single logical change
2. **Clear commit messages**: Follow conventional commit format when possible
3. **No merge commits**: Prefer rebasing over merging to keep history clean
### Branch Management
1. **Rebase on latest main** (if needed):
```bash
git fetch origin
git rebase origin/main
```
2. **Squash if appropriate**: If there are many small "WIP" commits, consider interactive rebase:
```bash
git rebase -i origin/main
```
Only suggest this if commits appear messy and the user is comfortable with rebasing.
### Push Changes
Ensure all commits are pushed:
```bash
git push origin HEAD
```
If the branch was rebased, you may need:
```bash
git push origin HEAD --force-with-lease
```
## Create the Pull Request
**IMPORTANT**: Read and use the PR template at `.github/pull_request_template.md`. The PR body format must **strictly match** the template structure. Do not deviate from the template format.
When filling out the template:
- Replace `#XXXX` with the actual issue number, or keep as `#XXXX` if no issue exists (for small fixes)
- Fill in all sections with relevant information gathered from commits and context
- Mark the appropriate "Type of Change" checkbox(es)
- Complete the "Pre-flight Checklist" items that apply
### Create PR with gh CLI
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main
```
Alternatively, create as draft if the user wants review before marking ready:
```bash
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main --draft
```
## Post-Creation
After creating the PR:
1. **Display the PR URL** so the user can review it
2. **Remind about CI checks**: Tests and linting will run automatically
3. **Suggest next steps**:
- Add reviewers if needed: `gh pr edit --add-reviewer USERNAME`
- Add labels if needed: `gh pr edit --add-label "bug"`
## Error Handling
### Common Issues
1. **No commits ahead of main**: The branch has no changes to submit
- Ask if the user meant to work on a different branch
2. **Branch not pushed**: Remote doesn't have the branch
- Push the branch first: `git push -u origin HEAD`
3. **PR already exists**: A PR for this branch already exists
- Show the existing PR: `gh pr view`
- Ask if they want to update it instead
4. **Merge conflicts**: Branch conflicts with base
- Guide user through resolving conflicts or rebasing
## Summary Checklist
Before finalizing, ensure:
- [ ] `gh` CLI is installed and authenticated
- [ ] Working directory is clean
- [ ] All commits are pushed
- [ ] Branch is up-to-date with base branch
- [ ] Related issue number is identified, or placeholder is used
- [ ] PR description follows the template exactly
- [ ] Appropriate type of change is selected
- [ ] Pre-flight checklist items are addressed
+3 -3
View File
@@ -72,12 +72,12 @@ POSTHOG_TELEMETRY_ENABLED=true # Enable PostHog telemetry (default: tru
# Example configurations:
#
# Console debugging (logs only):
# OTEL_TELEMETRY_ENABLED=1
# OTEL_TELEMETRY_ENABLED=true
# OTEL_LOGS_EXPORTER=console
# TEL_DEBUG_DIAGNOSTICS=true
#
# OTLP with gRPC (insecure, for local testing):
# OTEL_TELEMETRY_ENABLED=1
# OTEL_TELEMETRY_ENABLED=true
# OTEL_LOGS_EXPORTER=otlp
# OTEL_EXPORTER_OTLP_PROTOCOL=grpc
# OTEL_EXPORTER_OTLP_ENDPOINT=localhost:4317
@@ -85,7 +85,7 @@ POSTHOG_TELEMETRY_ENABLED=true # Enable PostHog telemetry (default: tru
# OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer your-token
#
# OTLP with HTTP/JSON (production):
# OTEL_TELEMETRY_ENABLED=1
# OTEL_TELEMETRY_ENABLED=true
# OTEL_LOGS_EXPORTER=otlp
# OTEL_EXPORTER_OTLP_PROTOCOL=http/json
# OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.example.com
-1
View File
@@ -1,4 +1,3 @@
/docs/
/.github/ @saoudrizwan @garoth @sjf
/README.md @saoudrizwan @nickbaumann98
/src/core/storage/ @celestial-vault
+173
View File
@@ -0,0 +1,173 @@
name: Claude Issue Triage
on:
issues:
types: [opened]
# Manual trigger for backfilling existing issues. Run from terminal:
# gh workflow run claude-issue-triage.yml -f issue_number=1234
# Or batch process:
# gh issue list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run claude-issue-triage.yml -f issue_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
issue_number:
description: 'Issue number to triage'
required: true
type: string
jobs:
claude-issue-triage:
runs-on: ubuntu-latest
timeout-minutes: 120
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> Claude can read the codebase but CANNOT write/push any code
# - issues: write -> Claude can comment and add labels (the only write access needed)
# - pull-requests: read -> Claude can view PR context but CANNOT create PRs
# This ensures that even if a malicious user attempts prompt injection via issue content,
# Claude cannot modify repository code, create branches, or open PRs.
permissions:
contents: read
issues: write
pull-requests: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Run Issue Response & Triage
id: triage
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
allowed_non_write_users: "*"
# Allow all tools - security is enforced by GitHub permissions above (contents: read, issues: write)
claude_args: --model claude-opus-4-5-20251101 --allowedTools "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch"
prompt: |
You're a GitHub issue first responder for the open source Cline repository.
**Issue:** #${{ github.event.issue.number || inputs.issue_number }}
**Title:** ${{ github.event.issue.title || 'See issue details below' }}
**Author:** @${{ github.event.issue.user.login || 'See issue details below' }}
## Your job
Investigate this issue thoroughly, then post a single helpful comment that helps the user and gives maintainers the context they need.
## Investigation
Start by reading the full issue:
gh issue view ${{ github.event.issue.number || inputs.issue_number }}
### Search for duplicates and related issues
Search thoroughly for existing issues that match this one:
gh issue list --search "<keywords from the issue>" --state all --limit 30
gh issue list --search "<error messages>" --state all --limit 20
gh issue list --search "<affected feature/component>" --state all --limit 20
For each relevant issue you find, read it including its comments:
gh issue view <number> --comments
You're looking for:
- **Duplicates**: Issues describing the same problem. Link to them and explain why you think they're duplicates. If closed, check how they were resolved - the solution might apply here.
- **Related issues**: Similar problems or context that could help. Pull useful information from their comments (workarounds others found, debugging steps that helped, maintainer explanations). Link to them and explain the connection.
If there are closed issues with solutions, surface those solutions prominently - this might immediately solve the user's problem.
### Analyze recent changes (ALWAYS DO THIS)
Many issues are regressions from recent releases. **Always** check what changed recently:
gh release list --limit 10
gh pr list --state merged --limit 50 --json number,title,mergedAt,author,body
Look for PRs merged in the last few weeks that might correlate with the issue. If you find a likely connection:
gh pr view <number>
gh pr diff <number>
git log --since="1 month ago" --oneline -- <relevant paths>
git show <commit>
**Always include your findings in your comment:**
- If you find a regression, call it out explicitly: which PR/commit likely caused it, who authored it, what changed, and suggest a fix direction if you can see one.
- If you don't find anything related, still mention it: "I analyzed recent PRs and releases but didn't find any changes that seem related to this issue."
### Search the codebase
Find the relevant code:
- Use grep/find to locate code related to the issue
- Key areas: `src/api/` (providers/models), `src/core/prompts/` (tools/prompts), platform-specific code for VS Code vs JetBrains
### Find documentation
Cline docs are at **https://docs.cline.bot/** and built with Mintlify from the `docs/` directory.
The URL structure maps directly to the file structure:
- `docs/getting-started/selecting-your-model.mdx` → https://docs.cline.bot/getting-started/selecting-your-model
- `docs/troubleshooting.mdx` → https://docs.cline.bot/troubleshooting
- Headings become anchors: `## Which Model` → `#which-model`
Search the `docs/` directory to find relevant documentation, then construct URLs to link users to:
```bash
ls docs/
grep -r "keyword" docs/ --include="*.mdx" -l
```
### Identify subject matter experts
For issues that clearly need engineering attention:
git log --since="6 months ago" --format="%an" -- <relevant paths> | sort | uniq -c | sort -rn | head -5
Cross-reference with GitHub usernames. Include in your response (@mention, do NOT assign):
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file |
## Weak model detection
Many issues are caused by users running small or non-frontier models that don't tool-call reliably. Signs include:
- Model failing to use tools correctly
- Nonsensical or malformed responses
- User is running a small/local model or older model version
If this looks like a weak model issue, kindly suggest they try reproducing with Claude Sonnet and report back if it persists. Link to https://docs.cline.bot/getting-started/selecting-your-model if helpful. Still label and triage normally.
## Your comment
Write a single comment as a helpful community member. Be conversational, not robotic. Include what's relevant:
- **Helpful response** - Answer their question, suggest a fix, provide a workaround. If you found solutions in related closed issues, surface those prominently.
- **Duplicates and related issues** - Link to any you found and explain why they're duplicates/related. Summarize useful context from their comments.
- **Regression analysis** - If this looks like a regression, explain what change likely caused it, link to the PR/commit, and tag the author.
- **Clarifying questions** - If you need more info, ask specific questions. Don't ask for things already provided.
- **SME table** - Include the table above if this needs engineering attention. Don't tag people for questions with obvious answers or weak-model issues.
- **Context for maintainers** - Relevant code paths, what you found. Keep it concise.
- **Docs links** - If there's relevant documentation, link to it naturally in your response as a recommendation (e.g., "For more details, check out [the Ollama setup guide](url)"). Do NOT add a "Sources" section at the end - integrate doc links into your response where they're helpful.
- **Possible Duplicates section** - ALWAYS include a "Possible Duplicates" section at the end of your comment listing issues that might be duplicates so maintainers can quickly close if appropriate. If none found, say "No obvious duplicates found."
## Labels
First, retrieve all available labels and read their descriptions to understand what each is for:
gh label list --json name,description --limit 100
Then apply the appropriate labels based on your analysis. Only use labels from the list above—do not create new labels.
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "label1,label2"
If your regression analysis found a likely culprit (a recent PR/commit that probably caused this issue), add the "Regression" label:
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "Regression"
IMPORTANT: After posting your comment, add the "Bot Responded" label to indicate this issue has received an automated response:
gh issue edit ${{ github.event.issue.number || inputs.issue_number }} --add-label "Bot Responded"
## Remember
- **This is a one-time automated response** - you will NOT see their reply or respond again. Never say things like "I can help you", "let me know", "once I have that info", or "I can give you more targeted help" - you won't be there to follow up. If you ask clarifying questions, frame them for the maintainers who will follow up, e.g., "If you can share X, that would help the maintainers diagnose this."
- Don't be formulaic. Respond to what the issue actually needs.
- Surface solutions from past issues - often the fastest path to helping.
- Connecting regressions to specific changes is extremely valuable.
- Link issues with #number so they're clickable.
+272
View File
@@ -0,0 +1,272 @@
name: Claude PR Review
on:
pull_request:
types: [opened, ready_for_review]
# Manual trigger for backfilling existing PRs. Run from terminal:
# gh workflow run claude-pr-review.yml -f pr_number=1234
# Or batch process open PRs:
# gh pr list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run claude-pr-review.yml -f pr_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to review'
required: true
type: string
jobs:
claude-pr-review:
# Runs on PR opened/ready_for_review (skips drafts) or manual trigger for backfilling
if: |
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 120
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> Claude can read the codebase but CANNOT write/push any code
# - pull-requests: write -> Claude can post reviews and inline suggestions
# - issues: read -> Claude can search for related issues
# NOTE: Even with pull-requests: write, Claude CANNOT merge PRs because branch protection
# requires 1 approval from a Code Owner. The GITHUB_TOKEN cannot bypass this.
permissions:
contents: read
pull-requests: write
issues: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get PR number
id: pr
run: |
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
else
echo "number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
fi
- name: Run PR Review
id: review
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
allowed_non_write_users: "*"
claude_args: --model claude-opus-4-5-20251101 --allowedTools "Bash,Read,Write,Edit,Glob,Grep,WebFetch,WebSearch"
prompt: |
You're a GitHub PR reviewer for the open source Cline repository. Your goal is to give the PR author helpful feedback and give maintainers the context they need to review efficiently.
PR: #${{ steps.pr.outputs.number }}
## Gather context
```bash
# Get full PR details
gh pr view ${{ steps.pr.outputs.number }} --json number,title,body,author,createdAt,updatedAt,isDraft,labels,commits,files,additions,deletions,changedFiles,baseRefName,headRefName,mergeable,reviewDecision
# Get the diff
gh pr diff ${{ steps.pr.outputs.number }}
# Check CI status
gh pr checks ${{ steps.pr.outputs.number }}
# Get existing review comments (to understand context and your previous feedback)
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/comments --jq '.[] | {user: .user.login, body: .body, path: .path, created_at: .created_at}'
# Get conversation comments
gh pr view ${{ steps.pr.outputs.number }} --comments
```
If this is a re-review (workflow_dispatch event):
Read your previous comments carefully. Understand what you asked for before.
Check if new commits or comments address your previous feedback.
## Check contributing guidelines
Flag (but don't block) if:
- Missing changeset - For user-facing changes, check if there's a `.changeset/` file:
```bash
gh pr diff ${{ steps.pr.outputs.number }} --name-only | grep '.changeset/' || echo "No changeset found"
```
If missing, ask them to run `npm run changeset`
- Missing tests - New features should have tests
## Find related issues and PRs
Search thoroughly for context that might help with the review:
```bash
# Find related issues for context
gh issue list --search "<keywords from the PR>" --state all --limit 30
gh issue list --search "<error messages or feature names>" --state all --limit 20
# Find similar PRs for reference
gh pr list --search "<keywords>" --state all --limit 30
```
For each relevant issue or PR you find, read it including comments:
```bash
gh issue view <number> --comments
gh pr view <number> --comments
```
Look for:
- Open issues this PR might fix that weren't linked in the description
- Similar PRs that went through review - what feedback did they get? What patterns did they follow?
- Context from maintainer discussions that could inform your review
## Find subject matter experts
For files changed in this PR, find who knows the code best:
```bash
# Get files changed
gh pr diff ${{ steps.pr.outputs.number }} --name-only
# For each relevant path, find contributors
git log --since="6 months ago" --format="%an" -- <path> | sort | uniq -c | sort -rn | head -5
```
Cross-reference git authors with GitHub usernames. Include an SME table in your response:
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file (15 commits in 6 months) |
| @username3 | Reviewed similar PR #Y with extensive feedback |
## Deep code review
This is the most important part. Don't just look for syntax issues - understand what the PR is trying to achieve and whether the implementation is the right approach.
Step 1: Understand the intent
Read the PR description and understand what the author is trying to accomplish. What problem are they solving? What feature are they adding?
Step 2: Form your own opinion first
Before analyzing their code, think about how YOU would implement this feature or fix. What files would you touch? What patterns would you follow? What edge cases would you handle?
Step 3: Compare approaches
Now look at their implementation. How does it compare to what you would have done?
- Is their approach better in some ways? Note what they did well.
- Is their approach missing something? Be specific about what and why.
- Are there edge cases they haven't considered?
- Does it follow the patterns established in similar parts of the codebase?
Step 4: Look at the bigger picture
- What other files or systems does this change interact with?
- Could this break anything else?
- Is there additional work needed beyond this PR to complete the feature?
- Does this fit well with the overall architecture?
Step 5: Find reference implementations
Look for similar changes in the codebase:
```bash
git log --oneline --all --grep="<relevant keywords>" | head -20
git log --oneline -- <similar files> | head -20
```
If this is adding a new API provider, look at how other providers are implemented.
If this is adding a new feature, look at how similar features were added.
Note where their implementation aligns with or diverges from established patterns.
Step 6: Standard code review checks
- DRY: Is there duplicated code that could be extracted?
- Error handling: Are errors handled appropriately?
- Security: Any injection risks, credential exposure, unsafe dependencies?
- Performance: Any obvious inefficiencies, memory leaks, N+1 patterns?
- Types: Is TypeScript used correctly? Any unsafe type assertions?
- Naming: Are variables and functions named clearly?
- Comments: Is complex logic explained? Are there outdated comments?
## Inline code suggestions
For specific code improvements, use GitHub's suggestion syntax via `gh api`.
This creates suggestions the author can commit with one click.
Single-line suggestion:
```bash
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews \
-X POST \
-f commit_id="$(gh pr view ${{ steps.pr.outputs.number }} --json headRefOid -q .headRefOid)" \
-f event="COMMENT" \
-f body="" \
-F comments='[
{
"path": "src/example.ts",
"line": 42,
"body": "Consider simplifying:\n\n```suggestion\nconst result = items.filter(Boolean);\n```"
}
]'
```
Multi-line suggestion (replacing lines 40-45):
```bash
gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews \
-X POST \
-f commit_id="$(gh pr view ${{ steps.pr.outputs.number }} --json headRefOid -q .headRefOid)" \
-f event="COMMENT" \
-f body="" \
-F comments='[
{
"path": "src/example.ts",
"start_line": 40,
"line": 45,
"body": "This can be simplified:\n\n```suggestion\nconst simplified = doThing();\n```"
}
]'
```
Use inline suggestions for concrete improvements. Use regular comments for questions or broader feedback.
## Post your review
After your investigation, post a single helpful comment that helps the author and gives maintainers context.
Start with a warm thank you for their contribution. Be conversational, not robotic.
Include what's relevant:
- In-depth explanation of what the PR does - Be comprehensive. A maintainer should be able to read this section and fully understand the author's intent, why they made the changes, how they implemented it, and what files/systems are affected. Don't just summarize - explain.
- Related issues/PRs you found that provide useful context (link to them)
- Your review findings (issues to address, suggestions, etc.)
- Clear next steps for the author
Include a "For Maintainers" section with:
- Anything else useful to help the maintainer resolve this PR
- Related issues/PRs with context on why they're relevant
- Open issues this PR might fix that weren't linked in the description
- Your recommendation: merge as-is, needs changes, needs discussion, close, etc.
- SME table - who should review this and why
For the SME table:
| SME | Reason |
|-----|--------|
| @username | Primary contributor to affected files |
## Update labels
Add appropriate labels based on your analysis:
```bash
gh label list --json name,description --limit 100
gh pr edit ${{ steps.pr.outputs.number }} --add-label "label1,label2"
```
When done, add the reviewed label:
```bash
gh pr edit ${{ steps.pr.outputs.number }} --add-label "Bot Reviewed"
```
## Remember
- This is a one-time automated response - you will NOT see their reply or respond again. Never say things like "let me know if you have questions", "I can help you with", or "feel free to ask" - you won't be there to follow up. Frame any questions for the maintainers who will follow up.
- Be helpful and welcoming - Many contributors are new to the project
- Be specific - Point to exact lines and suggest fixes, don't give vague feedback
- Think deeply - Don't just surface-level review, understand the intent and evaluate the approach
- Use inline suggestions - Make it easy for authors to accept changes
- You're a first-pass reviewer - A human maintainer will do final approval
+312
View File
@@ -0,0 +1,312 @@
name: Cline PR Code Review
on:
pull_request:
types:
[opened, ready_for_review]
# Manual trigger for backfilling existing PRs. Run from terminal:
# gh workflow run cline-pr-review.yml -f pr_number=1234
# Or batch process open PRs:
# gh pr list --state open --limit 10 --json number --jq '.[].number' | while read num; do
# gh workflow run cline-pr-review.yml -f pr_number=$num
# sleep 60
# done
workflow_dispatch:
inputs:
pr_number:
description: "PR number to review"
required: true
type: string
concurrency:
group: pr-review-${{ github.event.pull_request.number || inputs.pr_number }}
cancel-in-progress: true
jobs:
cline-pr-review:
# Runs on PR opened/ready_for_review (skips drafts) or manual trigger for backfilling
if: |
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 60
# SECURITY: These permissions are intentionally restrictive.
# - contents: read -> cline can read the codebase but CANNOT write/push any code
# - pull-requests: write -> cline can post reviews and inline suggestions
# - issues: read -> cline can search for related issues
# NOTE: Even with pull-requests: write, cline CANNOT merge PRs because branch protection
# requires 1 approval from a Code Owner. The GITHUB_TOKEN cannot bypass this.
permissions:
contents: read
pull-requests: write
issues: read
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: "npm"
- name: Install and Verify Cline CLI
run: |
npx cline version # verify installation
- name: Configure Cline with Anthropic
run: |
npx cline auth --provider anthropic \
--apikey "${{ secrets.ANTHROPIC_API_KEY }}" \
--modelid claude-opus-4-5-20251101
- name: Get PR number
id: pr
run: |
if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
else
echo "number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
fi
- name: Review PR with Cline
env:
PR_NUMBER: ${{ steps.pr.outputs.number }}
GITHUB_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
CLINE_COMMAND_PERMISSIONS: |
{
"allow": [
"gh pr diff *",
"gh pr view *",
"gh pr checks *",
"gh pr list *",
"gh label list *",
"gh issue list *",
"gh issue view *",
"git log *",
"gh pr comment ${{ steps.pr.outputs.number }} *",
"gh pr edit ${{ steps.pr.outputs.number }} *",
"gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/comments *",
"gh api repos/${{ github.repository }}/pulls/${{ steps.pr.outputs.number }}/reviews *"
]
}
run: |
npx cline --yolo 'You'\''re a GitHub PR reviewer for the open source Cline repository. Your goal is to give the PR author helpful feedback and give maintainers the context they need to review efficiently.
PR: #'"${PR_NUMBER}"'
## Gather context
```bash
# Get full PR details
gh pr view '"${PR_NUMBER}"' --json number,title,body,author,createdAt,updatedAt,isDraft,labels,commits,files,additions,deletions,changedFiles,baseRefName,headRefName,mergeable,reviewDecision
# Get the diff
gh pr diff '"${PR_NUMBER}"'
# Check CI status
gh pr checks '"${PR_NUMBER}"'
# Get existing review comments (to understand context and your previous feedback)
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/comments --jq '\''.[] | {user: .user.login, body: .body, path: .path, created_at: .created_at}'\''
# Get conversation comments
gh pr view '"${PR_NUMBER}"' --comments
```
If this is a re-review (workflow_dispatch event):
Read your previous comments carefully. Understand what you asked for before.
Check if new commits or comments address your previous feedback.
## Check contributing guidelines
Flag (but don'\''t block) if:
- Missing changeset - For user-facing changes, check if there'\''s a `.changeset/` file:
```bash
gh pr diff '"${PR_NUMBER}"' --name-only | grep '\''.changeset/'\'' || echo '\''No changeset found'\''
```
If missing, ask them to run `npm run changeset`
- Missing tests - New features should have tests
## Find related issues and PRs
Search thoroughly for context that might help with the review:
```bash
# Find related issues for context
gh issue list --search '\''<keywords from the PR>'\'' --state all --limit 30
gh issue list --search '\''<error messages or feature names>'\'' --state all --limit 20
# Find similar PRs for reference
gh pr list --search '\''<keywords>'\'' --state all --limit 30
```
For each relevant issue or PR you find, read it including comments:
```bash
gh issue view <number> --comments
gh pr view <number> --comments
```
Look for:
- Open issues this PR might fix that weren'\''t linked in the description
- Similar PRs that went through review - what feedback did they get? What patterns did they follow?
- Context from maintainer discussions that could inform your review
## Find subject matter experts
For files changed in this PR, find who knows the code best:
```bash
# Get files changed
gh pr diff '"${PR_NUMBER}"' --name-only
# For each relevant path, find contributors
git log --since='\''6 months ago'\'' --format='\''%an'\'' -- <path> | sort | uniq -c | sort -rn | head -5
```
Cross-reference git authors with GitHub usernames. Include an SME table in your response:
| SME | Reason |
|-----|--------|
| @username1 | Authored PR #X which modified this area |
| @username2 | Primary contributor to affected file (15 commits in 6 months) |
| @username3 | Reviewed similar PR #Y with extensive feedback |
## Bash command usage
Don'\''t use operators like `|`, `&&`, or `;` - run each command separately and analyze the output.
When referencing command outputs, quote them properly to avoid formatting issues.
## Deep code review
This is the most important part. Don'\''t just look for syntax issues - understand what the PR is trying to achieve and whether the implementation is the right approach.
Step 1: Understand the intent
Read the PR description and understand what the author is trying to accomplish. What problem are they solving? What feature are they adding?
Step 2: Form your own opinion first
Before analyzing their code, think about how YOU would implement this feature or fix. What files would you touch? What patterns would you follow? What edge cases would you handle?
Step 3: Compare approaches
Now look at their implementation. How does it compare to what you would have done?
- Is their approach better in some ways? Note what they did well.
- Is their approach missing something? Be specific about what and why.
- Are there edge cases they haven'\''t considered?
- Does it follow the patterns established in similar parts of the codebase?
Step 4: Look at the bigger picture
- What other files or systems does this change interact with?
- Could this break anything else?
- Is there additional work needed beyond this PR to complete the feature?
- Does this fit well with the overall architecture?
Step 5: Find reference implementations
Look for similar changes in the codebase:
```bash
git log --oneline --all --grep='\''<relevant keywords>'\'' | head -20
git log --oneline -- <similar files> | head -20
```
If this is adding a new API provider, look at how other providers are implemented.
If this is adding a new feature, look at how similar features were added.
Note where their implementation aligns with or diverges from established patterns.
Step 6: Standard code review checks
- DRY: Is there duplicated code that could be extracted?
- Error handling: Are errors handled appropriately?
- Security: Any injection risks, credential exposure, unsafe dependencies?
- Performance: Any obvious inefficiencies, memory leaks, N+1 patterns?
- Types: Is TypeScript used correctly? Any unsafe type assertions?
- Naming: Are variables and functions named clearly?
- Comments: Is complex logic explained? Are there outdated comments?
## Inline code suggestions
For specific code improvements, use GitHub'\''s suggestion syntax via `gh api`.
This creates suggestions the author can commit with one click.
Single-line suggestion:
```bash
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/reviews \
-X POST \
-f commit_id="$(gh pr view '"${PR_NUMBER}"' --json headRefOid -q .headRefOid)" \
-f event='\''COMMENT'\'' \
-f body='\'''\'' \
-F comments='\''[
{
"path": "src/example.ts",
"line": 42,
"body": "Consider simplifying:\n\n```suggestion\nconst result = items.filter(Boolean);\n```"
}
]'\''
```
Multi-line suggestion (replacing lines 40-45):
```bash
gh api repos/'"${GITHUB_REPO}"'/pulls/'"${PR_NUMBER}"'/reviews \
-X POST \
-f commit_id="$(gh pr view '"${PR_NUMBER}"' --json headRefOid -q .headRefOid)" \
-f event='\''COMMENT'\'' \
-f body='\'''\'' \
-F comments='\''[
{
"path": "src/example.ts",
"start_line": 40,
"line": 45,
"body": "This can be simplified:\n\n```suggestion\nconst simplified = doThing();\n```"
}
]'\''
```
Use inline suggestions for concrete improvements. Use regular comments for questions or broader feedback.
## Post your review
After your investigation, post a single helpful comment that helps the author and gives maintainers context.
Start with a warm thank you for their contribution. Be conversational, not robotic.
Include what'\''s relevant:
- In-depth explanation of what the PR does - Be comprehensive. A maintainer should be able to read this section and fully understand the author'\''s intent, why they made the changes, how they implemented it, and what files/systems are affected. Don'\''t just summarize - explain.
- Related issues/PRs you found that provide useful context (link to them)
- Your review findings (issues to address, suggestions, etc.)
- Clear next steps for the author
Include a '\''For Maintainers'\'' section with:
- Anything else useful to help the maintainer resolve this PR
- Related issues/PRs with context on why they'\''re relevant
- Open issues this PR might fix that weren'\''t linked in the description
- Your recommendation: merge as-is, needs changes, needs discussion, close, etc.
- SME table - who should review this and why
For the SME table:
| SME | Reason |
|-----|--------|
| @username | Primary contributor to affected files |
## Update labels
Add appropriate labels based on your analysis:
```bash
gh label list --json name,description --limit 100
gh pr edit '"${PR_NUMBER}"' --add-label '\''label1,label2'\''
```
When done, add the reviewed label:
```bash
gh pr edit '"${PR_NUMBER}"' --add-label '\''Bot Reviewed'\''
```
## Remember
- This is a one-time automated response - you will NOT see their reply or respond again. Never say things like '\''let me know if you have questions'\'', '\''I can help you with'\'', or '\''feel free to ask'\'' - you won'\''t be there to follow up. Frame any questions for the maintainers who will follow up.
- Be helpful and welcoming - Many contributors are new to the project
- Be specific - Point to exact lines and suggest fixes, don'\''t give vague feedback
- Think deeply - Don'\''t just surface-level review, understand the intent and evaluate the approach
- Use inline suggestions - Make it easy for authors to accept changes
- You'\''re a first-pass reviewer - A human maintainer will do final approval'
+130
View File
@@ -0,0 +1,130 @@
name: Publish NPM Release
on:
workflow_dispatch:
inputs:
confirm_publish:
description: 'Type "publish" to confirm you want to publish to NPM'
required: true
type: string
permissions:
contents: read
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
jobs:
test:
uses: ./.github/workflows/test.yml
publish-npm-release:
needs: test
name: Publish Cline CLI to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main' && github.event.inputs.confirm_publish == 'publish'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
uses: actions/cache@v4
id: root-cache
with:
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: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Read release version
id: version
run: |
# Read version from cli/package.json (stable version)
VERSION=$(node -p "require('./cli/package.json').version")
echo "Release version: $VERSION"
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Download ripgrep binaries
run: npm run download-ripgrep
- name: Clean previous builds
run: rm -rf dist-standalone
- name: Generate Protos (First Pass)
run: npm run protos && npm run protos-go
- name: Compile CLI
run: npm run compile-cli
- name: Compile CLI for all platforms
run: npm run compile-cli-all-platforms
- name: Build standalone NPM package
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
OTEL_TELEMETRY_ENABLED: "1"
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_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 }}
POSTHOG_TELEMETRY_ENABLED: "true"
run: npm run compile-standalone-npm
- name: Generate Protos (Second Pass - Bug Workaround)
run: npm run protos && npm run protos-go
- name: Verify build output
run: |
echo "Checking dist-standalone directory..."
ls -la dist-standalone/
echo "Verifying CLI binaries..."
ls -lh cli/bin/cline-* || echo "Warning: CLI binaries not found"
echo "Checking package.json in dist-standalone..."
cat dist-standalone/package.json | grep version
- name: Publish to NPM with latest tag
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}
run: |
echo "Publishing version ${{ steps.version.outputs.version }} to NPM with tag 'latest'..."
cd dist-standalone
npm publish --tag latest --access public
- name: Summary
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'latest'"
echo ""
echo "📦 Install with: npm install -g cline"
echo "🔗 NPM: https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}"
+175
View File
@@ -0,0 +1,175 @@
name: Publish NPM Nightly
on:
schedule:
- cron: '0 12 * * *' # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: read
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
jobs:
test:
uses: ./.github/workflows/test.yml
publish-npm-nightly:
needs: test
name: Publish Cline CLI (Nightly) to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for recent commits
id: check_commits
run: |
if [ $(git rev-list --count HEAD --since="24 hours ago") -eq 0 ]; then
echo "No commits in last 24 hours, skipping publish"
echo "skip=true" >> $GITHUB_OUTPUT
else
echo "Found recent commits, proceeding with publish"
echo "skip=false" >> $GITHUB_OUTPUT
fi
- name: Setup Node.js
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://registry.npmjs.org'
- name: Setup Go
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-go@v5
with:
go-version: '1.24'
cache-dependency-path: cli/go.sum
# Cache root dependencies - only reuse if package-lock.json exactly matches
- name: Cache root dependencies
if: steps.check_commits.outputs.skip != 'true'
uses: actions/cache@v4
id: root-cache
with:
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
if: steps.check_commits.outputs.skip != 'true'
uses: actions/cache@v4
id: webview-cache
with:
path: webview-ui/node_modules
key: ${{ runner.os }}-npm-webview-${{ hashFiles('webview-ui/package-lock.json') }}
- name: Install root dependencies
if: steps.check_commits.outputs.skip != 'true' && steps.root-cache.outputs.cache-hit != 'true'
run: npm ci --include=optional
- name: Install webview-ui dependencies
if: steps.check_commits.outputs.skip != 'true' && steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm ci --include=optional
- name: Generate nightly version with timestamp
if: steps.check_commits.outputs.skip != 'true'
id: version
run: |
# Read base version from cli/package.json (e.g., "1.0.9")
BASE_VERSION=$(node -p "require('./cli/package.json').version")
# Generate timestamp (Unix epoch seconds)
TIMESTAMP=$(date +%s)
# Create unique nightly version: 1.0.9-nightly.1736365200
VERSION="${BASE_VERSION}-nightly.${TIMESTAMP}"
echo "Base version: $BASE_VERSION"
echo "Generated nightly version: $VERSION"
echo "version=$VERSION" >> $GITHUB_OUTPUT
- name: Update cli/package.json with nightly version
if: steps.check_commits.outputs.skip != 'true'
run: |
# Update version with timestamp-based nightly version
node -e "
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('cli/package.json', 'utf8'));
pkg.version = '${{ steps.version.outputs.version }}';
fs.writeFileSync('cli/package.json', JSON.stringify(pkg, null, '\t'));
"
echo "Using version ${{ steps.version.outputs.version }} for build"
cat cli/package.json | grep '"version"'
- name: Download ripgrep binaries
if: steps.check_commits.outputs.skip != 'true'
run: npm run download-ripgrep
- name: Clean previous builds
if: steps.check_commits.outputs.skip != 'true'
run: rm -rf dist-standalone
- name: Generate Protos (First Pass)
if: steps.check_commits.outputs.skip != 'true'
run: npm run protos && npm run protos-go
- name: Compile CLI
if: steps.check_commits.outputs.skip != 'true'
run: npm run compile-cli
- name: Compile CLI for all platforms
if: steps.check_commits.outputs.skip != 'true'
run: npm run compile-cli-all-platforms
- name: Build standalone NPM package
if: steps.check_commits.outputs.skip != 'true'
env:
TELEMETRY_SERVICE_API_KEY: ${{ secrets.TELEMETRY_SERVICE_API_KEY }}
ERROR_SERVICE_API_KEY: ${{ secrets.ERROR_SERVICE_API_KEY }}
CLINE_ENVIRONMENT: production
OTEL_TELEMETRY_ENABLED: "1"
OTEL_METRICS_EXPORTER: otlp
OTEL_LOGS_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 }}
POSTHOG_TELEMETRY_ENABLED: "true"
run: npm run compile-standalone-npm
- name: Generate Protos (Second Pass - Bug Workaround)
if: steps.check_commits.outputs.skip != 'true'
run: npm run protos && npm run protos-go
- name: Verify build output
if: steps.check_commits.outputs.skip != 'true'
run: |
echo "Checking dist-standalone directory..."
ls -la dist-standalone/
echo "Verifying CLI binaries..."
ls -lh cli/bin/cline-* || echo "Warning: CLI binaries not found"
echo "Checking package.json in dist-standalone..."
cat dist-standalone/package.json | grep version
- name: Publish to NPM with nightly tag
if: steps.check_commits.outputs.skip != 'true'
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}
run: |
echo "Publishing version ${{ steps.version.outputs.version }} to NPM with tag 'nightly'..."
cd dist-standalone
npm publish --tag nightly --access public
- name: Summary
if: steps.check_commits.outputs.skip != 'true'
run: |
echo "✅ Successfully published cline@${{ steps.version.outputs.version }} to NPM with tag 'nightly'"
echo ""
echo "📦 Install with: npm install -g cline@nightly"
echo "🔗 NPM: https://www.npmjs.com/package/cline/v/${{ steps.version.outputs.version }}"
+21 -10
View File
@@ -36,6 +36,8 @@ jobs:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.tag }}
fetch-depth: 0
fetch-tags: true
- name: Setup Node.js
uses: actions/setup-node@v4
@@ -116,22 +118,31 @@ jobs:
echo "Successfully published release version ${{ steps.get_version.outputs.version }} to VS Code Marketplace and Open VSX Registry"
fi
# - name: Get Changelog Entry
# id: changelog
# uses: mindsers/changelog-reader-action@v2
# with:
# # This expects a standard Keep a Changelog format
# # "latest" means it will read whichever is the most recent version
# # set in "## [1.2.3] - 2025-01-28" style
# version: latest
- name: Get Previous Tag
id: prev_tag
run: |
CURRENT_TAG="${{ steps.validate_tag.outputs.tag }}"
PREV_TAG=$(git describe --tags --abbrev=0 "$CURRENT_TAG^" 2>/dev/null || echo "")
echo "prev_tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Get Changelog Entry
id: changelog
run: |
# Get content between first ## [ and second ## [
CONTENT=$(awk '/^## \[/{if(found) exit; found=1; next} found{print}' 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.validate_tag.outputs.tag }}
files: "*.vsix"
# body: ${{ steps.changelog.outputs.content }}
generate_release_notes: true
body: |
${{ steps.changelog.outputs.content }}
**Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ steps.prev_tag.outputs.prev_tag }}...${{ steps.validate_tag.outputs.tag }}
prerelease: ${{ github.event.inputs.release-type == 'pre-release' }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+11
View File
@@ -8,12 +8,14 @@ tmp
.DS_Store
.idea
.husky/_/
pnpm-lock.yaml
.clineignore
.venv
.actrc
CLAUDE.local.md
webview-ui/src/**/*.js
webview-ui/src/**/*.js.map
@@ -27,6 +29,10 @@ coverage-unit
*evals.env
.env
.secrets
.github/act/.secrets
.worktrees
## Generated files ##
src/generated/
@@ -35,3 +41,8 @@ webview-ui/src/services/grpc-client.ts
# E2E Tests
test-results
/.github/act
/pkg
.secrets
+16 -4
View File
@@ -12,7 +12,10 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
],
"outFiles": [
@@ -33,7 +36,10 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
],
"outFiles": [
@@ -54,7 +60,10 @@
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-workspace-trust",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"${workspaceFolder}"
],
"outFiles": [
@@ -77,7 +86,10 @@
"--user-data-dir=${workspaceFolder}/dist/tmp/user",
"--profile-temp",
"--sync=off",
"--disable-extensions", // Avoid conflicts with installed extensions
"--disable-extension",
"saoudrizwan.claude-dev", // Avoid conflicts with installed Cline
"--disable-extension",
"saoudrizwan.cline-nightly", // Avoid conflicts with installed Cline Nightly
"--extensionDevelopmentPath=${workspaceFolder}",
"${workspaceFolder}"
],
+1
View File
@@ -0,0 +1 @@
.gitignore
+95 -1
View File
@@ -1,5 +1,99 @@
# Changelog
## [3.49.1]
### Added
- Add telemetry to track usage of skills feature
- Add version headers to Cline backend requests
- Phase in Responses API usage instead of defaulting for every supported model
### Fixed
- Fix workflow slash command search to be case-insensitive
- Fix model display in ModelPickerModal when using LiteLLM
- Fix LiteLLM model fetching with default base URL
- Fix crash when OpenAI-compatible APIs send usage chunks with empty or null choices arrays at end of streaming
- Fix model ID for Kat Coder Pro Free model
## [3.49.0]
- Enable configuring an OTEL collector at runtime
- Removing Minimax-2.1 from free model list as the free trial has ended
- Improved image display in MCP responses
- Auto-sync remote MCP servers from remote config to local settings
## [3.48.0]
### Added
- Add Skills system for reusable, on-demand agent instructions
- Add new websearch tooling in Cline provider
- Add zai-glm-4.7 to Cerebras model list
- Add model refresh and improve reasoning support for Vercel AI Gateway
### Fixed
- Revert #8341 due to regressions in diff view/document truncation (see #8423, #8429)
- Fixed extension crash when using context menu selector
## [3.47.0]
### Added
- Added experimental support for Background Edits (allows editing files in background without opening the diff view)
- Updated free model to MiniMax M2.1 (replacing MiniMax M2)
- Added support for Azure based identity authentication in OpenAI Compatible provider and Azure OpenAI
- Add `supportsReasoning` property to Baseten models
### Fixed
- Prevent expired token usage in authenticated requests
- Exclude binary files without extensions from diffs
- Preserve file endings and trailing newlines
- Fix Cerebras rate limiting
- Fix Auto Compact for Claude Code provider
- Make Workspace and Favorites history filters independent
- Fix remote MCP server connection failures (404 response handling)
- Disable native tool calling for Deepseek 3.2 speciale
- Show notification instead of opening sidebar on update
- Fix Baseten model selector
### Refactored
- Modify prompts for parallel tool usage in Claude and Gemini 3 models
## [3.46.1]
### Fixed
- Remove GLM 4.6 from free models
## [3.46.0]
### Added
- Added GLM 4.7 model
- Enhanced background terminal execution with command tracking, log file output, zombie process prevention (10-minute timeout), and clickable log paths in UI
- Apply Patch tool for GPT-5+ models (replacing current diff edit tools)
### Fixed
- Duplicate error messages during streaming for Diff Edit tool when Parallel Tool Calling is not enabled
- Banner carousel styling and dismiss functionality
- Typos in Gemini system prompt overrides
- Model picker favorites ordering, star toggle, and keyboard navigation for OpenRouter and Vercel AI Gateway providers
- Fetch remote config values from the cache
### Refactored
- Anthropic handler to use metadata for reasoning support
- Bedrock provider to use metadata for reasoning support
## [3.45.1]
- Fixed MCP settings race condition where toggling auto-approve or changing timeout settings would cause the UI to flash and revert
## [3.45.0]
- Added Gemini 3 Flash Preview model
@@ -1624,4 +1718,4 @@ Add Opus 4.1 through Claude Code
## [0.0.6]
- Initial release
- Initial release
+4
View File
@@ -14,6 +14,10 @@ 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
- 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, if the change is user-facing and significant enough to warrant a changelog entry, run `npm run changeset` and create a patch changeset. Never create minor or major version bumps. Skip changesets for trivial fixes, internal refactors, or minor UI tweaks that users wouldn't notice.
## gRPC/Protobuf Communication
The extension and webview communicate via gRPC-like protocol over VS Code message passing.
+5 -3
View File
@@ -14,8 +14,9 @@ import (
)
var (
port int
verbose bool
port int
verbose bool
workspaces []string
)
func main() {
@@ -28,6 +29,7 @@ func main() {
rootCmd.Flags().IntVarP(&port, "port", "p", 51052, "port to listen on")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "verbose logging")
rootCmd.Flags().StringSliceVar(&workspaces, "workspace", nil, "workspace paths")
if err := rootCmd.Execute(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
@@ -39,7 +41,7 @@ func runServer(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
// Create gRPC hostbridge service
service := hostbridge.NewGrpcServer(port, verbose)
service := hostbridge.NewGrpcServer(port, verbose, workspaces)
// Handle graceful shutdown
ctx, cancel := context.WithCancel(ctx)
+69 -24
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"slices"
"strings"
"github.com/charmbracelet/huh"
@@ -25,12 +26,13 @@ var (
outputFormat string
// Task creation flags (for root command)
images []string
files []string
mode string
settings []string
yolo bool
oneshot bool
images []string
files []string
mode string
settings []string
yolo bool
oneshot bool
workspaces []string
)
func main() {
@@ -70,12 +72,23 @@ see the manual page: man cline`,
var instanceAddress string
// Validate workspace paths exist
if err := common.ValidateDirsExist(workspaces); err != nil {
return err
}
// Build the full workspace list: cwd first, then additional workspaces
allWorkspaces, err := buildWorkspaceList(workspaces)
if err != nil {
return fmt.Errorf("failed to build workspace list: %w", err)
}
// If --address flag not provided, start instance BEFORE getting prompt
if !cmd.Flags().Changed("address") {
if global.Config.Verbose {
fmt.Println("Starting new Cline instance...")
}
instance, err := global.Clients.StartNewInstance(ctx)
instance, err := global.Clients.StartNewInstance(ctx, allWorkspaces...)
if err != nil {
return fmt.Errorf("failed to start new instance: %w", err)
}
@@ -131,8 +144,8 @@ see the manual page: man cline`,
// If no prompt from args or stdin, show interactive input
if prompt == "" {
// Pass the mode flag to banner so it shows correct mode
prompt, err = promptForInitialTask(ctx, instanceAddress, mode)
// Pass the mode flag and workspaces to banner so it shows correct info
prompt, err = promptForInitialTask(ctx, instanceAddress, mode, allWorkspaces)
if err != nil {
// Check if user cancelled - exit cleanly without error
if err == huh.ErrUserAborted {
@@ -152,13 +165,14 @@ see the manual page: man cline`,
}
return cli.CreateAndFollowTask(ctx, prompt, cli.TaskOptions{
Images: images,
Files: files,
Mode: mode,
Settings: settings,
Yolo: yolo,
Address: instanceAddress,
Verbose: verbose,
Images: images,
Files: files,
Mode: mode,
Settings: settings,
Yolo: yolo,
Address: instanceAddress,
Verbose: verbose,
Workspaces: allWorkspaces,
})
},
}
@@ -175,6 +189,7 @@ see the manual page: man cline`,
rootCmd.Flags().BoolVarP(&yolo, "yolo", "y", false, "enable yolo mode (non-interactive)")
rootCmd.Flags().BoolVar(&yolo, "no-interactive", false, "enable yolo mode (non-interactive)")
rootCmd.Flags().BoolVarP(&oneshot, "oneshot", "o", false, "full autonomous mode")
rootCmd.Flags().StringSliceVarP(&workspaces, "workspace", "w", nil, "additional workspace paths (can be specified multiple times)")
rootCmd.AddCommand(cli.NewTaskCommand())
rootCmd.AddCommand(cli.NewInstanceCommand())
@@ -189,9 +204,9 @@ see the manual page: man cline`,
}
}
func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string) (string, error) {
func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string, workspaces []string) (string, error) {
// Show session banner before the initial input
showSessionBanner(ctx, instanceAddress, modeFlag)
showSessionBanner(ctx, instanceAddress, modeFlag, workspaces)
var prompt string
@@ -233,7 +248,7 @@ func promptForInitialTask(ctx context.Context, instanceAddress, modeFlag string)
}
// showSessionBanner displays session info before initial prompt
func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string) {
func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string, workspaces []string) {
bannerInfo := display.BannerInfo{
Version: global.CliVersion,
Mode: modeFlag, // Use the mode from command flag, not state
@@ -244,10 +259,7 @@ func showSessionBanner(ctx context.Context, instanceAddress, modeFlag string) {
bannerInfo.Mode = "plan"
}
// Get current working directory (this is what Cline will use)
if cwd, err := os.Getwd(); err == nil {
bannerInfo.Workdir = cwd
}
bannerInfo.Workdirs = workspaces
// Get provider/model using auth functions (same logic as auth menu)
manager, err := cli.NewTaskManagerForAddress(ctx, instanceAddress)
@@ -345,4 +357,37 @@ func getContentFromStdinAndArgs(args []string) (string, error) {
}
return content.String(), nil
}
}
// buildWorkspaceList builds the full workspace list with cwd as the first entry
func buildWorkspaceList(additionalWorkspaces []string) ([]string, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("failed to get current working directory: %w", err)
}
// Start with cwd
workspaces := []string{cwd}
// Add additional workspaces, avoiding duplicates
for _, ws := range additionalWorkspaces {
// Normalize the path
absPath, err := common.AbsPath(ws)
if err != nil {
return nil, fmt.Errorf("failed to resolve workspace path %s: %w", ws, err)
}
// Skip if it's the same as cwd
if absPath == cwd {
continue
}
// Check for duplicates
isDuplicate := slices.Contains(workspaces, absPath)
if !isDuplicate {
workspaces = append(workspaces, absPath)
}
}
return workspaces, nil
}
+1 -1
View File
@@ -1,6 +1,6 @@
module github.com/cline/cli
go 1.23.0
go 1.24.0
require (
github.com/atotto/clipboard v0.1.4
+26
View File
@@ -70,6 +70,10 @@ When using the instant task syntax **cline "prompt"** the following options are
: Starting mode. Options: **act** (default), **plan**
**-w**, **\--workspace** *path*
: Additional workspace paths. Can be specified multiple times to include multiple directories. The current working directory is always included as the first workspace. Example: cline -w /path/to/other/project "refactor shared code"
# GLOBAL OPTIONS
These options apply to all subcommands:
@@ -78,6 +82,28 @@ These options apply to all subcommands:
: Output format. Options: **rich** (default), **json**, **plain**
When you use **-F json**, the CLI prints each client message as JSON.
Each message is a **ClineMessage** object.
Required fields:
- **type**: "ask" or "say"
- **text**: message text
- **ts**: Unix epoch timestamp in milliseconds
Optional fields (omitted when empty):
- **reasoning**: reasoning text
- **say**: say subtype (present when type is "say")
- **ask**: ask subtype (present when type is "ask")
- **partial**: streaming flag
- **images**: list of image URIs
- **files**: list of file paths
- **lastCheckpointHash**: git checkpoint hash
- **isCheckpointCheckedOut**: checkpoint checkout flag
- **isOperationOutsideWorkspace**: workspace safety flag
**-h**, **\--help**
: Display help information for the command.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cline",
"version": "1.0.3",
"version": "1.0.9",
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
"main": "cline-core.js",
"bin": {
+43 -37
View File
@@ -47,7 +47,7 @@ func GetProviderConfigurations(ctx context.Context, manager *task.Manager) (*Pro
}
// Parse state_json as map[string]interface{}
var stateData map[string]interface{}
var stateData map[string]any
if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
@@ -57,7 +57,7 @@ func GetProviderConfigurations(ctx context.Context, manager *task.Manager) (*Pro
}
// Extract apiConfiguration object from state
apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{})
apiConfig, ok := stateData["apiConfiguration"].(map[string]any)
if !ok {
if global.Config.Verbose {
fmt.Println("[DEBUG] No apiConfiguration found in state")
@@ -128,11 +128,11 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
modelID := getProviderSpecificModelID(r.apiConfig, "plan", provider)
// Determine if credentials exist
hasCreds := checkAPIKeyExists(r.apiConfig, provider)
hasCreds := checkCredentialsExists(r.apiConfig, provider)
// Determine readiness: OCA uses auth state presence; others need creds and model
if provider == cline.ApiProvider_OCA {
state, _ := GetLatestOCAState(context.Background(), 2 *time.Second)
state, _ := GetLatestOCAState(context.Background(), 2*time.Second)
if state == nil || state.User == nil {
continue
}
@@ -156,7 +156,7 @@ func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay {
Mode: "Ready",
Provider: provider,
ModelID: modelID,
HasAPIKey: checkAPIKeyExists(r.apiConfig, provider),
HasAPIKey: checkCredentialsExists(r.apiConfig, provider),
BaseURL: baseURL,
})
seenProviders[provider] = true
@@ -192,7 +192,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
modelID := getProviderSpecificModelID(stateData, mode, provider)
// Check if API key exists
hasAPIKey := checkAPIKeyExists(stateData, provider)
hasCredentials := checkCredentialsExists(stateData, provider)
// Get base URL for Ollama (can be shown publicly)
baseURL := ""
@@ -206,7 +206,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
Mode: capitalizeMode(mode),
Provider: provider,
ModelID: modelID,
HasAPIKey: hasAPIKey,
HasAPIKey: hasCredentials,
BaseURL: baseURL,
}
}
@@ -215,7 +215,7 @@ func extractProviderFromState(stateData map[string]interface{}, mode string) *Pr
// Returns (provider, ok) where ok is false if the provider is unknown
func mapProviderStringToEnum(providerStr string) (cline.ApiProvider, bool) {
normalizedStr := strings.ToLower(providerStr)
// Map string values to enum values
switch normalizedStr {
case "anthropic":
@@ -303,23 +303,27 @@ func getProviderSpecificModelID(stateData map[string]interface{}, mode string, p
return modelID
}
// checkAPIKeyExists checks if API key field exists in state (never retrieve actual key)
func checkAPIKeyExists(stateData map[string]interface{}, provider cline.ApiProvider) bool {
// checkCredentialsExists checks if API key field exists in state (never retrieve actual key)
func checkCredentialsExists(stateData map[string]interface{}, provider cline.ApiProvider) bool {
// Get field mapping from centralized function
fields, err := GetProviderFields(provider)
if err != nil {
return false
}
keyField := fields.APIKeyField
// Check if the key exists and is not empty
if value, ok := stateData[keyField]; ok {
if value, ok := stateData[fields.APIKeyField]; ok {
if str, ok := value.(string); ok && str != "" {
return true
}
}
if value, ok := stateData[fields.UseProfileField]; ok {
if hasProfileField, ok := value.(bool); ok && hasProfileField {
return true
}
}
return false
}
@@ -438,13 +442,13 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
stateJSON := state.StateJson
// Parse state_json as map[string]interface{}
var stateData map[string]interface{}
var stateData map[string]any
if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil {
return nil, fmt.Errorf("failed to parse state JSON: %w", err)
}
// Extract apiConfiguration object from state
apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{})
apiConfig, ok := stateData["apiConfiguration"].(map[string]any)
if !ok {
verboseLog("[DEBUG] No apiConfiguration found in state")
verboseLog("[DEBUG] Available keys in stateData: %v", getMapKeys(stateData))
@@ -469,36 +473,38 @@ func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([
// Check each BYO provider for API key presence
providersToCheck := []struct {
provider cline.ApiProvider
keyField string
provider cline.ApiProvider
keyFields []string
}{
{cline.ApiProvider_ANTHROPIC, "apiKey"},
{cline.ApiProvider_OPENAI, "openAiApiKey"},
{cline.ApiProvider_OPENAI_NATIVE, "openAiNativeApiKey"},
{cline.ApiProvider_OPENROUTER, "openRouterApiKey"},
{cline.ApiProvider_XAI, "xaiApiKey"},
{cline.ApiProvider_BEDROCK, "awsAccessKey"},
{cline.ApiProvider_GEMINI, "geminiApiKey"},
{cline.ApiProvider_OLLAMA, "ollamaBaseUrl"}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, "cerebrasApiKey"},
{cline.ApiProvider_HICAP, "hicapApiKey"},
{cline.ApiProvider_NOUSRESEARCH, "nousResearchApiKey"},
{cline.ApiProvider_ANTHROPIC, []string{"apiKey"}},
{cline.ApiProvider_OPENAI, []string{"openAiApiKey"}},
{cline.ApiProvider_OPENAI_NATIVE, []string{"openAiNativeApiKey"}},
{cline.ApiProvider_OPENROUTER, []string{"openRouterApiKey"}},
{cline.ApiProvider_XAI, []string{"xaiApiKey"}},
{cline.ApiProvider_BEDROCK, []string{"awsAccessKey", "awsUseProfile"}},
{cline.ApiProvider_GEMINI, []string{"geminiApiKey"}},
{cline.ApiProvider_OLLAMA, []string{"ollamaBaseUrl"}}, // Ollama uses baseUrl instead of API key
{cline.ApiProvider_CEREBRAS, []string{"cerebrasApiKey"}},
{cline.ApiProvider_HICAP, []string{"hicapApiKey"}},
{cline.ApiProvider_NOUSRESEARCH, []string{"nousResearchApiKey"}},
}
for _, providerCheck := range providersToCheck {
verboseLog("[DEBUG] Checking for %s key: %s", GetProviderDisplayName(providerCheck.provider), providerCheck.keyField)
if value, ok := apiConfig[providerCheck.keyField]; ok {
verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "")
if str, ok := value.(string); ok && str != "" {
configuredProviders = append(configuredProviders, providerCheck.provider)
verboseLog("[DEBUG] ✓ Provider %s is configured", GetProviderDisplayName(providerCheck.provider))
verboseLog("[DEBUG] Checking for %s key: %s", GetProviderDisplayName(providerCheck.provider), providerCheck.keyFields)
for _, keyField := range providerCheck.keyFields {
if value, ok := apiConfig[keyField]; ok {
verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "")
if str, ok := value.(string); ok && str != "" {
configuredProviders = append(configuredProviders, providerCheck.provider)
verboseLog("[DEBUG] ✓ Provider %s is configured", GetProviderDisplayName(providerCheck.provider))
break
}
} else {
verboseLog("[DEBUG] Key %s not found", keyField)
}
} else {
verboseLog("[DEBUG] Key %s not found", providerCheck.keyField)
}
}
verboseLog("[DEBUG] Total configured providers: %d", len(configuredProviders))
for _, p := range configuredProviders {
verboseLog("[DEBUG] - %s", GetProviderDisplayName(p))
@@ -54,6 +54,7 @@ type ProviderFields struct {
// Provider-specific additional model ID fields
PlanModeProviderSpecificModelIDField string // e.g., "planModeOpenRouterModelId"
ActModeProviderSpecificModelIDField string // e.g., "actModeOpenRouterModelId"
UseProfileField string // e.g., "awsUseProfile" (for bedrock) (optional, empty if not applicable)
}
// GetProviderFields returns the field mapping for a given provider
@@ -96,6 +97,7 @@ func GetProviderFields(provider cline.ApiProvider) (ProviderFields, error) {
case cline.ApiProvider_BEDROCK:
return ProviderFields{
UseProfileField: "awsUseProfile",
APIKeyField: "awsAccessKey",
PlanModeModelIDField: "planModeApiModelId",
ActModeModelIDField: "actModeApiModelId",
@@ -356,6 +358,9 @@ func AddProviderPartial(ctx context.Context, manager *task.Manager, provider cli
if openRouterInfo, ok := modelInfo.(*cline.OpenRouterModelInfo); ok {
apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo
apiConfig.ActModeOpenRouterModelInfo = openRouterInfo
} else if ocaInfo, ok := modelInfo.(*cline.OcaModelInfo); ok {
apiConfig.PlanModeOcaModelInfo = ocaInfo
apiConfig.ActModeOcaModelInfo = ocaInfo
}
}
@@ -424,6 +429,9 @@ func UpdateProviderPartial(ctx context.Context, manager *task.Manager, provider
if openRouterInfo, ok := updates.ModelInfo.(*cline.OpenRouterModelInfo); ok {
apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo
apiConfig.ActModeOpenRouterModelInfo = openRouterInfo
} else if ocaInfo, ok := updates.ModelInfo.(*cline.OcaModelInfo); ok {
apiConfig.PlanModeOcaModelInfo = ocaInfo
apiConfig.ActModeOcaModelInfo = ocaInfo
}
}
+2 -2
View File
@@ -190,7 +190,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
}
// Step 3: Select model
modelID, _, err := pw.selectModel(cline.ApiProvider_OCA, "")
modelID, modelInfo, err := pw.selectModel(cline.ApiProvider_OCA, "")
if err != nil {
return fmt.Errorf("model selection failed: %w", err)
}
@@ -198,7 +198,7 @@ func (pw *ProviderWizard) handleAddOcaProvider() error {
// Step 4: Apply the OCA model configuration and set as active
updates := ProviderUpdatesPartial{
ModelID: &modelID,
ModelInfo: nil,
ModelInfo: modelInfo,
}
if err := UpdateProviderPartial(pw.ctx, pw.manager, cline.ApiProvider_OCA, updates, true); err != nil {
+22 -15
View File
@@ -15,23 +15,23 @@ import (
// BedrockConfig holds all AWS Bedrock-specific configuration fields
type BedrockConfig struct {
// Profile authentication fields
UseProfile bool // Always true for successful config
Profile string // Optional: AWS profile name (empty = default)
Region string // Required: AWS region
Endpoint string // Optional: Custom VPC endpoint URL
UseProfile bool // Always true for successful config
Profile string // Optional: AWS profile name (empty = default)
Region string // Required: AWS region
Endpoint string // Optional: Custom VPC endpoint URL
// Optional features
UseCrossRegionInference bool // Optional: Enable cross-region inference
UseGlobalInference bool // Optional: Use global inference endpoint
UsePromptCache bool // Optional: Enable prompt caching
UseCrossRegionInference bool // Optional: Enable cross-region inference
UseGlobalInference bool // Optional: Use global inference endpoint
UsePromptCache bool // Optional: Enable prompt caching
// Authentication method (always "profile")
Authentication string // Always set to "profile"
Authentication string // Always set to "profile"
// Legacy fields (no longer used in profile-only flow)
AccessKey string // No longer used
SecretKey string // No longer used
SessionToken string // No longer used
AccessKey string // No longer used
SecretKey string // No longer used
SessionToken string // No longer used
}
// PromptForBedrockConfig displays a profile-first authentication form for Bedrock configuration
@@ -130,7 +130,12 @@ func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *Bedr
// Build the API configuration with all Bedrock fields
apiConfig := &cline.ModelsApiConfiguration{}
// Set model ID fields
// Set provider for both Plan and Act modes
bedrockProvider := cline.ApiProvider_BEDROCK
apiConfig.PlanModeApiProvider = &bedrockProvider
apiConfig.ActModeApiProvider = &bedrockProvider
// Set model ID field - this is the primary model ID used by Cline Core
apiConfig.PlanModeApiModelId = proto.String(modelID)
apiConfig.ActModeApiModelId = proto.String(modelID)
apiConfig.PlanModeAwsBedrockCustomModelBaseId = proto.String(modelID)
@@ -166,6 +171,8 @@ func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *Bedr
// Build field mask including all fields we're setting (excluding access keys)
fieldPaths := []string{
"planModeApiProvider",
"actModeApiProvider",
"planModeApiModelId",
"actModeApiModelId",
"planModeAwsBedrockCustomModelBaseId",
+18 -130
View File
@@ -1,22 +1,19 @@
package display
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/common"
)
// BannerInfo contains information to display in the session banner
type BannerInfo struct {
Version string
Provider string
ModelID string
Workdir string
Mode string
Version string
Provider string
ModelID string
Workdirs []string // workspace directories
Mode string
}
// RenderSessionBanner renders a nice banner showing version, model, and workspace info
@@ -81,131 +78,22 @@ func RenderSessionBanner(info BannerInfo) string {
// Model line - dim gray
if info.Provider != "" && info.ModelID != "" {
lines = append(lines, dimStyle.Render(info.Provider+"/"+shortenPath(info.ModelID, 30)))
lines = append(lines, dimStyle.Render(info.Provider+"/"+common.ShortenPath(info.ModelID, 30)))
}
// Workspace line - dim gray
if info.Workdir != "" {
lines = append(lines, dimStyle.Render(shortenPath(info.Workdir, 45)))
for _, wd := range info.Workdirs {
lines = append(lines, dimStyle.Render(common.ShortenPath(wd, 45)))
}
// Checkpoint warning for multi-root workspaces
if len(info.Workdirs) > 1 {
warningStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("3")). // Yellow warning color
Italic(true)
lines = append(lines, "")
lines = append(lines, warningStyle.Render("⚠ Checkpoints disabled for multi-root workspaces"))
}
content := lipgloss.JoinVertical(lipgloss.Left, lines...)
return boxStyle.Render(content)
}
// shortenPath shortens a filesystem path to fit within maxLen
func shortenPath(path string, maxLen int) string {
// Try to replace home directory with ~ (cross-platform)
if homeDir, err := os.UserHomeDir(); err == nil {
if strings.HasPrefix(path, homeDir) {
shortened := "~" + path[len(homeDir):]
// Always use ~ version if we can
path = shortened
}
}
if len(path) <= maxLen {
return path
}
// If still too long, show last few path components
if len(path) > maxLen {
parts := strings.Split(path, string(filepath.Separator))
if len(parts) > 2 {
// Show last 2-3 components
lastParts := parts[len(parts)-2:]
shortened := "..." + string(filepath.Separator) + strings.Join(lastParts, string(filepath.Separator))
if len(shortened) <= maxLen {
return shortened
}
}
}
// Last resort: truncate with ellipsis
if len(path) > maxLen {
return "..." + path[len(path)-maxLen+3:]
}
return path
}
// ExtractBannerInfoFromState extracts banner info from state JSON
func ExtractBannerInfoFromState(stateJSON, version string) (BannerInfo, error) {
var state map[string]interface{}
if err := json.Unmarshal([]byte(stateJSON), &state); err != nil {
return BannerInfo{}, fmt.Errorf("failed to parse state JSON: %w", err)
}
info := BannerInfo{
Version: version,
}
// Extract mode
if mode, ok := state["mode"].(string); ok {
info.Mode = mode
}
// Extract workspace roots
if workspaceRoots, ok := state["workspaceRoots"].([]interface{}); ok && len(workspaceRoots) > 0 {
if root, ok := workspaceRoots[0].(map[string]interface{}); ok {
if path, ok := root["path"].(string); ok {
info.Workdir = path
}
}
}
// Extract API configuration to get provider/model
if apiConfig, ok := state["apiConfiguration"].(map[string]interface{}); ok {
// Try common keys for provider and model (both camelCase and lowercase variants)
providerKeys := []string{"apiProvider", "api_provider"}
modelKeys := []string{"apiModelId", "api_model_id"}
// Try to extract provider
for _, key := range providerKeys {
if provider, ok := apiConfig[key].(string); ok && provider != "" {
info.Provider = provider
break
}
}
// Try to extract model ID
for _, key := range modelKeys {
if modelID, ok := apiConfig[key].(string); ok && modelID != "" {
info.ModelID = shortenModelID(modelID)
break
}
}
}
return info, nil
}
// shortenModelID shortens long model IDs for display
func shortenModelID(modelID string) string {
// Remove date suffixes only if they're at the end (e.g., -20241022)
// Check if the model ID ends with -YYYYMMDD pattern
if len(modelID) > 9 {
suffix := modelID[len(modelID)-9:] // Last 9 chars: -20241022
if suffix[0] == '-' &&
(strings.HasPrefix(suffix[1:], "202") || strings.HasPrefix(suffix[1:], "201")) {
// Verify all remaining chars are digits
allDigits := true
for _, c := range suffix[1:] {
if c < '0' || c > '9' {
allDigits = false
break
}
}
if allDigits {
return modelID[:len(modelID)-9]
}
}
}
// If still too long, show first 40 chars
if len(modelID) > 40 {
return modelID[:37] + "..."
}
return modelID
}
+144
View File
@@ -0,0 +1,144 @@
package display
import (
"fmt"
"strings"
"github.com/cline/cli/pkg/cli/types"
)
// HookRenderer renders hook status messages in a CLI-native style.
//
// Goals:
// - Match ToolRenderers markdown look
// - Keep executions ungrouped
// - Render status + high-signal metadata (script paths, error summary)
//
// Note: hook stdout/stderr currently arrives as separate `hook_output_stream` messages.
// The CLI suppresses those by default and prints them only in --verbose mode.
// Future work could group streamed output under the corresponding hook block.
//
// It returns markdown (or rendered markdown when enabled); callers should print the
// returned string.
type HookRenderer struct {
mdRenderer *MarkdownRenderer
outputFormat string
}
func NewHookRenderer(mdRenderer *MarkdownRenderer, outputFormat string) *HookRenderer {
return &HookRenderer{mdRenderer: mdRenderer, outputFormat: outputFormat}
}
func (hr *HookRenderer) RenderHookStatus(h types.HookMessage) string {
statusText := strings.TrimSpace(h.Status)
if statusText == "" {
statusText = "unknown"
}
// Header: aligned with ToolRenderers phrasing so transcripts scan consistently.
// Example: "### Cline hook completed: PreToolUse (tool: read_file) (exit 0)"
var headerBuilder strings.Builder
headerBuilder.WriteString(fmt.Sprintf("### Cline hook %s: %s", statusText, h.HookName))
if h.ToolName != "" {
headerBuilder.WriteString(" ")
headerBuilder.WriteString(fmt.Sprintf("(tool: %s)", h.ToolName))
}
if statusText == "failed" && h.ExitCode != 0 {
headerBuilder.WriteString(" ")
headerBuilder.WriteString(fmt.Sprintf("(exit %d)", h.ExitCode))
}
header := headerBuilder.String()
var lines []string
lines = append(lines, header)
// Pending tool info (PreToolUse): show one high-signal line directly under the header.
if h.PendingToolInfo != nil {
if pending := hr.formatPendingToolInfo(h.PendingToolInfo); pending != "" {
lines = append(lines, fmt.Sprintf("- Pending: %s", pending))
}
}
// Script paths: one per line.
paths := make([]string, 0, len(h.ScriptPaths))
for _, p := range h.ScriptPaths {
p = strings.TrimSpace(p)
if p != "" {
paths = append(paths, p)
}
}
if len(paths) == 0 {
// Fallback when no script paths are provided.
lines = append(lines, "- *(no hook scripts found)*")
} else {
for _, p := range paths {
lines = append(lines, fmt.Sprintf("- Running hook: `%s`", p))
}
}
// On failure, show a minimal summary (full stderr reserved for verbose).
if statusText == "failed" && h.Error != nil {
if msg := strings.TrimSpace(h.Error.Message); msg != "" {
lines = append(lines, fmt.Sprintf("- Error: %s", msg))
}
// If we have a specific script path, include it as a hint.
if sp := strings.TrimSpace(h.Error.ScriptPath); sp != "" {
lines = append(lines, fmt.Sprintf("- Script: `%s`", sp))
}
}
markdown := strings.Join(lines, "\n")
return hr.renderMarkdown(markdown)
}
func (hr *HookRenderer) formatPendingToolInfo(info *types.ToolInfo) string {
if info == nil {
return ""
}
tool := strings.TrimSpace(info.Tool)
if tool == "" {
return ""
}
// Keep this intentionally compact and readable.
// Format: "<tool> <identifier>" where identifier is the most relevant param.
var ident string
switch {
case strings.TrimSpace(info.Path) != "":
ident = strings.TrimSpace(info.Path)
case strings.TrimSpace(info.Command) != "":
ident = strings.TrimSpace(info.Command)
case strings.TrimSpace(info.Url) != "":
ident = strings.TrimSpace(info.Url)
case strings.TrimSpace(info.McpTool) != "" && strings.TrimSpace(info.McpServer) != "":
ident = fmt.Sprintf("%s %s", strings.TrimSpace(info.McpServer), strings.TrimSpace(info.McpTool))
case strings.TrimSpace(info.ResourceUri) != "":
ident = strings.TrimSpace(info.ResourceUri)
case strings.TrimSpace(info.Regex) != "":
ident = strings.TrimSpace(info.Regex)
default:
ident = ""
}
if ident != "" {
return fmt.Sprintf("%s %s", tool, ident)
}
return tool
}
func (hr *HookRenderer) renderMarkdown(markdown string) string {
// Align with ToolRenderer: in plain mode or non-TTY, return markdown as-is.
if hr.outputFormat == "plain" || !isTTY() {
return markdown
}
if hr.mdRenderer == nil {
return markdown
}
rendered, err := hr.mdRenderer.Render(markdown)
if err != nil {
return markdown
}
return rendered
}
+69
View File
@@ -0,0 +1,69 @@
package display
import (
"strings"
"testing"
"github.com/cline/cli/pkg/cli/types"
)
func TestHookRenderer_RenderHookStatus_FailedShowsErrorAndScript(t *testing.T) {
hr := NewHookRenderer(nil, "plain")
msg := hr.RenderHookStatus(types.HookMessage{
HookName: "PreToolUse",
ToolName: "execute_command",
Status: "failed",
ExitCode: 2,
ScriptPaths: []string{"repo/.clinerules/hooks/PreToolUse"},
Error: &types.HookError{
Message: "boom",
ScriptPath: "repo/.clinerules/hooks/PreToolUse",
},
})
if !strings.Contains(msg, "### Cline hook failed: PreToolUse") {
t.Fatalf("expected header in rendered output, got: %q", msg)
}
if !strings.Contains(msg, "- Error: boom") {
t.Fatalf("expected error line in rendered output, got: %q", msg)
}
if !strings.Contains(msg, "- Script: `repo/.clinerules/hooks/PreToolUse`") {
t.Fatalf("expected script line in rendered output, got: %q", msg)
}
}
func TestHookRenderer_RenderHookStatus_PendingToolInfoAppearsDirectlyUnderHeader(t *testing.T) {
hr := NewHookRenderer(nil, "plain")
msg := hr.RenderHookStatus(types.HookMessage{
HookName: "PreToolUse",
ToolName: "write_to_file",
Status: "running",
PendingToolInfo: &types.ToolInfo{
Tool: "write_to_file",
Path: "src/foo.ts",
},
ScriptPaths: []string{"repo/.clinerules/hooks/PreToolUse"},
})
header := "### Cline hook running: PreToolUse"
pending := "- Pending: write_to_file src/foo.ts"
runningHook := "- Running hook: `repo/.clinerules/hooks/PreToolUse`"
headerIdx := strings.Index(msg, header)
if headerIdx == -1 {
t.Fatalf("expected header %q in output, got: %q", header, msg)
}
pendingIdx := strings.Index(msg, pending)
if pendingIdx == -1 {
t.Fatalf("expected pending line %q in output, got: %q", pending, msg)
}
runningIdx := strings.Index(msg, runningHook)
if runningIdx == -1 {
t.Fatalf("expected running hook line %q in output, got: %q", runningHook, msg)
}
if !(headerIdx < pendingIdx && pendingIdx < runningIdx) {
t.Fatalf("expected header < pending < runningHook ordering, got indexes header=%d pending=%d running=%d\nfull=%q", headerIdx, pendingIdx, runningIdx, msg)
}
}
+13 -3
View File
@@ -39,9 +39,12 @@ func NewStreamingSegment(sayType, prefix string, mdRenderer *MarkdownRenderer, s
// Render rich header immediately when creating segment (if in rich mode and TTY)
if shouldMarkdown && outputFormat != "plain" && isTTY() {
header := ss.generateRichHeader()
rendered, _ := mdRenderer.Render(header)
output.Println("")
output.Print(rendered)
// Skip empty headers.
if strings.TrimSpace(header) != "" {
rendered, _ := mdRenderer.Render(header)
output.Println("")
output.Print(rendered)
}
}
return ss
@@ -110,6 +113,9 @@ func (ss *StreamingSegment) renderFinal(currentBuffer string) {
if err := json.Unmarshal([]byte(currentBuffer), &tool); err == nil {
bodyContent = ss.toolRenderer.GenerateToolContentBody(&tool)
}
} else if ss.sayType == string(types.SayTypeHookStatus) {
// Hooks are rendered via the state stream; nothing to render here.
bodyContent = ""
} else if ss.sayType == string(types.SayTypeCommand) {
// Command output
bodyContent = "```shell\n" + currentBuffer + "\n```"
@@ -160,6 +166,10 @@ func (ss *StreamingSegment) generateRichHeader() string {
case string(types.SayTypeTool):
return ss.generateToolHeader()
case string(types.SayTypeHookStatus):
// Hooks are rendered from the state stream; dont emit a partial-stream header.
return ""
case "ask":
// Check the specific ask type
@@ -0,0 +1,20 @@
package display
import (
"testing"
"github.com/cline/cli/pkg/cli/types"
)
func TestStreamingSegment_generateRichHeader_HookIsEmpty(t *testing.T) {
ss := &StreamingSegment{
sayType: string(types.SayTypeHookStatus),
prefix: "HOOK",
msg: &types.ClineMessage{},
}
header := ss.generateRichHeader()
if header != "" {
t.Fatalf("expected empty header for hook segments to avoid double-render, got: %q", header)
}
}
+19 -1
View File
@@ -38,6 +38,18 @@ func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
s.mu.Lock()
defer s.mu.Unlock()
// Render hooks from the state stream only (not partial stream) to avoid duplicates.
//
// Rationale: hook status messages are often updated/reordered by the backend (e.g. PreToolUse
// hooks are moved above the corresponding tool message). The state stream represents the
// authoritative, “final” message ordering, while the partial stream is best-effort for
// incremental display.
//
// Only suppress *partial* hook messages; complete ones still flow through dedupe.
if msg.Partial && msg.Say == string(types.SayTypeHookStatus) {
return nil
}
// Check for deduplication
if s.dedupe.IsDuplicate(msg) {
return nil
@@ -91,7 +103,11 @@ func (s *StreamingDisplay) HandlePartialMessage(msg *types.ClineMessage) error {
func (s *StreamingDisplay) shouldRenderMarkdown(sayType string) bool {
switch sayType {
case string(types.SayTypeReasoning), string(types.SayTypeText), string(types.SayTypeCompletionResult), string(types.SayTypeTool), "ask":
case string(types.SayTypeReasoning),
string(types.SayTypeText),
string(types.SayTypeCompletionResult),
string(types.SayTypeTool),
"ask":
return true
default:
return false
@@ -110,6 +126,8 @@ func (s *StreamingDisplay) getPrefix(sayType string) string {
return "ASK"
case string(types.SayTypeCommand):
return "TERMINAL"
case string(types.SayTypeHookStatus):
return "HOOK"
default:
return strings.ToUpper(sayType)
}
+1 -1
View File
@@ -264,6 +264,6 @@ func (sr *SystemMessageRenderer) RenderInfo(title, message string) error {
func (sr *SystemMessageRenderer) RenderCheckpoint(timestamp string, id int64) error {
markdown := fmt.Sprintf("## [%s] Checkpoint created `%d`", timestamp, id)
rendered := sr.renderer.RenderMarkdown(markdown)
fmt.Printf(rendered)
fmt.Print(rendered)
return nil
}
+7
View File
@@ -339,6 +339,13 @@ func (tr *ToolRenderer) RenderCommandOutput(output string) string {
return result.String()
}
func (tr *ToolRenderer) RenderCommandPermissionDenied(command string) string {
command = strings.TrimSpace(command)
rendered := tr.renderMarkdown("### Command was denied")
message := fmt.Sprintf("Cline does not have permission to execute this command: `%s`", command)
return fmt.Sprintf("\n%s\n\n%s\n", rendered, message)
}
// RenderUserResponse renders user approval/rejection feedback
func (tr *ToolRenderer) RenderUserResponse(approved bool, feedback string) string {
var symbol, status string
+22 -14
View File
@@ -36,7 +36,7 @@ func (c *ClineClients) Initialize(ctx context.Context) error {
}
// StartNewInstance starts a new Cline instance and waits for cline-core to self-register
func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstanceInfo, error) {
func (c *ClineClients) StartNewInstance(ctx context.Context, workspaces ...string) (*common.CoreInstanceInfo, error) {
// Find available ports
corePort, hostPort, err := common.FindAvailablePortPair()
if err != nil {
@@ -48,7 +48,7 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan
}
// Start cline-host first
hostCmd, err := startClineHost(hostPort, corePort)
hostCmd, err := startClineHost(hostPort, workspaces)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
@@ -120,7 +120,7 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan
}
// StartNewInstanceAtPort starts a new Cline instance at the specified port and waits for self-registration
func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int) (*common.CoreInstanceInfo, error) {
func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int, workspaces ...string) (*common.CoreInstanceInfo, error) {
// Find available host port (core port + 1000)
hostPort := corePort + 1000
coreAddress := fmt.Sprintf("localhost:%d", corePort)
@@ -135,7 +135,7 @@ func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int)
}
// Start cline-host first
hostCmd, err := startClineHost(hostPort, corePort)
hostCmd, err := startClineHost(hostPort, workspaces)
if err != nil {
return nil, fmt.Errorf("failed to start cline-host: %w", err)
}
@@ -242,7 +242,7 @@ func (c *ClineClients) EnsureInstanceAtAddress(ctx context.Context, address stri
return fmt.Errorf("cannot start remote instance at %s", normalized)
}
func startClineHost(hostPort, corePort int) (*exec.Cmd, error) {
func startClineHost(hostPort int, workspaces []string) (*exec.Cmd, error) {
if Config.Verbose {
fmt.Printf("Starting cline-host on port %d\n", hostPort)
}
@@ -255,10 +255,18 @@ func startClineHost(hostPort, corePort int) (*exec.Cmd, error) {
binDir := path.Dir(execPath)
clineHostPath := path.Join(binDir, "cline-host")
// Start the cline-host process
cmd := exec.Command(clineHostPath,
// Build command arguments
args := []string{
"--verbose",
"--port", fmt.Sprintf("%d", hostPort))
"--port", fmt.Sprintf("%d", hostPort),
}
for _, ws := range workspaces {
args = append(args, "--workspace", ws)
}
// Start the cline-host process
cmd := exec.Command(clineHostPath, args...)
// Create logs directory in ~/.cline/logs
logsDir := path.Join(Config.ConfigPath, "logs")
@@ -333,7 +341,7 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres
if Config.Verbose {
fmt.Printf("Waiting for instance to clean up registry entry...\n")
}
for i := 0; i < 5; i++ {
for range 5 {
time.Sleep(1 * time.Second)
if !registry.HasInstanceAtAddress(address) {
if Config.Verbose {
@@ -408,15 +416,15 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
// This handles the case where we're running from cli/bin/cline
devClineCorePath := path.Join(binDir, "..", "..", "dist-standalone", "cline-core.js")
devInstallDir := path.Join(binDir, "..", "..", "dist-standalone")
if Config.Verbose {
fmt.Printf("Primary location not found, trying development path: %s\n", devClineCorePath)
}
if _, err := os.Stat(devClineCorePath); os.IsNotExist(err) {
return nil, fmt.Errorf("cline-core.js not found at '%s' or '%s'. Please ensure you're running from the correct location or reinstall with 'npm install -g cline'", clineCorePath, devClineCorePath)
}
finalClineCorePath = devClineCorePath
finalInstallDir = devInstallDir
if Config.Verbose {
@@ -475,7 +483,7 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
realNodeModules := path.Join(finalInstallDir, "node_modules")
fakeNodeModules := path.Join(finalInstallDir, "fake_node_modules")
nodePath := fmt.Sprintf("%s%c%s", realNodeModules, os.PathListSeparator, fakeNodeModules)
env = append(env,
fmt.Sprintf("NODE_PATH=%s", nodePath),
// These control gRPC debug logging
@@ -484,7 +492,7 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) {
"NODE_ENV=development",
)
cmd.Env = env
if Config.Verbose {
fmt.Printf("NODE_PATH set to: %s\n", nodePath)
}
+9 -4
View File
@@ -37,11 +37,16 @@ var (
func InitializeGlobalConfig(cfg *GlobalConfig) error {
if cfg.ConfigPath == "" {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
// Check CLINE_DIR environment variable first
if clineDir := os.Getenv("CLINE_DIR"); clineDir != "" {
cfg.ConfigPath = clineDir
} else {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
}
cfg.ConfigPath = filepath.Join(homeDir, ".cline")
}
// Ensure .cline directory exists
+1
View File
@@ -25,6 +25,7 @@ type DisplayContext struct {
State *types.ConversationState
Renderer *display.Renderer
ToolRenderer *display.ToolRenderer
HookRenderer *display.HookRenderer
SystemRenderer *display.SystemMessageRenderer
IsLast bool
IsPartial bool
+40 -12
View File
@@ -6,8 +6,8 @@ import (
"strings"
"github.com/cline/cli/pkg/cli/clerror"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/types"
)
// SayHandler handles SAY type messages
@@ -90,6 +90,12 @@ func (h *SayHandler) Handle(msg *types.ClineMessage, dc *DisplayContext) error {
return h.handleInfo(msg, dc)
case string(types.SayTypeTaskProgress):
return h.handleTaskProgress(msg, dc)
case string(types.SayTypeHookStatus):
return h.handleHookStatus(msg, dc)
case string(types.SayTypeHookOutputStream):
return h.handleHookOutputStream(msg, dc)
case string(types.SayTypeCommandPermissionDenied):
return h.handleCommandPermissionDenied(msg, dc)
default:
return h.handleDefault(msg, dc)
}
@@ -242,18 +248,17 @@ func (h *SayHandler) handleCompletionResult(msg *types.ClineMessage, dc *Display
}
func formatUserMessage(text string) string {
lines := strings.Split(text, "\n")
// Wrap each line in backticks
for i, line := range lines {
if line != "" {
lines[i] = fmt.Sprintf("`%s`", line)
}
}
return strings.Join(lines, "\n")
}
lines := strings.Split(text, "\n")
// Wrap each line in backticks
for i, line := range lines {
if line != "" {
lines[i] = fmt.Sprintf("`%s`", line)
}
}
return strings.Join(lines, "\n")
}
// handleUserFeedback handles user feedback messages
func (h *SayHandler) handleUserFeedback(msg *types.ClineMessage, dc *DisplayContext) error {
@@ -343,6 +348,18 @@ func (h *SayHandler) handleCommandOutput(msg *types.ClineMessage, dc *DisplayCon
return nil
}
func (h *SayHandler) handleCommandPermissionDenied(msg *types.ClineMessage, dc *DisplayContext) error {
if msg.Text == "" {
return nil
}
// Use unified ToolRenderer
rendered := dc.ToolRenderer.RenderCommandPermissionDenied(msg.Text)
output.Print(rendered)
return nil
}
func (h *SayHandler) handleTool(msg *types.ClineMessage, dc *DisplayContext) error {
var tool types.ToolMessage
if err := json.Unmarshal([]byte(msg.Text), &tool); err != nil {
@@ -517,5 +534,16 @@ func (h *SayHandler) handleTaskProgress(msg *types.ClineMessage, dc *DisplayCont
// handleDefault handles unknown SAY message types
func (h *SayHandler) handleDefault(msg *types.ClineMessage, dc *DisplayContext) error {
// Debug: log unhandled say types to help identify missing cases using output.Printf for CLI consistency
if dc.Verbose {
output.Printf("[DEBUG] Unhandled SAY type: '%s' (text preview: %s)\n", msg.Say, truncateForDisplay(msg.Text, 50))
}
return dc.Renderer.RenderMessage("SAY", msg.Text, true)
}
func truncateForDisplay(text string, maxLen int) string {
if len(text) <= maxLen {
return text
}
return text[:maxLen] + "..."
}
+198
View File
@@ -0,0 +1,198 @@
package handlers
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/cline/cli/pkg/cli/output"
"github.com/cline/cli/pkg/cli/types"
)
// Hook-specific SAY handlers and helpers.
// Kept in a separate file to keep say_handlers.go focused on routing.
// handleHookStatus handles hook execution status messages.
func (h *SayHandler) handleHookStatus(msg *types.ClineMessage, dc *DisplayContext) error {
hook, err := parseHookMessage(msg.Text)
if err != nil {
// Fallback to basic output if JSON parsing fails
return dc.Renderer.RenderMessage("HOOK", msg.Text, true)
}
logHookDebug(hook, dc)
hook.ScriptPaths = formatHookPaths(hook.ScriptPaths)
return renderHookStatus(hook, dc)
}
// handleHookOutputStream handles streaming output from hooks.
//
// Hook stdout/stderr currently arrives line-by-line from the backend as
// `hook_output_stream` messages. The CLI intentionally suppresses these by default
// to keep the transcript high-signal.
//
// In --verbose mode, we print each non-empty line prefixed with "HOOK>" for easy grepping.
// Future work could associate these lines with a specific hook execution and render them
// as a grouped section under the hook status header.
func (h *SayHandler) handleHookOutputStream(msg *types.ClineMessage, dc *DisplayContext) error {
if !dc.Verbose {
return nil
}
line := strings.TrimRight(msg.Text, "\n")
if strings.TrimSpace(line) == "" {
return nil
}
output.Printf("HOOK> %s\n", line)
return nil
}
func parseHookMessage(jsonText string) (types.HookMessage, error) {
var hook types.HookMessage
if err := json.Unmarshal([]byte(jsonText), &hook); err != nil {
return types.HookMessage{}, err
}
return hook, nil
}
func logHookDebug(hook types.HookMessage, dc *DisplayContext) {
if dc.Verbose {
output.Printf("[DEBUG] Hook parsed: name=%s, status=%s, toolName=%s, scriptPaths=%v\n",
hook.HookName, hook.Status, hook.ToolName, hook.ScriptPaths)
}
}
func formatHookPaths(paths []string) []string {
if len(paths) == 0 {
return paths
}
formatted := make([]string, 0, len(paths))
for _, p := range paths {
if strings.TrimSpace(p) == "" {
continue
}
formatted = append(formatted, formatHookPath(p))
}
return formatted
}
func renderHookStatus(hook types.HookMessage, dc *DisplayContext) error {
if dc.HookRenderer != nil {
rendered := dc.HookRenderer.RenderHookStatus(hook)
// Match ToolRenderers spacing: one leading newline, one trailing newline.
output.Print("\n")
output.Print(rendered)
output.Print("\n")
return nil
}
// Fallback: if HookRenderer not available
return dc.Renderer.RenderMessage("HOOK", fmt.Sprintf("%s %s", hook.HookName, hook.Status), true)
}
func formatHookPath(fullPath string) string {
// Normalize for display and prefix checks. This is display-only; do not use for IO.
normalized := normalizeSlashes(fullPath)
// If this is a repo-scoped hook script (i.e. lives under <repo>/.clinerules/hooks/),
// always include the repo name for disambiguation even in single-repo workspaces.
//
// This intentionally runs before workspace-relative formatting, which would otherwise
// collapse to ".clinerules/hooks/..." and lose the repo context.
if p, ok := tryRepoScopedHooksPath(normalized); ok {
return p
}
// Prefer workspace-relative paths first for readability, since most hook scripts
// live inside the current project.
if p, ok := tryWorkspaceRelativeHookPath(normalized); ok {
return p
}
// Follow existing CLI pattern: resolve home via os.UserHomeDir.
if p, ok := tryHomeTildePath(normalized); ok {
return p
}
// Secondary heuristic: if hook lives under <repo>/.clinerules, collapse to repo-relative.
if p, ok := tryRepoRelativeHookPath(normalized); ok {
return p
}
return fallbackLastComponents(normalized, 3)
}
func normalizeSlashes(p string) string {
return filepath.ToSlash(p)
}
func tryWorkspaceRelativeHookPath(normalizedPath string) (string, bool) {
root, err := os.Getwd()
if err != nil {
return "", false
}
// filepath.Rel expects OS-native paths, so we need to convert the normalized path
// back to OS-native format before calling Rel, then normalize the result for display.
targetOS := filepath.FromSlash(normalizedPath)
rel, err := filepath.Rel(root, targetOS)
if err != nil {
return "", false
}
// If it's not within the workspace, Rel will start with "..".
if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", false
}
return normalizeSlashes(rel), true
}
func tryHomeTildePath(normalizedPath string) (string, bool) {
homeDir, err := os.UserHomeDir()
if err != nil || strings.TrimSpace(homeDir) == "" {
return "", false
}
homeDir = normalizeSlashes(homeDir)
if !strings.HasPrefix(normalizedPath, homeDir) {
return "", false
}
rel := strings.TrimPrefix(normalizedPath, homeDir)
rel = strings.TrimPrefix(rel, "/")
return "~/" + rel, true
}
func tryRepoRelativeHookPath(normalizedPath string) (string, bool) {
parts := strings.Split(normalizedPath, "/")
for i, part := range parts {
if part == ".clinerules" && i > 0 {
repoName := parts[i-1]
return repoName + "/" + strings.Join(parts[i:], "/"), true
}
}
return "", false
}
// tryRepoScopedHooksPath returns a repo-prefixed path like
// "myrepo/.clinerules/hooks/PreToolUse" when the given path points to a hook script
// under a repo's .clinerules/hooks directory.
//
// This is more specific than tryRepoRelativeHookPath and is used to ensure hook script
// paths always include repo context.
func tryRepoScopedHooksPath(normalizedPath string) (string, bool) {
// Fast path check to avoid split work.
if !strings.Contains(normalizedPath, "/.clinerules/hooks/") {
return "", false
}
return tryRepoRelativeHookPath(normalizedPath)
}
func fallbackLastComponents(normalizedPath string, n int) string {
parts := strings.Split(normalizedPath, "/")
if len(parts) >= n {
return strings.Join(parts[len(parts)-n:], "/")
}
return normalizedPath
}
@@ -0,0 +1,41 @@
package handlers
import (
"os"
"path/filepath"
"testing"
)
func TestFormatHookPath_PrefersWorkspaceRelative(t *testing.T) {
// Create a stable workspace root (avoid TempDir's nested ".../001" patterns)
// so that workspace-relative formatting is deterministic.
root := filepath.Join(t.TempDir(), "workspace")
if err := os.MkdirAll(root, 0o755); err != nil {
t.Fatalf("MkdirAll: %v", err)
}
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Getwd: %v", err)
}
defer func() { _ = os.Chdir(oldWd) }()
if err := os.Chdir(root); err != nil {
t.Fatalf("Chdir: %v", err)
}
inside := filepath.Join(root, ".clinerules", "hooks", "pre.sh")
got := formatHookPath(inside)
// Repo-scoped hook scripts should always include the repo name (the directory
// immediately containing .clinerules) even when running inside that repo.
expected := "workspace/" + filepath.ToSlash(filepath.Join(".clinerules", "hooks", "pre.sh"))
if got != expected {
t.Fatalf("expected formatted path to be %q. got=%q", expected, got)
}
}
func TestFormatHookPath_FallsBackToLastComponents(t *testing.T) {
// Use an obviously non-workspace path (relative, but not prefixed with cwd).
got := formatHookPath("/var/tmp/foo/bar/baz.sh")
if got != "foo/bar/baz.sh" {
t.Fatalf("expected last 3 components fallback, got=%q", got)
}
}
+35
View File
@@ -0,0 +1,35 @@
package handlers
import (
"os"
"testing"
)
func TestFormatHookPath_HomeDirToTilde(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil || home == "" {
t.Skip("home dir not available; skipping")
}
got := formatHookPath(home + "/Documents/Cline/Hooks/TaskStart")
want := "~/Documents/Cline/Hooks/TaskStart"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFormatHookPath_WorkspaceRepoRelative(t *testing.T) {
got := formatHookPath("/Users/alice/dev/repo-name/.clinerules/hooks/TaskStart")
want := "repo-name/.clinerules/hooks/TaskStart"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestFormatHookPath_FallbackLast3Components(t *testing.T) {
got := formatHookPath("/a/b/c/d/e")
want := "c/d/e"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
+2 -2
View File
@@ -407,7 +407,7 @@ func newInstanceListCommand() *cobra.Command {
fmt.Print(strings.TrimLeft(rendered, "\n"))
}
fmt.Println("\n")
fmt.Println()
}
}
@@ -503,4 +503,4 @@ func newInstanceNewCommand() *cobra.Command {
cmd.Flags().BoolVarP(&setDefault, "default", "d", false, "set as default instance")
return cmd
}
}
+74 -22
View File
@@ -9,12 +9,13 @@ import (
"github.com/charmbracelet/bubbles/textarea"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/slash"
)
// InputType represents the type of input being collected
type InputType int
const INPUT_WIDTH = 46
const INPUT_WIDTH = 46
const (
InputTypeMessage InputType = iota
@@ -24,11 +25,11 @@ const (
// InputSubmitMsg is sent when the user submits input
type InputSubmitMsg struct {
Value string
InputType InputType
Approved bool // For approval type
NeedsFeedback bool // For approval type
NoAskAgain bool // For approval type - indicates "don't ask again" was selected
Value string
InputType InputType
Approved bool // For approval type
NeedsFeedback bool // For approval type
NoAskAgain bool // For approval type - indicates "don't ask again" was selected
}
// InputCancelMsg is sent when the user cancels input (Ctrl+C)
@@ -36,8 +37,8 @@ type InputCancelMsg struct{}
// ChangeInputTypeMsg changes the current input type
type ChangeInputTypeMsg struct {
InputType InputType
Title string
InputType InputType
Title string
Placeholder string
}
@@ -57,7 +58,7 @@ type InputModel struct {
placeholder string
currentMode string // "plan" or "act"
width int
lastHeight int // Track height for cleanup on submit
lastHeight int // Track height for cleanup on submit
// For approval type
approvalOptions []string
@@ -66,6 +67,9 @@ type InputModel struct {
// Styles (huh-inspired theme)
styles fieldStyles
// Slash command autocomplete dropdown
completion CompletionModel
}
// fieldStyles holds the styling for the input field
@@ -115,12 +119,17 @@ func newFieldStyles() fieldStyles {
// NewInputModel creates a new input model
func NewInputModel(inputType InputType, title, placeholder, currentMode string) InputModel {
return NewInputModelWithRegistry(inputType, title, placeholder, currentMode, nil)
}
// NewInputModelWithRegistry creates a new input model with slash command autocomplete support
func NewInputModelWithRegistry(inputType InputType, title, placeholder, currentMode string, registry *slash.Registry) InputModel {
ta := textarea.New()
ta.Placeholder = placeholder
ta.Focus()
ta.CharLimit = 0
ta.ShowLineNumbers = false
ta.Prompt = "" // Remove prompt prefix (this is what adds the inner border!)
ta.Prompt = "" // Remove prompt prefix (this is what adds the inner border!)
ta.SetHeight(5)
// Don't set width here - let WindowSizeMsg handle it
ta.SetWidth(INPUT_WIDTH)
@@ -138,11 +147,11 @@ func NewInputModel(inputType InputType, title, placeholder, currentMode string)
cursorColor = lipgloss.Color("39") // Blue for act
}
ta.FocusedStyle.CursorLine = lipgloss.NewStyle() // No cursor line highlighting
ta.FocusedStyle.EndOfBuffer = lipgloss.NewStyle() // No end-of-buffer styling
ta.FocusedStyle.CursorLine = lipgloss.NewStyle() // No cursor line highlighting
ta.FocusedStyle.EndOfBuffer = lipgloss.NewStyle() // No end-of-buffer styling
ta.FocusedStyle.Placeholder = styles.placeholder
ta.FocusedStyle.Text = styles.textArea
ta.FocusedStyle.Prompt = lipgloss.NewStyle() // No prompt styling
ta.FocusedStyle.Prompt = lipgloss.NewStyle() // No prompt styling
ta.Cursor.Style = lipgloss.NewStyle().Foreground(cursorColor)
ta.Cursor.TextStyle = styles.textArea
@@ -154,6 +163,7 @@ func NewInputModel(inputType InputType, title, placeholder, currentMode string)
currentMode: currentMode,
width: 0, // Will be set by first WindowSizeMsg
styles: styles,
completion: NewCompletionModel(registry),
}
// For approval type, set up options
@@ -217,13 +227,6 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return m, nil
default:
// Forward all other messages to textarea (including blink ticks)
if !m.suspended && (m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback) {
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
}
case tea.KeyMsg:
if m.suspended {
return m, nil
@@ -231,6 +234,31 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Handle keys for text input types (Message/Feedback)
if m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback {
// When completion menu is visible, let it handle navigation keys first
if m.completion.Visible() {
// ctrl+c always cancels, even with dropdown open
if msg.String() == "ctrl+c" {
return m, func() tea.Msg { return InputCancelMsg{} }
}
var handled bool
m.completion, cmd, handled = m.completion.Update(msg)
if handled {
// Check if a completion was selected
if applied := m.completion.Apply(); applied != "" {
m.textarea.SetValue(applied)
m.textarea.CursorEnd()
}
return m, cmd
}
// Key not handled by completion - pass to textarea and update completion
m.textarea, cmd = m.textarea.Update(msg)
m.completion.CheckInput(m.textarea.Value())
return m, cmd
}
// Normal key handling when completion menu is NOT visible
switch msg.String() {
case "ctrl+c":
return m, func() tea.Msg { return InputCancelMsg{} }
@@ -239,6 +267,11 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Open external editor (like huh does)
return m, m.openEditor()
case "tab":
// Tab without dropdown visible - do nothing special
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
case "enter":
// Intercept enter for submit (textarea handles alt+enter and ctrl+j for newlines)
return m.handleSubmit()
@@ -249,8 +282,9 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, cmd
}
// Pass all other keys to textarea (including alt+enter, ctrl+j for newlines)
// Pass all other keys to textarea, then check for slash completion
m.textarea, cmd = m.textarea.Update(msg)
m.completion.CheckInput(m.textarea.Value())
return m, cmd
}
@@ -276,6 +310,13 @@ func (m *InputModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
}
}
default:
// Forward all other messages to textarea (including blink ticks)
if !m.suspended && (m.inputType == InputTypeMessage || m.inputType == InputTypeFeedback) {
m.textarea, cmd = m.textarea.Update(msg)
return m, cmd
}
}
return m, nil
@@ -365,6 +406,11 @@ func (m *InputModel) View() string {
case InputTypeMessage, InputTypeFeedback:
parts = append(parts, m.textarea.View())
// Render completion dropdown if visible
if m.completion.Visible() {
parts = append(parts, m.completion.View())
}
case InputTypeApproval:
var options []string
for i, option := range m.approvalOptions {
@@ -411,7 +457,7 @@ func (m *InputModel) Clone() *InputModel {
ta.ShowLineNumbers = false
ta.Prompt = ""
ta.SetHeight(5)
ta.SetWidth(INPUT_WIDTH)
ta.SetWidth(INPUT_WIDTH)
ta.Focus()
// Configure keybindings
@@ -446,6 +492,7 @@ func (m *InputModel) Clone() *InputModel {
selectedOption: m.selectedOption,
pendingApproval: m.pendingApproval, // Preserve approval decision
styles: m.styles,
completion: NewCompletionModel(m.completion.registry), // Preserve registry, start fresh state
}
return clone
@@ -495,3 +542,8 @@ func (m *InputModel) openEditor() tea.Cmd {
return editorFinishedMsg{content: content, err: err}
})
}
// SetSlashRegistry sets the slash command registry for autocomplete
func (m *InputModel) SetSlashRegistry(registry *slash.Registry) {
m.completion.SetRegistry(registry)
}
+265
View File
@@ -0,0 +1,265 @@
package output
import (
"fmt"
"strings"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/cline/cli/pkg/cli/slash"
)
const maxVisibleCompletions = 7
// completionStyles holds the styling for the completion dropdown
type completionStyles struct {
menu lipgloss.Style
selected lipgloss.Style
normalName lipgloss.Style
description lipgloss.Style
scrollIndicator lipgloss.Style
}
// newCompletionStyles creates the default styles for the completion dropdown
func newCompletionStyles() completionStyles {
return completionStyles{
menu: lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("238")).
Padding(0, 1),
selected: lipgloss.NewStyle().
Background(lipgloss.Color("62")).
Foreground(lipgloss.Color("230")),
normalName: lipgloss.NewStyle().
Foreground(lipgloss.AdaptiveColor{Light: "235", Dark: "252"}),
description: lipgloss.NewStyle().
Foreground(lipgloss.Color("243")),
scrollIndicator: lipgloss.NewStyle().
Foreground(lipgloss.Color("243")),
}
}
// CompletionModel is a Bubbletea model for slash command autocomplete dropdown
type CompletionModel struct {
registry *slash.Registry
visible bool
matches []slash.Command
index int // selected item (0-based)
scroll int // scroll offset for long lists
styles completionStyles
// pendingApply holds the command to apply after selection
pendingApply string
}
// NewCompletionModel creates a new completion model with the given registry
func NewCompletionModel(registry *slash.Registry) CompletionModel {
return CompletionModel{
registry: registry,
styles: newCompletionStyles(),
}
}
// SetRegistry sets the slash command registry
func (m *CompletionModel) SetRegistry(registry *slash.Registry) {
m.registry = registry
}
// Visible returns whether the completion dropdown is currently visible
func (m CompletionModel) Visible() bool {
return m.visible
}
// Update handles key messages for the completion dropdown.
// Returns the updated model, any commands, and whether the key was handled.
// If handled is true, the parent should NOT pass the key to the textarea.
func (m CompletionModel) Update(msg tea.Msg) (CompletionModel, tea.Cmd, bool) {
if !m.visible {
return m, nil, false
}
keyMsg, ok := msg.(tea.KeyMsg)
if !ok {
return m, nil, false
}
switch keyMsg.String() {
case "up":
m.navigateUp()
return m, nil, true
case "down":
m.navigateDown()
return m, nil, true
case "tab", "enter":
// Select the current completion
if len(m.matches) > 0 {
selected := m.matches[m.index]
m.pendingApply = "/" + selected.Name + " "
}
m.Hide()
return m, nil, true
case "esc":
m.Hide()
return m, nil, true
}
// Key not handled by completion - let parent process it
return m, nil, false
}
// CheckInput updates the completion state based on the current input value.
// Call this after each input change to show/hide/update the dropdown.
func (m *CompletionModel) CheckInput(value string) {
if m.registry == nil {
return
}
// Only activate if input starts with "/" (first character requirement)
if !strings.HasPrefix(value, "/") {
m.Hide()
return
}
// Extract the command being typed (everything after "/" until space/newline)
rest := value[1:] // Everything after the "/"
// If there's whitespace, the command is complete - hide dropdown
if idx := strings.IndexAny(rest, " \n\t"); idx != -1 {
m.Hide()
return
}
// Update matches based on prefix
m.updateMatches(rest)
m.visible = len(m.matches) > 0
}
// Apply returns the command string to insert (if any) and clears the pending state.
// The parent should call this after Update returns handled=true for tab/enter.
func (m *CompletionModel) Apply() string {
result := m.pendingApply
m.pendingApply = ""
return result
}
// Hide hides the completion dropdown and resets state
func (m *CompletionModel) Hide() {
m.visible = false
m.matches = nil
m.index = 0
m.scroll = 0
}
// View renders the completion dropdown
func (m CompletionModel) View() string {
if !m.visible || len(m.matches) == 0 {
return ""
}
var lines []string
// Calculate visible range
endIdx := min(m.scroll+maxVisibleCompletions, len(m.matches))
// Show scroll indicator if there are items above
if m.scroll > 0 {
lines = append(lines, m.styles.scrollIndicator.Render(" ↑ more"))
}
// Find the longest command name for alignment
maxNameLen := 0
for _, cmd := range m.matches {
nameLen := len(cmd.Name) + 1 // +1 for the "/"
if nameLen > maxNameLen {
maxNameLen = nameLen
}
}
// Cap at reasonable width
if maxNameLen > 15 {
maxNameLen = 15
}
// Render visible items
for i := m.scroll; i < endIdx; i++ {
cmd := m.matches[i]
name := "/" + cmd.Name
desc := cmd.Description
// Truncate description if too long
maxDescLen := 35
if len(desc) > maxDescLen {
desc = desc[:maxDescLen-3] + "..."
}
// Pad name for alignment
paddedName := fmt.Sprintf("%-*s", maxNameLen, name)
if i == m.index {
// Selected item - highlight the entire line
line := fmt.Sprintf("> %s %s", paddedName, desc)
lines = append(lines, m.styles.selected.Render(line))
} else {
// Normal item
line := fmt.Sprintf(" %s %s", m.styles.normalName.Render(paddedName), m.styles.description.Render(desc))
lines = append(lines, line)
}
}
// Show scroll indicator if there are items below
if endIdx < len(m.matches) {
lines = append(lines, m.styles.scrollIndicator.Render(" ↓ more"))
}
return m.styles.menu.Render(strings.Join(lines, "\n"))
}
// updateMatches filters commands by prefix and updates the matches list
func (m *CompletionModel) updateMatches(prefix string) {
if m.registry == nil {
m.matches = nil
return
}
m.matches = m.registry.GetMatching(prefix)
// Reset selection if out of bounds
if m.index >= len(m.matches) {
m.index = 0
m.scroll = 0
}
m.adjustScroll()
}
// navigateUp moves selection up in the dropdown
func (m *CompletionModel) navigateUp() {
if len(m.matches) == 0 {
return
}
m.index--
if m.index < 0 {
m.index = len(m.matches) - 1
}
m.adjustScroll()
}
// navigateDown moves selection down in the dropdown
func (m *CompletionModel) navigateDown() {
if len(m.matches) == 0 {
return
}
m.index++
if m.index >= len(m.matches) {
m.index = 0
}
m.adjustScroll()
}
// adjustScroll ensures the selected item is visible in the dropdown
func (m *CompletionModel) adjustScroll() {
if m.index < m.scroll {
m.scroll = m.index
} else if m.index >= m.scroll+maxVisibleCompletions {
m.scroll = m.index - maxVisibleCompletions + 1
}
}
+125
View File
@@ -0,0 +1,125 @@
package slash
import (
"context"
"strings"
"sync"
"github.com/cline/grpc-go/client"
"github.com/cline/grpc-go/cline"
)
// Command represents a slash command available for autocomplete
type Command struct {
Name string
Description string
Section string // "default", "custom", or "cli"
CLICompatible bool
}
// Registry holds available slash commands for autocomplete
type Registry struct {
mu sync.RWMutex
commands []Command
}
// CLI-local commands (handled by CLI, not sent to backend)
var cliLocalCommands = []Command{
{Name: "plan", Description: "Switch to plan mode", Section: "cli", CLICompatible: true},
{Name: "act", Description: "Switch to act mode", Section: "cli", CLICompatible: true},
{Name: "cancel", Description: "Cancel the current task", Section: "cli", CLICompatible: true},
{Name: "exit", Description: "Exit follow mode", Section: "cli", CLICompatible: true},
}
// NewRegistry creates a new slash command registry
func NewRegistry() *Registry {
return &Registry{
commands: make([]Command, 0),
}
}
// FetchFromBackend fetches available commands from cline-core backend
func (r *Registry) FetchFromBackend(ctx context.Context, c *client.ClineClient) error {
resp, err := c.Slash.GetAvailableSlashCommands(ctx, &cline.EmptyRequest{})
if err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
// Start with CLI-local commands
r.commands = append([]Command{}, cliLocalCommands...)
// Add backend commands (only CLI-compatible ones)
for _, cmd := range resp.Commands {
if cmd.CliCompatible {
r.commands = append(r.commands, Command{
Name: cmd.Name,
Description: cmd.Description,
Section: cmd.Section,
CLICompatible: cmd.CliCompatible,
})
}
}
return nil
}
// GetCommands returns all available commands
func (r *Registry) GetCommands() []Command {
r.mu.RLock()
defer r.mu.RUnlock()
// Return a copy to avoid race conditions
result := make([]Command, len(r.commands))
copy(result, r.commands)
return result
}
// GetMatching returns commands that start with the given prefix (case-insensitive)
func (r *Registry) GetMatching(prefix string) []Command {
r.mu.RLock()
defer r.mu.RUnlock()
prefix = strings.ToLower(prefix)
var matches []Command
for _, cmd := range r.commands {
if strings.HasPrefix(strings.ToLower(cmd.Name), prefix) {
matches = append(matches, cmd)
}
}
return matches
}
// IsValid checks if a command name is valid
func (r *Registry) IsValid(name string) bool {
r.mu.RLock()
defer r.mu.RUnlock()
name = strings.ToLower(name)
for _, cmd := range r.commands {
if strings.ToLower(cmd.Name) == name {
return true
}
}
return false
}
// IsCLILocal checks if a command is handled locally by CLI (not sent to backend)
func (r *Registry) IsCLILocal(name string) bool {
name = strings.ToLower(name)
for _, cmd := range cliLocalCommands {
if strings.ToLower(cmd.Name) == name {
return true
}
}
return false
}
// HasCommands returns true if the registry has any commands loaded
func (r *Registry) HasCommands() bool {
r.mu.RLock()
defer r.mu.RUnlock()
return len(r.commands) > 0
}
+8 -7
View File
@@ -20,13 +20,14 @@ import (
// TaskOptions contains options for creating a task
type TaskOptions struct {
Images []string
Files []string
Mode string
Settings []string
Yolo bool
Address string
Verbose bool
Images []string
Files []string
Mode string
Settings []string
Yolo bool
Address string
Verbose bool
Workspaces []string
}
func NewTaskCommand() *cobra.Command {
+16 -13
View File
@@ -38,13 +38,13 @@ type InputHandler struct {
// NewInputHandler creates a new input handler
func NewInputHandler(manager *Manager, coordinator *StreamCoordinator, cancelFunc context.CancelFunc) *InputHandler {
return &InputHandler{
manager: manager,
coordinator: coordinator,
cancelFunc: cancelFunc,
isRunning: false,
pollTicker: time.NewTicker(500 * time.Millisecond),
resultChan: make(chan output.InputSubmitMsg, 1),
cancelChan: make(chan struct{}, 1),
manager: manager,
coordinator: coordinator,
cancelFunc: cancelFunc,
isRunning: false,
pollTicker: time.NewTicker(500 * time.Millisecond),
resultChan: make(chan output.InputSubmitMsg, 1),
cancelChan: make(chan struct{}, 1),
}
}
@@ -281,11 +281,12 @@ func determineAutoApprovalAction(msg *types.ClineMessage) (string, error) {
func (ih *InputHandler) promptForInput(ctx context.Context) (string, bool, error) {
currentMode := ih.manager.GetCurrentMode()
model := output.NewInputModel(
model := output.NewInputModelWithRegistry(
output.InputTypeMessage,
"Cline is ready for your message...",
"/plan or /act to switch modes\nctrl+e to open editor",
"/plan or /act to switch modes\nctrl+e to open editor\ntab to autocomplete commands",
currentMode,
ih.manager.GetSlashRegistry(),
)
return ih.runInputProgram(ctx, model)
@@ -295,12 +296,13 @@ func (ih *InputHandler) promptForInput(ctx context.Context) (string, bool, error
func (ih *InputHandler) promptForApproval(ctx context.Context, msg *types.ClineMessage) (bool, string, error) {
// Store the approval message for later use in determining auto-approval action
ih.approvalMessage = msg
model := output.NewInputModel(
model := output.NewInputModelWithRegistry(
output.InputTypeApproval,
"Let Cline use this tool?",
"",
ih.manager.GetCurrentMode(),
ih.manager.GetSlashRegistry(), // Pass registry for feedback input after approval
)
message, shouldSend, err := ih.runInputProgram(ctx, model)
@@ -395,7 +397,7 @@ func (ih *InputHandler) runInputProgram(ctx context.Context, model output.InputM
// Need to collect feedback - will be handled by model state change
return "", false, nil
}
// Check if NoAskAgain was selected
if result.NoAskAgain && result.Approved && ih.approvalMessage != nil {
// Determine which auto-approval action to enable
@@ -411,7 +413,7 @@ func (ih *InputHandler) runInputProgram(ctx context.Context, model output.InputM
}
}
}
// Store approval state for when feedback comes back
ih.feedbackApproval = false
ih.feedbackApproved = result.Approved
@@ -441,6 +443,7 @@ func (w *inputProgramWrapper) Init() tea.Cmd {
}
func (w *inputProgramWrapper) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case output.InputSubmitMsg:
// Handle input submission - clear the screen before quitting
+66 -4
View File
@@ -14,6 +14,7 @@ import (
"github.com/cline/cli/pkg/cli/display"
"github.com/cline/cli/pkg/cli/global"
"github.com/cline/cli/pkg/cli/handlers"
"github.com/cline/cli/pkg/cli/slash"
"github.com/cline/cli/pkg/cli/types"
"github.com/cline/grpc-go/client"
"github.com/cline/grpc-go/cline"
@@ -32,10 +33,12 @@ type Manager struct {
clientAddress string
state *types.ConversationState
renderer *display.Renderer
hookRenderer *display.HookRenderer
toolRenderer *display.ToolRenderer
systemRenderer *display.SystemMessageRenderer
streamingDisplay *display.StreamingDisplay
handlerRegistry *handlers.HandlerRegistry
slashRegistry *slash.Registry
isStreamingMode bool
isInteractive bool
currentMode string // "plan" or "act"
@@ -46,6 +49,7 @@ func NewManager(client *client.ClineClient) *Manager {
state := types.NewConversationState()
renderer := display.NewRenderer(global.Config.OutputFormat)
toolRenderer := display.NewToolRenderer(renderer.GetMdRenderer(), global.Config.OutputFormat)
hookRenderer := display.NewHookRenderer(renderer.GetMdRenderer(), global.Config.OutputFormat)
systemRenderer := display.NewSystemMessageRenderer(renderer, renderer.GetMdRenderer(), global.Config.OutputFormat)
streamingDisplay := display.NewStreamingDisplay(state, renderer)
@@ -59,10 +63,12 @@ func NewManager(client *client.ClineClient) *Manager {
clientAddress: "", // Will be set when client is provided
state: state,
renderer: renderer,
hookRenderer: hookRenderer,
toolRenderer: toolRenderer,
systemRenderer: systemRenderer,
streamingDisplay: streamingDisplay,
handlerRegistry: registry,
slashRegistry: slash.NewRegistry(),
currentMode: "plan", // Default mode
}
}
@@ -76,6 +82,10 @@ func NewManagerForAddress(ctx context.Context, address string) (*Manager, error)
manager := NewManager(client)
manager.clientAddress = address
// Fetch slash commands from backend (non-blocking, errors are logged)
manager.fetchSlashCommands(ctx)
return manager, nil
}
@@ -93,9 +103,25 @@ func NewManagerForDefault(ctx context.Context) (*Manager, error) {
manager.clientAddress = global.Clients.GetRegistry().GetDefaultInstance()
}
// Fetch slash commands from backend (non-blocking, errors are logged)
manager.fetchSlashCommands(ctx)
return manager, nil
}
// fetchSlashCommands fetches available slash commands from the backend
// This is non-blocking and errors are logged but don't prevent manager creation
func (m *Manager) fetchSlashCommands(ctx context.Context) {
if err := m.slashRegistry.FetchFromBackend(ctx, m.client); err != nil {
if global.Config.Verbose {
m.renderer.RenderDebug("Failed to fetch slash commands: %v", err)
}
// Non-fatal: CLI-local commands are still available
} else if global.Config.Verbose {
m.renderer.RenderDebug("Loaded %d slash commands", len(m.slashRegistry.GetCommands()))
}
}
// SwitchToInstance switches the manager to use a different Cline instance
func (m *Manager) SwitchToInstance(ctx context.Context, address string) error {
m.mu.Lock()
@@ -966,6 +992,15 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeCommandPermissionDenied):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeBrowserActionLaunch):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
@@ -1020,6 +1055,26 @@ func (m *Manager) processStateUpdate(stateUpdate *cline.State, coordinator *Stre
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeHookStatus):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
fmt.Println()
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeHookOutputStream):
// Hook stdout/stderr streaming arrives as hook_output_stream messages.
// These are intentionally suppressed unless verbose (see SayHandler.handleHookOutputStream),
// but we still need to route them through the normal handler pipeline in streaming/follow
// mode so verbose users actually see `HOOK> ...` lines.
msgKey := fmt.Sprintf("%d", msg.Timestamp)
if !coordinator.IsProcessedInCurrentTurn(msgKey) {
m.displayMessage(msg, false, false, i)
coordinator.MarkProcessedInCurrentTurn(msgKey)
}
case msg.Say == string(types.SayTypeAPIReqStarted):
msgKey := fmt.Sprintf("%d", msg.Timestamp)
apiInfo := types.APIRequestInfo{Cost: -1}
@@ -1151,12 +1206,14 @@ func (m *Manager) displayMessage(msg *types.ClineMessage, isLast, isPartial bool
m.mu.RUnlock()
dc := &handlers.DisplayContext{
State: m.state,
Renderer: m.renderer,
ToolRenderer: m.toolRenderer,
SystemRenderer: m.systemRenderer,
State: m.state,
Renderer: m.renderer,
ToolRenderer: m.toolRenderer,
HookRenderer: m.hookRenderer,
SystemRenderer: m.systemRenderer,
IsLast: isLast,
IsPartial: isPartial,
Verbose: global.Config.Verbose,
MessageIndex: messageIndex,
IsStreamingMode: isStreaming,
IsInteractive: isInteractive,
@@ -1263,6 +1320,11 @@ func (m *Manager) GetCurrentMode() string {
return m.currentMode
}
// GetSlashRegistry returns the slash command registry
func (m *Manager) GetSlashRegistry() *slash.Registry {
return m.slashRegistry
}
// extractModeFromState extracts the current mode from state JSON
func (m *Manager) extractModeFromState(stateJson string) string {
var rawState map[string]interface{}
+6
View File
@@ -296,6 +296,12 @@ func setSimpleField(settings *cline.Settings, key, value string) error {
return err
}
settings.HooksEnabled = boolPtr(val)
case "azure_identity":
val, err := parseBool(value)
if err != nil {
return err
}
settings.AzureIdentity = boolPtr(val)
// Integer fields
case "request_timeout_ms":
+12 -11
View File
@@ -3,15 +3,16 @@ package types
// HistoryItem represents a task history item from taskHistory.json
// This struct matches the JSON format stored on disk
type HistoryItem struct {
Id string `json:"id"`
Ulid string `json:"ulid,omitempty"`
Ts int64 `json:"ts"`
Task string `json:"task"`
TokensIn int32 `json:"tokensIn"`
TokensOut int32 `json:"tokensOut"`
CacheWrites int32 `json:"cacheWrites,omitempty"`
CacheReads int32 `json:"cacheReads,omitempty"`
TotalCost float64 `json:"totalCost"`
Size int64 `json:"size,omitempty"`
IsFavorited bool `json:"isFavorited,omitempty"`
Id string `json:"id"`
Ulid string `json:"ulid,omitempty"`
Ts int64 `json:"ts"`
Task string `json:"task"`
TokensIn int32 `json:"tokensIn"`
TokensOut int32 `json:"tokensOut"`
CacheWrites int32 `json:"cacheWrites,omitempty"`
CacheReads int32 `json:"cacheReads,omitempty"`
TotalCost float64 `json:"totalCost"`
Size int64 `json:"size,omitempty"`
IsFavorited bool `json:"isFavorited,omitempty"`
WorkspacePaths []string `json:"workspacePaths,omitempty"`
}
+52 -5
View File
@@ -47,11 +47,11 @@ const (
AskTypeResumeTask AskType = "resume_task"
AskTypeResumeCompletedTask AskType = "resume_completed_task"
AskTypeMistakeLimitReached AskType = "mistake_limit_reached"
AskTypeBrowserActionLaunch AskType = "browser_action_launch"
AskTypeUseMcpServer AskType = "use_mcp_server"
AskTypeNewTask AskType = "new_task"
AskTypeCondense AskType = "condense"
AskTypeReportBug AskType = "report_bug"
AskTypeBrowserActionLaunch AskType = "browser_action_launch"
AskTypeUseMcpServer AskType = "use_mcp_server"
AskTypeNewTask AskType = "new_task"
AskTypeCondense AskType = "condense"
AskTypeReportBug AskType = "report_bug"
)
// SayType represents different types of SAY messages
@@ -87,6 +87,11 @@ const (
SayTypeLoadMcpDocumentation SayType = "load_mcp_documentation"
SayTypeInfo SayType = "info"
SayTypeTaskProgress SayType = "task_progress"
// Hook status streaming from the backend.
// These values must match the backend "say" strings emitted by the extension.
SayTypeHookStatus SayType = "hook_status"
SayTypeHookOutputStream SayType = "hook_output_stream"
SayTypeCommandPermissionDenied SayType = "command_permission_denied"
)
// ToolMessage represents a tool-related message
@@ -145,6 +150,42 @@ type APIRequestRetryStatus struct {
ErrorSnippet string `json:"errorSnippet,omitempty"`
}
// HookMessage represents hook execution metadata sent from the backend
type HookMessage struct {
HookName string `json:"hookName"` // Type of hook (TaskStart, PreToolUse, etc.)
ToolName string `json:"toolName,omitempty"` // Optional tool name for tool-specific hooks
Status string `json:"status"` // "running", "completed", "cancelled", or "failed"
ScriptPaths []string `json:"scriptPaths,omitempty"` // Full paths to hook script(s)
PendingToolInfo *ToolInfo `json:"pendingToolInfo,omitempty"` // Metadata about the pending tool execution (PreToolUse)
ExitCode int `json:"exitCode,omitempty"` // Exit code for completed/failed hooks
HasJsonResponse bool `json:"hasJsonResponse,omitempty"` // Whether hook returned JSON
Error *HookError `json:"error,omitempty"` // Error details if hook failed
}
// ToolInfo represents a compact subset of tool parameters for UI display.
// This mirrors the extension's pendingToolInfo shape and is used by the CLI to
// show what tool the PreToolUse hook is gating.
type ToolInfo struct {
Tool string `json:"tool"`
Path string `json:"path,omitempty"`
Command string `json:"command,omitempty"`
Content string `json:"content,omitempty"`
Diff string `json:"diff,omitempty"`
Regex string `json:"regex,omitempty"`
Url string `json:"url,omitempty"`
McpTool string `json:"mcpTool,omitempty"`
McpServer string `json:"mcpServer,omitempty"`
ResourceUri string `json:"resourceUri,omitempty"`
}
// HookError represents structured error information from a failed hook
type HookError struct {
Type string `json:"type"` // Error type: "execution", "timeout", "validation", etc.
Message string `json:"message"` // Human-readable error message
Details string `json:"details,omitempty"` // Additional error details
ScriptPath string `json:"scriptPath,omitempty"` // Path to script that failed
}
// GetTimestamp returns a formatted timestamp string
func (m *ClineMessage) GetTimestamp() string {
return time.Unix(m.Timestamp/1000, 0).Format("15:04:05")
@@ -324,6 +365,12 @@ func convertProtoSayType(sayType cline.ClineSay) string {
return string(SayTypeInfo)
case cline.ClineSay_TASK_PROGRESS:
return string(SayTypeTaskProgress)
case cline.ClineSay_HOOK_STATUS:
return string(SayTypeHookStatus)
case cline.ClineSay_HOOK_OUTPUT_STREAM:
return string(SayTypeHookOutputStream)
case cline.ClineSay_COMMAND_PERMISSION_DENIED:
return string(SayTypeCommandPermissionDenied)
default:
return "unknown"
}
+71
View File
@@ -4,7 +4,9 @@ import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
@@ -183,3 +185,72 @@ DEBUGGING STEPS:
For additional help, visit: https://github.com/cline/cline/issues
`, maxRetries, lastErr, GetNodeVersion())
}
// validateDirsExist validates that all workspace paths exist on the filesystem
func ValidateDirsExist(paths []string) error {
for _, p := range paths {
info, err := os.Stat(p)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("path does not exist: %s", p)
}
return fmt.Errorf("failed to access path %s: %w", p, err)
}
if !info.IsDir() {
return fmt.Errorf("path is not a directory: %s", p)
}
}
return nil
}
// absPath returns the absolute path, resolving symlinks
func AbsPath(path string) (string, error) {
// First get absolute path
abs, err := filepath.Abs(path)
if err != nil {
return "", err
}
// Then resolve any symlinks
resolved, err := filepath.EvalSymlinks(abs)
if err != nil {
// If symlink resolution fails, return the absolute path
return abs, nil
}
return resolved, nil
}
// shortenPath shortens a filesystem path to fit within maxLen
func ShortenPath(path string, maxLen int) string {
// Try to replace home directory with ~ (cross-platform)
if homeDir, err := os.UserHomeDir(); err == nil {
if strings.HasPrefix(path, homeDir) {
shortened := "~" + path[len(homeDir):]
// Always use ~ version if we can
path = shortened
}
}
if len(path) <= maxLen {
return path
}
// If still too long, show last few path components
if len(path) > maxLen {
parts := strings.Split(path, string(filepath.Separator))
if len(parts) > 2 {
// Show last 2-3 components
lastParts := parts[len(parts)-2:]
shortened := "..." + string(filepath.Separator) + strings.Join(lastParts, string(filepath.Separator))
if len(shortened) <= maxLen {
return shortened
}
}
}
// Last resort: truncate with ellipsis
if len(path) > maxLen {
return "..." + path[len(path)-maxLen+3:]
}
return path
}
+4 -2
View File
@@ -16,15 +16,17 @@ import (
type GrpcServer struct {
port int
verbose bool
workspaces []string
server *grpc.Server
shutdownCh chan struct{}
}
// NewGrpcServer creates a new GrpcServer
func NewGrpcServer(port int, verbose bool) *GrpcServer {
func NewGrpcServer(port int, verbose bool, workspaces []string) *GrpcServer {
return &GrpcServer{
port: port,
verbose: verbose,
workspaces: workspaces,
shutdownCh: make(chan struct{}),
}
}
@@ -50,7 +52,7 @@ func (s *GrpcServer) Start(ctx context.Context) error {
grpc_health_v1.RegisterHealthServer(s.server, healthServer)
// Register services
workspaceService := NewSimpleWorkspaceService(s.verbose)
workspaceService := NewSimpleWorkspaceService(s.verbose, s.workspaces)
host.RegisterWorkspaceServiceServer(s.server, workspaceService)
windowService := NewWindowService(s.verbose)
+20 -8
View File
@@ -12,13 +12,15 @@ import (
// SimpleWorkspaceService implements a basic workspace service without complex dependencies
type SimpleWorkspaceService struct {
host.UnimplementedWorkspaceServiceServer
verbose bool
verbose bool
workspaces []string
}
// NewSimpleWorkspaceService creates a new SimpleWorkspaceService
func NewSimpleWorkspaceService(verbose bool) *SimpleWorkspaceService {
func NewSimpleWorkspaceService(verbose bool, workspaces []string) *SimpleWorkspaceService {
return &SimpleWorkspaceService{
verbose: verbose,
verbose: verbose,
workspaces: workspaces,
}
}
@@ -28,14 +30,24 @@ func (s *SimpleWorkspaceService) GetWorkspacePaths(ctx context.Context, req *hos
log.Printf("GetWorkspacePaths called")
}
// Get current working directory as the workspace
cwd, err := os.Getwd()
if err != nil {
return nil, err
paths := []string{}
if len(s.workspaces) == 0 {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
paths = append(paths, cwd)
} else {
paths = s.workspaces
}
if s.verbose {
log.Printf("Returning configured workspaces: %v", paths)
}
return &host.GetWorkspacePathsResponse{
Paths: []string{cwd},
Paths: paths,
}, nil
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

+43
View File
@@ -95,6 +95,12 @@ INSTANT TASK OPTIONS
-m, --mode mode
Starting mode. Options: act (default), plan
-w, --workspace path
Additional workspace paths. Can be specified multiple times to
include multiple directories. The current working directory is
always included as the first workspace. Example: cline -w
/path/to/other/project "refactor shared code"
GLOBAL OPTIONS
These options apply to all subcommands:
@@ -371,6 +377,43 @@ COPYRIGHT
Copyright © 2025 Cline Bot Inc. Licensed under the Apache License 2.0.
```
## JSON output (-F json)
When you run a command with `-F json` (or `--output-format json`), Cline prints each client message as JSON.
### ClineMessage schema
| Field | Type | Required | Notes |
|-------|------|----------|-------|
| `type` | `"ask" or "say"` | Yes | Top-level message category. |
| `text` | `string` | Yes | Human-readable message content. |
| `ts` | `number` | Yes | Unix epoch timestamp in milliseconds. |
| `reasoning` | `string` | No | Omitted when empty. |
| `say` | `string` | No | Omitted when empty. Present when `type` is `"say"`. |
| `ask` | `string` | No | Omitted when empty. Present when `type` is `"ask"`. |
| `partial` | `boolean` | No | Omitted when false. `true` for streaming updates. |
| `images` | `string[]` | No | Omitted when empty. Image URIs when included with a message. |
| `files` | `string[]` | No | Omitted when empty. File paths when attached to a message. |
| `lastCheckpointHash` | `string` | No | Omitted when empty. Git checkpoint hash when available. |
| `isCheckpointCheckedOut` | `boolean` | No | Omitted when false. `true` if Cline checked out a checkpoint. |
| `isOperationOutsideWorkspace` | `boolean` | No | Omitted when false. `true` if an operation happened outside the workspace. |
<Note>
Most fields are optional and omitted when empty. If you parse this output, treat missing fields as “not present”, not as empty strings.
</Note>
### Example
```json
{
"type": "say",
"text": "Cline is about to run a command.",
"ts": 1760501486669,
"say": "command",
"partial": false
}
```
### Shell Completion
Generate autocompletion scripts for various shells:
+5 -1
View File
@@ -115,6 +115,7 @@
},
"features/auto-approve",
"features/auto-compact",
"features/background-edit",
"features/checkpoints",
"features/cline-rules",
{
@@ -149,6 +150,7 @@
},
"features/multiroot-workspace",
"features/plan-and-act",
"features/skills",
{
"group": "Slash Commands",
"pages": [
@@ -278,6 +280,7 @@
"pages": [
"enterprise-solutions/overview",
"enterprise-solutions/onboarding",
"enterprise-solutions/sso-setup",
"enterprise-solutions/team-management/managing-members",
{
"group": "SaaS Provider Configuration",
@@ -317,7 +320,8 @@
"pages": [
"enterprise-solutions/monitoring/overview",
"enterprise-solutions/monitoring/telemetry",
"enterprise-solutions/monitoring/opentelemetry"
"enterprise-solutions/monitoring/opentelemetry",
"enterprise-solutions/monitoring/opentelemetry_override"
]
}
]
@@ -0,0 +1,811 @@
# Cline Rules: YAML `paths` Frontmatter — Implementation Plan
This document proposes a technical design for adding **conditional applicability** to **Cline Rules** using **YAML frontmatter** with a `paths` list (similar in spirit to Claude Code rules).
Scope constraints (explicit):
- ✅ Only plan + design for **Cline Rules** (`~/Documents/Cline/Rules` and workspace `.clinerules{,/}`) and **remote global rules**.
- ✅ Only add **one conditional mechanism**: YAML frontmatter key `paths`.
- ✅ Include matching semantics + prompt-build integration + toggle behavior + tests.
- ❌ Exclude workflows.
- ❌ Exclude hooks.
- ❌ Exclude other conditionals (model/provider/mode/etc.).
---
## 1. Background: Current behavior (baseline)
Today, Cline Rules are concatenated verbatim into the system prompt, with enable/disable determined solely by toggles:
- Global file-based rules: `~/Documents/Cline/Rules/*`
- Workspace rules: `<workspace>/.clinerules` (directory or legacy file)
- Remote rules: `remoteGlobalRules[]` from remote config
The prompt is (re)built for each API request in `Task.attemptApiRequest()` (`src/core/task/index.ts`).
There is **no metadata parsing** for Cline Rules.
---
## 2. Goal
Allow a Cline Rule file to declare YAML frontmatter:
```md
---
paths:
- "apps/web/**"
- "packages/*/src/**"
---
<rule body>
```
And only include the rules body in the prompt if the current workspace context “matches” one of the declared `paths`.
This is intended as the **minimal on-ramp** to conditional rules.
### 2.1 Architecture Principle: Generic Foundation
While v1 implements **only** the `paths` conditional, the implementation will use generic abstractions to enable easy addition of future conditionals (e.g., `mode`, `provider`, `model`, `tags`) without major refactoring.
Key design decisions:
1. **Rule Evaluation Context** - Instead of passing `pathContext: string[]` throughout the codebase, we'll use a structured `RuleEvaluationContext` object that can grow over time.
2. **Conditional Evaluator Pattern** - Each conditional type has its own evaluator function with a consistent signature, making it easy to add new conditionals by registering new evaluators.
3. **Generic Naming** - Use "evaluation" and "conditional" terminology rather than path-specific names in core abstractions.
4. **V1 Constraint** - Despite the generic foundation, v1 will only implement and document `paths`. Other conditionals will be added in future iterations.
---
## 3. Proposed rule schema (v1)
### 3.1 Frontmatter structure
The frontmatter uses YAML format and supports conditional fields. In v1, only `paths` is implemented.
```yaml
---
paths:
- "apps/web/**"
- "packages/*/src/**"
---
```
**V1 supported conditionals:**
- `paths?: string[]` - Rule applies only when context matches these path patterns. If omitted or empty → rule applies universally (current behavior).
**Future conditionals (not implemented in v1):**
- `mode?: "act" | "plan" | ["act", "plan"]` - Rule applies in specific modes
- `provider?: string | string[]` - Rule applies for specific providers
- `model?: string | string[]` - Rule applies for specific models
- `tags?: string | string[]` - Rule applies when workspace has matching tags
### 3.2 Conditional evaluation semantics
When multiple conditionals are present (future versions):
- All conditionals must evaluate to true (AND logic)
- If a conditional key is omitted, it places no constraint (always true for that dimension)
Example (future):
```yaml
---
paths: ["src/**"]
mode: "act"
---
```
This rule applies only when working in `src/**` AND in act mode.
### 3.3 Body
The remainder of the markdown file after frontmatter.
### 3.4 Validation rules
- If YAML frontmatter fails to parse: **fail open** (treat as universal rule) and keep entire file as body.
- If a conditional key is unrecognized: ignore that key (treat as if omitted).
- If a conditional value has wrong type: ignore that conditional.
- Rationale: Robustness over strictness; avoid silently dropping rules.
---
## 4. Conditional evaluation semantics
We need a deterministic and explainable definition of "does this rule apply right now?"
### 4.0 Generic evaluation architecture
The rule evaluation system uses a **conditional evaluator pattern**:
```typescript
// Generic context object passed to all evaluators
type RuleEvaluationContext = {
paths?: string[] // v1: implemented
mode?: "act" | "plan" // future
provider?: string // future
model?: string // future
// extensible for future conditionals
}
// Generic evaluator signature
type ConditionalEvaluator = (
frontmatterValue: unknown,
context: RuleEvaluationContext
) => boolean
// Registry of evaluators
const conditionalEvaluators: Record<string, ConditionalEvaluator> = {
paths: evaluatePathsConditional, // v1: implemented
mode: evaluateModeConditional, // future: placeholder
provider: evaluateProviderConditional, // future: placeholder
// future conditionals register here
}
// Generic rule evaluation
function evaluateRuleConditionals(
frontmatter: Record<string, unknown>,
context: RuleEvaluationContext
): boolean {
// A rule applies if ALL present conditionals evaluate to true
for (const [key, value] of Object.entries(frontmatter)) {
const evaluator = conditionalEvaluators[key]
if (!evaluator) continue // unknown conditional: ignore
if (!evaluator(value, context)) return false
}
return true // all conditionals passed (or none present)
}
```
**V1 Implementation Note:** In v1, only `evaluatePathsConditional` is implemented. The generic architecture exists but only handles the `paths` key. Future conditionals will add new evaluators to the registry without changing the core evaluation logic.
### 4.1 Paths Conditional: Inputs to matching
We should treat `paths` as a proxy for the implicit condition:
> “When the work you are about to do involves files matching these paths, these expectations apply.”
At the exact moment Cline builds the system prompt (immediately before `api.createMessage(...)`), it does **not** have a perfect, structured representation of what the request “is about.”
So we need a proxy set of **evidence** to determine which paths are relevant for *this request*.
#### Recommended v1 evidence stack
The evidence stack is not prioritized for comparison — we are looking for *any* positive indication that a rule should (in spirit) apply. All sources contribute to a single candidate path set.
1) **Explicit referenced paths (high confidence)**
- Paths resolved from user mentions (e.g. `@file` / "context mentions" that resolve to workspace files).
- Paths targeted by tool calls in the immediately preceding turn(s), especially:
- `read_file`, `write_to_file`, `apply_patch`, `list_files`, `search_files`.
2) **Path-like strings in user message text (medium confidence)**
- Parse the current user message for path-like patterns (e.g., `apps/web/`, `src/components/Button.tsx`, `packages/*/lib`).
- This solves the **"first turn" problem**: a user typing "add a new component to apps/web" should activate a rule scoped to `apps/web/**`, even though no file context exists yet.
- Implementation notes:
- Use a regex to extract candidates that look like relative paths (contain `/`, no spaces, reasonable file/dir name characters).
- Validate candidates against actual workspace structure when possible (exists check) to reduce false positives.
- If validation is too expensive, treat these as low-confidence candidates that still contribute to matching.
3) **Observed workspace context (medium confidence)**
- **Visible files (open editors)**: Files currently visible in VS Code editor panes.
- **Open tabs**: All files with open tabs in VS Code (may not be visible but are in the tab bar).
- **Recently modified files** (scoped definition — see §4.1.1 below).
4) **Fallback (conservative)**
- If there is no evidence from any source, do **not** activate path-scoped rules.
#### 4.1.1 Defining "recently modified files"
To avoid surprising activations, "recently modified" is **strictly scoped** for v1:
- **Scope**: Files modified **by Cline** (via `write_to_file`, `apply_patch`, or similar tools) **during the current task**.
- **Not included**: Files modified by the user directly, files modified in previous tasks, or files from git history.
- **Rationale**: This keeps the evidence set predictable and directly tied to the current interaction. A rule activating because of a file Cline touched makes sense; a rule activating because of a random git change from yesterday does not.
- **Implementation**: Track tool target paths in `Task` state as tools execute. This list is already partially maintained for checkpoint purposes.
#### 4.1.2 Defining "currently applicable files" (summary)
The **candidate path set** for rule matching is the union of:
| Source | Description | Persistence |
|--------|-------------|-------------|
| `@file` mentions | Resolved paths from explicit user mentions | Current turn |
| Tool targets | Paths from tool calls (`read_file`, `write_to_file`, etc.) | Current task (last N turns, e.g., 3) |
| Path-like text | Parsed from user message prose | Current turn |
| Open tabs | All tabbed files in VS Code | Snapshot at prompt build |
| Visible editors | Currently visible editor panes | Snapshot at prompt build |
| Task-modified files | Files Cline has written during this task | Current task |
All paths are normalized to root-relative POSIX format, deduplicated, and capped (e.g., 100 entries max).
Reasoning:
- This aligns with the “rules are constraints for the work youre about to do” mental model.
- It is still deterministic and explainable (“it activated because you referenced/edited X”).
- It avoids heavy repo scans or semantic inference.
### 4.2 Paths Conditional: What paths are matched against
- Use repo-relative paths (relative to `Task.cwd` / primary workspace root).
- Normalize to POSIX-style slashes for glob consistency.
### 4.3 Paths Conditional: Glob implementation
Use a well-tested glob matcher (recommended):
- `minimatch` OR `picomatch`.
Design notes:
- `.clineignore` already uses gitignore semantics via `ignore` library, but these are *not* the same as globbing. Reusing `ignore` would be confusing.
- `picomatch` is fast and handles common glob syntax; `minimatch` is also common. Either is fine; pick one consistent with existing deps.
### 4.4 Paths Conditional: Match rule
A rule with `paths` applies if:
- Any candidate “context path” matches any pattern in `paths`.
Edge cases:
- If no candidate paths exist (no tabs/visible/recently modified):
- Option A (recommended): **do not activate path-scoped rules** (conservative).
- Option B: activate path-scoped rules if pattern is `**` or `/`-equivalent.
Recommendation: Option A.
Rationale: Otherwise path-based conditionals become “randomly always on” early in a task before any file context exists.
### 4.5 Paths Conditional: Multi-root workspaces
We should be compatible with both single-root and multi-root workspaces.
In multi-root workspaces, the simplest mental model is:
> “A `paths` pattern is evaluated against the files path **within whatever workspace root it belongs to**.”
So we do **not** need separate matching logic; we just need to make sure we generate candidate paths from *all* workspace roots.
#### Proposed v1 approach (root-agnostic matching)
1) Build a candidate list of **repo-relative paths per root**
- For every evidence path (mentions/tool targets/visible/open/recent), compute:
- `relPath = path.relative(rootPath, absolutePath)` for the root that contains it
- Normalize `relPath` to POSIX.
2) Match frontmatter `paths[]` globs against `relPath`.
3) A rule applies if **any** candidate `relPath` matches.
This yields the intuitive outcome we want:
- A rule with `paths: ["apps/web/**"]` activates when the request context includes any file under `apps/web/` in *any* workspace root.
#### Implementation note
Even with “root-agnostic matching”, we still need to know which root a path belongs to in order to compute `relPath` correctly. But this can be an internal detail of the candidate-generation step; the matcher can remain purely `glob(pattern) vs relPath`.
---
### 4.6 Paths Conditional: Prompt-build timing and context
This is critical context for why the evidence stack exists.
Prompt building happens for each request in `Task.attemptApiRequest()` and occurs *just before* calling the model provider (`api.createMessage(systemPrompt, ...)`).
At that moment we have:
- The **current requests userContent** (already constructed in `recursivelyMakeClineRequests`).
- The **conversation history**.
- The **environment details** we choose to inject.
We do *not* have:
- A reliable, structured “intent” object describing which files will be touched next.
Therefore, path-scoped rules must be driven by observable evidence (mentions/tool targets/UI context) rather than by perfect prediction.
## 5. Data flow design
### 5.1 Parse frontmatter (shared utility)
We already have frontmatter parsing in `src/core/context/instructions/user-instructions/skills.ts`:
- Regex-based extraction
- `js-yaml` parsing
- Fail-open fallback
Plan:
- Extract this into a reusable helper module, e.g.:
- `src/core/context/instructions/user-instructions/frontmatter.ts`
Proposed API:
```ts
export type FrontmatterParseResult = {
data: Record<string, unknown>
body: string
hadFrontmatter: boolean
parseError?: string
}
export function parseYamlFrontmatter(markdown: string): FrontmatterParseResult
```
Then:
- Update `skills.ts` to use this helper (non-functional change).
- Use the same helper for rule parsing.
### 5.2 Extend rule loading to include metadata
Currently, `getRuleFilesTotalContent()` reads files and concatenates as:
```ts
`${relativePath}\n` + file.trim()
```
We will extend this to:
1) Read file
2) Parse frontmatter
3) Decide applicability
4) If applicable, include **body only** (not frontmatter) in the prompt.
### 5.3 Where applicability is decided
There are two viable insertion points:
#### Option 1 (recommended): Decide applicability inside `getRuleFilesTotalContent()`
Pros:
- Centralizes rule file reading + concatenation.
- Keeps `cline-rules.ts` orchestration simple.
Cons:
- Needs additional input: evaluation context.
Implementation with **generic signature**:
```ts
getRuleFilesTotalContent(
ruleFilePaths: string[],
basePath: string,
toggles: ClineRulesToggles,
opts?: {
evaluationContext?: RuleEvaluationContext
}
)
```
The function:
1. Parses frontmatter from each file
2. Calls `evaluateRuleConditionals(frontmatter, opts.evaluationContext)`
3. Includes body only if evaluation returns true
#### Option 2: Decide applicability in `getGlobalClineRules()` and `getLocalClineRules()`
Pros:
- More explicit; no signature change on helper.
Cons:
- Duplicates logic between global and local.
Recommendation: Option 1 with generic `evaluationContext`.
### 5.4 Building evaluation context in prompt-build step
At prompt build time (`Task.attemptApiRequest()`), we should construct a **RuleEvaluationContext** object.
For v1, this includes only `paths`:
```ts
private buildRuleEvaluationContext(): RuleEvaluationContext {
return {
paths: this.getRulePathContext(), // existing helper, returns string[]
// future: mode, provider, model, etc.
}
}
private getRulePathContext(): string[] {
// Existing implementation from §4.1
// Returns bounded, normalized list of root-relative paths
}
```
This generic structure makes future additions trivial:
```ts
// Future example:
private buildRuleEvaluationContext(): RuleEvaluationContext {
return {
paths: this.getRulePathContext(),
mode: this.mode, // future: add mode
provider: this.api.getInfo().name, // future: add provider
model: this.api.getModel().id, // future: add model
}
}
```
**V1 implementation:**
- Only `paths` is gathered and populated
- Other fields remain undefined
- The generic structure exists but is only partially used
#### v1 rules for building the paths context
1) Include **explicit referenced paths** when available
- Best source: mention parsing already resolves files; we should plumb those resolved paths into a structured list.
- Additionally, record tool target paths as part of task state (or extract them from recent tool executions) so they can influence the next prompt build.
2) Include **observed UI/workspace context**
- visible/open/recently modified
3) Normalize and bound
- convert all to root-relative paths (for each path, pick its containing root)
- convert to POSIX
- de-duplicate and sort for determinism
- cap to N entries (e.g. 50)
Then pass `evaluationContext` into rule loader calls so the loader can decide applicability.
---
## 6. Behavior with toggles
Toggles remain the primary user control.
- If a rule is toggled off → it is not included, regardless of `paths`.
- If toggled on:
- If no `paths` → include.
- If `paths` → include only if applicable.
UI will still show the rule as "enabled" because the toggle is enabled, but it may not be active due to path mismatch.
### 6.1 UI notification for conditional rule activation
When conditional rules (any type, not just paths) are included in the current API request, the user should be informed. This provides transparency and helps users understand why certain behaviors or constraints are being applied.
#### v1 approach: Simple in-chat notification
Display a brief, non-intrusive message in the webview-ui task flow when conditional rules are activated. This appears as part of the API request context (similar to how we show environment details or context mentions).
**Proposed UX:**
- When one or more conditional rules activate, show a collapsible/expandable notice in the chat UI.
- Format:
```
📋 Conditional rules applied: [rule-name-1], [rule-name-2]
```
- Clicking/expanding shows which conditions were met (e.g., "matched paths: apps/web/**, src/**" or future: "mode: act, provider: anthropic")
**Implementation notes:**
Return metadata from `getRuleFilesTotalContent()`:
```ts
type RuleLoadResult = {
content: string
activatedConditionalRules: Array<{
name: string
matchedConditions: Record<string, string[]> // e.g., { "paths": ["apps/web/**"] }
}>
}
```
- Pass this metadata back to the Task
- Emit `say("conditional_rules_applied", metadata)` to webview
- The webview renders a generic conditional notification
**V1 specifics:**
- `matchedConditions` will only contain `"paths"` key
- UI message can show "matched paths: X, Y"
- Future conditionals just add more keys to `matchedConditions`
**Why this matters:**
- Users will otherwise be confused when behavior differs based on what files they're working with.
- Debugging rule issues becomes much easier: "Oh, my `frontend-conventions` rule activated because I mentioned `apps/web/`."
- Builds trust in the conditional system — users can see it working.
### 6.2 Future UI considerations (out of scope for v1)
- "Inactive" indicator in rules list when a rule is toggled on but path-filtered out
- Hover tooltip showing which paths a rule would match
- Quick action to "always include" a path-scoped rule for this task
---
## 7. Remote rules (`remoteGlobalRules`) and `paths`
Remote rules are appended in `getGlobalClineRules()` as `rule.contents`.
We need to support frontmatter in `contents` as well, because enterprises will likely want the same conditional power.
Plan:
- Treat `rule.contents` as a markdown file body that *may* contain YAML frontmatter.
- Parse it with `parseYamlFrontmatter`.
- Apply the same `paths` semantics.
**Important:** `remoteGlobalRules` currently are not prefixed with a file path, only `rule.name`.
We will keep that behavior: `name` functions as the “identifier header” in the combined instruction blob.
---
## 8. Prompt formatting & debuggability
To preserve debuggability, we should ensure the prompt still indicates which rule produced which text.
Current file-based formatting uses:
```
relative/path/to/rule.md
<full file content>
```
After this change, it becomes:
```
relative/path/to/rule.md
<body only (frontmatter removed)>
```
For path-scoped rules, it may be helpful to optionally include a short “(paths matched)” note, but thats extra prompt tokens.
Recommendation for v1: do not add notes.
---
## 9. Testing plan
We need confidence in:
1) YAML parsing correctness
2) Matching semantics
3) No regressions for rules without frontmatter
4) Remote rules handling
### 9.1 Unit tests
Add tests for new helper `parseYamlFrontmatter`:
- no frontmatter → `data={}`, `body=original`
- valid frontmatter with `paths` list
- malformed YAML → fail open
- frontmatter with non-array paths → ignore `paths` (treat as universal)
Add tests for path matching helper:
- exact file match
- glob match (`**`, `*`)
- windows path normalization (ensure posix conversion)
- empty context paths: path-scoped rules inactive
Add tests for `extractPathLikeStrings`:
- extracts paths with `/` separators (e.g., `src/components/Button.tsx`)
- extracts directory paths (e.g., `apps/web/`)
- ignores URLs (e.g., `https://example.com/path`)
- ignores paths with spaces or invalid characters
- handles mixed prose with multiple path candidates
- validates against workspace structure when feasible
- respects deduplication and capping
### 9.2 Integration-ish tests for rule loading
For `getLocalClineRules` / `getGlobalClineRules` (in `cline-rules.ts`):
- create temp workspace with `.clinerules/` and 2 files:
- one universal
- one with paths
- set context paths list and verify only correct rule included
Remote rules:
- simulate `remoteGlobalRules` with a `contents` that has frontmatter
- verify inclusion/exclusion based on context paths + `remoteRulesToggles`
---
## 10. Implementation steps (sequenced)
1) **Add shared frontmatter parser**
- new `frontmatter.ts`
- reuse regex+js-yaml approach from `skills.ts`
2) **Refactor skills** to use shared parser (no behavior changes)
3) **Add generic conditional evaluation system**
- Define `RuleEvaluationContext` type
- Define `ConditionalEvaluator` type
- Create evaluator registry pattern
- Implement `evaluateRuleConditionals()` function
4) **Implement paths conditional evaluator** (v1 only conditional)
- pick glob library (prefer `picomatch` or `minimatch`)
- implement `evaluatePathsConditional(pathsFrontmatter, context)`
- register in `conditionalEvaluators` registry
5) **Add path-like string extraction utility** (paths conditional support)
- implement `extractPathLikeStrings(text: string): string[]`
- regex-based extraction for path-like patterns in prose
- optional: validation against workspace structure
6) **Thread evaluation context into prompt build** (generic infrastructure)
- add `Task.buildRuleEvaluationContext()` (returns generic object)
- add `Task.getRulePathContext()` (paths-specific helper)
- implement evidence gathering for paths from all sources:
- `@file` mentions (from mention parsing)
- tool target paths (from task state)
- path-like strings in user message (new utility)
- open tabs / visible editors (VS Code API)
- task-modified files (from checkpoint/tool tracking)
- normalize, dedupe, and cap at 100 entries
7) **Update rule concatenation with generic evaluation**
- extend `getRuleFilesTotalContent` signature to accept `RuleEvaluationContext`
- use `evaluateRuleConditionals()` to filter rules
- return `RuleLoadResult` with `activatedConditionalRules` metadata
- update `getGlobalClineRules` for remote rule contents similarly
8) **Add UI notification for activated conditional rules**
- add new `say` message type: `"conditional_rules_applied"`
- emit notification from Task when conditional rules activate
- render generic conditional notification in webview-ui chat stream (collapsible)
- show matched conditions (v1: paths only)
9) **Add tests**
- unit tests for frontmatter parsing
- unit tests for generic conditional evaluation
- unit tests for path-like string extraction
- unit tests for paths conditional (globs, edge cases)
- integration tests for rule loading with evaluation context
- remote rules tests
10) **Docs**
- add/update docs.cline.bot content later (out of scope)
- for repo: update any local documentation describing `.clinerules` format
---
## 11. Risks & mitigations
### Risk: nondeterministic “context paths”
If we base matching on visible/open/recent files, rule activation could vary between runs.
Mitigation:
- Use a stable, deterministic set (sorted + deduped).
- Keep the rule inactive if there is zero context.
### Risk: token bloat
If we include too many paths or add verbose debug text.
Mitigation:
- Cap context paths and do not include debug notes in prompt.
### Risk: performance overhead
Parsing YAML for every rule every request could be expensive.
Mitigation:
- Cache parsed frontmatter per file path + mtime (future optimization).
- For v1, keep it simple; rule counts are typically small.
---
## 12. Acceptance criteria
### Core functionality
- A rule file with `paths` frontmatter is only included when it matches the current path context.
- Rules without `paths` behave exactly as before.
- Malformed YAML does not break prompt building (fail open).
- Remote rules can also include `paths` and behave consistently.
### Evidence stack
- Path context is gathered from all defined sources: `@file` mentions, tool targets, path-like strings in user message, open tabs, visible editors, and task-modified files.
- Path-like strings in user message prose are parsed and contribute to matching (solves first-turn problem).
- "Recently modified files" only includes files Cline has written during the current task.
- All paths are normalized to root-relative POSIX format, deduplicated, and capped.
### User visibility
- When path-scoped rules activate, a notification is displayed in the webview-ui chat stream.
- The notification identifies which conditional rules were applied.
### Quality
- All new logic is covered by tests.
- Performance remains acceptable for typical rule counts (< 50 rules).
---
## 13. Future conditional extensions (post-v1)
The generic architecture enables straightforward addition of new conditionals. This section documents the pattern for future work.
### 13.1 Adding a new conditional type
To add a new conditional (e.g., `mode`), follow these steps:
1. **Define the evaluator function:**
```ts
function evaluateModeConditional(
frontmatterValue: unknown,
context: RuleEvaluationContext
): boolean {
// Validate frontmatterValue type
if (typeof frontmatterValue !== "string" && !Array.isArray(frontmatterValue)) {
return true // invalid type: ignore this conditional
}
// Normalize to array
const modes = Array.isArray(frontmatterValue) ? frontmatterValue : [frontmatterValue]
// Check if current mode matches
return context.mode !== undefined && modes.includes(context.mode)
}
```
2. **Register the evaluator:**
```ts
conditionalEvaluators["mode"] = evaluateModeConditional
```
3. **Populate context in `buildRuleEvaluationContext()`:**
```ts
private buildRuleEvaluationContext(): RuleEvaluationContext {
return {
paths: this.getRulePathContext(),
mode: this.mode, // ADD THIS LINE
// ...
}
}
```
4. **Add tests** for the new evaluator (see §9.1 pattern)
5. **Update documentation** to advertise the new conditional
### 13.2 Candidate future conditionals
Potential conditionals that follow this pattern:
| Conditional | Type | Example | Use Case |
|-------------|------|---------|----------|
| `mode` | `"act" \| "plan"` | `mode: "act"` | Different rules for planning vs execution |
| `provider` | `string \| string[]` | `provider: ["anthropic", "openai"]` | Provider-specific best practices |
| `model` | `string \| string[]` | `model: "claude-3-5-sonnet-*"` | Model-specific constraints |
| `tags` | `string \| string[]` | `tags: ["frontend", "typescript"]` | Workspace/project classification |
| `os` | `string \| string[]` | `os: ["darwin", "linux"]` | Platform-specific rules |
| `env` | `string` | `env: "production"` | Environment-specific rules |
Each requires:
- An evaluator function following the `ConditionalEvaluator` signature
- Context population in `buildRuleEvaluationContext()`
- Tests
The core evaluation system (`evaluateRuleConditionals`) requires **no changes**.
### 13.3 Advanced: Conditional expression language (future consideration)
For complex logic beyond AND (e.g., OR, NOT), we could add an expression language:
```yaml
---
when: "(paths:src/** OR paths:lib/**) AND mode:act"
---
```
This is out of scope for v1 and near-term iterations, but the generic architecture doesn't preclude it.
@@ -31,7 +31,7 @@ Check which models are available in your region first. Some newer models might n
<Frame>
<img
src="https://storage.googleapis.com/cline-static-assets-prod/assets/AWS%20Remote%20Config.gif"
src="https://assets.int.cline.bot/assets/AWS%20Remote%20Config.gif"
/>
</Frame>
@@ -27,7 +27,7 @@ If you don't have AWS credentials yet, reach out to your IT or cloud team to get
<Frame>
<img
src="https://storage.googleapis.com/cline-static-assets-prod/assets/VS%20Code%20Bedrock%20API%20Key.gif"
src="https://assets.int.cline.bot/assets/VS%20Code%20Bedrock%20API%20Key.gif"
/>
</Frame>
@@ -42,76 +42,45 @@ Cline supports three OTLP export protocols:
- **HTTP/protobuf**
- **HTTP/JSON**
### Export Destinations
You can export to:
- **Console** (for testing)
- **OTLP endpoint** (your own collector or observability platform)
## Configuration
OpenTelemetry is configured using environment variables before launching Cline.
OpenTelemetry is configured using [Remote Configuration](/enterprise-solutions/configuration/remote-configuration/overview#how-remote-configuration-works) from the [dashboard](https://app.cline.bot/dashboard/organization?tab=settings).
### Basic Setup
Enable OpenTelemetry and configure an OTLP endpoint:
Enable OpenTelemetry, configure an OTLP endpoint and select a protocol:
```bash
# Enable OpenTelemetry
export OTEL_TELEMETRY_ENABLED=1
<Frame>
<img
src="https://assets.int.cline.bot/assets/open_telemetry_main_options.png"
/>
</Frame>
# Configure metrics and logs export
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
If you're using gRPC, you can opt out of TLS.
# Set your OTLP endpoint
export OTEL_EXPORTER_OTLP_ENDPOINT=https://your-collector:4317
Once the collector has been configured, you can enable logs and/or metrics collection. At least one of them needs to be enabled.
# Optional: Set protocol (default is grpc)
export OTEL_EXPORTER_OTLP_PROTOCOL=grpc
```
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `OTEL_TELEMETRY_ENABLED` | Enable OpenTelemetry (`1` or `true`) | Disabled |
| `OTEL_METRICS_EXPORTER` | Metrics exporter type (`console`, `otlp`, or both) | None |
| `OTEL_LOGS_EXPORTER` | Logs exporter type (`console`, `otlp`, or both) | None |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint URL | None |
| `OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol (`grpc`, `http/protobuf`, `http/json`) | `grpc` |
| `OTEL_EXPORTER_OTLP_INSECURE` | Allow insecure connections | `false` |
| `OTEL_EXPORTER_OTLP_HEADERS` | Custom headers (comma-separated `key=value` pairs) | None |
You only need to configure it further if you need an advanced configuration.
### Advanced Configuration
**Separate endpoints for metrics and logs:**
```bash
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://metrics-collector:4317
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://logs-collector:4317
```
You can add custom protocols and endpoints for both, logs and metrics. You can also configure the metrics export interval, and the logs batch size, batch timeout and max queue size.
<Frame>
<img
src="https://assets.int.cline.bot/assets/open_telemetry_metrics_and_logs.png"
/>
</Frame>
**Custom headers for authentication:**
```bash
export OTEL_EXPORTER_OTLP_HEADERS="api-key=your-key,x-custom-header=value"
```
**Multiple exporters (console + OTLP):**
```bash
export OTEL_METRICS_EXPORTER=console,otlp
export OTEL_LOGS_EXPORTER=console,otlp
```
Finally, if your collector needs authentication headers, you can add key value pairs in the headers section.
**Export intervals:**
```bash
# Metrics export interval in milliseconds (default: 60000)
export OTEL_METRIC_EXPORT_INTERVAL=30000
# Logs batch size and timeout
export OTEL_LOG_BATCH_SIZE=512
export OTEL_LOG_BATCH_TIMEOUT=5000
export OTEL_LOG_MAX_QUEUE_SIZE=2048
```
<Frame>
<img
src="https://assets.int.cline.bot/assets/open_telemetry_headers.png"
/>
</Frame>
## Integration Examples
@@ -119,73 +88,46 @@ export OTEL_LOG_MAX_QUEUE_SIZE=2048
Export to Datadog using their OTLP endpoint:
```bash
export OTEL_TELEMETRY_ENABLED=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_ENDPOINT=https://api.datadoghq.com
export OTEL_EXPORTER_OTLP_HEADERS="dd-api-key=YOUR_DD_API_KEY"
```
<Frame>
<img
src="https://assets.int.cline.bot/assets/open_telemetry_datadog_example.png"
/>
</Frame>
### New Relic
Export to New Relic:
```bash
export OTEL_TELEMETRY_ENABLED=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317
export OTEL_EXPORTER_OTLP_HEADERS="api-key=YOUR_NEW_RELIC_LICENSE_KEY"
```
<Frame>
<img
src="https://assets.int.cline.bot/assets/open_telemetry_relic_example.png"
/>
</Frame>
### Grafana Cloud
Export to Grafana Cloud:
```bash
export OTEL_TELEMETRY_ENABLED=1
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp-gateway-prod-us-central-0.grafana.net/otlp
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic YOUR_BASE64_CREDENTIALS"
```
<Frame>
<img
src="https://assets.int.cline.bot/assets/open_telemetry_grafana_example.png"
/>
</Frame>
## Testing Configuration
Test your configuration with console output before sending to a real endpoint:
```bash
# Enable console output to see what data would be exported
export OTEL_TELEMETRY_ENABLED=1
export OTEL_METRICS_EXPORTER=console
export OTEL_LOGS_EXPORTER=console
```
Then launch Cline and check the console output for metrics and logs.
To test your configuration, log in to your account, perform some actions in a task, wait for the export interval, and verify that the data has arrived at your collector.
## Troubleshooting
### No Data Being Exported
If you arent getting any data in your collector, the easiest way to verify your integration is to enable the developer tools in your editor.
1. **Verify OpenTelemetry is enabled:**
```bash
echo $OTEL_TELEMETRY_ENABLED
```
Should output `1` or `true`
To do this, open the [webview developer tools](https://code.visualstudio.com/api/extension-guides/webview#inspecting-and-debugging-webviews).
2. **Check exporters are configured:**
```bash
echo $OTEL_METRICS_EXPORTER
echo $OTEL_LOGS_EXPORTER
```
Once youve done so, if you perform some actions that trigger metrics and/or logs (such as doing a task with Cline),
you will see error logs if any error occurs when sending the data to your collector.
3. **Test with console exporter first:**
```bash
export OTEL_METRICS_EXPORTER=console
export OTEL_LOGS_EXPORTER=console
```
If you don't see any logs, enable [debug mode](#debug-mode).
### Connection Errors
@@ -194,10 +136,7 @@ Then launch Cline and check the console output for metrics and logs.
curl -v https://your-otlp-endpoint:4317
```
2. **Check if insecure mode is needed:**
```bash
export OTEL_EXPORTER_OTLP_INSECURE=true
```
2. **Check if insecure mode is needed** by opting out of TLS
3. **Verify authentication headers:**
Double-check your API keys and authentication headers are correct
@@ -207,7 +146,7 @@ Then launch Cline and check the console output for metrics and logs.
Enable debug logging to see detailed OpenTelemetry information:
```bash
export TEL_DEBUG_DIAGNOSTICS=true
TEL_DEBUG_DIAGNOSTICS=true code .
```
This will output detailed information about:
@@ -218,7 +157,7 @@ This will output detailed information about:
## What Gets Exported
When Opentelemetry is enabled, Cline exports:
When OpenTelemetry is enabled, Cline exports:
### Metrics
- Feature usage counts
@@ -238,9 +177,9 @@ Exported data is already anonymous and doesn't include code content, file paths,
## Limitations
Current OpenTelemetry support in Cline:
- ✅ OTLP metrics export (console, gRPC, HTTP)
- ✅ OTLP logs export (console, gRPC, HTTP)
- ✅ Basic configuration via environment variables
- ✅ OTLP metrics export (gRPC, HTTP)
- ✅ OTLP logs export (gRPC, HTTP)
- ✅ Basic configuration via [Remote Configuration](/enterprise-solutions/configuration/remote-configuration/overview#how-remote-configuration-works)
- ❌ Distributed tracing (not yet implemented)
- ❌ Custom instrumentation API (not yet exposed)
- ❌ Sampling configuration (uses defaults)
@@ -0,0 +1,266 @@
---
title: "OpenTelemetry Integration Override"
sidebarTitle: "OpenTelemetry Override"
description: "Export Cline telemetry to your observability platform using OpenTelemetry Protocol (OTLP)"
---
Cline includes opt-in OpenTelemetry support for exporting metrics and logs to your own observability infrastructure using the OpenTelemetry Protocol (OTLP).
<Note>
OpenTelemetry integration is **optional** and intended for advanced users with existing observability infrastructure. Most users won't need this feature.
</Note>
## What is OpenTelemetry?
[OpenTelemetry](https://opentelemetry.io/) is an industry-standard observability framework that provides a unified way to collect and export telemetry data (metrics, logs, and traces).
Cline's OpenTelemetry support allows you to:
- Export telemetry to your own systems
- Integrate with observability platforms like Datadog, New Relic, Grafana Cloud, etc.
- Maintain full control over your monitoring data
- Use your organization's existing monitoring infrastructure
## Supported Features
Cline supports OpenTelemetry's **OTLP (OpenTelemetry Protocol)** export with:
<CardGroup cols={2}>
<Card title="Metrics Export" icon="chart-bar">
Export metrics about Cline usage, performance, and errors
</Card>
<Card title="Logs Export" icon="file-lines">
Export structured logs for debugging and analysis
</Card>
</CardGroup>
### Export Formats
Cline supports three OTLP export protocols:
- **gRPC** (default, recommended)
- **HTTP/protobuf**
- **HTTP/JSON**
### Export Destinations
You can export to:
- **Console** (for testing)
- **OTLP endpoint** (your own collector or observability platform)
## Configuration
OpenTelemetry is configured using environment variables before launching Cline.
### Basic Setup
Enable OpenTelemetry and configure an OTLP endpoint:
```bash
# Enable OpenTelemetry
export CLINE_OTEL_TELEMETRY_ENABLED=true
# Configure metrics and logs export
export CLINE_OTEL_METRICS_EXPORTER=otlp
export CLINE_OTEL_LOGS_EXPORTER=otlp
# Set your OTLP endpoint
export CLINE_OTEL_EXPORTER_OTLP_ENDPOINT=https://your-collector:4317
# Optional: Set protocol (default is grpc)
export CLINE_OTEL_EXPORTER_OTLP_PROTOCOL=grpc
```
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `CLINE_OTEL_TELEMETRY_ENABLED` | Enable OpenTelemetry (`true`) | Disabled |
| `CLINE_OTEL_METRICS_EXPORTER` | Metrics exporter type (`console`, `otlp`, or both) | None |
| `CLINE_OTEL_LOGS_EXPORTER` | Logs exporter type (`console`, `otlp`, or both) | None |
| `CLINE_OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint URL | None |
| `CLINE_OTEL_EXPORTER_OTLP_PROTOCOL` | Protocol (`grpc`, `http/protobuf`, `http/json`) | `grpc` |
| `CLINE_OTEL_EXPORTER_OTLP_INSECURE` | Allow insecure connections | `false` |
| `CLINE_OTEL_EXPORTER_OTLP_HEADERS` | Custom headers (comma-separated `key=value` pairs) | None |
### Advanced Configuration
**Separate endpoints for metrics and logs:**
```bash
export CLINE_OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://metrics-collector:4317
export CLINE_OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://logs-collector:4317
```
**Custom headers for authentication:**
```bash
export CLINE_OTEL_EXPORTER_OTLP_HEADERS="api-key=your-key,x-custom-header=value"
```
**Multiple exporters (console + OTLP):**
```bash
export CLINE_OTEL_METRICS_EXPORTER=console,otlp
export CLINE_OTEL_LOGS_EXPORTER=console,otlp
```
**Export intervals:**
```bash
# Metrics export interval in milliseconds (default: 60000)
export CLINE_OTEL_METRIC_EXPORT_INTERVAL=30000
# Logs batch size and timeout
export CLINE_OTEL_LOG_BATCH_SIZE=512
export CLINE_OTEL_LOG_BATCH_TIMEOUT=5000
export CLINE_OTEL_LOG_MAX_QUEUE_SIZE=2048
```
## Integration Examples
### Datadog
Export to Datadog using their OTLP endpoint:
```bash
export CLINE_OTEL_TELEMETRY_ENABLED=true
export CLINE_OTEL_METRICS_EXPORTER=otlp
export CLINE_OTEL_LOGS_EXPORTER=otlp
export CLINE_OTEL_EXPORTER_OTLP_ENDPOINT=https://api.datadoghq.com
export CLINE_OTEL_EXPORTER_OTLP_HEADERS="dd-api-key=YOUR_DD_API_KEY"
```
### New Relic
Export to New Relic:
```bash
export CLINE_OTEL_TELEMETRY_ENABLED=true
export CLINE_OTEL_METRICS_EXPORTER=otlp
export CLINE_OTEL_LOGS_EXPORTER=otlp
export CLINE_OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.nr-data.net:4317
export CLINE_OTEL_EXPORTER_OTLP_HEADERS="api-key=YOUR_NEW_RELIC_LICENSE_KEY"
```
### Grafana Cloud
Export to Grafana Cloud:
```bash
export CLINE_OTEL_TELEMETRY_ENABLED=true
export CLINE_OTEL_METRICS_EXPORTER=otlp
export CLINE_OTEL_LOGS_EXPORTER=otlp
export CLINE_OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp-gateway-prod-us-central-0.grafana.net/otlp
export CLINE_OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic YOUR_BASE64_CREDENTIALS"
```
## Testing Configuration
Test your configuration with console output before sending to a real endpoint:
```bash
# Enable console output to see what data would be exported
export CLINE_OTEL_TELEMETRY_ENABLED=true
export CLINE_OTEL_METRICS_EXPORTER=console
export CLINE_OTEL_LOGS_EXPORTER=console
```
Then launch Cline and check the console output for metrics and logs.
## Troubleshooting
### No Data Being Exported
1. **Verify OpenTelemetry is enabled:**
```bash
echo $CLINE_OTEL_TELEMETRY_ENABLED
```
Should output `true`
2. **Check exporters are configured:**
```bash
echo $CLINE_OTEL_METRICS_EXPORTER
echo $CLINE_OTEL_LOGS_EXPORTER
```
3. **Test with console exporter first:**
```bash
export CLINE_OTEL_METRICS_EXPORTER=console
export CLINE_OTEL_LOGS_EXPORTER=console
```
### Connection Errors
1. **Verify endpoint is accessible:**
```bash
curl -v https://your-otlp-endpoint:4317
```
2. **Check if insecure mode is needed:**
```bash
export CLINE_OTEL_EXPORTER_OTLP_INSECURE=true
```
3. **Verify authentication headers:**
Double-check your API keys and authentication headers are correct
### Debug Mode
Enable debug logging to see detailed OpenTelemetry information:
```bash
export TEL_DEBUG_DIAGNOSTICS=true
```
This will output detailed information about:
- Configuration being used
- Exporters being created
- Connection attempts
- Export successes/failures
## What Gets Exported
When OpenTelemetry is enabled, Cline exports:
### Metrics
- Feature usage counts
- Task execution metrics
- Error rates and types
- Performance measurements
### Logs
- System events
- Error logs with context
- Operational information
<Warning>
Exported data is already anonymous and doesn't include code content, file paths, or sensitive information. However, you're responsible for securing the data once exported to your systems.
</Warning>
## Limitations
Current OpenTelemetry support in Cline:
- ✅ OTLP metrics export (console, gRPC, HTTP)
- ✅ OTLP logs export (console, gRPC, HTTP)
- ✅ Basic configuration via environment variables
- ❌ Distributed tracing (not yet implemented)
- ❌ Custom instrumentation API (not yet exposed)
- ❌ Sampling configuration (uses defaults)
## Best Practices
1. **Test First**: Always test with console exporter before sending to production
2. **Secure Credentials**: Never hardcode API keys; use secure environment variable management
3. **Monitor Costs**: Be aware of data ingestion costs with your observability platform
4. **Start Simple**: Begin with metrics only, add logs if needed
5. **Use Compression**: OTLP supports compression; check if your endpoint requires it
## Next Steps
<CardGroup cols={2}>
<Card title="Cline Telemetry" icon="chart-simple" href="/enterprise-solutions/monitoring/telemetry">
Configure simple built-in telemetry
</Card>
<Card title="OpenTelemetry Docs" icon="book" href="https://opentelemetry.io/docs/">
Learn more about OpenTelemetry
</Card>
</CardGroup>
@@ -8,14 +8,20 @@ Cline includes optional monitoring capabilities for organizations that want to t
## Monitoring Options
<CardGroup cols={2}>
<CardGroup cols={2}>
<Card title="OpenTelemetry" icon="chart-line" href="/enterprise-solutions/monitoring/opentelemetry">
Export metrics and logs to your own observability backends
</Card>
<Card title="OpenTelemetry Override" icon="chart-line" href="/enterprise-solutions/monitoring/opentelemetry_override">
Export to your own observability backends through environment variables (advanced)
</Card>
</CardGroup>
<CardGroup cols={1}>
<Card title="Cline Telemetry" icon="chart-simple" href="/enterprise-solutions/monitoring/telemetry">
Built-in anonymous usage tracking that helps improve Cline (opt-in)
</Card>
<Card title="OpenTelemetry" icon="chart-line" href="/enterprise-solutions/monitoring/opentelemetry">
Export metrics and logs to your own observability backends (advanced)
</Card>
</Card>
</CardGroup>
## Cline Telemetry
+4
View File
@@ -22,6 +22,10 @@ Your IdP administrator will receive an email with a link to register their organ
### Step 2: Configure Your Identity Provider
<Info>
For a short overview of where SSO configuration lives (Cline dashboard vs WorkOS vs your IdP), see [SSO Setup](/enterprise-solutions/sso-setup).
</Info>
Connect your identity provider (IdP) to WorkOS:
1. In the WorkOS dashboard, go to **AuthKit → Connections**
+61
View File
@@ -0,0 +1,61 @@
---
title: "SSO Setup"
sidebarTitle: "SSO Setup"
description: "Configure Single Sign-On (SSO) for Cline Enterprise via WorkOS AuthKit."
---
## Overview
Cline Enterprise integrates with your identity provider (IdP) via **WorkOS AuthKit** for SSO.
This page describes, at a high level, how SSO is set up for Cline Enterprise using WorkOS AuthKit.
If you havent completed initial onboarding, start with [Onboarding](/enterprise-solutions/onboarding).
## Where setup happens
SSO setup spans two places:
1) **Cline Dashboard (app.cline.bot)**
- Where you sign in and verify SSO works for your organization.
2) **WorkOS dashboard**
- Where your IdP connection is configured (AuthKit → Connections). Your designated admin receives access to this during enterprise onboarding.
## Using the Cline Dashboard
Use the Cline Dashboard at https://app.cline.bot to:
- complete sign-in and onboarding flows
- verify users can authenticate via SSO
## Configure your IdP connection in WorkOS
During enterprise onboarding, your designated admin will receive an invitation email from WorkOS with a link to access your organization's WorkOS dashboard.
<Frame>
<img src="/assets/workos-invite-email.png" alt="WorkOS invitation email example" />
</Frame>
To connect your IdP to Cline Enterprise, configure your identity provider in **WorkOS AuthKit**:
1. In the WorkOS dashboard, go to **AuthKit → Connections**
2. Click **Add Connection**
3. Select your identity provider (e.g., Okta, Microsoft Entra ID/Azure AD, Google Workspace, Generic SAML/OIDC)
4. Follow the provider-specific instructions in WorkOS
WorkOSs UI and required fields vary by provider. For details, follow WorkOS documentation:
- https://workos.com/docs/authkit/sso
## Keycloak note (IdP compatibility)
Cline Enterprises default SSO integration is **via WorkOS**.
If you use **Keycloak** as your IdP, the supported path is to configure Keycloak in WorkOS as a **Generic SAML** or **Generic OIDC** provider (using the settings WorkOS requests for those provider types).
## Verification
After configuring WorkOS:
1) Attempt an SSO sign-in from https://app.cline.bot.
2) Confirm the sign-in completes (you are redirected back successfully).
## Troubleshooting
- **Redirect URI mismatch**: confirm the redirect/callback URL configured in WorkOS matches what was provided during your Cline Enterprise onboarding.
For additional troubleshooting guidance, refer to WorkOS documentation:
- https://workos.com/docs/authkit/sso
@@ -13,46 +13,6 @@ Cline is your AI assistant that can:
- Automate repetitive tasks
- Integrate with external tools
## First Steps
1. **Start a Task**
- Type your request in the chat
- Example: "Create a new React component called Header"
2. **Provide Context**
- Use @ mentions to add files, folders, or URLs
- Example: "@file:src/components/App.tsx"
3. **Review Changes**
- Cline will show diffs before making changes
- You can edit or reject changes
## Key Features
1. **File Editing**
- Create new files
- Modify existing code
- Search and replace across files
2. **Terminal Commands**
- Run npm commands
- Start development servers
- Install dependencies
3. **Code Analysis**
- Find and fix errors
- Refactor code
- Add documentation
4. **Browser Integration**
- Test web pages
- Capture screenshots
- Inspect console logs
## Available Tools
@@ -84,6 +44,7 @@ Cline has access to the following tools for various tasks:
- `ask_followup_question`: Ask user for clarification
- `attempt_completion`: Present final results
Each tool has specific parameters and usage patterns. Here are some examples:
- Create a new file (write_to_file):
+77 -32
View File
@@ -1,59 +1,104 @@
The Auto Approve menu lets you set fine-grained permissions on what you allow Cline to do in an automated way.
---
title: "Auto Approve"
sidebarTitle: "Auto Approve"
description: "Let Cline take specific actions without asking for approval every time."
---
Auto Approve lets you decide which actions Cline can take without prompting you each time. It keeps you out of approval popups during routine work, while still letting you keep tight control over high-risk actions.
If you find yourself repeatedly clicking approve for the same safe operations, Auto Approve is the setting that fixes that. The goal is fewer interruptions without losing the ability to review changes when it matters.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/docs/assets/auto-approve.png" alt="Auto Approve" />
<video
style={{ width: "100%" }}
src="https://storage.googleapis.com/cline_public_images/autoapprove.mp4"
autoPlay
controls
playsInline
/>
</Frame>
## How it works
By default, Cline will ask for your permission before calling any tool, including reading or writing files.
Auto Approve is evaluated per tool call. When Cline is about to read a file, edit a file, run a command, or use the browser, Cline checks your Auto Approve settings for that category.
If you want to allow Cline to do something without asking, you can set the Auto Approve permission for that tool.
A few details matter in practice:
## Permission Options
- **Workspace vs outside your workspace**: “Read all files” and “Edit all files” only extend the base toggle. If the base toggle is off, the “all files” option does nothing.
- **Read project files**
- **Terminal commands**: Cline treats terminal commands as either safe or requiring approval. “Execute safe commands” covers the first category. “Execute all commands” extends this to commands flagged as requiring approval.
- Allows Cline to read files within your current workspace without asking
- **Read all files**
- Extends read permission to files outside your workspace (system files, config files, etc.)
- **Notifications**: If enabled, Cline sends OS-level notifications when approval is required, and when an auto-approved terminal command has been running for 30 seconds and may need attention.
- **Edit project files**
<Note>
[YOLO mode](/features/yolo-mode) bypasses these granular approvals.
</Note>
- Allows Cline to modify files within your current workspace without confirmation
- **Edit all files**
- Extends modification permission to files outside your workspace
## Permissions
- **Execute safe commands**
These labels match what you see in the Auto Approve menu.
- Allows execution of terminal commands that the model deems non-destructive
- **Execute all commands**
- Permits execution of any terminal command without asking
| Setting | What it allows | Notes |
|--------|-----------------|------|
| Read project files | Read files, list files, search in your workspace | Good default for most tasks |
| Read all files | Read files outside your workspace | Requires “Read project files” |
| Edit project files | Create and edit files in your workspace | Consider using checkpoints |
| Edit all files | Edit files outside your workspace | Requires “Edit project files” |
| Execute safe commands | Run terminal commands marked safe | Can still run long |
| Execute all commands | Run commands marked as requiring approval | Requires “Execute safe commands” |
| Use the browser | Allows use of the browser tool for web fetching and searching | Proxy issues can apply |
| Use MCP servers | Use MCP tools and access MCP resources | Some servers also have per-tool auto-approve |
| Enable notifications | Notifies you about long-running auto-approved commands | Helpful for terminal work |
- **Use the browser**
<Warning>
“Read all files” and “Edit all files” only matter if their base toggle is enabled. They extend access outside your workspace.
</Warning>
- Allows Cline to use the browser tool to fetch web content
<Card title="Networking & proxies" icon="globe" href="/troubleshooting/networking-and-proxies">
If browser-based tools fail in corporate networks, this page covers the common fixes.
</Card>
- **Use MCP servers**
## Safe vs approval-required command examples
- Permits connection to and usage of MCP servers for extended functionality
Cline does not use a fixed allowlist of safe or unsafe commands. The model marks each command with a `requires_approval` flag based on the command and its arguments, and Auto Approve uses that flag.
- **Maximum requests**
- Sets the number of consecutive automated actions Cline can take before requiring your input
These are examples, not guarantees.
## Best Practices
### Commonly treated as safe
Personally, I like to keep auto-editing disabled because it gives me a chance to review changes every step of the way.
| Example | Why it is usually safe |
|--------|-------------------------|
| `npm run build` | Build output, no direct file deletions |
| `npm test` | Runs tests |
| `git status` | Read-only |
| `ls -la` | Read-only |
| `cat package.json` | Read-only |
For most serious development workflows, I recommend starting with:
### Commonly requires approval
- Auto-approving read access to project files
- Setting a reasonable maximum request limit (10-20)
| Example | Why it often needs approval |
|--------|------------------------------|
| `npm install <pkg>` | Modifies dependencies and lockfiles |
| `rm -rf <path>` | Deletes files |
| `mv <a> <b>` | Moves files (can overwrite) |
| `sed -i ...` | In-place file edits |
| `curl https://...` | Downloads and executes remote code |
This gives Cline enough freedom to explore your codebase without constant interruptions, while still requiring permission for edits or potentially destructive actions.
<Note>
Whether a command is treated as safe depends on the exact command, flags, and the current task. When in doubt, keep command auto-approval off and approve commands manually.
</Note>
As you build more trust in Cline's capabilities with your specific projects, you can gradually increase the permissions to match your comfort level.
## Enable notifications
Remember that you can always adjust these settings as your needs change - tighten permissions for critical production work, or loosen them when prototyping and exploring.
Auto-approved actions can run for a while, especially long terminal commands. If you enable notifications, Cline can notify you when an auto-approved command has been running for a while and may need attention.
You can even use the quick "star" actions to quickly toggle your auto-approved selections on and off as you go.
## Recommendations
A good default setup is:
- Enable **Read project files**
- Leave **Edit project files**, **Execute safe commands**, **Use the browser**, and **Use MCP servers** off until you have a specific reason to enable them
If you enable edits, use [Checkpoints](/features/checkpoints) so you can roll back quickly.
If youre working in a sensitive environment (production credentials, personal files, corporate devices), keep external file access and command execution locked down and approve actions manually as you go.
+51
View File
@@ -0,0 +1,51 @@
---
title: "Background Edit"
sidebarTitle: "Background Edit"
---
Background Edit lets Cline make file changes without opening the diff editor, so you can keep writing code while Cline works on other files in the background.
<Note>
This feature is marked as experimental.
</Note>
## How It Works
By default, Cline opens a side-by-side diff editor tab for each file it modifies. With Background Edit enabled:
- Edits write directly to your files without opening new tabs
- Changes appear as collapsible diff blocks in the chat panel
- Your editor focus stays on whatever file you had open
## Enabling Background Edit
1. Click the settings icon (gear) in the top-right corner of the Cline panel
2. Go to "**Feature Settings**"
3. Toggle "**Enable Background Edit**" on
## Viewing Changes
File changes display directly in the chat panel with:
- **File action icons** showing whether the file was added, updated, or deleted
- **Stats** showing additions (+) and deletions (-) at a glance
- **Collapsible diffs** you can expand or collapse by clicking the file header
- **Real-time streaming** as changes appear line-by-line
Green highlights additions, red highlights deletions.
## When to Use It
This feature works well when you:
- Use [auto-approve mode](/features/auto-approve) and prefer reviewing changes after the fact
- Work on tasks with many small file changes
- Want to stay focused on your current file
Stick with the default diff editor if you prefer reviewing each change before it saves, or need to make inline edits to Cline's proposed changes.
## Relationship with Other Features
- **Checkpoints**: Still created after each file operation
- **Auto-approve**: Pairs well for uninterrupted workflows
- **Message editing**: Restoring from a previous message works as expected
@@ -3,94 +3,192 @@ title: "Keyboard Shortcuts"
sidebarTitle: "Keyboard Shortcuts"
---
Cline's keyboard shortcuts let you access AI assistance without taking your hands off the keyboard. Speed up your workflow by using hotkeys for common Cline actions.
Speed up your workflow by accessing Cline's AI assistance without taking your hands off the keyboard.
## Default Keyboard Shortcuts
<Tip>
**The One Shortcut You Need:** `Ctrl+'` (Windows/Linux) or `Cmd+'` (macOS)
Cline comes with the following built-in keyboard shortcuts to streamline your workflow:
This context-aware shortcut handles your most common needs:
- **With text selected:** Adds code to Cline chat
- **Without selection:** Focuses the chat input
| Action | Windows/Linux | macOS | Condition | Description |
| ----------------------- | ------------- | ------- | ---------------------------- | ----------------------------------------- |
| Add to Cline | `Ctrl+'` | `Cmd+'` | When text is selected | Adds selected code to Cline chat |
| Focus Chat Input | `Ctrl+'` | `Cmd+'` | When no text is selected | Focuses the Cline chat input field |
| Generate Commit Message | (unset) | (unset) | When Git is the SCM provider | Available through the Source Control view |
Master this one shortcut, and you're 90% there.
</Tip>
## Available Commands for Custom Shortcuts
## Default Shortcuts
While Cline has only a few default keyboard shortcuts, you can assign your own shortcuts to any of these commands:
Cline has minimal default shortcuts by design, so they won't conflict with your existing VSCode setup:
| Command ID | Description |
| ---------------------------------------------------------------------------------------- | --------------------------------------------- |
| [`cline.addToChat`](/features/commands-and-shortcuts/code-commands) | Adds selected code to Cline chat |
| [`cline.addTerminalOutputToChat`](/features/commands-and-shortcuts/terminal-integration) | Adds terminal output to Cline |
| `cline.focusChatInput` | Focuses the Cline chat input field |
| [`cline.generateGitCommitMessage`](/features/commands-and-shortcuts/git-integration) | Generates a commit message for staged changes |
| [`cline.explainCode`](/features/commands-and-shortcuts/code-commands) | Explains selected code |
| [`cline.improveCode`](/features/commands-and-shortcuts/code-commands) | Suggests improvements for selected code |
| [`cline.fixWithCline`](/features/commands-and-shortcuts/code-commands) | Fixes code with errors |
| `claude-dev.SidebarProvider.focus` | Opens and focuses the Cline sidebar |
| Shortcut | Windows/Linux | macOS | What It Does |
| -------- | ------------- | ----- | ------------ |
| **Add to Chat / Focus Input** | `Ctrl+'` | `Cmd+'` | Context-aware: adds selected code or focuses chat |
## Customizing Keyboard Shortcuts
That's it! Everything else is available for you to customize.
You can customize Cline's keyboard shortcuts to match your preferences:
## Quick Workflow Examples
1. Open the Keyboard Shortcuts editor in VSCode:
Here's how keyboard shortcuts fit into real coding workflows:
- Press `Ctrl+K Ctrl+S` (Windows/Linux) or `Cmd+K Cmd+S` (macOS)
- Or go to File > Preferences > Keyboard Shortcuts
### Debug & Fix Workflow
2. Search for "Cline" to see all available commands
1. **Find error in code** → VSCode highlights it
2. **Select the problematic code** → `Shift+Arrow` or `Ctrl+L` / `Cmd+L`
3. **Send to Cline** → `Ctrl+'` / `Cmd+'`
4. **Ask for help** → Type your question, hit `Enter`
3. Click on the pencil icon next to any command to change its shortcut
### Code Review Workflow
4. Press the keys you want to assign to that command
1. **Review a function** → Select it with `Ctrl+L` / `Cmd+L`
2. **Get AI review** → `Ctrl+'` / `Cmd+'` then ask "Review this"
3. **Iterate** → Apply suggestions and repeat
5. Press Enter to save the new shortcut
### Terminal Integration Workflow
## Suggested Custom Shortcuts
1. **Open terminal** → Press `` Ctrl+` `` / `` Cmd+` ``
2. **Run your command** → Execute in terminal
3. **Capture output** → Press `Alt+T` (after assigning shortcut)
4. **Get help** → Ask Cline to interpret errors or output
Here are some suggested shortcuts you might find useful:
<Info>
**Pro Tip:** Assign `Alt+T` to the `cline.addTerminalOutputToChat` command for quick terminal output capture. Without a shortcut, you can still right-click in the terminal and select "Add to Cline" - but the keyboard approach is much faster for frequent debugging workflows.
</Info>
| Action | Suggested Shortcut | Command ID | Description |
| --------------------- | ------------------------------ | ----------------------------------------- | ----------------------------- |
| Open Cline Sidebar | `Ctrl+Shift+C` / `Cmd+Shift+C` | `claude-dev.SidebarProvider.focus` | Opens the Cline sidebar panel |
| New Task | `Alt+N` | `cline.plusButtonClicked` | Starts a new Cline task |
| Add Terminal to Cline | `Alt+T` | `cline.addTerminalOutputToChat` | Adds terminal output to Cline |
| Clear Current Task | `Alt+C` | (Requires custom keybinding to UI action) | Clears the current task |
## Customizing Shortcuts
## Keyboard-Only Workflow
Want to assign shortcuts to more Cline commands? Here's how:
With the right shortcuts, you can use Cline without ever touching the mouse:
**Step 1:** Open VSCode's Keyboard Shortcuts editor
- Press `Ctrl+K Ctrl+S` (Windows/Linux) or `Cmd+K Cmd+S` (macOS)
- Or: **File → Preferences → Keyboard Shortcuts**
1. Select code with keyboard navigation (`Shift+Arrow` keys)
2. Send to Cline with `Ctrl+'` / `Cmd+'`
3. Type your question and press Enter
4. Review the response and apply suggestions
**Step 2:** Search for "Cline"
## Editor Integration Shortcuts
**Step 3:** Click the ✏️ icon next to any command
Cline's keyboard shortcuts integrate seamlessly with VSCode's built-in shortcuts:
**Step 4:** Press your desired key combo, then `Enter`
- Use VSCode's selection shortcuts (`Ctrl+L` / `Cmd+L` to select line, etc.) before sending code to Cline
- Combine with VSCode's split editor shortcuts to view code and Cline side by side
- Use VSCode's terminal focus shortcut (`` Ctrl+` `` / `` Cmd+` ``) before capturing terminal output
<Warning>
**Avoid Conflicts:** Check that your shortcut doesn't override important VSCode commands. The shortcuts editor will warn you about conflicts.
</Warning>
## Tips for Effective Use
## Available Commands Reference
- **Learn the default shortcut first**: The `Ctrl+'` / `Cmd+'` shortcut is versatile - it adds selected code to chat when text is selected, or focuses the chat input when nothing is selected
- **Create muscle memory**: Use keyboard shortcuts consistently to build habits
- **Customize for your workflow**: Assign shortcuts to commands you use frequently
- **Consider ergonomics**: Choose shortcuts that are comfortable for your keyboard layout
<Accordion title="Task Management Commands">
Keyboard shortcuts may seem like a small optimization, but they can significantly speed up your workflow when using Cline regularly. By keeping your hands on the keyboard, you maintain your coding flow while still getting AI assistance exactly when you need it.
These commands help you navigate and manage Cline tasks:
## How to Find All Available Commands
| Command ID | Description | Suggested Shortcut |
| ---------- | ----------- | ------------------ |
| `cline.plusButtonClicked` | Start a new task | `Ctrl+Shift+N` / `Cmd+Shift+N` |
| `cline.historyButtonClicked` | Open task history | `Ctrl+Shift+H` / `Cmd+Shift+H` |
| `claude-dev.SidebarProvider.focus` | Open Cline sidebar | `Ctrl+Shift+L` / `Cmd+Shift+L` |
To see all Cline commands that can be assigned shortcuts:
**Note:** `claude-dev` prefix is for historical reasons - it works with Cline.
1. Open the Command Palette (`Ctrl+Shift+P` / `Cmd+Shift+P`)
2. Type "Cline" to filter the list
3. Browse the available commands
</Accordion>
<Accordion title="Code Interaction Commands">
Work directly with your code:
| Command ID | Description | Suggested Shortcut |
| ---------- | ----------- | ------------------ |
| `cline.addToChat` | Add selected code to chat | `Ctrl+'` / `Cmd+'` ⭐ (default) |
| `cline.focusChatInput` | Focus chat input | `Ctrl+'` / `Cmd+'` ⭐ (default) |
| `cline.explainCode` | Explain selected code | `Ctrl+Shift+E` / `Cmd+Shift+E` |
| `cline.improveCode` | Suggest code improvements | `Ctrl+Shift+I` / `Cmd+Shift+I` |
⭐ These share the same shortcut - it's context-aware!
</Accordion>
<Accordion title="Terminal Integration Commands">
Connect Cline with your terminal:
| Command ID | Description | Suggested Shortcut |
| ---------- | ----------- | ------------------ |
| `cline.addTerminalOutputToChat` | Add terminal output to Cline | `Alt+T` |
**Tip:** Use this after running commands to get help interpreting output or fixing errors.
</Accordion>
<Accordion title="Git Integration Commands">
Generate commit messages with AI:
| Command ID | Description | Suggested Shortcut |
| ---------- | ----------- | ------------------ |
| `cline.generateGitCommitMessage` | Generate commit message | `Ctrl+Shift+G` / `Cmd+Shift+G` |
| `cline.abortGitCommitMessage` | Stop generation | `Ctrl+Shift+Esc` / `Cmd+Shift+Esc` |
</Accordion>
<Accordion title="Settings & Configuration Commands (Advanced)">
These commands open Cline's configuration panels. Most users access these via the sidebar buttons, but keyboard shortcuts can be useful for:
- **Frequent MCP server developers** who constantly adjust server configurations
- **Demo/presentation scenarios** where you need quick, keyboard-only navigation
- **Accessibility workflows** where mouse usage is minimized
| Command ID | Description | Suggested Shortcut |
| ---------- | ----------- | ------------------ |
| `cline.settingsButtonClicked` | Open Cline settings | `Ctrl+Alt+,` / `Cmd+Opt+,` |
| `cline.mcpButtonClicked` | Open MCP servers config | `Ctrl+Alt+M` / `Cmd+Opt+M` |
| `cline.accountButtonClicked` | Open account settings | `Ctrl+Alt+A` / `Cmd+Opt+A` |
| `cline.openWalkthrough` | Open walkthrough guide | (not recommended) |
**Our take:** Unless you're constantly tweaking settings or building MCP servers, the sidebar buttons are more convenient. But if you find yourself opening these panels frequently, shortcuts can save time.
</Accordion>
## What About "Fix with Cline"?
<Warning>
**You CAN'T assign a keyboard shortcut to "Fix with Cline"**
This command only appears in the **lightbulb menu** (💡) when VSCode detects errors in your code. It needs the error context to work, so it's not available as a standalone command.
**Workarounds:**
- Click the 💡 lightbulb icon that appears next to errors
- Or select code with errors and use `Ctrl+'` / `Cmd+'` to ask Cline to fix them
- Or right-click and select "Add to Cline"
</Warning>
Learn more about code actions in our [Code Commands documentation](/features/commands-and-shortcuts/code-commands).
## Best Practices
<Tip>
**Start Simple**
Don't try to memorize 20 shortcuts on day one. Start with:
1. `Ctrl+'` / `Cmd+'` (the essential one)
2. Add 1-2 more based on your actual usage patterns
3. Build muscle memory over time
</Tip>
**Choose Shortcuts Wisely:**
- **Be ergonomic:** Use comfortable key combinations
- **Create patterns:** Group related commands (e.g., all Cline shortcuts use `Ctrl+Shift+...`)
- **Avoid conflicts:** Don't override VSCode essentials like `Ctrl+C` or `Ctrl+S`
- **Use modifiers:** Combine `Ctrl`/`Cmd` + `Shift` + `Alt` to reduce conflicts
**Build the Habit:**
- Use shortcuts consistently for a week to build muscle memory
- Keep a note of your custom shortcuts until they're automatic
- Review monthly to see if your workflow has changed
## Discovering Commands
Not sure what commands are available? Use VSCode's Command Palette:
1. Press `Ctrl+Shift+P` / `Cmd+Shift+P`
2. Type "Cline" to filter
3. Browse all available commands
4. Assign shortcuts to your favorites
<Frame>
<img
@@ -99,4 +197,8 @@ To see all Cline commands that can be assigned shortcuts:
/>
</Frame>
This helps you discover features you might not have known about and assign shortcuts to the ones you use most frequently.
---
<Info>
**Remember:** The goal isn't to memorize every possible shortcut. Master `Ctrl+'` / `Cmd+'` first, then gradually add shortcuts for commands you use frequently. Quality over quantity!
</Info>
+200 -104
View File
@@ -1,164 +1,260 @@
---
title: "Multiroot Workspace Support"
sidebarTitle: "Multiroot Workspace"
title: "Multi-Root Workspaces"
sidebarTitle: "Multi-Root Workspaces"
---
Cline's Multiroot feature works seamlessly with VSCode's multi-root workspaces, letting you manage multiple project folders in a single workspace.
Cline works with VSCode's multi-root workspaces, letting you manage multiple project folders or repositories in a single window. Whether you're working with a monorepo or separate Git repositories, Cline can read files, write code, and run commands across all of them.
<Frame>
<video
src="https://storage.googleapis.com/cline_public_images/multiworkspace.mp4"
autoPlay
muted
loop
playsInline
controls
/>
</Frame>
<Warning>
Multi-root workspaces have two limitations:
- **Cline rules** only work in the primary workspace folder
- **Checkpoints** are disabled (restored when you return to a single folder)
See [Current Limitations](#current-limitations) for details.
</Warning>
## Understanding Multi-Root Workspaces
Before diving in, it helps to understand the two common patterns for organizing related projects.
### Why Use Multi-Root Workspaces?
Cline can complete tasks that span multiple projects or repositories:
- **Refactoring**: Update an API contract and fix all consumers across repos
- **Feature development**: Implement a feature that touches frontend, backend, and shared code
- **Dependency updates**: Coordinate version bumps across related projects
- **Documentation**: Generate docs that reference code from multiple repositories
**Example prompt:**
```
Update the User type in the contracts repo, then update both the frontend
and backend to use the new fields. Make sure the API validates the new
required field.
```
## Setting Up a Multi-Root Workspace
### Monorepos vs Multiple Repositories
**Monorepo**: One Git repository containing multiple projects or packages. All code shares the same version history.
```
my-company/ # Single Git repo
├── .git/
├── packages/
│ ├── web/ # React frontend
│ ├── api/ # Node.js backend
│ └── shared/ # Common utilities
└── package.json
```
**Multiple Repositories**: Separate Git repositories, each with their own history, opened together in one VSCode workspace.
```
~/projects/
├── fullstack.code-workspace # Workspace config file
├── frontend/ # git@github.com:acme/frontend.git
│ └── .git/
├── backend/ # git@github.com:acme/backend.git
│ └── .git/
└── contracts/ # git@github.com:acme/api-contracts.git
└── .git/
```
Cline supports both patterns, as well as hybrid setups where some folders are Git repositories and others are not. The key difference: with multiple repositories, each folder has its own `.git` directory and Cline tracks them independently.
### Adding Folders to Your Workspace
You can add folders to your workspace in several ways:
- **File menu**: Use `File > Add Folder to Workspace` in VSCode
- **Drag and drop**: Drag folders directly into VSCode's file explorer
- **Workspace file**: Create a `.code-workspace` file (recommended for teams)
- **Command palette**: Run `Workspaces: Add Folder to Workspace`
For detailed instructions, see [Microsoft's multi-root workspace guide](https://code.visualstudio.com/docs/editor/multi-root-workspaces).
## Working with Multiple Repositories
When you open separate Git repositories in one workspace, Cline treats each as an independent project with its own version control.
### What Cline Tracks Per Repository
For each workspace folder, Cline detects:
| Property | Description |
|----------|-------------|
| **Path** | Absolute path to the folder |
| **Name** | Derived from folder name or workspace file |
| **VCS Type** | Git, Mercurial, or None |
| **Commit Hash** | Current HEAD commit (for Git/Mercurial repos) |
This means Cline understands that your frontend and backend might be at different commits, on different branches, or even use different version control systems.
<Note>
**Important:** Multi-root workspaces are currently an experimental feature and have the following limitations:
- **Cline rules** only work in the first workspace folder
- **Checkpoints** are automatically disabled with a warning message
- Both features are restored when you return to a single-folder workspace
While Cline detects VCS information for all workspace folders, certain features only use the **primary workspace** (the first folder): [Cline rules](/features/cline-rules), [workflows](/features/slash-commands/workflows/index), and [Git-related features](/features/at-mentions/git-mentions) like `@git` mentions.
</Note>
## What is multiroot workspace support?
## Referencing Files Across Workspaces
Instead of being limited to one project folder, Cline can read files, write code, and run commands across all folders in your VSCode workspace. This is helpful when working with monorepos, microservices, or when you're working on related projects simultaneously.
### Natural Language References
### How it works
When you open multiple workspace folders in VSCode, Cline automatically:
- Designates one folder as the **primary workspace** (typically the first folder added)
- Tracks all workspace folders and their paths
- Resolves file paths intelligently across workspaces
- Displays workspace information in the environment details for each API request
## Getting Started
### Setting Up Multi-Root Workspaces
1. **Add folders to your workspace:**
- Use `File > Add Folder to Workspace` in VSCode
- Or create a `.code-workspace` file with multiple folder paths
- Drag and drop folders to the File Explorer
- Select multiple folders when opening a new workspace
2. **Start using Cline** - Cline will automatically detect all your workspace folders and interact with them as needed.
For detailed instructions on setting up multi-root workspaces in VS Code, see [Microsoft's official guide](https://code.visualstudio.com/docs/editing/workspaces/multi-root-workspaces).
### Technical behavior
**Workspace detection**
- Cline detects all workspace folders when a task starts
- The first workspace folder becomes the primary workspace by default
- Each workspace can have its own VCS (Git, SVN, etc.)
**Path resolution**
- Relative paths are resolved relative to the primary workspace
- You can use workspace hints to target specific workspaces: `@workspaceName:path/to/file`
- Cline attempts to intelligently determine which workspace a file belongs to
**Command execution**
- Commands execute in the appropriate workspace context
- The working directory is set based on where files are being accessed
## Working across workspaces
### Referencing specific workspaces
You can reference different workspaces naturally in your prompts:
Cline understands natural references to your workspaces:
```
"Read the package.json in my frontend folder and compare it with the backend dependencies"
"Read the package.json in the frontend folder"
```
```
"Create a shared utility function and update both the client and server to use it"
"Compare the user model in backend with the TypeScript types in contracts"
```
```
"Search for TODO comments across all my workspace folders"
"Search for TODO comments across all workspaces"
```
### Workspace hints
### Workspace Hints Syntax
Use workspace hints to explicitly reference files in specific workspaces:
For explicit references, use the `@workspace:path` syntax:
```
@frontend:src/App.tsx
@backend:server.ts
```
| Syntax | Description |
|--------|-------------|
| `@frontend:src/App.tsx` | File in the "frontend" workspace |
| `@backend:server.ts` | File in the "backend" workspace |
| `@contracts:types/` | Folder in the "contracts" workspace |
This syntax helps Cline resolve ambiguity when multiple workspaces contain similarly named files.
This syntax is especially useful when:
- Multiple workspaces have files with the same name
- You want to be explicit about which project you mean
- Cline needs to resolve ambiguity
### How Workspace Names Work
## Common use cases
Workspace names are derived from:
1. The `name` field in your `.code-workspace` file (if specified)
2. The folder name (default)
If two folders have the same name, append numbers or use the workspace file to give them unique names.
## Common Configurations
### Monorepo Development
Perfect for when you have related projects in one repository:
```
my-app.code-workspace
~/projects/my-app/
├── my-app.code-workspace # Workspace config file
├── web/ (React frontend)
├── api/ (Node.js backend)
├── api/ (Node.js backend)
├── mobile/ (React Native)
└── shared/ (Common utilities)
```
Ask Cline: *"Update the API endpoint in both web and mobile apps to match the new backend route"*
All folders share one Git history. Changes across packages are atomic.
### Microservices Architecture
**Example prompt:** *"Update the API endpoint in both web and mobile apps to match the new backend route"*
Manage multiple services from one workspace:
### Microservices with Separate Repos
```
services.code-workspace
├── user-service/
├── payment-service/
├── notifications/
── infrastructure/
~/projects/services/
├── services.code-workspace # Workspace config file
├── user-service/ (git: github.com/acme/user-service)
├── payment-service/ (git: github.com/acme/payment-service)
── gateway/ (git: github.com/acme/api-gateway)
└── proto/ (git: github.com/acme/service-protos)
```
### Full-Stack Development
Each service has its own repository. Cline can update the proto definitions and regenerate clients across all services.
Keep everything together while maintaining separation:
**Example prompt:** *"Add a new field to the UserProfile message in proto, then update user-service and gateway to handle it"*
### Full-Stack with Shared Contracts
```
fullstack.code-workspace
├── client/ (Frontend)
├── server/ (Backend API)
├── docs/ (Documentation)
└── deploy/ (Scripts & config)
~/projects/fullstack/
├── fullstack.code-workspace # Workspace config file
├── client/ (git: github.com/acme/web-client)
├── server/ (git: github.com/acme/api-server)
└── types/ (git: github.com/acme/shared-types)
```
The types repository defines interfaces used by both client and server. When you update a type, Cline can fix both consumers.
### Auto-Approve Integration
### Hybrid Setup
Multiroot workspaces work with [Auto Approve](/features/auto-approve):
```
~/projects/project/
├── project.code-workspace # Workspace config file
├── main-app/ (git: github.com/acme/main-app)
├── vendor/ (no VCS - vendored dependencies)
└── scripts/ (no VCS - local automation)
```
- Enable permissions for operations within workspace folders
- Restrict auto-approve for files outside your workspace(s)
- Configure different levels for different workspace folders
Mix of repositories and plain folders. Cline adapts to each folder's configuration.
### Cross-Workspace Operations
## Current Limitations
Cline can complete tasks spanning multiple workspaces:
Two features have limitations in multi-root workspace mode:
- **Refactoring**: Update imports and references across projects
- **Feature development**: Implement features requiring changes in multiple services
- **Documentation**: Generate docs referencing code from multiple folders
- **Testing**: Build & run tests across all workspaces and analyze results
### Cline Rules
When working with large multiroot workspaces, start in [Plan mode](/features/plan-and-act) to let Cline understand your project structure before making changes.
[Cline rules](/features/cline-rules) (`.clinerules/` directory) only work in the **primary workspace** (the first folder in your workspace). Rules in other workspace folders are ignored.
**Workaround:** Place shared rules in the primary workspace, or use global rules (`~/Documents/Cline/Rules/`) which apply everywhere.
### Checkpoints
[Checkpoints](/features/checkpoints) are disabled in multi-root workspace mode. Cline displays a warning when this happens.
**Why:** Checkpoints use a shadow Git repository to track changes. With multiple repositories, coordinating checkpoints across independent Git histories adds complexity that isn't yet supported.
**Workaround:** Use your normal Git workflow. Commit frequently, or create branches for experimental work.
Both limitations are restored when you return to a single-folder workspace.
## Best Practices
### Organizing Your Workspaces
1. **Group related projects** that often need coordinated changes
2. **Use consistent folder structures** across workspaces when possible
3. **Name folders clearly** so Cline can understand your project structure
2. **Use a workspace file** for reproducible setups across your team
3. **Name folders clearly** so workspace hints are intuitive
4. **Consider the primary workspace** for Cline rules placement
### Effective Prompting & Tips
### Effective Prompting
When working with multiroot workspaces, these approaches work best:
- **Be specific** when it matters: *"Update the user model in the backend workspace"*
- **Reference relationships**: *"The frontend uses types from the contracts workspace"*
- **Describe cross-workspace changes**: *"This needs to update both web and mobile"*
- **Scope searches** for large codebases: *"Search for 'TODO' only in the frontend workspace"*
- **Be specific** about which workspace when it matters: *"Update the user model in the backend workspace"*
- **Reference relationships**: *"The frontend uses the API types from the shared workspace"*
- **Describe cross-workspace operations**: *"This change needs to be reflected in both the web and mobile apps"*
- **Scope your searches** when dealing with large codebases: *"Search for 'TODO' in just the frontend workspace"*
- **Break down large tasks** into workspace-specific operations when possible
- **Consider excluding large folders** like `node_modules` from your workspace search Scope
### Working with Large Workspaces
- Break large tasks into workspace-specific operations when possible
- Use [Plan mode](/features/plan-and-act) to let Cline understand structure first
- Add a `.clineignore` file to reduce noise, speed up scanning, and keep Cline focused on source code:
```text
# Dependencies
**/node_modules/
# Build outputs
**/dist/
**/build/
# VCS metadata
**/.git/
```
For more patterns and gotchas, see the [.clineignore File Guide](/prompting/prompt-engineering-guide#clineignore-file-guide).
+231
View File
@@ -0,0 +1,231 @@
---
title: "Skills"
sidebarTitle: "Skills"
description: "Extend Cline with reusable, on-demand instruction sets for specialized tasks"
---
Skills are modular instruction sets that extend Cline's capabilities for specific tasks. Each skill packages detailed guidance, workflows, and optional resources that Cline loads only when relevant to your request.
Unlike rules (which are always active), skills load on-demand. You can install dozens of skills without affecting context or performance because Cline only sees the skill name and description until it's actually needed.
<Note>
Skills is an experimental feature. Enable it in Settings → Features → Enable Skills.
</Note>
## Why Skills?
Consider how you'd onboard a new team member: you wouldn't dump every document on them at once. You'd give them a brief overview, then point them to detailed guides when they're working on specific tasks.
Skills work the same way:
- **At startup**: Cline sees only a brief description of each skill
- **When triggered**: Cline loads the full instructions for that specific skill
- **As needed**: Skills can bundle additional files that Cline reads only when referenced
This progressive loading means you can package extensive domain knowledge without burning context tokens on information that isn't relevant to the current task.
## Creating a Skill
Every skill is a directory containing a `SKILL.md` file with YAML frontmatter:
```
my-skill/
├── SKILL.md # Required: main instructions
├── docs/ # Optional: additional documentation
│ └── advanced.md
└── scripts/ # Optional: utility scripts
└── helper.sh
```
The `SKILL.md` file has two parts: metadata and instructions.
```yaml
---
name: my-skill
description: Brief description of what this skill does and when to use it.
---
# My Skill
Detailed instructions for Cline to follow when this skill is activated.
## Steps
1. First, do this
2. Then do that
3. For advanced usage, see [advanced.md](docs/advanced.md)
```
**Required fields:**
- `name`: Must exactly match the directory name
- `description`: Tells Cline when to use this skill (max 1024 characters)
The description is critical because it's how Cline decides whether to activate a skill. Be specific about what the skill does and when it should be used.
## Where Skills Live
Skills can be stored in two locations:
**Global Skills** apply to all your projects:
- **macOS/Linux:** `~/.cline/skills/`
- **Windows:** `C:\Users\USERNAME\.cline\skills\`
**Project Skills** apply only to the current workspace:
- `.cline/skills/` (recommended)
- `.clinerules/skills/`
- `.claude/skills/` (for Claude Code compatibility)
When a global skill and project skill have the same name, the global skill takes precedence. This lets you customize skills for your personal workflow while still using project defaults.
## Managing Skills
Click the scale icon below the chat input to open the rules and workflows panel. When skills are enabled, you'll see a Skills tab where you can:
- View all available skills (global and workspace)
- Toggle individual skills on or off
- Create new skills from a template
- Delete skills you no longer need
Skills are enabled by default when discovered. Toggle them off if you want them available but not active for the current project.
## How Cline Uses Skills
When you send a message, Cline sees a list of available skills with their descriptions. If your request matches a skill's description, Cline activates it using the `use_skill` tool, which loads the full instructions.
For example, if you have a skill for deploying to AWS:
```yaml
---
name: aws-deploy
description: Deploy applications to AWS using CDK. Use when deploying, updating infrastructure, or managing AWS resources.
---
```
Asking "deploy this to AWS" would trigger Cline to activate the skill, load its detailed instructions, and follow them to complete your request.
## Example: Data Analysis Skill
Here's a practical skill for data analysis tasks. Create a directory called `data-analysis/` with this `SKILL.md`:
```yaml
---
name: data-analysis
description: Analyze data files and generate insights. Use when working with CSV, Excel, or JSON data files that need exploration, cleaning, or visualization.
---
```
Then add the instructions in the body of the file:
````markdown
# Data Analysis
When analyzing data files, follow this workflow:
## 1. Understand the Data
- Read a sample of the file to understand its structure
- Identify column types and data quality issues
- Note any missing values or anomalies
## 2. Ask Clarifying Questions
Before diving in, ask the user:
- What specific insights are they looking for?
- Are there any known data quality issues?
- What format do they want for the output?
## 3. Perform Analysis
Use pandas for data manipulation:
```python
import pandas as pd
# Load and explore
df = pd.read_csv("data.csv")
print(df.head())
print(df.describe())
print(df.info())
```
For visualization, prefer matplotlib or seaborn depending on complexity.
## 4. Present Findings
- Start with a summary of key insights
- Support findings with specific numbers
- Include visualizations where they add clarity
- End with recommendations or next steps
````
## Bundling Supporting Files
Skills can include additional files that Cline accesses only when needed:
```
complex-skill/
├── SKILL.md
├── docs/
│ ├── setup.md
│ └── troubleshooting.md
├── templates/
│ └── config.yaml
└── scripts/
└── validate.py
```
Reference these in your instructions:
````markdown
For initial setup, follow [setup.md](docs/setup.md).
Use the config template at `templates/config.yaml` as a starting point.
Run the validation script to check your configuration:
```bash
python scripts/validate.py
```
````
Cline reads these files using `read_file` when the instructions reference them. Scripts can be executed directly, with only the output entering the context (not the script code itself).
## Ideas for Skills
Skills shine when you have tasks that:
- Require detailed, multi-step workflows
- Need domain-specific knowledge or best practices
- Would otherwise require repeating the same instructions across conversations
Some possibilities:
- **Release management**: Version bumping, changelog generation, git tagging, and publishing
- **Code review**: Your team's specific review checklist and quality standards
- **Database migrations**: Safely evolving schemas with rollback procedures
- **API integration**: Connecting to specific third-party services with proper error handling
- **Documentation**: Your preferred structure, style guide, and tooling
- **Debugging workflows**: Systematic approaches to diagnosing specific types of issues
- **Infrastructure**: Terraform/CDK patterns for your cloud setup
The best skills encode institutional knowledge that would otherwise live only in experienced developers' heads.
## Skills vs Rules vs Workflows
| Feature | Purpose | When Active |
|---------|---------|-------------|
| **Rules** | Define how Cline should behave | Always (or contextually) |
| **Workflows** | Step-by-step task automation | Invoked with `/workflow.md` |
| **Skills** | Domain expertise loaded on-demand | Triggered by matching requests |
**Rules** set constraints and preferences (like "always use TypeScript" or "follow this style guide").
**Workflows** are explicit sequences you invoke for specific tasks (like `/release.md` for a release process).
**Skills** are expertise that Cline activates automatically when relevant (like data analysis knowledge when you're working with CSV files).
Use rules for ongoing constraints, workflows for explicit automation, and skills for domain knowledge that should be available but not always active.
## Related Features
- [Cline Rules](/features/cline-rules) for always-active project guidance
- [Workflows](/features/slash-commands/workflows/index) for explicit task automation
- [Hooks](/features/hooks/index) for injecting custom logic at key moments
@@ -12,6 +12,19 @@ sidebarTitle: "/deep-planning"
/>
</Frame>
## Demo Video
Watch Deep Planning in action as Cline investigates a codebase, asks clarifying questions, and generates a comprehensive implementation plan:
<Frame>
<video
muted
controls
playsInline
src="https://storage.googleapis.com/cline_public_images/docs/assets/Cline-Deep-Planning-Demo.mp4"
/>
</Frame>
When you use `/deep-planning`, Cline follows a four-step process that mirrors how senior developers approach complex features: thorough investigation, discussion & clarification of requirements, detailed planning, and structured task creation with progress tracking.
## The Four-Step Process
@@ -120,8 +120,38 @@ Controls a built-in browser to interact with websites or local servers. Useful f
</browser_action>
```
### Leverage MCP Tools
You can use Model Context Protocol (MCP) tools within your workflows to interact with external services like GitHub, Slack, or databases. This allows you to create powerful end-to-end automations.
### Leveraging MCP Tools
MCP tools allow Cline to interact with external services like GitHub, Slack, or databases. You can reference them in your workflows using natural language or explicit XML tags for deterministic control.
#### Natural Language (Heuristic)
Most of the time, the simplest way to use an MCP tool is to describe the action you want Cline to take.
```markdown
1. Fetch the latest issues from the github-repo MCP server.
2. Summarize the critical bugs.
3. Post the summary to the #engineering channel using the slack-notifications MCP.
```
#### Explicit XML Tag (Deterministic)
For critical automation where you need exact control over parameters, use the `use_mcp_tool` tag.
```xml
<use_mcp_tool>
<server_name>github-repo-manager</server_name>
<tool_name>create_issue</tool_name>
<arguments>
{
"owner": "cline",
"repo": "cline",
"title": "Automated Bug Report",
"body": "Found a regression in the latest build."
}
</arguments>
</use_mcp_tool>
```
### Manage Context Window
Be mindful of Cline's context window. If a workflow is too long or processes too much data, it might exceed the token limit.
+55
View File
@@ -0,0 +1,55 @@
---
title: "Web Tools"
sidebarTitle: "Web Tools"
description: "Search the web and fetch content from URLs directly within Cline"
---
Web Tools give Cline the ability to search the internet and fetch content from specific URLs during your tasks. This is useful when you need up-to-date information, documentation lookups, or research that goes beyond your local codebase and the LLM's internal knowledge.
<Warning>
Web Tools require the **Cline provider**. They are not available when using other providers like OpenRouter, Anthropic, AWS Bedrock, etc.
</Warning>
## How Web Tools Work
Cline has two web tools:
- **web_search**: Searches the web and returns a list of relevant webpages based on your query
- **web_fetch**: Fetches and analyzes content from a specific URL
When Cline determines that web information would help complete your task, it will use these tools automatically. The tools call Cline's backend API, which handles the search or fetch operation and returns the results.
## Enabling Web Tools
Web Tools are available when using the Cline provider. To use them:
1. Make sure you're signed in to Cline
2. Ensure you're using the Cline provider
3. Enable the Web Tools toggle in the Feature Settings menu
<Note>
Web tools can be auto-approved using the "Use the browser" setting in [Auto Approve](/features/auto-approve).
</Note>
## Use Cases
### Looking Up Documentation
When working with unfamiliar libraries or APIs:
- Search for official documentation
- Fetch specific API reference pages
- Get examples and usage patterns
### Research Before Implementation
Before implementing a feature:
- Search for best practices and common patterns
- Find recent discussions about approaches
- Look up known issues or limitations
### Checking Latest Information
For time-sensitive information:
- Latest release notes and changelogs
- Recent bug fixes or security updates
- Current recommended versions
+2310 -1422
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -13,7 +13,7 @@
"license": "ISC",
"description": "",
"dependencies": {
"mintlify": "^4.2.23"
"mintlify": "^4.2.249"
},
"overrides": {
"tar-fs": "^3.1.1",
+3 -2
View File
@@ -18,7 +18,8 @@ Cerebras delivers the world's fastest AI inference through their revolutionary w
Cline supports the following Cerebras models:
- `zai-glm-4.6` - Intelligent general purpose model with 1,500 tokens/s
- `zai-glm-4.6` - Fast general-purpose model on Cerebras (up to 1,000 tokens/s). To be deprecated soon.
- `zai-glm-4.7` - Highly capable general-purpose model on Cerebras (up to 1,000 tokens/s), competitive with leading proprietary models on coding tasks.
- `qwen-3-235b-a22b-instruct-2507` - Advanced instruction-following model
- `qwen-3-235b-a22b-thinking-2507` - Reasoning model with step-by-step thinking
- `llama-3.3-70b` - Meta's Llama 3.3 model optimized for speed
@@ -89,7 +90,7 @@ Works with any OpenAI-compatible tool—Cursor, Continue.dev, Cline, or any othe
- **Speed Advantage:** Cerebras excels at making reasoning models practical for real-time use. Perfect for agentic workflows that require multiple LLM calls.
- **Free Tier:** Start with the free model to experience Cerebras speed before upgrading to paid plans.
- **Context Windows:** Models support context windows ranging from 64K to 128K tokens for including substantial code context.
- **Context Windows:** Models support context windows ranging from 64K to 131K tokens for including substantial code context.
- **Rate Limits:** Generous rate limits designed for development workflows. Check your dashboard for current limits.
- **Pricing:** Competitive pricing with significant speed advantages. Visit [Cerebras Cloud](https://cloud.cerebras.ai/) for current rates.
- **Real-Time Applications:** Ideal for applications where AI response time matters—code generation, debugging, and interactive development.
+2 -1
View File
@@ -16,7 +16,7 @@ This document focuses on setting up providers _other than_ the official OpenAI A
The key to using an OpenAI-compatible provider with Cline is to configure these main settings:
1. **Base URL:** This is the API endpoint specific to the provider. It will _not_ be `https://api.openai.com/v1` (that URL is for the official OpenAI API).
2. **API Key:** This is the secret key you obtain from your chosen provider.
2. **API Key:** This is the secret key you obtain from your chosen provider. (or **Use Azure Identity Authentication**)
3. **Model ID:** This is the specific name or identifier for the model you wish to use.
You'll find these settings in the Cline settings panel (click the ⚙️ icon):
@@ -25,6 +25,7 @@ You'll find these settings in the Cline settings panel (click the ⚙️ icon):
- **Base URL:** Enter the base URL provided by your chosen provider. **This is a crucial step.**
- **API Key:** Enter your API key from the provider.
- **Model:** Choose or enter the model ID.
- **Use Azure Identity Authentication:** Check the box to authenticate with your Azure managed identity (Note that this will not trigger the authentication, it will use the existing one (e.g., "az login"))
- **Model Configuration:** This section allows you to customize advanced parameters for the model, such as:
- Max Output Tokens
- Context Window size
+8 -11
View File
@@ -16,20 +16,17 @@ Cline supports accessing models directly through the official OpenAI API.
### Supported Models
Cline is compatible with a variety of OpenAI models, including but not limited to:
Cline is compatible with a variety of OpenAI models, including common choices from OpenAI's featured/frontier lists:
- 'o3'
- `o3-mini` (medium reasoning effort)
- 'o4-mini'
- `o3-mini-high` (high reasoning effort)
- `o3-mini-low` (low reasoning effort)
- `o1`
- `o1-preview`
- `o1-mini`
- `gpt-5.2`
- `gpt-5.2-codex`
- `gpt-5-mini`
- `gpt-5-nano`
- `gpt-4.1`
- `gpt-4o`
- `gpt-4o-mini`
- 'gpt-4.1'
- 'gpt-4.1-mini'
- `o3`
- `o4-mini`
For the most current list of available models and their capabilities, please refer to the official [OpenAI Models documentation](https://platform.openai.com/docs/models).
@@ -6,12 +6,17 @@ description: "Complete guide to resolving terminal integration issues in Cline"
This guide helps you resolve terminal integration issues in Cline. Terminal integration is crucial for Cline to execute commands and read their output, enabling it to understand errors, test results, and command responses.
<Tip>
If you're experiencing terminal issues, try switching to a simpler shell like `bash` in the Cline settings, under "Terminal Settings"
## Try This First: Background Execution Mode
This resolves most terminal integration problems.
The simplest fix for most terminal issues is switching to **Background Execution Mode**:
</Tip>
1. Click **Settings** (top right of Cline chat)
2. Go to **Terminal Settings**
3. Set **Terminal Execution Mode** → **Background Exec**
This runs commands in a background process instead of VSCode's terminal, bypassing most integration issues. The guide below is for users who specifically need VSCode's integrated terminal.
---
## Quick Diagnosis Flowchart
+15 -1
View File
@@ -4,7 +4,21 @@ sidebarTitle: "Terminal Quick Fixes"
description: "Quick solutions for common terminal issues"
---
**Here is a list of common fixes, starting with the most applicable:**
## Try This First: Background Execution Mode
The simplest fix for most terminal issues is switching to **Background Execution Mode**:
1. Click **Settings** (top right of Cline chat)
2. Go to **Terminal Settings**
3. Set **Terminal Execution Mode** → **Background Exec**
This runs commands in a background process instead of VSCode's terminal, bypassing most integration issues.
---
## Other Fixes
If you need VSCode's integrated terminal, try these:
- **Switch to bash** (solves most instances)
+1 -1
View File
@@ -1,4 +1,4 @@
streamlit>=1.28.0
streamlit==1.43.2
plotly>=5.17.0
pandas>=2.0.0
numpy>=1.24.0
+285 -159
View File
File diff suppressed because it is too large Load Diff
+10 -5
View File
@@ -2,7 +2,7 @@
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"version": "3.45.0",
"version": "3.49.1",
"icon": "assets/icons/icon.png",
"engines": {
"vscode": "^1.84.0"
@@ -346,11 +346,10 @@
"compile-cli": "scripts/build-cli.sh",
"compile-cli-all-platforms": "scripts/build-cli-all-platforms.sh",
"compile-cli-man-page": "pandoc cli/man/cline.1.md -s -t man -o cli/man/cline.1",
"build:npm": "scripts/build-npm-package.sh",
"test:install": "bash scripts/test-install.sh",
"dev:cli:watch": "node scripts/dev-cli-watch.mjs",
"postcompile-standalone": "node scripts/package-standalone.mjs",
"postcompile-standalone-npm": "node scripts/package-standalone.mjs --target=npm",
"postcompile-standalone-npm": "node scripts/package-npm.mjs",
"dev": "npm run protos && npm run watch",
"watch": "npm-run-all -p watch:*",
"watch:esbuild": "node esbuild.mjs --watch",
@@ -367,7 +366,7 @@
"clean:all": "npm run clean:build && npm run clean:deps",
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"check-types": "npm run protos && npx tsc --noEmit && cd webview-ui && npx tsc -b --noEmit",
"check-types": "npm run protos && npx tsc --noEmit && cd webview-ui && npx tsc --noEmit",
"lint": "biome lint --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error && npm run lint:proto",
"lint:proto": "bash ./scripts/proto-lint.sh",
"format": "biome format --changed --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error",
@@ -417,10 +416,12 @@
"@types/clone-deep": "^4.0.4",
"@types/diff": "^5.2.1",
"@types/get-folder-size": "^3.0.4",
"@types/js-yaml": "^4.0.9",
"@types/mocha": "^10.0.7",
"@types/node": "20.x",
"@types/pdf-parse": "^1.1.4",
"@types/proxyquire": "^1.3.31",
"@types/shell-quote": "^1.7.5",
"@types/should": "^11.2.0",
"@types/sinon": "^17.0.4",
"@types/turndown": "^5.0.5",
@@ -456,6 +457,7 @@
"@anthropic-ai/vertex-sdk": "^0.6.4",
"@aws-sdk/client-bedrock-runtime": "^3.922.0",
"@aws-sdk/credential-providers": "^3.922.0",
"@azure/identity": "^4.13.0",
"@bufbuild/protobuf": "^2.2.5",
"@cerebras/cerebras_cloud_sdk": "^1.35.0",
"@google-cloud/vertexai": "^1.9.3",
@@ -463,7 +465,7 @@
"@grpc/grpc-js": "^1.9.15",
"@grpc/reflection": "^1.0.4",
"@mistralai/mistralai": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.11.1",
"@modelcontextprotocol/sdk": "^1.25.1",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/core": "^2.1.0",
"@opentelemetry/exporter-logs-otlp-grpc": "^0.56.0",
@@ -486,6 +488,7 @@
"@playwright/test": "^1.55.1",
"@sap-ai-sdk/ai-api": "^2.1.0",
"@sap-ai-sdk/orchestration": "^2.1.0",
"@sap-cloud-sdk/connectivity": "^4.2.0",
"@streamparser/json": "^0.0.22",
"@tailwindcss/vite": "^4.1.14",
"@types/uuid": "^10.0.0",
@@ -511,6 +514,7 @@
"image-size": "^2.0.2",
"isbinaryfile": "^5.0.2",
"jschardet": "^3.1.4",
"json5": "^2.2.3",
"mammoth": "^1.11.0",
"nanoid": "^5.1.6",
"nice-grpc": "^2.1.12",
@@ -529,6 +533,7 @@
"puppeteer-core": "^23.4.0",
"reconnecting-eventsource": "^1.6.4",
"serialize-error": "^11.0.3",
"shell-quote": "^1.8.3",
"simple-git": "^3.27.0",
"strip-ansi": "^7.1.2",
"tailwindcss": "^4.1.14",
+54
View File
@@ -81,6 +81,18 @@ service FileService {
// Deletes an existing hook file
rpc deleteHook(DeleteHookRequest) returns (DeleteHookResponse);
// Refreshes all skill toggles (discovers skills and their enabled state)
rpc refreshSkills(EmptyRequest) returns (RefreshedSkills);
// Toggles a skill on or off
rpc toggleSkill(ToggleSkillRequest) returns (SkillsToggles);
// Creates a new skill from template
rpc createSkillFile(CreateSkillRequest) returns (SkillsToggles);
// Deletes an existing skill directory
rpc deleteSkillFile(DeleteSkillRequest) returns (SkillsToggles);
}
// Response for refreshRules operation
@@ -278,3 +290,45 @@ message DeleteHookRequest {
message DeleteHookResponse {
HooksToggles hooks_toggles = 1;
}
// Skill information structure
message SkillInfo {
string name = 1; // Name of the skill (matches directory name)
string description = 2; // Description from SKILL.md frontmatter
string path = 3; // Full path to SKILL.md file
bool enabled = 4; // Whether the skill is enabled
}
// Response for refreshSkills operation
message RefreshedSkills {
repeated SkillInfo global_skills = 1;
repeated SkillInfo local_skills = 2;
}
// Maps from skill path to enabled/disabled status
message SkillsToggles {
map<string, bool> global_skills_toggles = 1;
map<string, bool> local_skills_toggles = 2;
}
// Request to toggle a skill
message ToggleSkillRequest {
Metadata metadata = 1;
string skill_path = 2; // Path to the skill directory
bool is_global = 3; // Whether this is a global or workspace skill
bool enabled = 4; // Whether to enable or disable the skill
}
// Request to create a skill
message CreateSkillRequest {
Metadata metadata = 1;
string skill_name = 2; // Name of the skill to create
bool is_global = 3; // Whether to create in global or workspace skills directory
}
// Request to delete a skill
message DeleteSkillRequest {
Metadata metadata = 1;
string skill_path = 2; // Path to the skill directory
bool is_global = 3; // Whether this is a global or workspace skill
}
+22 -12
View File
@@ -49,6 +49,8 @@ service ModelsService {
rpc refreshOcaModels(StringRequest) returns (OcaCompatibleModelInfo);
// Fetches available models from AIhubmix
rpc getAihubmixModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
// Refreshes and returns Vercel AI Gateway models
rpc refreshVercelAiGatewayModelsRpc(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
}
// List of VS Code LM models
@@ -229,6 +231,7 @@ message ModelsApiOptions {
optional string minimax_api_line = 41;
optional string aihubmix_base_url = 42;
optional string aihubmix_app_code = 43;
optional bool azure_identity = 44;
// Plan mode configurations
optional ApiProvider plan_mode_api_provider = 100;
@@ -380,6 +383,10 @@ message OcaModelInfo {
string model_name = 17;
// The API format used by this model
optional ApiFormat api_format = 18;
// Supports reasoning
optional bool supports_reasoning = 19;
// reasoning effort options
repeated string reasoning_effort_options = 20;
}
// Aggregated OCA model catalog keyed by model identifier
@@ -567,6 +574,7 @@ message ModelsApiConfiguration {
optional string aihubmix_base_url = 83;
optional string aihubmix_app_code = 84;
optional string nous_research_api_key = 85;
optional bool azure_identity = 86;
// Plan mode configurations
optional ApiProvider plan_mode_api_provider = 100;
@@ -602,12 +610,13 @@ message ModelsApiConfiguration {
optional OpenRouterModelInfo plan_mode_vercel_ai_gateway_model_info = 130;
optional string plan_mode_oca_model_id = 131;
optional OcaModelInfo plan_mode_oca_model_info = 132;
optional string plan_mode_hicap_model_id = 133;
optional OpenRouterModelInfo plan_mode_hicap_model_info = 134;
optional string plan_mode_aihubmix_model_id = 135;
optional OpenAiCompatibleModelInfo plan_mode_aihubmix_model_info = 136;
optional string plan_mode_nous_research_model_id = 137;
optional string gemini_plan_mode_thinking_level = 138;
optional string plan_mode_oca_reasoning_effort = 133;
optional string plan_mode_hicap_model_id = 134;
optional OpenRouterModelInfo plan_mode_hicap_model_info = 135;
optional string plan_mode_aihubmix_model_id = 136;
optional OpenAiCompatibleModelInfo plan_mode_aihubmix_model_info = 137;
optional string plan_mode_nous_research_model_id = 138;
optional string gemini_plan_mode_thinking_level = 139;
// Act mode configurations
optional ApiProvider act_mode_api_provider = 200;
@@ -643,10 +652,11 @@ message ModelsApiConfiguration {
optional OpenRouterModelInfo act_mode_vercel_ai_gateway_model_info = 230;
optional string act_mode_oca_model_id = 231;
optional OcaModelInfo act_mode_oca_model_info = 232;
optional string act_mode_hicap_model_id = 233;
optional OpenRouterModelInfo act_mode_hicap_model_info = 234;
optional string act_mode_aihubmix_model_id = 235;
optional OpenAiCompatibleModelInfo act_mode_aihubmix_model_info = 236;
optional string act_mode_nous_research_model_id = 237;
optional string gemini_act_mode_thinking_level = 238;
optional string act_mode_oca_reasoning_effort = 233;
optional string act_mode_hicap_model_id = 234;
optional OpenRouterModelInfo act_mode_hicap_model_info = 235;
optional string act_mode_aihubmix_model_id = 236;
optional OpenAiCompatibleModelInfo act_mode_aihubmix_model_info = 237;
optional string act_mode_nous_research_model_id = 238;
optional string gemini_act_mode_thinking_level = 239;
}
+7
View File
@@ -229,6 +229,9 @@ message Settings {
optional OpenAiCompatibleModelInfo act_mode_aihubmix_model_info = 133;
optional bool cline_web_tools_enabled = 134;
optional bool hooks_enabled = 135;
optional bool azure_identity = 136;
optional bool skills_enabled = 137;
optional bool opt_out_of_remote_config = 138;
}
message DictationSettings {
@@ -369,6 +372,10 @@ message UpdateSettingsRequest {
optional OnboardingModelGroup onboarding_models = 33;
optional bool cline_web_tools_enabled = 34;
optional bool enable_parallel_tool_calling = 35;
optional bool background_edit_enabled = 36;
optional string oca_reasoning_effort = 37;
optional bool skills_enabled = 38;
optional bool opt_out_of_remote_config = 39;
}
message UpdateTerminalConnectionTimeoutRequest {
+9 -5
View File
@@ -67,6 +67,9 @@ enum ClineSay {
TASK_PROGRESS = 27;
ERROR_RETRY = 28;
GENERATE_EXPLANATION = 29;
HOOK_STATUS = 30;
HOOK_OUTPUT_STREAM = 31;
COMMAND_PERMISSION_DENIED = 32;
}
// Enum for ClineSayTool tool types
@@ -220,6 +223,10 @@ message ClineMessage {
ClineModelInfo model_info = 23;
}
message ShowWebviewEvent {
bool preserve_editor_focus = 1; // When true, webview should not steal focus from editor
}
// UiService provides methods for managing UI interactions
service UiService {
// Scrolls to a specific settings section in the settings view
@@ -258,11 +265,8 @@ service UiService {
// Subscribe to relinquish control events
rpc subscribeToRelinquishControl(EmptyRequest) returns (stream Empty);
// Subscribe to focus chat input events
rpc subscribeToFocusChatInput(EmptyRequest) returns (stream Empty);
// Subscribe to webview visibility change events
rpc subscribeToDidBecomeVisible(EmptyRequest) returns (stream Empty);
// Subscribe to show webview events
rpc subscribeToShowWebview(EmptyRequest) returns (stream ShowWebviewEvent);
// Returns the HTML for the webview index page. This is only used by external clients, not by the vscode webview.
rpc getWebviewHtml(EmptyRequest) returns (String);
+2
View File
@@ -55,8 +55,10 @@ enum Setting {
}
message GetTelemetrySettingsResponse {
Setting is_enabled = 1;
optional string error_level = 2;
}
message TelemetrySettingsEvent {
Setting is_enabled = 1;
optional string error_level = 2;
}
-154
View File
@@ -1,154 +0,0 @@
#!/usr/bin/env bash
# Script to build the Cline NPM package with telemetry keys injected
# This script ensures all environment variables are properly set and builds are successful
set -e # Exit on error
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Required environment variables
REQUIRED_VARS=(
"TELEMETRY_SERVICE_API_KEY"
"ERROR_SERVICE_API_KEY"
)
# Optional but recommended environment variables
OPTIONAL_VARS=(
"CLINE_ENVIRONMENT"
"POSTHOG_TELEMETRY_ENABLED"
)
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Cline NPM Package Build Script${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
# Step 1: Verify required environment variables are set
echo -e "${BLUE}Step 1: Verifying environment variables...${NC}"
MISSING_VARS=()
for VAR in "${REQUIRED_VARS[@]}"; do
if [ -z "${!VAR}" ]; then
MISSING_VARS+=("$VAR")
echo -e "${RED}$VAR is not set${NC}"
else
# Show first 10 chars for verification (don't expose full key)
VAR_VALUE="${!VAR}"
echo -e "${GREEN}$VAR is set (${VAR_VALUE:0:10}...)${NC}"
fi
done
# Check optional variables
for VAR in "${OPTIONAL_VARS[@]}"; do
if [ -z "${!VAR}" ]; then
echo -e "${YELLOW}$VAR is not set (optional)${NC}"
else
echo -e "${GREEN}$VAR is set: ${!VAR}${NC}"
fi
done
if [ ${#MISSING_VARS[@]} -gt 0 ]; then
echo -e "\n${RED}Error: Missing required environment variables:${NC}"
printf '%s\n' "${MISSING_VARS[@]}"
echo -e "\n${YELLOW}Please set these variables before running the build:${NC}"
echo -e "export TELEMETRY_SERVICE_API_KEY=\"your_posthog_api_key\""
echo -e "export ERROR_SERVICE_API_KEY=\"your_error_tracking_api_key\""
exit 1
fi
# Step 2: Verify Node.js can see the environment variables
echo -e "\n${BLUE}Step 2: Verifying Node.js can access environment variables...${NC}"
if node -e "
const telemetryKey = process.env.TELEMETRY_SERVICE_API_KEY;
const errorKey = process.env.ERROR_SERVICE_API_KEY;
if (!telemetryKey || !errorKey) {
console.error('Node.js cannot see environment variables!');
process.exit(1);
}
console.log('✓ TELEMETRY_SERVICE_API_KEY visible to Node.js');
console.log('✓ ERROR_SERVICE_API_KEY visible to Node.js');
"; then
echo -e "${GREEN}✓ Node.js can access environment variables${NC}"
else
echo -e "${RED}✗ Node.js cannot access environment variables${NC}"
echo -e "${YELLOW}Make sure to use 'export' when setting variables:${NC}"
echo -e "export TELEMETRY_SERVICE_API_KEY=\"...\""
exit 1
fi
# Step 3: Clean previous builds
echo -e "\n${BLUE}Step 3: Cleaning previous builds...${NC}"
rm -rf dist-standalone
echo -e "${GREEN}✓ Cleaned dist-standalone directory${NC}"
# Step 4: Build Go CLI binaries for all platforms
echo -e "\n${BLUE}Step 4: Building Go CLI binaries for all platforms...${NC}"
if npm run compile-cli-all-platforms; then
echo -e "${GREEN}✓ Go CLI binaries built successfully${NC}"
# Verify binaries were created
if ls cli/bin/cline-* 1> /dev/null 2>&1; then
echo -e "${GREEN}✓ CLI binaries verified:${NC}"
ls -lh cli/bin/cline-* | awk '{print " " $9 " (" $5 ")"}'
else
echo -e "${RED}✗ No CLI binaries found in cli/bin/${NC}"
exit 1
fi
else
echo -e "${RED}✗ Failed to build Go CLI binaries${NC}"
exit 1
fi
# Step 5: Build the standalone package with esbuild
echo -e "\n${BLUE}Step 5: Building standalone package with esbuild...${NC}"
if npm run compile-standalone-npm; then
echo -e "${GREEN}✓ Standalone package built successfully${NC}"
else
echo -e "${RED}✗ Failed to build standalone package${NC}"
exit 1
fi
# Step 6: Verify telemetry keys were injected
echo -e "\n${BLUE}Step 6: Verifying telemetry keys were injected...${NC}"
# Check if the compiled file still has process.env references (bad)
if grep -q "process.env.TELEMETRY_SERVICE_API_KEY" dist-standalone/cline-core.js; then
echo -e "${RED}✗ Keys were NOT injected! Found 'process.env.TELEMETRY_SERVICE_API_KEY' in compiled code${NC}"
echo -e "${YELLOW}This means the environment variables were not replaced during build${NC}"
exit 1
fi
# Check if actual keys are present (good)
if grep -q "data.cline.bot" dist-standalone/cline-core.js; then
# Extract a snippet of the PostHog config
POSTHOG_CONFIG=$(grep -A 3 "data.cline.bot" dist-standalone/cline-core.js | head -5)
if echo "$POSTHOG_CONFIG" | grep -q "apiKey.*phc_"; then
echo -e "${GREEN}✓ Telemetry keys successfully injected into compiled code${NC}"
else
echo -e "${YELLOW}⚠ PostHog config found but apiKey format unclear${NC}"
echo -e "${YELLOW}Config snippet:${NC}"
echo "$POSTHOG_CONFIG"
fi
else
echo -e "${YELLOW}⚠ Could not verify PostHog config in compiled code${NC}"
fi
# Step 7: Display build summary
echo -e "\n${BLUE}========================================${NC}"
echo -e "${GREEN}Build completed successfully!${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "${GREEN}Package location:${NC} dist-standalone/"
echo -e "${GREEN}Package version:${NC} $(node -p "require('./dist-standalone/package.json').version" 2>/dev/null || echo "unknown")"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo -e "1. Test locally: ${YELLOW}cd dist-standalone && npm link${NC}"
echo -e "2. Verify: ${YELLOW}cline version${NC}"
echo -e "3. Publish: ${YELLOW}cd dist-standalone && npm publish${NC}"
echo ""
echo -e "${YELLOW}Note: Check PostHog dashboard after running cline commands to verify telemetry${NC}"
+7
View File
@@ -43,6 +43,13 @@ const PLATFORMS = [
binaryPath: "rg",
isZip: false,
},
{
name: "linux-arm64",
archiveName: `ripgrep-${RIPGREP_VERSION}-aarch64-unknown-linux-gnu.tar.gz`,
url: `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}/ripgrep-${RIPGREP_VERSION}-aarch64-unknown-linux-gnu.tar.gz`,
binaryPath: "rg",
isZip: false,
},
{
name: "win-x64",
archiveName: `ripgrep-${RIPGREP_VERSION}-x86_64-pc-windows-msvc.zip`,
+10 -1
View File
@@ -49,9 +49,18 @@ fi
# Create installation directory
mkdir -p "$INSTALL_DIR/bin"
# Copy standalone package first (includes node_modules, cline-core.js, etc.)
# Copy standalone package first (cline-core.js, wasm files, etc.)
rsync -a --exclude='bin' "$PROJECT_ROOT/dist-standalone/" "$INSTALL_DIR/"
# Install runtime dependencies (grpc-health-check, better-sqlite3, etc.)
# These are external dependencies not bundled into cline-core.js
echo -e "${CYAN}${NC} ${DIM}Installing runtime dependencies...${NC}"
cd "$PROJECT_ROOT/standalone/runtime-files"
npm install --silent 2>/dev/null || npm install
cp -r node_modules "$INSTALL_DIR/"
cp -r vscode "$INSTALL_DIR/node_modules/"
cd "$PROJECT_ROOT"
# Detect platform for native modules
os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch=$(uname -m)
+486
View File
@@ -0,0 +1,486 @@
#!/usr/bin/env node
/**
* NPM Package Builder for Cline CLI
*
* This script builds the Cline CLI NPM package (dist-standalone/).
* It is completely independent from package-standalone.mjs (JetBrains build).
*
* Usage: node scripts/package-npm.mjs
*
* Prerequisites:
* - npm run protos && npm run protos-go
* - npm run compile-cli
* - npm run compile-cli-all-platforms
* - npm run download-ripgrep
*/
import { execSync } from "child_process"
import fs from "fs"
import { cp } from "fs/promises"
import path from "path"
const BUILD_DIR = "dist-standalone"
const RUNTIME_DEPS_DIR = "standalone/runtime-files"
const RIPGREP_BINARIES_DIR = `${BUILD_DIR}/ripgrep-binaries`
const CLI_BINARIES_DIR = "cli/bin"
const IS_VERBOSE = process.argv.includes("-v") || process.argv.includes("--verbose")
async function main() {
console.log("🚀 Building Cline NPM Package\n")
await installNodeDependencies()
await copyCliBinaries()
await copyRipgrepBinaries()
await copyProtoDescriptors()
await createNpmPackageFiles()
await createFakeNodeModules()
await createNpmIgnoreFile()
await createPostinstallScript()
console.log("\n✅ Build complete!")
console.log(`\n📦 NPM package ready in ${BUILD_DIR}/`)
console.log(`To publish: cd ${BUILD_DIR} && npm publish`)
}
/**
* Install node dependencies in the build directory
*/
async function installNodeDependencies() {
// Clean modules from any previous builds
await rmrf(path.join(BUILD_DIR, "node_modules"))
await cpr(RUNTIME_DEPS_DIR, BUILD_DIR)
console.log("Running npm install in distribution directory...")
execSync("npm install", { stdio: "inherit", cwd: BUILD_DIR })
// Move the vscode directory into node_modules.
// It can't be installed using npm because it will create a symlink which cannot be unzipped correctly on windows.
fs.renameSync(`${BUILD_DIR}/vscode`, `${BUILD_DIR}/node_modules/vscode`)
}
/**
* Copy CLI binaries (cline and cline-host) for all platforms
* The Go binaries are cross-compiled for darwin/linux arm64/amd64
*/
async function copyCliBinaries() {
console.log("Copying CLI binaries for all platforms...")
const platforms = [
{ os: "darwin", arch: "arm64" },
{ os: "darwin", arch: "amd64" },
{ os: "linux", arch: "amd64" },
{ os: "linux", arch: "arm64" },
]
const binDir = path.join(BUILD_DIR, "bin")
// Create bin directory
fs.mkdirSync(binDir, { recursive: true })
// Copy all platform-specific binaries
for (const { os, arch } of platforms) {
const platformSuffix = `${os}-${arch}`
// Copy cline binary
const clineSource = path.join(CLI_BINARIES_DIR, `cline-${platformSuffix}`)
const clineDest = path.join(binDir, `cline-${platformSuffix}`)
if (!fs.existsSync(clineSource)) {
console.error(`Error: CLI binary not found at ${clineSource}`)
console.error(`Please run: npm run compile-cli-all-platforms`)
process.exit(1)
}
await cpr(clineSource, clineDest)
fs.chmodSync(clineDest, 0o755)
console.log(`✓ cline-${platformSuffix} copied`)
// Copy cline-host binary
const hostSource = path.join(CLI_BINARIES_DIR, `cline-host-${platformSuffix}`)
const hostDest = path.join(binDir, `cline-host-${platformSuffix}`)
if (!fs.existsSync(hostSource)) {
console.error(`Error: CLI binary not found at ${hostSource}`)
console.error(`Please run: npm run compile-cli-all-platforms`)
process.exit(1)
}
await cpr(hostSource, hostDest)
fs.chmodSync(hostDest, 0o755)
console.log(`✓ cline-host-${platformSuffix} copied`)
}
console.log(`✓ All CLI binaries copied to ${binDir}`)
}
/**
* Copy ripgrep binaries for ALL platforms
* Ripgrep is needed by cline-core for file searching
* The postinstall script will select the correct binary for the user's platform
*/
async function copyRipgrepBinaries() {
console.log("Copying ripgrep binaries for all platforms...")
const platforms = [
{ dir: "darwin-arm64", binary: "rg" },
{ dir: "darwin-x64", binary: "rg" },
{ dir: "linux-x64", binary: "rg" },
{ dir: "linux-arm64", binary: "rg" },
// { dir: "win-x64", binary: "rg.exe" }, // Windows not supported yet
]
const ripgrepDir = path.join(BUILD_DIR, "ripgrep")
// Create ripgrep directory
fs.mkdirSync(ripgrepDir, { recursive: true })
// Check if ripgrep binaries exist, download if missing
const firstPlatform = platforms[0]
const firstBinaryPath = path.join(RIPGREP_BINARIES_DIR, firstPlatform.dir, firstPlatform.binary)
if (!fs.existsSync(firstBinaryPath)) {
console.log(`Ripgrep binaries not found, downloading...`)
try {
execSync("npm run download-ripgrep", { stdio: "inherit" })
} catch (error) {
console.error(`Error downloading ripgrep: ${error.message}`)
console.error(`Please run: npm run download-ripgrep`)
process.exit(1)
}
}
// Copy all platform-specific binaries
for (const { dir, binary } of platforms) {
const source = path.join(RIPGREP_BINARIES_DIR, dir, binary)
const dest = path.join(ripgrepDir, `rg-${dir}`)
if (!fs.existsSync(source)) {
console.error(`Error: Ripgrep binary not found at ${source}`)
console.error(`Please run: npm run download-ripgrep`)
process.exit(1)
}
await cpr(source, dest)
fs.chmodSync(dest, 0o755)
console.log(`✓ rg-${dir} copied`)
}
console.log(`✓ All ripgrep binaries copied to ${ripgrepDir}`)
}
/**
* Verify proto descriptors exist in the build directory
* The proto/descriptor_set.pb file is generated by build-proto.mjs to dist-standalone/proto/
* We do NOT copy from proto/ source because that would overwrite the freshly generated descriptor
*/
async function copyProtoDescriptors() {
console.log("Verifying proto descriptors...")
const protoDest = path.join(BUILD_DIR, "proto")
const descriptorPath = path.join(protoDest, "descriptor_set.pb")
// Check if descriptor_set.pb exists in the build directory
// It should have been generated by `npm run protos` which runs build-proto.mjs
if (!fs.existsSync(descriptorPath)) {
console.error(`Error: proto/descriptor_set.pb not found at ${descriptorPath}`)
console.error(`Please run: npm run protos`)
console.error(`Note: build-proto.mjs generates the descriptor to dist-standalone/proto/`)
process.exit(1)
}
// Verify the descriptor is recent (not stale)
const stats = fs.statSync(descriptorPath)
const ageMinutes = (Date.now() - stats.mtimeMs) / 1000 / 60
if (ageMinutes > 60) {
console.warn(`Warning: descriptor_set.pb is ${Math.round(ageMinutes)} minutes old`)
console.warn(`Consider running: npm run protos`)
}
console.log(`✓ Proto descriptors verified at ${protoDest}`)
}
/**
* Copy NPM package files (package.json, README.md, and man page) from cli/ directory
*/
async function createNpmPackageFiles() {
console.log("Copying NPM package files...")
// Copy package.json from cli/ directory
const packageJsonSource = path.join("cli", "package.json")
const packageJsonDest = path.join(BUILD_DIR, "package.json")
if (!fs.existsSync(packageJsonSource)) {
console.error(`Error: NPM package.json not found at ${packageJsonSource}`)
process.exit(1)
}
await cpr(packageJsonSource, packageJsonDest)
console.log(`✓ package.json copied from ${packageJsonSource}`)
// Copy README.md from cli/ directory
const readmeSource = path.join("cli", "README.md")
const readmeDest = path.join(BUILD_DIR, "README.md")
if (!fs.existsSync(readmeSource)) {
console.error(`Error: NPM README.md not found at ${readmeSource}`)
process.exit(1)
}
await cpr(readmeSource, readmeDest)
console.log(`✓ README.md copied from ${readmeSource}`)
// Copy man page from cli/man/ directory
const manPageSource = path.join("cli", "man", "cline.1")
const manDir = path.join(BUILD_DIR, "man")
const manPageDest = path.join(manDir, "cline.1")
if (!fs.existsSync(manPageSource)) {
console.error(`Error: Man page not found at ${manPageSource}`)
process.exit(1)
}
// Create man directory if it doesn't exist
fs.mkdirSync(manDir, { recursive: true })
await cpr(manPageSource, manPageDest)
console.log(`✓ Man page copied from ${manPageSource}`)
}
/**
* Create fake_node_modules directory with vscode stub
* This directory will be added to NODE_PATH so Node.js can find the vscode module
* without npm interfering with the real node_modules directory
*/
async function createFakeNodeModules() {
console.log("Creating fake_node_modules with vscode stub...")
const vscodeSource = path.join(BUILD_DIR, "node_modules", "vscode")
const fakeNodeModulesDir = path.join(BUILD_DIR, "fake_node_modules")
const vscodeDest = path.join(fakeNodeModulesDir, "vscode")
if (!fs.existsSync(vscodeSource)) {
console.error(`Error: vscode stub module not found at ${vscodeSource}`)
process.exit(1)
}
// Create fake_node_modules directory
fs.mkdirSync(fakeNodeModulesDir, { recursive: true })
// Copy vscode stub into fake_node_modules
await cpr(vscodeSource, vscodeDest)
console.log(`✓ fake_node_modules/vscode created at ${vscodeDest}`)
}
/**
* Create .npmignore file to ensure necessary files are included
*/
async function createNpmIgnoreFile() {
console.log("Creating .npmignore file...")
// Create .npmignore that excludes build artifacts
// Note: proto/ directory is NOT excluded because proto/descriptor_set.pb is needed at runtime
const npmignoreContent = `# Exclude build artifacts and unnecessary files
binaries/
ripgrep-binaries/
standalone.zip
cline-core.js.map
package-lock.json
tree-sitter*.wasm
node_modules/vscode
`
const npmignorePath = path.join(BUILD_DIR, ".npmignore")
fs.writeFileSync(npmignorePath, npmignoreContent)
console.log(`✓ .npmignore created`)
}
/**
* Create postinstall script for NPM package
* This script selects the correct platform-specific binary and creates symlinks
*/
async function createPostinstallScript() {
console.log("Creating postinstall script...")
const postinstallScript = `#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const os = require('os');
// Detect current platform and architecture
function getPlatformInfo() {
const platform = os.platform();
const arch = os.arch();
// Map Node.js arch names to Go arch names (for CLI binaries)
let goArch = arch;
if (arch === 'x64') {
goArch = 'amd64';
}
// Map for ripgrep binaries (uses different naming)
let rgArch = arch;
if (arch === 'arm64') {
rgArch = 'arm64';
} else if (arch === 'x64') {
rgArch = 'x64';
}
return { platform, arch, goArch, rgArch };
}
// Setup platform-specific binaries
function setupBinaries() {
const { platform, goArch, rgArch } = getPlatformInfo();
const cliPlatformSuffix = \`\${platform}-\${goArch}\`;
const rgPlatformSuffix = \`\${platform}-\${rgArch}\`;
console.log(\`Setting up Cline CLI for \${cliPlatformSuffix}...\`);
// Setup CLI binaries
const binDir = path.join(__dirname, 'bin');
// Check if platform-specific binaries exist
const clineSource = path.join(binDir, \`cline-\${cliPlatformSuffix}\`);
const clineHostSource = path.join(binDir, \`cline-host-\${cliPlatformSuffix}\`);
if (!fs.existsSync(clineSource)) {
console.error(\`Error: Binary not found for platform \${cliPlatformSuffix}\`);
console.error(\`Expected: \${clineSource}\`);
console.error(\`Supported platforms: darwin-arm64, darwin-amd64, linux-amd64, linux-arm64\`);
process.exit(1);
}
if (!fs.existsSync(clineHostSource)) {
console.error(\`Error: Binary not found for platform \${cliPlatformSuffix}\`);
console.error(\`Expected: \${clineHostSource}\`);
process.exit(1);
}
// Create symlinks or copies to the generic names
const clineTarget = path.join(binDir, 'cline');
const clineHostTarget = path.join(binDir, 'cline-host');
// Remove existing files if they exist
[clineTarget, clineHostTarget].forEach(target => {
if (fs.existsSync(target)) {
try {
fs.unlinkSync(target);
} catch (e) {
console.warn(\`Warning: Could not remove existing file \${target}: \${e.message}\`);
}
}
});
// On Unix, create symlinks; on Windows, copy files
if (platform === 'win32') {
// Windows: copy files
fs.copyFileSync(clineSource, clineTarget);
fs.copyFileSync(clineHostSource, clineHostTarget);
console.log('✓ Copied platform-specific CLI binaries');
} else {
// Unix: create symlinks
fs.symlinkSync(path.basename(clineSource), clineTarget);
fs.symlinkSync(path.basename(clineHostSource), clineHostTarget);
console.log('✓ Created symlinks to platform-specific CLI binaries');
// Make binaries executable
try {
fs.chmodSync(clineSource, 0o755);
fs.chmodSync(clineHostSource, 0o755);
fs.chmodSync(clineTarget, 0o755);
fs.chmodSync(clineHostTarget, 0o755);
} catch (error) {
console.warn(\`Warning: Could not set executable permissions: \${error.message}\`);
}
}
// Setup ripgrep binary
console.log(\`Setting up ripgrep for \${rgPlatformSuffix}...\`);
const ripgrepDir = path.join(__dirname, 'ripgrep');
const rgSource = path.join(ripgrepDir, \`rg-\${rgPlatformSuffix}\`);
const rgTarget = path.join(__dirname, 'rg');
if (!fs.existsSync(rgSource)) {
console.error(\`Error: ripgrep binary not found for platform \${rgPlatformSuffix}\`);
console.error(\`Expected: \${rgSource}\`);
console.error(\`Supported platforms: darwin-arm64, darwin-x64, linux-x64, linux-arm64\`);
process.exit(1);
}
// Remove existing rg if it exists
if (fs.existsSync(rgTarget)) {
try {
fs.unlinkSync(rgTarget);
} catch (e) {
console.warn(\`Warning: Could not remove existing ripgrep: \${e.message}\`);
}
}
// Copy ripgrep binary to root (where cline-core expects it)
fs.copyFileSync(rgSource, rgTarget);
// Make ripgrep executable (Unix only)
if (platform !== 'win32') {
try {
fs.chmodSync(rgTarget, 0o755);
} catch (error) {
console.warn(\`Warning: Could not set ripgrep executable permissions: \${error.message}\`);
}
}
console.log('✓ Copied platform-specific ripgrep binary');
console.log('✓ Cline CLI installation complete');
console.log('');
console.log('Usage:');
console.log(' cline - Start Cline CLI');
console.log(' cline-host - Start Cline host service');
console.log('');
console.log('Documentation: https://docs.cline.bot');
}
try {
setupBinaries();
} catch (error) {
console.error(\`Installation failed: \${error.message}\`);
console.error('Please report this issue at: https://github.com/cline/cline/issues');
process.exit(1);
}
`
const postinstallPath = path.join(BUILD_DIR, "postinstall.js")
fs.writeFileSync(postinstallPath, postinstallScript)
fs.chmodSync(postinstallPath, 0o755)
console.log(`✓ postinstall.js created`)
}
/* cp -r */
async function cpr(source, dest) {
log_verbose(`Copying ${source} -> ${dest}`)
await cp(source, dest, {
recursive: true,
preserveTimestamps: true,
dereference: false, // preserve symlinks instead of following them
})
}
/* rm -rf */
async function rmrf(dir) {
if (fs.existsSync(dir)) {
log_verbose(`Removing ${dir}`)
fs.rmSync(dir, { recursive: true, force: true })
}
}
function log_verbose(...args) {
if (IS_VERBOSE) {
console.log(...args)
}
}
await main()
+9 -459
View File
@@ -13,8 +13,6 @@ import { rmrf } from "./file-utils.mjs"
const BUILD_DIR = "dist-standalone"
const BINARIES_DIR = `${BUILD_DIR}/binaries`
const RUNTIME_DEPS_DIR = "standalone/runtime-files"
const RIPGREP_BINARIES_DIR = `${BUILD_DIR}/ripgrep-binaries`
const CLI_BINARIES_DIR = "cli/bin"
const IS_DEBUG_BUILD = process.env.IS_DEBUG_BUILD === "true"
// This should match the node version packaged with the JetBrains plugin.
@@ -30,63 +28,15 @@ const SUPPORTED_BINARY_MODULES = ["better-sqlite3"]
const UNIVERSAL_BUILD = !process.argv.includes("-s")
const IS_VERBOSE = process.argv.includes("-v") || process.argv.includes("--verbose")
// Parse --target flag (e.g., --target=npm)
// Default behavior is JetBrains build (no binaries)
// Use --target=npm for npm package build (CLI binaries but no Node.js)
const targetArg = process.argv.find((arg) => arg.startsWith("--target="))
const BUILD_TARGET = targetArg ? targetArg.split("=")[1] : "jetbrains"
const IS_NPM_BUILD = BUILD_TARGET === "npm"
// Detect current platform
function getCurrentPlatform() {
const platform = os.platform()
const arch = os.arch()
if (platform === "darwin") {
return arch === "arm64" ? "darwin-arm64" : "darwin-x64"
} else if (platform === "linux") {
return "linux-x64"
} else if (platform === "win32") {
return "win-x64"
}
throw new Error(`Unsupported platform: ${platform}-${arch}`)
}
async function main() {
const buildType = IS_NPM_BUILD ? "NPM Package" : "JetBrains"
console.log(`🚀 Building Cline ${buildType} Package\n`)
await installNodeDependencies()
if (IS_NPM_BUILD) {
await copyCliBinaries()
await copyRipgrepBinary()
await copyProtoDescriptors()
await createNpmPackageFiles()
await createFakeNodeModules()
await createNpmIgnoreFile()
await createPostinstallScript()
}
if (UNIVERSAL_BUILD && !IS_NPM_BUILD) {
console.log("\nBuilding universal package for all platforms...")
if (UNIVERSAL_BUILD) {
console.log("Building universal package for all platforms...")
await packageAllBinaryDeps()
} else if (IS_NPM_BUILD) {
console.log("\nNPM build: Keeping native modules in node_modules for npm to handle...")
} else {
console.log(`\nBuilding package for ${os.platform()}-${os.arch()}...`)
}
if (!IS_NPM_BUILD) {
console.log("\n📦 Creating final package...")
await zipDistribution()
}
console.log("\n✅ Build complete!")
if (IS_NPM_BUILD) {
console.log(`\n📦 NPM package ready in ${BUILD_DIR}/`)
console.log(`To publish: cd ${BUILD_DIR} && npm publish`)
console.log(`Building package for ${os.platform()}-${os.arch()}...`)
}
await zipDistribution()
}
async function installNodeDependencies() {
@@ -104,389 +54,6 @@ async function installNodeDependencies() {
fs.renameSync(`${BUILD_DIR}/vscode`, `${BUILD_DIR}/node_modules/vscode`)
}
/**
* Copy CLI binaries (cline and cline-host) for all platforms
* The Go binaries are cross-compiled for darwin/linux arm64/amd64
*/
async function copyCliBinaries() {
console.log("Copying CLI binaries for all platforms...")
const platforms = [
{ os: "darwin", arch: "arm64" },
{ os: "darwin", arch: "amd64" },
{ os: "linux", arch: "amd64" },
{ os: "linux", arch: "arm64" },
]
const binDir = path.join(BUILD_DIR, "bin")
// Create bin directory
fs.mkdirSync(binDir, { recursive: true })
// Copy all platform-specific binaries
for (const { os, arch } of platforms) {
const platformSuffix = `${os}-${arch}`
// Copy cline binary
const clineSource = path.join(CLI_BINARIES_DIR, `cline-${platformSuffix}`)
const clineDest = path.join(binDir, `cline-${platformSuffix}`)
if (!fs.existsSync(clineSource)) {
console.error(`Error: CLI binary not found at ${clineSource}`)
console.error(`Please run: npm run compile-cli`)
process.exit(1)
}
await cpr(clineSource, clineDest)
fs.chmodSync(clineDest, 0o755)
console.log(`✓ cline-${platformSuffix} copied`)
// Copy cline-host binary
const hostSource = path.join(CLI_BINARIES_DIR, `cline-host-${platformSuffix}`)
const hostDest = path.join(binDir, `cline-host-${platformSuffix}`)
if (!fs.existsSync(hostSource)) {
console.error(`Error: CLI binary not found at ${hostSource}`)
console.error(`Please run: npm run compile-cli`)
process.exit(1)
}
await cpr(hostSource, hostDest)
fs.chmodSync(hostDest, 0o755)
console.log(`✓ cline-host-${platformSuffix} copied`)
}
console.log(`✓ All platform binaries copied to ${binDir}`)
}
/**
* Copy proto descriptors directory
* The proto/descriptor_set.pb file is needed by cline-core for gRPC reflection
*/
async function copyProtoDescriptors() {
console.log("Copying proto descriptors...")
const protoSource = "proto"
const protoDest = path.join(BUILD_DIR, "proto")
// Check if proto directory exists
if (!fs.existsSync(protoSource)) {
console.error(`Error: proto directory not found at ${protoSource}`)
console.error(`Please ensure the proto files have been generated`)
process.exit(1)
}
// Check if descriptor_set.pb exists
const descriptorPath = path.join(protoSource, "descriptor_set.pb")
if (!fs.existsSync(descriptorPath)) {
console.error(`Error: proto/descriptor_set.pb not found at ${descriptorPath}`)
console.error(`Please run: npm run protos`)
process.exit(1)
}
// Copy the entire proto directory
await cpr(protoSource, protoDest)
console.log(`✓ Proto descriptors copied to ${protoDest}`)
}
/**
* Copy ripgrep binary for the current platform
* Ripgrep is needed by cline-core for file searching
*/
async function copyRipgrepBinary() {
const currentPlatform = getCurrentPlatform()
const binaryName = currentPlatform.startsWith("win") ? "rg.exe" : "rg"
const ripgrepBinarySource = path.join(RIPGREP_BINARIES_DIR, currentPlatform, binaryName)
const ripgrepBinaryDest = path.join(BUILD_DIR, binaryName)
console.log(`Copying ripgrep binary for ${currentPlatform}...`)
// Check if ripgrep binaries exist, download if missing
if (!fs.existsSync(ripgrepBinarySource)) {
console.log(`Ripgrep binary not found, downloading...`)
try {
execSync("npm run download-ripgrep", { stdio: "inherit" })
} catch (error) {
console.error(`Error downloading ripgrep: ${error.message}`)
console.error(`Please run: npm run download-ripgrep`)
process.exit(1)
}
// Check again after download
if (!fs.existsSync(ripgrepBinarySource)) {
console.error(`Error: Ripgrep binary still not found at ${ripgrepBinarySource}`)
console.error(`Download may have failed. Please run: npm run download-ripgrep`)
process.exit(1)
}
}
// Copy ripgrep binary to the root of dist-standalone (where cline-core.js is)
await cpr(ripgrepBinarySource, ripgrepBinaryDest)
// Make it executable (Unix only)
if (!currentPlatform.startsWith("win")) {
fs.chmodSync(ripgrepBinaryDest, 0o755)
}
console.log(`✓ Ripgrep binary copied to ${ripgrepBinaryDest}`)
}
/**
* Create a VERSION file with build metadata
*/
async function createVersionFile() {
const packageJson = JSON.parse(fs.readFileSync("package.json", "utf8"))
const version = packageJson.version
const platform = getCurrentPlatform()
const buildDate = new Date().toISOString()
const versionInfo = {
version,
platform,
buildDate,
nodeVersion: TARGET_NODE_VERSION,
}
const versionPath = path.join(BUILD_DIR, "VERSION.txt")
fs.writeFileSync(versionPath, JSON.stringify(versionInfo, null, 2))
console.log(`✓ VERSION file created: ${version} (${platform})`)
}
/**
* Copy NPM package files (package.json, README.md, and man page) from cli/ directory
*/
async function createNpmPackageFiles() {
console.log("Copying NPM package files...")
// Copy package.json from cli/ directory
const packageJsonSource = path.join("cli", "package.json")
const packageJsonDest = path.join(BUILD_DIR, "package.json")
if (!fs.existsSync(packageJsonSource)) {
console.error(`Error: NPM package.json not found at ${packageJsonSource}`)
process.exit(1)
}
await cpr(packageJsonSource, packageJsonDest)
console.log(`✓ package.json copied from ${packageJsonSource}`)
// Copy README.md from cli/ directory
const readmeSource = path.join("cli", "README.md")
const readmeDest = path.join(BUILD_DIR, "README.md")
if (!fs.existsSync(readmeSource)) {
console.error(`Error: NPM README.md not found at ${readmeSource}`)
process.exit(1)
}
await cpr(readmeSource, readmeDest)
console.log(`✓ README.md copied from ${readmeSource}`)
// Copy man page from cli/man/ directory
const manPageSource = path.join("cli", "man", "cline.1")
const manDir = path.join(BUILD_DIR, "man")
const manPageDest = path.join(manDir, "cline.1")
if (!fs.existsSync(manPageSource)) {
console.error(`Error: Man page not found at ${manPageSource}`)
process.exit(1)
}
// Create man directory if it doesn't exist
fs.mkdirSync(manDir, { recursive: true })
await cpr(manPageSource, manPageDest)
console.log(`✓ Man page copied from ${manPageSource}`)
}
/**
* Create fake_node_modules directory with vscode stub
* This directory will be added to NODE_PATH so Node.js can find the vscode module
* without npm interfering with the real node_modules directory
*/
async function createFakeNodeModules() {
console.log("Creating fake_node_modules with vscode stub...")
const vscodeSource = path.join(BUILD_DIR, "node_modules", "vscode")
const fakeNodeModulesDir = path.join(BUILD_DIR, "fake_node_modules")
const vscodeDest = path.join(fakeNodeModulesDir, "vscode")
if (!fs.existsSync(vscodeSource)) {
console.error(`Error: vscode stub module not found at ${vscodeSource}`)
process.exit(1)
}
// Create fake_node_modules directory
fs.mkdirSync(fakeNodeModulesDir, { recursive: true })
// Copy vscode stub into fake_node_modules
await cpr(vscodeSource, vscodeDest)
console.log(`✓ fake_node_modules/vscode created at ${vscodeDest}`)
}
/**
* Create .npmignore file to ensure necessary files are included
*/
async function createNpmIgnoreFile() {
console.log("Creating .npmignore file...")
// Create .npmignore that excludes build artifacts
// Note: proto/ directory is NOT excluded because proto/descriptor_set.pb is needed at runtime
const npmignoreContent = `# Exclude build artifacts and unnecessary files
binaries/
ripgrep-binaries/
standalone.zip
cline-core.js.map
package-lock.json
tree-sitter*.wasm
node_modules/vscode
`
const npmignorePath = path.join(BUILD_DIR, ".npmignore")
fs.writeFileSync(npmignorePath, npmignoreContent)
console.log(`✓ .npmignore created`)
}
/**
* Create postinstall script for NPM package
* This script selects the correct platform-specific binary and creates symlinks
*/
async function createPostinstallScript() {
console.log("Creating postinstall script...")
const postinstallScript = `#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const os = require('os');
// Detect current platform and architecture
function getPlatformInfo() {
const platform = os.platform();
const arch = os.arch();
// Map Node.js arch names to Go arch names
let goArch = arch;
if (arch === 'x64') {
goArch = 'amd64';
}
let goPlatform = platform;
return { platform: goPlatform, arch: goArch };
}
// Setup platform-specific binaries
function setupBinaries() {
const { platform, arch } = getPlatformInfo();
const platformSuffix = \`\${platform}-\${arch}\`;
console.log(\`Setting up Cline CLI for \${platformSuffix}...\`);
const binDir = path.join(__dirname, 'bin');
// Check if platform-specific binaries exist
const clineSource = path.join(binDir, \`cline-\${platformSuffix}\`);
const clineHostSource = path.join(binDir, \`cline-host-\${platformSuffix}\`);
if (!fs.existsSync(clineSource)) {
console.error(\`Error: Binary not found for platform \${platformSuffix}\`);
console.error(\`Expected: \${clineSource}\`);
console.error(\`Supported platforms: darwin-arm64, darwin-amd64, linux-amd64, linux-arm64\`);
process.exit(1);
}
if (!fs.existsSync(clineHostSource)) {
console.error(\`Error: Binary not found for platform \${platformSuffix}\`);
console.error(\`Expected: \${clineHostSource}\`);
process.exit(1);
}
// Create symlinks or copies to the generic names
const clineTarget = path.join(binDir, 'cline');
const clineHostTarget = path.join(binDir, 'cline-host');
// Remove existing files if they exist
[clineTarget, clineHostTarget].forEach(target => {
if (fs.existsSync(target)) {
try {
fs.unlinkSync(target);
} catch (e) {
console.warn(\`Warning: Could not remove existing file \${target}: \${e.message}\`);
}
}
});
// On Unix, create symlinks; on Windows, copy files
if (platform === 'win32') {
// Windows: copy files
fs.copyFileSync(clineSource, clineTarget);
fs.copyFileSync(clineHostSource, clineHostTarget);
console.log('✓ Copied platform-specific binaries');
} else {
// Unix: create symlinks
fs.symlinkSync(path.basename(clineSource), clineTarget);
fs.symlinkSync(path.basename(clineHostSource), clineHostTarget);
console.log('✓ Created symlinks to platform-specific binaries');
// Make binaries executable
try {
fs.chmodSync(clineSource, 0o755);
fs.chmodSync(clineHostSource, 0o755);
fs.chmodSync(clineTarget, 0o755);
fs.chmodSync(clineHostTarget, 0o755);
} catch (error) {
console.warn(\`Warning: Could not set executable permissions: \${error.message}\`);
}
}
// Check ripgrep binary
const rgBinary = platform === 'win32' ? 'rg.exe' : 'rg';
const rgPath = path.join(__dirname, rgBinary);
if (!fs.existsSync(rgPath)) {
console.error(\`Error: ripgrep binary not found at \${rgPath}\`);
process.exit(1);
}
// Make ripgrep executable (Unix only)
if (platform !== 'win32') {
try {
fs.chmodSync(rgPath, 0o755);
} catch (error) {
console.warn(\`Warning: Could not set ripgrep executable permissions: \${error.message}\`);
}
}
console.log('✓ Cline CLI installation complete');
console.log('');
console.log('Usage:');
console.log(' cline - Start Cline CLI');
console.log(' cline-host - Start Cline host service');
console.log('');
console.log('Documentation: https://docs.cline.bot');
}
try {
setupBinaries();
} catch (error) {
console.error(\`Installation failed: \${error.message}\`);
console.error('Please report this issue at: https://github.com/cline/cline/issues');
process.exit(1);
}
`
const postinstallPath = path.join(BUILD_DIR, "postinstall.js")
fs.writeFileSync(postinstallPath, postinstallScript)
fs.chmodSync(postinstallPath, 0o755)
console.log(`✓ postinstall.js created`)
}
/**
* Downloads prebuilt binaries for each platform for the modules that include binaries. It uses `npx prebuild-install`
* to download the binary.
@@ -539,9 +106,8 @@ async function packageAllBinaryDeps() {
}
async function zipDistribution() {
// Default JetBrains build
const zipFilename = "standalone.zip"
const zipPath = path.join(BUILD_DIR, zipFilename)
// Zip the build directory (excluding any pre-existing output zip).
const zipPath = path.join(BUILD_DIR, "standalone.zip")
const output = fs.createWriteStream(zipPath)
const startTime = Date.now()
const archive = archiver("zip", { zlib: { level: 6 } })
@@ -559,31 +125,15 @@ async function zipDistribution() {
})
archive.pipe(output)
// Build ignore lists for build directory and extension directory
const ignorePatterns = ["standalone.zip", "standalone-cli.zip"]
const extensionIgnores = ["dist/**"]
// For JetBrains builds, exclude binaries from both directories
// JetBrains provides their own Node.js, so exclude all binaries
ignorePatterns.push(
"bin/**", // Exclude entire bin directory
"node-binaries/**", // Exclude all platform-specific Node.js binaries
)
extensionIgnores.push(
"cli/bin/**", // Exclude CLI binaries from extension
"node-binaries/**", // Exclude node-binaries from extension
)
console.log("JetBrains build: Excluding Node.js and CLI binaries (JetBrains provides its own Node.js)")
// Add all the files from the standalone build dir.
archive.glob("**/*", {
cwd: BUILD_DIR,
ignore: ignorePatterns,
ignore: ["standalone.zip"],
})
// Exclude the same files as the VCE vscode extension packager.
const isIgnored = createIsIgnored(extensionIgnores)
// Also ignore the dist directory, the build directory for the extension.
const isIgnored = createIsIgnored(["dist/**"])
// Add the whole cline directory under "extension", except the for the ignored files.
archive.directory(process.cwd(), "extension", (entry) => {
+1
View File
@@ -77,6 +77,7 @@ function createMockService<T extends grpc.UntypedServiceImplementation>(serviceN
case "getTelemetrySettings":
callback(null, {
isEnabled: 2, // Setting.DISABLED
errorLevel: "all",
})
return
+4 -16
View File
@@ -76,19 +76,9 @@ export async function initialize(context: vscode.ExtensionContext): Promise<Webv
await showVersionUpdateAnnouncement(context)
// Initialize banner service
// Initialize banner service (TEMPORARILY DISABLED - not fetching banners to prevent API hammering)
BannerService.initialize(webview.controller)
BannerService.get()
.fetchActiveBanners()
.then((banners) => {
if (banners.length > 0) {
Logger.log(`BannerService: ${banners.length} active banner(s) fetched.`)
// Banners are now cached and can be accessed by the frontend when needed
}
})
.catch((error) => {
Logger.error("BannerService: Failed to fetch banners on startup", error)
})
// DISABLED: .getActiveBanners(true)
telemetryService.captureExtensionActivated()
@@ -104,17 +94,15 @@ async function showVersionUpdateAnnouncement(context: vscode.ExtensionContext) {
if (!previousVersion || currentVersion !== previousVersion) {
Logger.log(`Cline version changed: ${previousVersion} -> ${currentVersion}. First run or update detected.`)
// Use the same condition as announcements: focus when there's a new announcement to show
// Check if there's a new announcement to show
const lastShownAnnouncementId = context.globalState.get<string>("lastShownAnnouncementId")
const latestAnnouncementId = getLatestAnnouncementId()
if (lastShownAnnouncementId !== latestAnnouncementId) {
// Focus Cline when there's a new announcement to show (major/minor updates or fresh installs)
// Show notification when there's a new announcement (major/minor updates or fresh installs)
const message = previousVersion
? `Cline has been updated to v${currentVersion}`
: `Welcome to Cline v${currentVersion}`
await HostProvider.workspace.openClineSidebarPanel({})
await new Promise((resolve) => setTimeout(resolve, 200))
HostProvider.window.showMessage({
type: ShowMessageType.INFORMATION,
message,

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