Compare commits

..

1 Commits

Author SHA1 Message Date
cline-test 366d383f49 Add a GitHub Action that tells how to manually test a PR 2026-02-09 14:51:13 -08:00
544 changed files with 23401 additions and 25020 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Add support for bundled endpoints.json in enterprise distributions. Extensions can now include a pre-configured endpoints.json file that automatically switches Cline to self-hosted mode. Includes packaging scripts for VSIX, NPM, and JetBrains plugins.
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Replace the LiteLLM model list with a selector
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Add GitHub Actions workflow to build CLI from any commit for testing
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
fix(cli): prevent hang when spawned without TTY
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Add Claude Opus 4.6 model support
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Supports rendering markdown table in chat view.
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Fix CLI crashing in CI environments and with stdin redirection (e.g., `cline "prompt" < /dev/null`). Now checks both stdin and stdout TTY status before using Ink, and only errors on empty stdin when no prompt is provided.
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Fix JetBrains sign-in regression by adding fallback for openExternal RPC
+7
View File
@@ -0,0 +1,7 @@
---
"cline": patch
---
fix: use vscode.env.openExternal for auth in remote environments
Fixes OAuth authentication in VS Code Server and remote environments by routing browser URL opening through VS Code's native openExternal API instead of the npm 'open' package.
@@ -0,0 +1,7 @@
---
"cline": patch
---
fix: use vscode.env.asExternalUri for auth callback URLs only in VS Code Web
Fixes OAuth callback redirect in VS Code Web (`code serve-web`) environments by using `vscode.env.asExternalUri()` to resolve the callback URI. This is gated behind a `vscode.env.uiKind === UIKind.Web` check so regular desktop VS Code continues to use the `vscode://` URI directly, avoiding unintended transformations from `asExternalUri`.
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Updating script documentation and removing unnecessary continue on error
+5
View File
@@ -0,0 +1,5 @@
---
"cline": patch
---
Fix Bedrock model id
+5
View File
@@ -0,0 +1,5 @@
---
"claude-dev": patch
---
Unify ViewHeader Styles Across All Views
+5
View File
@@ -0,0 +1,5 @@
---
"cline": minor
---
Add Generate API Key on Hicap Provider selection
+5 -20
View File
@@ -147,29 +147,14 @@ When filling out the template:
### Create PR with gh CLI
**Use a temporary file for the PR body** to avoid shell escaping issues, newline problems, and other command-line flakiness:
1. Write the PR body to a temporary file:
```
/tmp/pr-body.md
```
2. Create the PR using the file:
```bash
gh pr create --title "PR_TITLE" --body-file /tmp/pr-body.md --base main
```
3. Clean up the temporary file:
```bash
rm /tmp/pr-body.md
```
For draft PRs:
```bash
gh pr create --title "PR_TITLE" --body-file /tmp/pr-body.md --base main --draft
gh pr create --title "PR_TITLE" --body "PR_BODY" --base main
```
**Why use a file?** Passing complex markdown with newlines, special characters, and checkboxes directly via `--body` is error-prone. The `--body-file` flag handles all content reliably.
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
-11
View File
@@ -147,17 +147,6 @@ Required steps:
Common mistake: Adding only the return value without the `context.globalState.get()` call. This compiles but the value is always `undefined` on load.
Settings plumbing gotcha: if a key is user-toggleable from settings, wire both controller update paths:
- `src/core/controller/state/updateSettings.ts` for webview `updateSetting(...)`
- `src/core/controller/state/updateSettingsCli.ts` for CLI/ACP settings updates
Missing one path causes a toggle to appear to change in one surface while the backend state stays unchanged.
Webview toggle gotcha: settings changes must also round-trip back in state payloads.
- Add the field to `UpdateSettingsRequest` in `proto/cline/state.proto` (for webview update requests), then run `npm run protos`
- Include the key in `Controller.getStateToPostToWebview()` (`src/core/controller/index.ts`)
- Ensure `ExtensionState` and webview defaults include the key (`src/shared/ExtensionMessage.ts`, `webview-ui/src/context/ExtensionStateContext.tsx`)
If this round-trip wiring is missing, the backend value can update but the toggle in webview appears stuck or reverts.
## StateManager Cache vs Direct globalState Access
StateManager uses an in-memory cache populated during `StateManager.initialize(context)` in `common.ts`. For most state, use `controller.stateManager.setGlobalState()`/`getGlobalStateKey()`.
-49
View File
@@ -1,49 +0,0 @@
# THIS IS AUTOGENERATED. DO NOT EDIT MANUALLY
version = 1
name = "cline"
[setup]
script = '''
if [ ! -d "node_modules" ]; then
MAIN_WORKTREE="$(git worktree list | head -n1 | awk '{print $1}')"
ln -s "$MAIN_WORKTREE/node_modules" node_modules
ln -s "$MAIN_WORKTREE/webview-ui/node_modules" webview-ui/node_modules
fi
'''
[[actions]]
name = "VS Code"
icon = "run"
command = "chmod +x ./scripts/run-extension-host.sh && ./scripts/run-extension-host.sh production"
[[actions]]
name = "CLI"
icon = "run"
command = '''
npm run cli:build
npm run cli:run
'''
[[actions]]
name = "npm install"
icon = "tool"
command = '''
rm node_modules
rm webview-ui/node_modules
npm run install:all
'''
[[actions]]
name = "pull main"
icon = "tool"
command = '''
git fetch origin main
if ! git merge-base --is-ancestor main origin/main; then
echo "Local main has commits not on origin/main. Aborting..."
exit 1
fi
git update-ref refs/heads/main refs/remotes/origin/main
echo "main updated to $(git rev-parse --short main)"
'''
+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.
+290
View File
@@ -0,0 +1,290 @@
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: Print HEAD commit
run: |
echo "HEAD is at: $(git rev-parse HEAD)"
echo "Short: $(git rev-parse --short HEAD)"
git log -1 --format="Commit: %H%nAuthor: %an <%ae>%nDate: %ad%nMessage: %s"
- 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 by noting the commit hash you reviewed:
```bash
git rev-parse --short HEAD
```
Include this at the top of your comment: "Reviewed at commit: <short hash>"
Then thank them 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
At the very bottom of your comment, append this exact footer:
```text
---
Generated by Claude PR Review
```
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
@@ -1,70 +0,0 @@
name: Smoke Tests
on:
push:
branches: [main]
paths:
- 'src/core/**'
- 'src/shared/**'
- 'proto/**'
- 'evals/**'
- '.github/workflows/cline-evals-regression.yml'
pull_request:
paths:
- 'src/core/**'
- 'src/shared/**'
- 'proto/**'
- 'evals/**'
- '.github/workflows/cline-evals-regression.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: smoke-tests-${{ github.ref }}
cancel-in-progress: true
jobs:
smoke-tests:
name: Smoke Tests
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build and install CLI
run: |
npm run protos
cd cli && npm install && npm run build && npm link
echo "$(npm config get prefix)/bin" >> $GITHUB_PATH
- name: Verify CLI
run: cline --version
- name: Run smoke tests
env:
CLINE_API_KEY: ${{ secrets.CLINE_API_KEY }}
run: |
cline auth -p cline -k "$CLINE_API_KEY" -m "anthropic/claude-sonnet-4.5"
npx tsx evals/smoke-tests/run-smoke-tests.ts --trials 1 --parallel
- name: Generate summary
if: always()
run: cat evals/smoke-tests/results/latest/summary.md >> $GITHUB_STEP_SUMMARY
- name: Upload results
uses: actions/upload-artifact@v4
if: always()
with:
name: smoke-test-results-${{ github.run_id }}
path: evals/smoke-tests/results/latest/
retention-days: 30
@@ -0,0 +1,101 @@
name: Cline PR Manual Verification Plan
on:
# Manual trigger only. Run from terminal:
# gh workflow run cline-pr-manual-verification-plan.yml -f pr_number=1234
workflow_dispatch:
inputs:
pr_number:
description: "PR number to generate a verification plan for"
required: true
type: string
concurrency:
group: pr-verification-plan-${{ inputs.pr_number }}
cancel-in-progress: true
jobs:
cline-pr-manual-verification-plan:
runs-on: ubuntu-latest
timeout-minutes: 5
# 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: Print HEAD commit
run: |
echo "HEAD is at: $(git rev-parse HEAD)"
echo "Short: $(git rev-parse --short HEAD)"
git log -1 --format="Commit: %H%nAuthor: %an <%ae>%nDate: %ad%nMessage: %s"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: "npm"
- name: Configure Cline with Cline Provider
run: |
npx cline@nightly auth --provider cline \
--apikey "${{ secrets.CLINE_API_KEY }}" \
--modelid anthropic/claude-opus-4.6
- name: Get PR number
id: pr
run: echo "number=${{ inputs.pr_number }}" >> $GITHUB_OUTPUT
- name: Get PR branch info
id: branches
env:
GH_TOKEN: ${{ github.token }}
run: |
PR_NUM="${{ steps.pr.outputs.number }}"
BASE_REF=$(gh pr view "$PR_NUM" --json baseRefName -q '.baseRefName')
HEAD_REF=$(gh pr view "$PR_NUM" --json headRefName -q '.headRefName')
MERGE_BASE=$(git merge-base "origin/${BASE_REF}" HEAD)
echo "base_ref=${BASE_REF}" >> $GITHUB_OUTPUT
echo "head_ref=${HEAD_REF}" >> $GITHUB_OUTPUT
echo "merge_base=${MERGE_BASE}" >> $GITHUB_OUTPUT
echo "merge_base_short=$(git rev-parse --short ${MERGE_BASE})" >> $GITHUB_OUTPUT
- name: Generate manual verification plan with Cline
env:
PR_NUMBER: ${{ steps.pr.outputs.number }}
GITHUB_REPO: ${{ github.repository }}
GH_TOKEN: ${{ github.token }}
BASE_REF: ${{ steps.branches.outputs.base_ref }}
HEAD_REF: ${{ steps.branches.outputs.head_ref }}
MERGE_BASE: ${{ steps.branches.outputs.merge_base }}
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@nightly --yolo --verbose 'Please come up to speed on the changes in the diff between `git --no-pager diff '"${MERGE_BASE}"'..HEAD` (PR #'"${PR_NUMBER}"': '"${HEAD_REF}"' → '"${BASE_REF}"') and assess the architecture decisions made in this change set. We are interested also in coming up with an effective set of steps for manual verification of the changes to show that the change set is fully working as intended.'
+326
View File
@@ -0,0 +1,326 @@
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: Print HEAD commit
run: |
echo "HEAD is at: $(git rev-parse HEAD)"
echo "Short: $(git rev-parse --short HEAD)"
git log -1 --format="Commit: %H%nAuthor: %an <%ae>%nDate: %ad%nMessage: %s"
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: "npm"
- name: Configure Cline with Cline Provider
run: |
npx cline@nightly auth --provider cline \
--apikey "${{ secrets.CLINE_API_KEY }}" \
--modelid anthropic/claude-opus-4.6
- 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@nightly --yolo --verbose '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 by noting the commit hash you reviewed:
```bash
git rev-parse --short HEAD
```
Include this at the top of your comment: "Reviewed at commit: <short hash>"
Then thank them 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
At the very bottom of your comment, append this exact footer:
```text
---
Generated by Cline PR Code Review
```
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'
+14 -4
View File
@@ -1,7 +1,7 @@
name: Publish NPM Release
on:
workflow_call:
workflow_dispatch:
inputs:
confirm_publish:
description: 'Type "publish" to confirm you want to publish to NPM'
@@ -10,7 +10,6 @@ on:
permissions:
contents: write # Required for pushing tags
id-token: write # Required for npm trusted publishing (OIDC)
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
@@ -21,7 +20,7 @@ jobs:
publish-npm-release:
needs: test
name: Publish Cline CLI to NPM
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main' && inputs.confirm_publish == 'publish'
if: github.repository == 'cline/cline' && github.ref == 'refs/heads/main' && github.event.inputs.confirm_publish == 'publish'
runs-on: ubuntu-latest
steps:
@@ -31,10 +30,19 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "24.x"
node-version: "20.x"
registry-url: "https://registry.npmjs.org"
# 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') }}
- name: Install root dependencies and CLI dependencies
if: steps.check_commits.outputs.skip != 'true'
run: npm ci --include=optional # this will also install cli deps because "cli" in included in root package.json workspaces field
- name: Generate Protos
@@ -73,6 +81,8 @@ jobs:
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
+15 -15
View File
@@ -1,17 +1,12 @@
name: Publish NPM Nightly
on:
workflow_call:
inputs:
force_publish:
description: "Force publish even if there are no commits in the last 24 hours"
required: false
type: boolean
default: false
schedule:
- cron: "0 12 * * *" # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
permissions:
contents: read
id-token: write # Required for npm trusted publishing (OIDC)
checks: write # Required by test workflow
pull-requests: write # Required by test workflow
@@ -32,12 +27,6 @@ jobs:
- name: Check for recent commits
id: check_commits
run: |
if [ "${{ inputs.force_publish }}" = "true" ]; then
echo "force_publish enabled, proceeding with publish"
echo "skip=false" >> $GITHUB_OUTPUT
exit 0
fi
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
@@ -50,9 +39,18 @@ jobs:
if: steps.check_commits.outputs.skip != 'true'
uses: actions/setup-node@v4
with:
node-version: "24.x"
node-version: "20.x"
registry-url: "https://registry.npmjs.org"
# 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') }}
- name: Install root dependencies and CLI dependencies
if: steps.check_commits.outputs.skip != 'true'
run: npm ci --include=optional # this will also install cli deps because "cli" in included in root package.json workspaces field
@@ -120,6 +118,8 @@ jobs:
- 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
@@ -1,55 +0,0 @@
name: Publish CLI (Trusted)
on:
schedule:
- cron: "0 12 * * *" # 4 AM PST (UTC-8) = 12 UTC
workflow_dispatch:
inputs:
publish_target:
description: "Which publish flow to run"
required: true
default: "main"
type: choice
options:
- main
- nightly
confirm_publish:
description: 'Required when publish_target=main. Type "publish" to confirm release publish.'
required: false
type: string
force_nightly_publish:
description: "Force nightly publish even with no commits in last 24h"
required: false
type: boolean
default: false
permissions:
id-token: write # Required for npm trusted publishing (OIDC)
contents: write # Required because npm-main creates/pushes git tags
checks: write # Required by nested reusable test workflow
pull-requests: write # Required by nested reusable test workflow
jobs:
publish-main:
if: |
github.repository == 'cline/cline' && (
github.event_name == 'workflow_dispatch' &&
github.event.inputs.publish_target == 'main' &&
github.event.inputs.confirm_publish == 'publish' &&
!endsWith(github.actor, '[bot]')
)
uses: ./.github/workflows/npm-main.yaml
secrets: inherit
with:
confirm_publish: ${{ github.event.inputs.confirm_publish }}
publish-nightly:
if: |
github.repository == 'cline/cline' && (
github.event_name == 'schedule' ||
(github.event_name == 'workflow_dispatch' && github.event.inputs.publish_target == 'nightly')
)
uses: ./.github/workflows/npm-nightly.yaml
secrets: inherit
with:
force_publish: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.force_nightly_publish == 'true' }}
+16
View File
@@ -38,6 +38,22 @@ jobs:
with:
node-version: "lts/*"
# 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
run: npm ci --include=optional
+18
View File
@@ -44,10 +44,28 @@ jobs:
with:
node-version: "lts/*"
# 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 install --include=optional
- name: Install webview-ui dependencies
if: steps.webview-cache.outputs.cache-hit != 'true'
run: cd webview-ui && npm install --include=optional
- name: Install Publishing Tools
-3
View File
@@ -48,6 +48,3 @@ test-results
.secrets
*.tsbuildinfo
# Smoke test results (generated)
evals/smoke-tests/results/
-3
View File
@@ -1,3 +0,0 @@
[submodule "evals/cline-bench"]
path = evals/cline-bench
url = https://github.com/cline/cline-bench.git
+12 -93
View File
@@ -1,86 +1,5 @@
# Changelog
## [3.65.0]
### Added
- Add /skills slash command to CLI for viewing and managing installed skills
### Fixed
- Fix aggressive context compaction caused by accidental clicks on the context window progress bar silently setting a very low auto-condense threshold
- Fix infinite retry loop when write_to_file fails with missing content parameter.
- Fixed default claude model
## [3.64.0]
### Added
- Added sonnet 4.6
## [3.63.0]
### Added
- added zai GLM 5 Free promo
### Fixed
- Restore reasoning trace visibility in chat and improve the thinking row UX so reasoning is visible, then collapsible after completion.
## [3.62.0]
### Fixed
- Banners now display immediately when opening the extension instead of requiring user interaction first
- Resolved 17 security vulnerabilities including high-severity DoS issues in dependencies (body-parser, axios, qs, tar, and others)
## [3.61.0]
- UI/UX fixes with minimax model family
## [3.60.0]
- Fixes for Minimax model family
## [3.59.0]
- Added Minimax 2.5 Free Promo
- Fixed Response chaining for OpenAI's Responses API
## [3.58.0]
### Added
- Subagent: replace legacy subagents with the native `use_subagents` tool
- Bundle `endpoints.json` support so packaged distributions can ship required endpoints out-of-the-box
- Amazon Bedrock: support parallel tool calling
- New "double-check completion" experimental feature to verify work before marking tasks complete
- CLI: new task controls/flags including custom `--thinking` token budget and `--max-consecutive-mistakes` for yolo runs
- Remote config: new UI/options (including connection/test buttons) and support for syncing deletion of remotely configured MCP servers
- Vertex / Claude Code: add 1M context model options for Claude Opus 4.6
- ZAI/GLM: add GLM-5
### Fixed
- CLI: handle stdin redirection correctly in CI/headless environments
- CLI: preserve OAuth callback paths during auth redirects
- VS Code Web: generate auth callback URLs via `vscode.env.asExternalUri` (OAuth callback reliability)
- Terminal: surface command exit codes in results and improve long-running `execute_command` timeout behavior
- UI: add loading indicator and fix `api_req_started` rendering
- Task streaming: prevent duplicate streamed text rows after completion
- API: preserve selected Vercel model when model metadata is missing
- Telemetry: route PostHog networking through proxy-aware shared fetch and ensure telemetry flushes on shutdown
- CI: increase Windows E2E test timeout to reduce flakiness
### Changed
- Settings/model UX: move "reasoning effort" into model configuration and expose it in settings
- CLI provider selection: limit provider list to those remotely configured
- UI: consolidate ViewHeader component/styling across views
- Tools: add auto-approval support for `attempt_completion` commands
- Remotely configured MCP server schema now supports custom headers
## [3.57.1]
### Fixed
@@ -92,7 +11,7 @@
### Added
- Cline CLI 2.0 now available. Install with `npm install -g cline`
- Anthopic Opus 4.6
- Anthopic Opus 4.6
- Minimax-2.1 and Kimi-k2.5 now available for free for a limited time promo
- Codex-5.3 through ChatGPT subscription
@@ -112,23 +31,23 @@
### Added
- **CLI authentication:** Added Vercel AI Gateway and Cline API key provider support for headless CI/automation workflows
- **New model:** Added Kimi-K2.5 model to Moonshot provider (262K context, image support, prompt caching)
- **Prompt variant:** Added Trinity Large prompt variant for improved tool-calling support
- **OpenTelemetry:** Added support for custom headers on metrics and logs endpoints
- **Social links:** Added community icons (X, Discord, GitHub, Reddit, LinkedIn) to the What's New modal
- __CLI authentication:__ Added Vercel AI Gateway and Cline API key provider support for headless CI/automation workflows
- __New model:__ Added Kimi-K2.5 model to Moonshot provider (262K context, image support, prompt caching)
- __Prompt variant:__ Added Trinity Large prompt variant for improved tool-calling support
- __OpenTelemetry:__ Added support for custom headers on metrics and logs endpoints
- __Social links:__ Added community icons (X, Discord, GitHub, Reddit, LinkedIn) to the What's New modal
### Fixed
- **LiteLLM:** Fixed thinking configuration not appearing for reasoning-capable models
- **OpenTelemetry:** Fixed endpoint path handling (no longer incorrectly appends `/v1/logs` or `/v1/metrics`) and ensured logs are sent regardless of VSCode telemetry settings
- **CLI auth:** Fixed `cline auth` displaying incorrect provider information after configuration
- __LiteLLM:__ Fixed thinking configuration not appearing for reasoning-capable models
- __OpenTelemetry:__ Fixed endpoint path handling (no longer incorrectly appends `/v1/logs` or `/v1/metrics`) and ensured logs are sent regardless of VSCode telemetry settings
- __CLI auth:__ Fixed `cline auth` displaying incorrect provider information after configuration
### Changed
- **Hooks:** Hook scripts now run from the workspace repository root instead of filesystem root
- **Default settings:** Enabled multi-root workspaces, parallel tool calling, and skills by default; disabled strict plan mode by default
- **Settings UI:** Refreshed feature settings section with collapsible design
- __Hooks:__ Hook scripts now run from the workspace repository root instead of filesystem root
- __Default settings:__ Enabled multi-root workspaces, parallel tool calling, and skills by default; disabled strict plan mode by default
- __Settings UI:__ Refreshed feature settings section with collapsible design
## [3.55.0]
-27
View File
@@ -1,27 +0,0 @@
# Security Policy
## Supported Versions
We actively patch only the most recent minor release of Cline. Older versions receive fixes at our discretion.
## Reporting a Vulnerability
We appreciate your efforts to responsibly disclose your findings and will make every effort to acknowledge your contributions.
To report a security issue, please use the GitHub Security Advisory ["Report a Vulnerability"](https://github.com/cline/cline/security/advisories/new) tab.
The team will send a response indicating the next steps in handling your report. After the initial reply, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance.
When reporting, please include:
- A short summary of the issue
- Steps to reproduce or a proof of concept
- Any logs, stack traces, or screenshots that might help us understand the problem
We acknowledge reports within 48 hours and aim to release a fix or mitigation within 30 days. While we work on a resolution, please keep the details private.
## Escalation
If you do not receive an acknowledgement of your report within 5 business days, you may send an email to security@cline.bot.
Thank you for helping us keep Cline users safe.
-95
View File
@@ -1,95 +0,0 @@
# cline
## [2.4.1]
### Fixed
- Fix infinite retry loop when write_to_file fails with missing content parameter. Provides progressive guidance to the model, escalating from suggestions to hard stops, with context window awareness to break the loop.
## [2.4.0]
### Added
- Adding Anthropic Sonnet 4.6
- Allows users to enter custom aws region when selecting bedrock as a provider in CLI
- Keep reasoning rows visible when low-stakes tool groups start immediately after reasoning.
- Restore reasoning trace visibility in chat and improve the thinking row UX so streamed reasoning is visible, then collapsible after completion.
### Fixed
- Banners now display immediately when opening the extension instead of requiring user interaction first
- Resolved 17 security vulnerabilities including high-severity DoS issues in dependencies (body-parser, axios, qs, tar, and others)
## [2.2.2]
- Allows users to enter custom aws region when selecting bedrock as a provider
- Prevent Parent Container Scrolling In Dropdowns
## [2.2.1]
- Added Minimax 2.5 Free Promo
- Fixed Response chaining for OpenAI's Responses API
## [2.2.0]
### Added
- Subagent: replace legacy subagents with the native `use_subagents` tool
- Bundle `endpoints.json` support so packaged distributions can ship required endpoints out-of-the-box
- Amazon Bedrock: support parallel tool calling
- New "double-check completion" experimental feature to verify work before marking tasks complete
- CLI: new task controls/flags including custom `--thinking` token budget and `--max-consecutive-mistakes` for yolo runs
- Remote config: new UI/options (including connection/test buttons) and support for syncing deletion of remotely configured MCP servers
- Vertex / Claude Code: add 1M context model options for Claude Opus 4.6
- ZAI/GLM: add GLM-5
### Fixed
- CLI: handle stdin redirection correctly in CI/headless environments
- CLI: preserve OAuth callback paths during auth redirects
- VS Code Web: generate auth callback URLs via `vscode.env.asExternalUri` (OAuth callback reliability)
- Terminal: surface command exit codes in results and improve long-running `execute_command` timeout behavior
- UI: add loading indicator and fix `api_req_started` rendering
- Task streaming: prevent duplicate streamed text rows after completion
- API: preserve selected Vercel model when model metadata is missing
- Telemetry: route PostHog networking through proxy-aware shared fetch and ensure telemetry flushes on shutdown
- CI: increase Windows E2E test timeout to reduce flakiness
### Changed
- Settings/model UX: move "reasoning effort" into model configuration and expose it in settings
- CLI provider selection: limit provider list to those remotely configured
- UI: consolidate ViewHeader component/styling across views
- Tools: add auto-approval support for `attempt_completion` commands
- Remotely configured MCP server schema now supports custom headers
## [2.1.0]
### Minor Changes
- 42ce100: Add Generate API Key on Hicap Provider selection
### Patch Changes
- 195294f: Add support for bundled endpoints.json in enterprise distributions. Extensions can now include a pre-configured endpoints.json file that automatically switches Cline to self-hosted mode. Includes packaging scripts for VSIX, NPM, and JetBrains plugins.
- a1f2601: Replace the LiteLLM model list with a selector
- 739d75a: Add Claude Code provider support for Claude Opus 4.6 and Sonnet 4.5 1M variants via both full model names and aliases (`opus[1m]`, `sonnet[1m]`), and align the `opus` alias with Opus 4.6.
- 8440380: Add GitHub Actions workflow to build CLI from any commit for testing
- b1a8db2: fix(cli): prevent hang when spawned without TTY
- 7c87017: Add Claude Opus 4.6 model support
- d116ac5: Supports rendering markdown table in chat view.
- 6d8fb85: Fix CLI crashing in CI environments and with stdin redirection (e.g., `cline "prompt" < /dev/null`). Now checks both stdin and stdout TTY status before using Ink, and only errors on empty stdin when no prompt is provided.
- 70a9904: Fix JetBrains sign-in regression by adding fallback for openExternal RPC
- f440f3a: fix: use vscode.env.openExternal for auth in remote environments
Fixes OAuth authentication in VS Code Server and remote environments by routing browser URL opening through VS Code's native openExternal API instead of the npm 'open' package.
- 70a9904: fix: use vscode.env.asExternalUri for auth callback URLs only in VS Code Web
Fixes OAuth callback redirect in VS Code Web (`code serve-web`, Codespaces) by using `vscode.env.asExternalUri()` to resolve the callback URI. This is gated behind a `vscode.env.uiKind === UIKind.Web` check so regular desktop VS Code continues to use the `vscode://` URI directly. The `getCallbackUrl` API now accepts a `path` parameter so the full callback URI (including route) is resolved correctly, and callers pass their path directly instead of appending after.
- 5308ded: Updating script documentation and removing unnecessary continue on error
- b514f18: Prevent duplicate streamed text rows when a partial text update arrives after the same text was already finalized.
- 26391c9: Fix Bedrock model id
- d19a877: Unify ViewHeader Styles Across All Views
- 5dcaa8c: Add Vertex Claude Opus 4.6 1M model option and global endpoint support, and pass the 1M beta header for Vertex Claude requests.
+2 -1
View File
@@ -45,7 +45,7 @@ cline
### Use any API and Model
Cline supports API providers like ChatGPT, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, Cerebras, Groq, and Moonshot. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using a Cline Account, you'll always have access to the newest models as soon as they're available.
Cline supports API providers like ChatGPT, Anthropic, OpenAI, Google Gemini, AWS Bedrock, Azure, GCP Vertex, Cerebras and Groq. You can also configure any OpenAI compatible API, or use a local model through LM Studio/Ollama. If you're using a Cline Account, you'll always have access to the newest models as soon as they're available.
<!-- Transparent pixel to create line break after floating image -->
@@ -79,3 +79,4 @@ Get the same Cline experience with enterprise-grade controls: SSO (SAML/OIDC), g
## License
[Apache 2.0 © 2026 Cline Bot Inc.](./LICENSE)
+2 -8
View File
@@ -125,13 +125,13 @@ authentication wizard, or use quick setup flags.
Options:
.PP
\f[B]\-p\f[R], \f[B]\-\-provider\f[R] \f[I]id\f[R] : Provider ID for
quick setup (e.g., openai\-native, anthropic, openrouter, moonshot)
quick setup (e.g., openai\-native, anthropic, openrouter)
.PP
\f[B]\-k\f[R], \f[B]\-\-apikey\f[R] \f[I]key\f[R] : API key for the
provider
.PP
\f[B]\-m\f[R], \f[B]\-\-modelid\f[R] \f[I]id\f[R] : Model ID to
configure (e.g., gpt\-4o, claude\-sonnet\-4\-5\-20250929, kimi\-k2.5)
configure (e.g., gpt\-4o, claude\-sonnet\-4\-5\-20250929)
.PP
\f[B]\-b\f[R], \f[B]\-\-baseurl\f[R] \f[I]url\f[R] : Base URL (optional,
for OpenAI\-compatible providers)
@@ -242,9 +242,6 @@ cline \-m claude\-sonnet\-4\-5\-20250929 \(dqRefactor this function\(dq
\f[I]# Quick auth setup with model\f[R]
cline auth \-p anthropic \-k sk\-ant\-xxxxx \-m claude\-sonnet\-4\-5\-20250929
\f[I]# Quick auth setup for Moonshot\f[R]
cline auth \-p moonshot \-k sk\-xxxxx \-m kimi\-k2.5
.EE
.SS Including Images
.IP
@@ -312,9 +309,6 @@ cline auth \-p anthropic \-k sk\-ant\-api\-xxxxx
\f[I]# Quick setup for OpenAI\f[R]
cline auth \-p openai\-native \-k sk\-xxxxx \-m gpt\-4o
\f[I]# Quick setup for Moonshot\f[R]
cline auth \-p moonshot \-k sk\-xxxxx \-m kimi\-k2.5
\f[I]# OpenAI\-compatible provider with custom base URL\f[R]
cline auth \-p openai \-k your\-api\-key \-b https://api.example.com/v1
.EE
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cline",
"version": "2.4.1",
"version": "2.0.5",
"description": "Autonomous coding agent CLI - capable of creating/editing files, running commands, using the browser, and more",
"main": "dist/cli.mjs",
"bin": {
+28 -10
View File
@@ -12,7 +12,11 @@
import type * as acp from "@agentclientprotocol/sdk"
import type { TerminalHandle } from "@agentclientprotocol/sdk"
import { DEFAULT_TERMINAL_OUTPUT_LINE_LIMIT, PROCESS_HOT_TIMEOUT_NORMAL } from "@integrations/terminal/constants"
import {
DEFAULT_SUBAGENT_TERMINAL_OUTPUT_LINE_LIMIT,
DEFAULT_TERMINAL_OUTPUT_LINE_LIMIT,
PROCESS_HOT_TIMEOUT_NORMAL,
} from "@integrations/terminal/constants"
import type {
ITerminal,
ITerminalManager,
@@ -138,12 +142,12 @@ export interface ManagedTerminal {
* Wraps ACP terminal operations and emits events compatible with ITerminalProcess.
*/
class AcpTerminalProcess extends EventEmitter<TerminalProcessEvents> implements ITerminalProcess {
isHot = false
waitForShellIntegration = false
isHot: boolean = false
waitForShellIntegration: boolean = false
private _unretrievedOutput = ""
private _continued = false
private _completed = false
private _unretrievedOutput: string = ""
private _continued: boolean = false
private _completed: boolean = false
private _hotTimeout: NodeJS.Timeout | null = null
private _exitWaitTimeout: NodeJS.Timeout | null = null
private readonly manager: AcpTerminalManager
@@ -393,7 +397,7 @@ export class AcpTerminalManager implements ITerminalManager {
private readonly numericIdToStringId: Map<number, string> = new Map()
/** Next numeric ID to assign */
private nextNumericId = 1
private nextNumericId: number = 1
/** Active processes indexed by numeric terminal ID */
private readonly processes: Map<number, AcpTerminalProcess> = new Map()
@@ -402,8 +406,9 @@ export class AcpTerminalManager implements ITerminalManager {
private readonly terminalInfos: Map<number, TerminalInfo> = new Map()
// Configuration options for ITerminalManager
private terminalReuseEnabled = true
private terminalReuseEnabled: boolean = true
private terminalOutputLineLimit: number = DEFAULT_TERMINAL_OUTPUT_LINE_LIMIT
private subagentTerminalOutputLineLimit: number = DEFAULT_SUBAGENT_TERMINAL_OUTPUT_LINE_LIMIT
/**
* Creates a new AcpTerminalManager.
@@ -662,6 +667,14 @@ export class AcpTerminalManager implements ITerminalManager {
this.terminalOutputLineLimit = limit
}
/**
* Set the maximum number of output lines for subagent commands.
* @param limit Maximum number of lines
*/
setSubagentTerminalOutputLineLimit(limit: number): void {
this.subagentTerminalOutputLineLimit = limit
}
/**
* Set the default terminal profile.
* @param profile The profile identifier
@@ -674,10 +687,15 @@ export class AcpTerminalManager implements ITerminalManager {
* Process output lines, potentially truncating if over limit.
* @param outputLines Array of output lines
* @param overrideLimit Optional limit override
* @param isSubagentCommand Whether this is a subagent command
* @returns Processed output string
*/
processOutput(outputLines: string[], overrideLimit?: number): string {
const limit = overrideLimit !== undefined ? overrideLimit : this.terminalOutputLineLimit
processOutput(outputLines: string[], overrideLimit?: number, isSubagentCommand?: boolean): string {
const limit = isSubagentCommand
? overrideLimit !== undefined
? overrideLimit
: this.subagentTerminalOutputLineLimit
: this.terminalOutputLineLimit
if (outputLines.length > limit) {
const halfLimit = Math.floor(limit / 2)
+3 -6
View File
@@ -28,8 +28,6 @@ import {
groqModels,
mistralDefaultModelId,
mistralModels,
moonshotDefaultModelId,
moonshotModels,
openAiCodexDefaultModelId,
openAiNativeDefaultModelId,
openAiNativeModels,
@@ -74,7 +72,6 @@ const providerModels: Record<string, { models: Record<string, unknown>; defaultI
bedrock: { models: bedrockModels, defaultId: bedrockDefaultModelId },
deepseek: { models: deepSeekModels, defaultId: deepSeekDefaultModelId },
mistral: { models: mistralModels, defaultId: mistralDefaultModelId },
moonshot: { models: moonshotModels, defaultId: moonshotDefaultModelId },
groq: { models: groqModels, defaultId: groqDefaultModelId },
xai: { models: xaiModels, defaultId: xaiDefaultModelId },
}
@@ -249,8 +246,8 @@ export class ClineAgent implements acp.Agent {
},
hostBridgeClientProvider,
(message: string) => Logger.info(message),
async (path: string) => {
return AuthHandler.getInstance().getCallbackUrl(path)
async () => {
return AuthHandler.getInstance().getCallbackUrl()
},
async () => "", // get binary location not needed in ACP mode
this.ctx.EXTENSION_DIR,
@@ -976,7 +973,7 @@ export class ClineAgent implements acp.Agent {
// Get the callback URL first to ensure the server is ready
let callbackUrl: string
try {
callbackUrl = await authHandler.getCallbackUrl("/auth")
callbackUrl = await authHandler.getCallbackUrl()
Logger.debug("[ClineAgent] Callback URL ready:", callbackUrl)
} catch (error) {
Logger.error("[ClineAgent] Failed to get callback URL:", error)
-4
View File
@@ -312,10 +312,6 @@ function translateSayMessage(
// API request finished - no specific update needed
break
case "subagent_usage":
// Hidden aggregate metrics event used for task-level accounting.
break
case "task":
// Task started - don't echo the user's prompt back to them
// The ACP client already knows what they typed
+9 -20
View File
@@ -5,13 +5,12 @@
import { Box, Text, useApp, useInput } from "ink"
import Spinner from "ink-spinner"
// biome-ignore lint/style/useImportType: React is used as a value by JSX (jsx: "react" in tsconfig)
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { refreshOcaModels } from "@/core/controller/models/refreshOcaModels"
import { StateManager } from "@/core/storage/StateManager"
import { openAiCodexOAuthManager } from "@/integrations/openai-codex/oauth"
import { AuthService } from "@/services/auth/AuthService"
import { openAiCodexDefaultModelId, openRouterDefaultModelId } from "@/shared/api"
import { StringRequest } from "@/shared/proto/cline/common"
import { liteLlmDefaultModelId, openAiCodexDefaultModelId, openRouterDefaultModelId } from "@/shared/api"
import { openExternal } from "@/utils/env"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
@@ -32,7 +31,6 @@ import {
} from "./FeaturedModelPicker"
import { ImportView } from "./ImportView"
import { getDefaultModelId, hasModelPicker, ModelPicker } from "./ModelPicker"
import { OcaEmployeeCheck } from "./OcaEmployeeCheck"
import { getProviderLabel } from "./ProviderPicker"
type AuthStep =
@@ -45,7 +43,6 @@ type AuthStep =
| "success"
| "error"
| "cline_auth"
| "oca_employee_check"
| "oca_auth"
| "cline_model"
| "openai_codex_auth"
@@ -163,6 +160,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const [modelId, setModelId] = useState("")
const [baseUrl, setBaseUrl] = useState("")
const [errorMessage, setErrorMessage] = useState("")
const [authStatus, setAuthStatus] = useState<string>("")
const [providerSearch, setProviderSearch] = useState("")
const [providerIndex, setProviderIndex] = useState(0)
const [clineModelIndex, setClineModelIndex] = useState(0)
@@ -173,14 +171,11 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
// OCA auth hook - enabled when step is oca_auth
const handleOcaAuthSuccess = useCallback(async () => {
await applyProviderConfig({ providerId: "oca", controller })
// Fetch OCA models from the API - this sets actModeOcaModelId/planModeOcaModelId in state
await refreshOcaModels(controller, StringRequest.create({ value: "" }))
const stateManager = StateManager.get()
stateManager.setGlobalState("welcomeViewCompleted", true)
await stateManager.flushPendingState()
setSelectedProvider("oca")
const actModelId = stateManager.getGlobalSettingsKey("actModeOcaModelId") || ""
setModelId(actModelId)
setModelId(liteLlmDefaultModelId)
setStep("success")
}, [controller])
@@ -322,6 +317,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const startClineAuth = useCallback(async () => {
try {
setStep("cline_auth")
setAuthStatus("Starting authentication...")
await AuthService.getInstance(controller).createAuthRequest()
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : String(error))
@@ -331,6 +327,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const startOcaAuth = useCallback(() => {
setStep("oca_auth")
setAuthStatus("Starting authentication...")
initiateOcaAuth()
}, [initiateOcaAuth])
@@ -361,8 +358,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
(value: string) => {
setSelectedProvider(value)
if (value === "oca") {
// Show employee check screen before starting auth
setStep("oca_employee_check")
startOcaAuth()
} else if (value === "openai-codex") {
setStep("openai_codex_auth")
startOpenAiCodexAuth()
@@ -538,11 +534,8 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
setBaseUrl("")
setStep("modelid")
break
case "oca_employee_check":
setStep("provider")
break
case "oca_auth":
setStep("oca_employee_check")
setStep("provider")
break
case "cline_auth":
setStep("menu")
@@ -646,7 +639,7 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
<Box flexDirection="column">
<Text color="white">Model ID</Text>
<Text> </Text>
<Text color="gray">e.g., claude-sonnet-4-6, gpt-4o</Text>
<Text color="gray">e.g., claude-sonnet-4-20250514, gpt-4o</Text>
<Text> </Text>
<TextInput onChange={setModelId} onSubmit={handleModelIdSubmit} placeholder="model-id" value={modelId} />
<Text> </Text>
@@ -682,9 +675,6 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
</Box>
)
case "oca_employee_check":
return <OcaEmployeeCheck isActive={step === "oca_employee_check"} onCancel={goBack} onSignIn={startOcaAuth} />
case "oca_auth":
case "cline_auth":
return (
@@ -770,7 +760,6 @@ export const AuthView: React.FC<AuthViewProps> = ({ controller, onComplete, onEr
const [menuIndex, setMenuIndex] = useState(0)
// Steps that allow going back with escape (apikey handled by ApiKeyInput component)
// OcaEmployeeCheck handles its own escape key, so oca_employee_check is not in this list
const canGoBack = [
"provider",
"modelid",
+9 -19
View File
@@ -114,11 +114,8 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
// Filtered regions
const filteredRegions = useMemo(() => {
const search = regionSearch.toLowerCase().trim()
if (!search) {
return AWS_REGIONS
}
return AWS_REGIONS.filter((r) => r.toLowerCase().includes(search))
const search = regionSearch.toLowerCase()
return search ? AWS_REGIONS.filter((r) => r.includes(search)) : AWS_REGIONS
}, [regionSearch])
const {
@@ -173,18 +170,10 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
}
}, [step, authMethod, onCancel])
const getSelectedRegion = useCallback(() => {
if (filteredRegions.length > 0 && regionIndex >= 0 && regionIndex < filteredRegions.length) {
return filteredRegions[regionIndex]
}
// If no matches, use the search term as custom region
return regionSearch.trim() || "us-east-1"
}, [filteredRegions, regionIndex, regionSearch])
const finish = useCallback(() => {
const config: BedrockConfig = {
awsAuthentication: authMethod === "default" ? "credentials" : authMethod,
awsRegion: getSelectedRegion(),
awsRegion: filteredRegions[regionIndex] || "us-east-1",
awsUseCrossRegionInference: crossRegion,
}
if (authMethod === "profile") {
@@ -195,7 +184,7 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
if (sessionToken) config.awsSessionToken = sessionToken
}
onComplete(config)
}, [authMethod, profileName, accessKey, secretKey, sessionToken, getSelectedRegion, crossRegion, onComplete])
}, [authMethod, profileName, accessKey, secretKey, sessionToken, filteredRegions, regionIndex, crossRegion, onComplete])
// Handle input for auth_method, region, and options steps
useInput(
@@ -215,11 +204,11 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
} else if (step === "region") {
if (key.escape) {
goBack()
} else if (key.upArrow && filteredRegions.length > 0) {
} else if (key.upArrow) {
setRegionIndex((prev) => (prev > 0 ? prev - 1 : filteredRegions.length - 1))
} else if (key.downArrow && filteredRegions.length > 0) {
} else if (key.downArrow) {
setRegionIndex((prev) => (prev < filteredRegions.length - 1 ? prev + 1 : 0))
} else if (key.return && (filteredRegions.length > 0 || regionSearch.trim())) {
} else if (key.return && filteredRegions.length > 0) {
setStep("options")
} else if (key.backspace || key.delete) {
setRegionSearch((prev) => prev.slice(0, -1))
@@ -341,7 +330,7 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
<Text color="white">AWS Region</Text>
<Text> </Text>
<Box>
<Text color="gray">Search or enter custom region: </Text>
<Text color="gray">Search: </Text>
<Text color="white">{regionSearch}</Text>
<Text inverse> </Text>
</Box>
@@ -361,6 +350,7 @@ export const BedrockSetup: React.FC<BedrockSetupProps> = ({ isActive, onComplete
{showRegionBottom && (
<Text color="gray">... {filteredRegions.length - regionVisibleStart - regionVisibleCount} more below</Text>
)}
{filteredRegions.length === 0 && <Text color="gray">No regions match "{regionSearch}"</Text>}
<Text> </Text>
<Text color="gray">Type to search, arrows to navigate, Enter to select, Esc to go back</Text>
</Box>
-106
View File
@@ -1,106 +0,0 @@
import type { ClineMessage } from "@shared/ExtensionMessage"
import { render } from "ink-testing-library"
import React from "react"
import { describe, expect, it, vi } from "vitest"
import { ChatMessage } from "./ChatMessage"
vi.mock("../hooks/useTerminalSize", () => ({
useTerminalSize: () => ({
columns: 120,
rows: 40,
resizeKey: 0,
}),
}))
describe("ChatMessage subagent rendering", () => {
it("renders subagent approval prompts as a tree", () => {
const message: ClineMessage = {
ts: Date.now(),
type: "ask",
ask: "use_subagents",
text: JSON.stringify({
prompts: [
"Find codebase stats and size",
"Find funny comments and easter eggs",
"Find unusual patterns and history",
],
}),
}
const { lastFrame } = render(React.createElement(ChatMessage, { message, mode: "act" }))
const frame = lastFrame() || ""
expect(frame).toContain("Cline wants to run subagents")
expect(frame).toContain("├─ Find codebase stats and size")
expect(frame).toContain("├─ Find funny comments and easter eggs")
expect(frame).toContain("└─ Find unusual patterns and history")
})
it("renders subagent progress rows with compact token stats and completion checks", () => {
const message: ClineMessage = {
ts: Date.now(),
type: "say",
say: "subagent",
text: JSON.stringify({
status: "running",
total: 3,
completed: 1,
successes: 1,
failures: 0,
toolCalls: 21,
inputTokens: 0,
outputTokens: 0,
contextWindow: 0,
maxContextTokens: 0,
maxContextUsagePercentage: 0,
items: [
{
index: 1,
prompt: "Find codebase stats and size",
status: "completed",
toolCalls: 5,
inputTokens: 0,
outputTokens: 0,
totalCost: 0.034,
contextTokens: 24400,
contextWindow: 200000,
contextUsagePercentage: 12.2,
},
{
index: 2,
prompt: "Find funny comments and easter eggs",
status: "running",
toolCalls: 11,
inputTokens: 0,
outputTokens: 0,
totalCost: 0.056,
contextTokens: 31600,
contextWindow: 200000,
contextUsagePercentage: 15.8,
},
{
index: 3,
prompt: "Find unusual patterns and history",
status: "pending",
toolCalls: 5,
inputTokens: 0,
outputTokens: 0,
totalCost: 0,
contextTokens: 28900,
contextWindow: 200000,
contextUsagePercentage: 14.4,
},
],
}),
}
const { lastFrame } = render(React.createElement(ChatMessage, { isStreaming: true, message, mode: "act" }))
const frame = lastFrame() || ""
expect(frame).toContain("Cline is running subagents")
expect(frame).toContain("✓ Find codebase stats and size")
expect(frame).toContain("5 tool uses · 24.4k tokens · $0.03")
expect(frame).toContain("11 tool uses · 31.6k tokens · $0.06")
expect(frame).toContain("5 tool uses · 28.9k tokens · $0.00")
})
})
+7 -16
View File
@@ -17,7 +17,6 @@ import { useTerminalSize } from "../hooks/useTerminalSize"
import { jsonParseSafe } from "../utils/parser"
import { getToolDescription, isFileEditTool, parseToolFromMessage } from "../utils/tools"
import { DiffView } from "./DiffView"
import { SubagentMessage } from "./SubagentMessage"
/**
* Add "(Tab)" hint after "Act mode" mentions.
@@ -25,7 +24,7 @@ import { SubagentMessage } from "./SubagentMessage"
* Matches just "Act mode" without requiring "to " prefix because markdown
* processing may split "toggle to **Act mode**" into separate text chunks.
*/
function addActModeHint(text: string, keyPrefix: string): React.ReactNode[] {
function addActModeHint(text: string): React.ReactNode[] {
// Match "Act mode" in various capitalizations, but not if already followed by (Tab)
const actModeRegex = /\bact\s+mode\b(?!\s*\(tab\))/gi
const parts = text.split(actModeRegex)
@@ -42,7 +41,7 @@ function addActModeHint(text: string, keyPrefix: string): React.ReactNode[] {
}
if (matches[i]) {
nodes.push(
<React.Fragment key={`${keyPrefix}-act-mode-${i}`}>
<React.Fragment key={`act-mode-${i}`}>
{matches[i]}
<Text color="gray"> (Tab)</Text>
</React.Fragment>,
@@ -60,8 +59,6 @@ function addActModeHint(text: string, keyPrefix: string): React.ReactNode[] {
*/
function renderInlineMarkdown(text: string): React.ReactNode[] {
const nodes: React.ReactNode[] = []
let hintCallIndex = 0
const addHintedText = (value: string) => addActModeHint(value, `hint-${hintCallIndex++}`)
// Match **bold**, *italic*, or `code` - order matters (** before *)
const regex = /(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`)/g
let lastIndex = 0
@@ -71,7 +68,7 @@ function renderInlineMarkdown(text: string): React.ReactNode[] {
// Add text before match (with Act Mode hint processing)
if (match.index > lastIndex) {
const beforeText = text.slice(lastIndex, match.index)
nodes.push(...addHintedText(beforeText))
nodes.push(...addActModeHint(beforeText))
}
const fullMatch = match[0]
@@ -80,7 +77,7 @@ function renderInlineMarkdown(text: string): React.ReactNode[] {
if (fullMatch.startsWith("**") && fullMatch.endsWith("**")) {
// Bold - also process for Act Mode hints inside bold text
const boldContent = fullMatch.slice(2, -2)
const hintedContent = addHintedText(boldContent)
const hintedContent = addActModeHint(boldContent)
nodes.push(
<Text bold key={key}>
{hintedContent}
@@ -103,10 +100,10 @@ function renderInlineMarkdown(text: string): React.ReactNode[] {
// Add remaining text (with Act Mode hint processing)
if (lastIndex < text.length) {
nodes.push(...addHintedText(text.slice(lastIndex)))
nodes.push(...addActModeHint(text.slice(lastIndex)))
}
return nodes.length > 0 ? nodes : addHintedText(text)
return nodes.length > 0 ? nodes : addActModeHint(text)
}
/**
@@ -227,7 +224,7 @@ function truncate(text: string, maxLength: number): string {
/**
* Format tool result for display
*/
function formatToolResult(result: string, maxLines = 5): string[] {
function formatToolResult(result: string, maxLines: number = 5): string[] {
const lines = result.split("\n")
if (lines.length <= maxLines) {
return lines
@@ -449,10 +446,6 @@ export const ChatMessage: React.FC<ChatMessageProps> = ({ message, mode, isStrea
)
}
if ((type === "ask" && ask === "use_subagents") || say === "use_subagents" || say === "subagent") {
return <SubagentMessage isStreaming={isStreaming} message={message} mode={mode} />
}
// MCP response
if (say === "mcp_server_response" && text) {
const lines = formatToolResult(text, 8)
@@ -807,8 +800,6 @@ export const ChatMessageList: React.FC<ChatMessageListProps> = ({ messages, maxM
const displayMessages = messages.filter((m) => {
// Skip api_req_finished, they're just markers
if (m.say === "api_req_finished") return false
// Skip hidden aggregated usage messages
if (m.say === "subagent_usage") return false
// Skip empty text messages
if (m.say === "text" && !m.text?.trim()) return false
// Skip checkpoint messages
+5 -80
View File
@@ -150,28 +150,9 @@ import { HighlightedInput } from "./HighlightedInput"
import { HistoryPanelContent } from "./HistoryPanelContent"
import { providerModels } from "./ModelPicker"
import { SettingsPanelContent } from "./SettingsPanelContent"
import { SkillsPanelContent } from "./SkillsPanelContent"
import { SlashCommandMenu } from "./SlashCommandMenu"
import { ThinkingIndicator } from "./ThinkingIndicator"
/**
* Persistent input storage that survives React remounts (e.g., during terminal resize).
* Keyed by a stable identifier so each task/session maintains its own input state.
*/
interface PersistedInputState {
text: string
cursorPos: number
pastedTexts: Map<number, string>
pasteCounter: number
}
const inputStateStorage = new Map<string, PersistedInputState>()
function getInputStorageKey(controller: any, taskId?: string): string {
// Use taskId if available, otherwise fall back to controller instance
return taskId || (controller?.task?.taskId ?? "default")
}
interface ChatViewProps {
controller?: any
onExit?: () => void
@@ -370,9 +351,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
insertText: insertTextAtCursor,
} = useTextInput()
// Get storage key for persisting input across remounts
const storageKey = useMemo(() => getInputStorageKey(ctrl, taskId), [ctrl, taskId])
// Refs for text input and cursor position (used by useHomeEndKeys and to avoid stale closures in useInput)
const textInputRef = useRef(textInput)
textInputRef.current = textInput
@@ -389,10 +367,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
const [userScrolled, setUserScrolled] = useState(false)
// Pasted text storage - maps placeholder number to full pasted content
const [pastedTexts, setPastedTexts] = useState<Map<number, string>>(() => {
return inputStateStorage.get(storageKey)?.pastedTexts ?? new Map()
})
const pasteCounterRef = useRef<number>(inputStateStorage.get(storageKey)?.pasteCounter ?? 0)
const [pastedTexts, setPastedTexts] = useState<Map<number, string>>(new Map())
const pasteCounterRef = useRef(0)
// Track paste timing to combine chunks that arrive in rapid succession
const lastPasteTimeRef = useRef<number>(0)
const activePasteNumRef = useRef<number>(0)
@@ -413,7 +389,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
| { type: "settings"; initialMode?: "model-picker" | "featured-models"; initialModelKey?: "actModelId" | "planModelId" }
| { type: "history" }
| { type: "help" }
| { type: "skills" }
| null
>(null)
@@ -427,29 +402,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
// Track when we're exiting to hide UI elements before exit
const [isExiting, setIsExiting] = useState(false)
// Restore input state from storage on mount (after resize remount)
useEffect(() => {
const stored = inputStateStorage.get(storageKey)
if (stored) {
setTextInput(stored.text)
setCursorPos(stored.cursorPos)
setPastedTexts(stored.pastedTexts)
pasteCounterRef.current = stored.pasteCounter
}
}, [storageKey, setTextInput, setCursorPos])
// Persist input state to storage whenever it changes (survives remount)
useEffect(() => {
if (textInput || pastedTexts.size > 0) {
inputStateStorage.set(storageKey, {
text: textInput,
cursorPos,
pastedTexts: new Map(pastedTexts),
pasteCounter: pasteCounterRef.current,
})
}
}, [storageKey, textInput, cursorPos, pastedTexts])
// Task switch handling: when switching tasks via /history, we clear the terminal and
// increment a counter used as the root Box's key. This forces React to remount the tree,
// giving us a fresh Static instance. Mirrors how App.tsx handles resize with resizeKey.
@@ -542,14 +494,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
clearState() // Force clear React state (bypasses empty messages check)
setTextInput("")
setCursorPos(0)
// Clear persisted state
inputStateStorage.delete(storageKey)
// Post the now-empty state
if (ctrl) {
ctrl.postStateToWebview()
}
}, [ctrl, clearState, storageKey])
}, [ctrl, clearState])
const refs = useRef({
searchTimeout: null as NodeJS.Timeout | null,
@@ -810,8 +760,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
setCursorPos(0)
setPastedTexts(new Map()) // Clear stored pastes
pasteCounterRef.current = 0
// Clear persisted state
inputStateStorage.delete(storageKey)
try {
await ctrl.task.handleWebviewAskResponse(responseType, expandedText)
@@ -819,7 +767,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
// Controller may be disposed
}
},
[ctrl, pendingAsk, pastedTexts, storageKey],
[ctrl, pendingAsk, pastedTexts],
)
// Handle cancel/interrupt
@@ -910,8 +858,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
setCursorPos(0)
setPastedTexts(new Map()) // Clear stored pastes
pasteCounterRef.current = 0
// Clear persisted state
inputStateStorage.delete(storageKey)
try {
// Convert image paths to data URLs if needed
@@ -939,7 +885,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
onError?.()
}
},
[ctrl, onError, pastedTexts, storageKey],
[ctrl, onError, pastedTexts],
)
// Auto-submit initial prompt if provided
@@ -1158,14 +1104,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
setSlashMenuDismissed(true)
return
}
if (cmd.name === "skills") {
setActivePanel({ type: "skills" })
setTextInput("")
setCursorPos(0)
setSelectedSlashIndex(0)
setSlashMenuDismissed(true)
return
}
if (cmd.name === "clear") {
clearViewAndResetTask()
setSelectedSlashIndex(0)
@@ -1555,19 +1493,6 @@ export const ChatView: React.FC<ChatViewProps> = ({
{/* Help panel */}
{activePanel?.type === "help" && <HelpPanelContent onClose={() => setActivePanel(null)} />}
{/* Skills panel */}
{activePanel?.type === "skills" && ctrl && (
<SkillsPanelContent
controller={ctrl}
onClose={() => setActivePanel(null)}
onUseSkill={(skillPath) => {
setActivePanel(null)
setTextInput(`@${skillPath} `)
setCursorPos(skillPath.length + 2)
}}
/>
)}
{/* Slash command menu - below input (takes priority over file menu) */}
{showSlashMenu && !activePanel && (
<Box paddingLeft={1} paddingRight={1}>
+18 -124
View File
@@ -13,7 +13,6 @@ import {
import { Box, Text, useApp, useInput } from "ink"
import React, { useMemo, useState } from "react"
import { useStdinContext } from "../context/StdinContext"
import { fuzzyFilter } from "../utils/fuzzy-search"
import {
BooleanSelect,
buildConfigEntries,
@@ -22,8 +21,6 @@ import {
HookInfo,
HookRow,
MAX_VISIBLE,
ObjectEditorPanel,
ObjectEditorState,
parseValue,
SEPARATOR,
SectionHeader,
@@ -108,8 +105,6 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
const [isEditing, setIsEditing] = useState(false)
const [selectedIndex, setSelectedIndex] = useState(0)
const [editValue, setEditValue] = useState("")
const [searchQuery, setSearchQuery] = useState("")
const [objectEditor, setObjectEditor] = useState<ObjectEditorState | null>(null)
// Build entries for settings tab
const configEntries = useMemo(
@@ -117,13 +112,6 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
[globalState, workspaceState],
)
const filteredConfigEntries = useMemo(() => {
if (!searchQuery.trim()) {
return configEntries
}
return fuzzyFilter(configEntries, searchQuery, (entry) => `${entry.key} ${String(entry.value ?? "")}`)
}, [configEntries, searchQuery])
// Build entries for rules tab
const ruleEntries = useMemo(() => {
const entries: ToggleEntry[] = []
@@ -171,7 +159,7 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
const currentListLength = useMemo(() => {
switch (currentTab) {
case "settings":
return filteredConfigEntries.length
return configEntries.length
case "rules":
return ruleEntries.length
case "workflows":
@@ -183,14 +171,7 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
default:
return 0
}
}, [
currentTab,
filteredConfigEntries.length,
ruleEntries.length,
workflowEntries.length,
hookEntries.length,
skillEntries.length,
])
}, [currentTab, configEntries.length, ruleEntries.length, workflowEntries.length, hookEntries.length, skillEntries.length])
// Get available tabs
const availableTabs = useMemo(() => {
@@ -210,11 +191,10 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
setCurrentTab(newTab)
setSelectedIndex(0)
setIsEditing(false)
setObjectEditor(null)
}
// Settings tab handlers
const selectedConfigEntry = filteredConfigEntries[selectedIndex]
const selectedConfigEntry = configEntries[selectedIndex]
const handleSettingsSave = (value: string | boolean) => {
if (!selectedConfigEntry) {
@@ -230,43 +210,6 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
setIsEditing(false)
}
const getObjectAtPath = (root: Record<string, unknown>, path: string[]): Record<string, unknown> => {
let current: unknown = root
for (const segment of path) {
if (!current || typeof current !== "object") {
return {}
}
current = (current as Record<string, unknown>)[segment]
}
return current && typeof current === "object" ? (current as Record<string, unknown>) : {}
}
const setObjectValueAtPath = (
root: Record<string, unknown>,
path: string[],
key: string,
value: unknown,
): Record<string, unknown> => {
if (path.length === 0) {
return { ...root, [key]: value }
}
const [head, ...rest] = path
const child = root[head]
const childObj = child && typeof child === "object" ? (child as Record<string, unknown>) : {}
return {
...root,
[head]: setObjectValueAtPath(childObj, rest, key, value),
}
}
const persistObjectEditor = (nextObject: Record<string, unknown>, source: "global" | "workspace", key: string) => {
if (source === "global" && onUpdateGlobal) {
onUpdateGlobal(key as GlobalStateAndSettingsKey, nextObject as never)
} else if (source === "workspace" && onUpdateWorkspace) {
onUpdateWorkspace(key as LocalStateKey, nextObject as never)
}
}
const handleSettingsReset = () => {
if (!selectedConfigEntry?.isEditable || selectedConfigEntry.source !== "global") {
return
@@ -297,22 +240,15 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
// Input handling
useInput(
(input, key) => {
if (objectEditor) {
return
}
if (key.escape) {
if (input.toLowerCase() === "q" || key.escape) {
exit()
}
if (key.leftArrow || key.rightArrow || (input >= "1" && input <= "5")) {
const currentTabIndex = availableTabs.findIndex((t) => t.key === currentTab)
const targetIdx =
input >= "1" && input <= "5"
? Number.parseInt(input) - 1
: key.leftArrow
? (currentTabIndex - 1 + availableTabs.length) % availableTabs.length
: (currentTabIndex + 1) % availableTabs.length
// Tab navigation with Tab key or number keys
if (key.tab || (input >= "1" && input <= "5")) {
const targetIdx = key.tab
? (availableTabs.findIndex((t) => t.key === currentTab) + 1) % availableTabs.length
: parseInt(input) - 1
if (targetIdx >= 0 && targetIdx < availableTabs.length) {
handleTabChange(availableTabs[targetIdx].key)
}
@@ -320,45 +256,21 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
}
// List navigation (arrow keys and vim-style j/k)
if (key.upArrow) {
if (key.upArrow || input === "k") {
setSelectedIndex((i) => (i > 0 ? i - 1 : currentListLength - 1))
} else if (key.downArrow) {
} else if (key.downArrow || input === "j") {
setSelectedIndex((i) => (i < currentListLength - 1 ? i + 1 : 0))
}
// Tab-specific actions
if (currentTab === "settings") {
if ((key.return || key.tab) && selectedConfigEntry?.isEditable) {
if (selectedConfigEntry.type === "boolean") {
handleSettingsSave(!selectedConfigEntry.value)
return
}
if (selectedConfigEntry.type === "object") {
const value =
selectedConfigEntry.value && typeof selectedConfigEntry.value === "object"
? (selectedConfigEntry.value as Record<string, unknown>)
: {}
setObjectEditor({
source: selectedConfigEntry.source,
key: selectedConfigEntry.key,
path: [],
value,
selectedIndex: 0,
isEditingValue: false,
editValue: "",
})
return
}
if ((key.return || input === "e") && selectedConfigEntry?.isEditable) {
setEditValue(selectedConfigEntry.value !== undefined ? String(selectedConfigEntry.value) : "")
setIsEditing(true)
} else if (key.ctrl && input.toLowerCase() === "r") {
} else if (input === "r") {
handleSettingsReset()
} else if (key.backspace || key.delete) {
setSearchQuery((prev) => prev.slice(0, -1))
} else if (input && !key.ctrl && !key.meta && !key.escape && !key.upArrow && !key.downArrow) {
setSearchQuery((prev) => prev + input)
}
} else if (key.return || key.tab || input === " ") {
} else if (key.return || input === " ") {
// Toggle for rules/workflows/hooks/skills
handleToggle()
}
@@ -426,31 +338,13 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
)
}
if (objectEditor && currentTab === "settings") {
return (
<ObjectEditorPanel
getObjectAtPath={getObjectAtPath}
onClose={() => setObjectEditor(null)}
onPersist={(nextObject) => persistObjectEditor(nextObject, objectEditor.source, objectEditor.key)}
setObjectValueAtPath={setObjectValueAtPath}
setState={setObjectEditor}
state={objectEditor}
/>
)
}
// Render tab content
const renderTabContent = () => {
switch (currentTab) {
case "settings": {
const visibleEntries = filteredConfigEntries.slice(startIndex, startIndex + MAX_VISIBLE)
const visibleEntries = configEntries.slice(startIndex, startIndex + MAX_VISIBLE)
return (
<React.Fragment>
<Box>
<Text>Search: </Text>
<Text color="white">{searchQuery}</Text>
<Text inverse> </Text>
</Box>
<Box>
<Text>Data directory: </Text>
<Text color="blue" underline>
@@ -613,12 +507,12 @@ export const ConfigView: React.FC<ConfigViewProps> = ({
// Help text based on current tab
const getHelpText = () => {
const base = "↑/↓ Navigate • ←/→ tabs • 1-5 tabs • Esc Exit"
const base = "↑/↓/j/k Navigate • Tab/1-5 Switch tabs • q/Esc Exit"
if (currentTab === "settings") {
return `${base} Type to search • Enter/Tab Edit (booleans toggle) • Backspace clear search • Ctrl+R Reset`
return `${base} • Enter/e Edit • r Reset`
}
const openFolder = onOpenFolder ? " • o Open folder" : ""
return `${base} • Enter/Tab/Space Toggle${openFolder}`
return `${base} • Enter/Space Toggle${openFolder}`
}
return (
+11 -180
View File
@@ -46,19 +46,16 @@ export interface SkillInfo {
enabled: boolean
}
export interface ObjectEditorState {
source: "global" | "workspace"
key: string
path: string[]
value: Record<string, unknown>
selectedIndex: number
isEditingValue: boolean
editValue: string
}
export const EXCLUDED_KEYS = new Set([
"taskHistory",
"primaryRootIndex",
"subagentsEnabled",
"subagentTerminalOutputLineLimit",
"welcomeViewCompleted",
"isNewUser",
])
export const EXCLUDED_KEYS = new Set(["taskHistory", "primaryRootIndex", "welcomeViewCompleted", "isNewUser"])
export const EDITABLE_TYPES: Set<ValueType> = new Set(["string", "number", "boolean", "object"])
export const EDITABLE_TYPES: Set<ValueType> = new Set(["string", "number", "boolean"])
export const MAX_VISIBLE = 12
export const SEPARATOR = "─".repeat(80)
@@ -138,7 +135,7 @@ export function parseValue(input: string, type: ValueType): unknown {
return input.toLowerCase() === "true" || input === "1"
}
if (type === "number") {
const num = Number.parseFloat(input)
const num = parseFloat(input)
return Number.isNaN(num) ? 0 : num
}
if (type === "object") {
@@ -220,7 +217,7 @@ export const TextInput: React.FC<TextInputProps> = ({ label, onChange, onCancel,
</Text>
<Box>
<Text color="white">{value}</Text>
<Text color="cyan">|</Text>
<Text inverse> </Text>
</Box>
<Text color="gray">Type: {type} Enter to save Esc to cancel</Text>
</Box>
@@ -382,169 +379,3 @@ export const SectionHeader: React.FC<{ title: string }> = ({ title }) => (
</Text>
</Box>
)
interface ObjectEditorPanelProps {
state: ObjectEditorState
setState: React.Dispatch<React.SetStateAction<ObjectEditorState | null>>
onClose: () => void
onPersist: (nextObject: Record<string, unknown>) => void
getObjectAtPath: (root: Record<string, unknown>, path: string[]) => Record<string, unknown>
setObjectValueAtPath: (root: Record<string, unknown>, path: string[], key: string, value: unknown) => Record<string, unknown>
}
export const ObjectEditorPanel: React.FC<ObjectEditorPanelProps> = ({
state,
setState,
onClose,
onPersist,
getObjectAtPath,
setObjectValueAtPath,
}) => {
const { isRawModeSupported } = useStdinContext()
const currentNode = getObjectAtPath(state.value, state.path)
const objectEntries = Object.entries(currentNode).sort(([a], [b]) => a.localeCompare(b))
const selectedEntry = objectEntries[state.selectedIndex]
const breadcrumb = [state.key, ...state.path].join(" ")
useInput(
(input, key) => {
if (state.isEditingValue) {
if (key.escape) {
setState((prev) => (prev ? { ...prev, isEditingValue: false, editValue: "" } : prev))
return
}
if (key.return) {
if (!selectedEntry) {
setState((prev) => (prev ? { ...prev, isEditingValue: false, editValue: "" } : prev))
return
}
const [entryKey, entryValue] = selectedEntry
let parsed: unknown = state.editValue
if (typeof entryValue === "boolean") {
parsed = state.editValue.toLowerCase() === "true" || state.editValue === "1"
} else if (typeof entryValue === "number") {
const maybeNum = Number(state.editValue)
parsed = Number.isNaN(maybeNum) ? 0 : maybeNum
}
const nextObject = setObjectValueAtPath(state.value, state.path, entryKey, parsed)
onPersist(nextObject)
setState((prev) => (prev ? { ...prev, value: nextObject, isEditingValue: false, editValue: "" } : prev))
return
}
if (key.backspace || key.delete) {
setState((prev) => (prev ? { ...prev, editValue: prev.editValue.slice(0, -1) } : prev))
return
}
if (input && !key.ctrl && !key.meta) {
setState((prev) => (prev ? { ...prev, editValue: prev.editValue + input } : prev))
}
return
}
if (key.escape) {
if (state.path.length > 0) {
setState((prev) => (prev ? { ...prev, path: prev.path.slice(0, -1), selectedIndex: 0 } : prev))
} else {
onClose()
}
return
}
if (key.upArrow || input === "k") {
setState((prev) =>
prev
? {
...prev,
selectedIndex:
objectEntries.length > 0
? prev.selectedIndex > 0
? prev.selectedIndex - 1
: objectEntries.length - 1
: 0,
}
: prev,
)
return
}
if (key.downArrow || input === "j") {
setState((prev) =>
prev
? {
...prev,
selectedIndex:
objectEntries.length > 0
? prev.selectedIndex < objectEntries.length - 1
? prev.selectedIndex + 1
: 0
: 0,
}
: prev,
)
return
}
if (key.return || key.tab) {
if (!selectedEntry) {
return
}
const [entryKey, entryValue] = selectedEntry
if (typeof entryValue === "boolean") {
const nextObject = setObjectValueAtPath(state.value, state.path, entryKey, !entryValue)
onPersist(nextObject)
setState((prev) => (prev ? { ...prev, value: nextObject } : prev))
return
}
if (entryValue && typeof entryValue === "object" && !Array.isArray(entryValue)) {
setState((prev) => (prev ? { ...prev, path: [...prev.path, entryKey], selectedIndex: 0 } : prev))
return
}
setState((prev) =>
prev
? { ...prev, isEditingValue: true, editValue: entryValue !== undefined ? String(entryValue) : "" }
: prev,
)
}
},
{ isActive: isRawModeSupported },
)
return (
<Box flexDirection="column">
<Text bold color="white">
Edit Nested Object
</Text>
<Text color="gray">{SEPARATOR}</Text>
<Text color="cyan">{breadcrumb}</Text>
{state.isEditingValue ? (
<Box flexDirection="column" marginTop={1}>
<Box>
<Text color="white">{state.editValue}</Text>
<Text color="cyan">|</Text>
</Box>
<Text color="gray">Enter to save Esc to cancel</Text>
</Box>
) : (
<Box flexDirection="column" marginTop={1}>
{objectEntries.length === 0 ? (
<Text color="gray">No nested keys at this level.</Text>
) : (
objectEntries.map(([key, value], idx) => {
const isSelected = idx === state.selectedIndex
const valueText =
value && typeof value === "object" && !Array.isArray(value) ? "{...}" : String(value)
return (
<Text color={isSelected ? "cyan" : undefined} key={key}>
{isSelected ? " " : " "}
<Text color="cyan">{key}</Text>
<Text color="gray">: </Text>
<Text color="white">{valueText}</Text>
</Text>
)
})
)}
<Text color="gray">/ Navigate Enter/Tab Edit or drill in Esc Back/Close</Text>
</Box>
)}
</Box>
)
}
+2 -2
View File
@@ -39,7 +39,7 @@ export const FeaturedModelPicker: React.FC<FeaturedModelPickerProps> = ({
const isSelected = i === selectedIndex
return (
<Box flexDirection="column" key={`${model.id}-${model.labels[0] || "default"}`} marginBottom={1}>
<Box flexDirection="column" key={model.id} marginBottom={1}>
<Box>
<Text color={isSelected ? COLORS.primaryBlue : undefined}>{isSelected ? " " : " "}</Text>
<Text bold color={isSelected ? COLORS.primaryBlue : "white"}>
@@ -81,7 +81,7 @@ export const FeaturedModelPicker: React.FC<FeaturedModelPickerProps> = ({
* Get the maximum valid index for the featured model picker
* (includes "Browse all" option if showBrowseAll is true)
*/
export function getFeaturedModelMaxIndex(showBrowseAll = true): number {
export function getFeaturedModelMaxIndex(showBrowseAll: boolean = true): number {
const featuredModels = getAllFeaturedModels()
return showBrowseAll ? featuredModels.length : featuredModels.length - 1
}
-24
View File
@@ -43,30 +43,6 @@ export const HelpPanelContent: React.FC<HelpPanelContentProps> = ({ onClose }) =
</Text>
</Box>
<Box flexDirection="column">
<Text bold>Keyboard Shortcuts</Text>
<Text>
{" "}
<Text color="white">Ctrl+U</Text> - Clear entire input (delete to start)
</Text>
<Text>
{" "}
<Text color="white">Ctrl+K</Text> - Delete from cursor to end
</Text>
<Text>
{" "}
<Text color="white">Ctrl+W</Text> - Delete word backwards
</Text>
<Text>
{" "}
<Text color="white">Ctrl+A / Ctrl+E</Text> - Jump to start / end of input
</Text>
<Text>
{" "}
<Text color="white">Alt/Option+/</Text> - Move by word
</Text>
</Box>
<Box flexDirection="column">
<Text bold>Slash Commands</Text>
<Text>
+4 -18
View File
@@ -6,7 +6,6 @@
import { Box, Text } from "ink"
import Spinner from "ink-spinner"
import React, { useEffect, useMemo, useState } from "react"
import { refreshOcaModels } from "@/core/controller/models/refreshOcaModels"
import { refreshOpenRouterModels } from "@/core/controller/models/refreshOpenRouterModels"
import {
type ApiProvider,
@@ -65,7 +64,6 @@ import {
xaiDefaultModelId,
xaiModels,
} from "@/shared/api"
import { StringRequest } from "@/shared/proto/cline/common"
import { filterOpenRouterModelIds } from "@/shared/utils/model-filters"
import { COLORS } from "../constants/colors"
import { getOpenRouterDefaultModelId, usesOpenRouterModels } from "../utils/openrouter-models"
@@ -107,7 +105,7 @@ export function hasStaticModels(provider: string): boolean {
}
export function hasModelPicker(provider: string): boolean {
return hasStaticModels(provider) || usesOpenRouterModels(provider) || provider === "oca"
return hasStaticModels(provider) || usesOpenRouterModels(provider)
}
export function getDefaultModelId(provider: string): string {
@@ -134,7 +132,7 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ provider, controller,
const [isLoading, setIsLoading] = useState(false)
const [asyncModels, setAsyncModels] = useState<string[]>([])
// Fetch async models (OpenRouter or OCA) when needed
// Fetch OpenRouter models when needed using shared core function
useEffect(() => {
if (usesOpenRouterModels(provider)) {
setIsLoading(true)
@@ -147,23 +145,11 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ provider, controller,
.finally(() => {
setIsLoading(false)
})
} else if (provider === "oca") {
setIsLoading(true)
refreshOcaModels(controller, StringRequest.create({ value: "" }))
.then((result) => {
if (result.models) {
const modelIds = Object.keys(result.models).sort((a, b) => a.localeCompare(b))
setAsyncModels(modelIds)
}
})
.finally(() => {
setIsLoading(false)
})
}
}, [provider, controller])
const modelList = useMemo(() => {
if (usesOpenRouterModels(provider) || provider === "oca") {
if (usesOpenRouterModels(provider)) {
return asyncModels
}
return getModelList(provider)
@@ -194,7 +180,7 @@ export const ModelPicker: React.FC<ModelPickerProps> = ({ provider, controller,
}
// If async fetch returned no models, render nothing
if ((usesOpenRouterModels(provider) || provider === "oca") && modelList.length === 0) {
if (usesOpenRouterModels(provider) && modelList.length === 0) {
return null
}
-88
View File
@@ -1,88 +0,0 @@
/**
* OCA (Oracle Cloud Assist) employee check component.
* Shows a checkbox for "I'm an Oracle Employee" and a sign-in button.
* Sets ocaMode in state before triggering the OAuth flow.
*/
import { Box, Text, useInput } from "ink"
// biome-ignore lint/style/useImportType: React is used as a value by JSX (jsx: "react" in tsconfig)
import React, { useCallback, useState } from "react"
import { StateManager } from "@/core/storage/StateManager"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
interface OcaEmployeeCheckProps {
/** Whether this component is active and should handle input */
isActive: boolean
/** Called when user confirms and wants to proceed with sign-in */
onSignIn: () => void
/** Called when user presses Escape to go back */
onCancel: () => void
}
export const OcaEmployeeCheck: React.FC<OcaEmployeeCheckProps> = ({ isActive, onSignIn, onCancel }) => {
const { isRawModeSupported } = useStdinContext()
const [isEmployee, setIsEmployee] = useState(true) // Default to checked (internal), matching extension behavior
const [selectedIndex, setSelectedIndex] = useState(0) // 0 = checkbox, 1 = sign in button
const ITEM_COUNT = 2
const handleSignIn = useCallback(async () => {
// Persist ocaMode to state before starting auth
const stateManager = StateManager.get()
stateManager.setGlobalState("ocaMode", isEmployee ? "internal" : "external")
await stateManager.flushPendingState()
onSignIn()
}, [isEmployee, onSignIn])
useInput(
(_input, key) => {
if (key.escape) {
onCancel()
return
}
if (key.upArrow) {
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : ITEM_COUNT - 1))
} else if (key.downArrow) {
setSelectedIndex((prev) => (prev < ITEM_COUNT - 1 ? prev + 1 : 0))
} else if (key.tab || (key.return && selectedIndex === 0)) {
// Toggle checkbox when Tab is pressed or Enter on checkbox item
if (selectedIndex === 0) {
setIsEmployee((prev) => !prev)
}
} else if (key.return && selectedIndex === 1) {
// Sign in button
handleSignIn()
}
},
{ isActive: isRawModeSupported && isActive },
)
return (
<Box flexDirection="column">
<Text color="white">Oracle Code Assist</Text>
<Text> </Text>
{/* Checkbox: I'm an Oracle Employee */}
<Text>
<Text bold color={selectedIndex === 0 ? COLORS.primaryBlue : undefined}>
{selectedIndex === 0 ? "" : " "}{" "}
</Text>
<Text color={selectedIndex === 0 || isEmployee ? COLORS.primaryBlue : "gray"}>{isEmployee ? "[✓]" : "[ ]"}</Text>
<Text color={selectedIndex === 0 ? COLORS.primaryBlue : "white"}> I'm an Oracle Employee</Text>
{selectedIndex === 0 && <Text color="gray"> (Tab to toggle)</Text>}
</Text>
{/* Sign in button */}
<Text>
<Text bold color={selectedIndex === 1 ? COLORS.primaryBlue : undefined}>
{selectedIndex === 1 ? "" : " "}{" "}
</Text>
<Text color={selectedIndex === 1 ? COLORS.primaryBlue : "white"}>Sign in with Oracle Code Assist</Text>
{selectedIndex === 1 && <Text color="gray"> (Enter)</Text>}
</Text>
<Text> </Text>
<Text color="gray">Please ask your IT administrator to set up Oracle Code Assist as a model provider.</Text>
<Text> </Text>
<Text color="gray">Arrows to navigate, Tab to toggle, Enter to continue, Esc to go back</Text>
</Box>
)
}
+3 -29
View File
@@ -14,12 +14,10 @@ import Spinner from "ink-spinner"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { buildApiHandler } from "@/core/api"
import type { Controller } from "@/core/controller"
import { refreshOcaModels } from "@/core/controller/models/refreshOcaModels"
import { StateManager } from "@/core/storage/StateManager"
import { openAiCodexOAuthManager } from "@/integrations/openai-codex/oauth"
import { ClineAccountService } from "@/services/account/ClineAccountService"
import { AuthService, ClineAccountOrganization } from "@/services/auth/AuthService"
import { StringRequest } from "@/shared/proto/cline/common"
import { openExternal } from "@/utils/env"
import { supportsReasoningEffortForModel } from "@/utils/model-utils"
import { version as CLI_VERSION } from "../../package.json"
@@ -39,7 +37,6 @@ import {
} from "./FeaturedModelPicker"
import { LanguagePicker } from "./LanguagePicker"
import { hasModelPicker, ModelPicker } from "./ModelPicker"
import { OcaEmployeeCheck } from "./OcaEmployeeCheck"
import { OrganizationPicker } from "./OrganizationPicker"
import { Panel, PanelTab } from "./Panel"
import { getProviderLabel, ProviderPicker } from "./ProviderPicker"
@@ -85,12 +82,6 @@ const TABS: PanelTab[] = [
// Settings configuration for simple boolean toggles
const FEATURE_SETTINGS = {
subagents: {
stateKey: "subagentsEnabled",
default: false,
label: "Subagents",
description: "Let Cline run focused subagents in parallel to explore the codebase for you",
},
autoCondense: {
stateKey: "useAutoCondense",
default: false,
@@ -165,7 +156,6 @@ export const SettingsPanelContent: React.FC<SettingsPanelContentProps> = ({
const [isEnteringApiKey, setIsEnteringApiKey] = useState(false)
const [isConfiguringBedrock, setIsConfiguringBedrock] = useState(false)
const [isWaitingForCodexAuth, setIsWaitingForCodexAuth] = useState(false)
const [isShowingOcaEmployeeCheck, setIsShowingOcaEmployeeCheck] = useState(false)
const [codexAuthError, setCodexAuthError] = useState<string | null>(null)
const [pendingProvider, setPendingProvider] = useState<string | null>(null)
const [apiKeyValue, setApiKeyValue] = useState("")
@@ -239,8 +229,6 @@ export const SettingsPanelContent: React.FC<SettingsPanelContentProps> = ({
// OCA auth hook
const handleOcaAuthSuccess = useCallback(async () => {
await applyProviderConfig({ providerId: "oca", controller })
// Fetch OCA models from the API - this sets actModeOcaModelId/planModeOcaModelId in state
await refreshOcaModels(controller!, StringRequest.create({ value: "" }))
setProvider("oca")
refreshModelIds()
}, [controller, refreshModelIds])
@@ -1084,8 +1072,8 @@ export const SettingsPanelContent: React.FC<SettingsPanelContentProps> = ({
setProvider("oca")
refreshModelIds()
} else {
// Not logged in - show employee check before auth
setIsShowingOcaEmployeeCheck(true)
// Not logged in - trigger OAuth
startOcaAuth()
}
return
}
@@ -1376,7 +1364,7 @@ export const SettingsPanelContent: React.FC<SettingsPanelContentProps> = ({
return
}
},
{ isActive: isRawModeSupported && !isEnteringApiKey && !isConfiguringBedrock && !isShowingOcaEmployeeCheck },
{ isActive: isRawModeSupported && !isEnteringApiKey && !isConfiguringBedrock },
)
// Render content
@@ -1552,19 +1540,6 @@ export const SettingsPanelContent: React.FC<SettingsPanelContentProps> = ({
)
}
if (isShowingOcaEmployeeCheck) {
return (
<OcaEmployeeCheck
isActive={isShowingOcaEmployeeCheck}
onCancel={() => setIsShowingOcaEmployeeCheck(false)}
onSignIn={() => {
setIsShowingOcaEmployeeCheck(false)
startOcaAuth()
}}
/>
)
}
if (isWaitingForOcaAuth) {
return (
<Box flexDirection="column">
@@ -1746,7 +1721,6 @@ export const SettingsPanelContent: React.FC<SettingsPanelContentProps> = ({
!!codexAuthError ||
isPickingOrganization ||
isWaitingForClineAuth ||
isShowingOcaEmployeeCheck ||
isWaitingForOcaAuth ||
isEditing
@@ -1,230 +0,0 @@
/**
* Tests for SkillsPanelContent component
*
* Tests keyboard interactions and callbacks.
* Rendering tests are limited due to ink-testing-library constraints with nested components.
*/
import { render } from "ink-testing-library"
// biome-ignore lint/correctness/noUnusedImports: React must be in scope for JSX in this test file.
import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
// Mock refreshSkills
const mockRefreshSkills = vi.fn()
vi.mock("@/core/controller/file/refreshSkills", () => ({
refreshSkills: () => mockRefreshSkills(),
}))
// Mock toggleSkill
const mockToggleSkill = vi.fn()
vi.mock("@/core/controller/file/toggleSkill", () => ({
toggleSkill: (...args: unknown[]) => mockToggleSkill(...args),
}))
// Mock child_process exec
const mockExec = vi.fn()
vi.mock("node:child_process", () => ({
exec: (...args: unknown[]) => mockExec(...args),
}))
// Mock StdinContext
vi.mock("../context/StdinContext", () => ({
useStdinContext: () => ({ isRawModeSupported: true }),
}))
import { SkillsPanelContent } from "./SkillsPanelContent"
// Helper to wait for async state updates
const delay = (ms = 60) => new Promise((resolve) => setTimeout(resolve, ms))
describe("SkillsPanelContent", () => {
const mockController = {} as any
const mockOnClose = vi.fn()
const mockOnUseSkill = vi.fn()
const defaultProps = {
controller: mockController,
onClose: mockOnClose,
onUseSkill: mockOnUseSkill,
}
beforeEach(() => {
vi.clearAllMocks()
mockRefreshSkills.mockResolvedValue({
globalSkills: [],
localSkills: [],
})
})
describe("keyboard interactions", () => {
it("should call onClose when Escape is pressed", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
stdin.write("\x1B") // Escape
await delay()
expect(mockOnClose).toHaveBeenCalled()
})
it("should call onUseSkill with skill path when Enter is pressed on a skill", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [{ name: "test-skill", description: "Test", path: "/test/path/SKILL.md", enabled: true }],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
stdin.write("\r") // Enter
await delay()
expect(mockOnUseSkill).toHaveBeenCalledWith("/test/path/SKILL.md")
})
it("should call toggleSkill when Space is pressed on a skill", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [{ name: "test-skill", description: "Test", path: "/test/path/SKILL.md", enabled: true }],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
stdin.write(" ") // Space
await delay()
expect(mockToggleSkill).toHaveBeenCalledWith(
mockController,
expect.objectContaining({
skillPath: "/test/path/SKILL.md",
isGlobal: true,
enabled: false, // toggled from true to false
}),
)
})
it("should open marketplace URL when Enter is pressed on marketplace item", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [{ name: "skill", description: "desc", path: "/path", enabled: true }],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
// Navigate down to marketplace (past the one skill)
stdin.write("\x1B[B") // Down arrow
await delay()
stdin.write("\r") // Enter
await delay()
// Should have called exec with open command
expect(mockExec).toHaveBeenCalled()
const execCall = mockExec.mock.calls[0][0]
expect(execCall).toContain("https://skills.sh/")
})
it("should navigate through skills with arrow keys", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [
{ name: "skill-1", description: "First", path: "/path1", enabled: true },
{ name: "skill-2", description: "Second", path: "/path2", enabled: true },
],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
// Navigate down
stdin.write("\x1B[B") // Down arrow
await delay()
// Press Enter - should use second skill
stdin.write("\r")
await delay()
expect(mockOnUseSkill).toHaveBeenCalledWith("/path2")
})
it("should navigate with vim keys (j/k)", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [
{ name: "skill-1", description: "First", path: "/path1", enabled: true },
{ name: "skill-2", description: "Second", path: "/path2", enabled: true },
],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
// Navigate down with j
stdin.write("j")
await delay()
// Press Enter - should use second skill
stdin.write("\r")
await delay()
expect(mockOnUseSkill).toHaveBeenCalledWith("/path2")
})
it("should revert optimistic toggle on failure", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [{ name: "test-skill", description: "Test", path: "/test/path/SKILL.md", enabled: true }],
localSkills: [],
})
mockToggleSkill.mockRejectedValueOnce(new Error("toggle failed"))
const { stdin, lastFrame } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
stdin.write(" ") // Space to toggle
await delay(100)
// toggleSkill was called with enabled: false (toggled from true)
expect(mockToggleSkill).toHaveBeenCalledWith(mockController, expect.objectContaining({ enabled: false }))
const frame = lastFrame() || ""
expect(frame).toContain("● test-skill")
expect(frame).not.toContain("○ test-skill")
})
it("should wrap navigation at list boundaries", async () => {
mockRefreshSkills.mockResolvedValue({
globalSkills: [{ name: "only-skill", description: "Only", path: "/only", enabled: true }],
localSkills: [],
})
const { stdin } = render(<SkillsPanelContent {...defaultProps} />)
await delay()
// Navigate up from first item (should wrap to last - marketplace)
stdin.write("\x1B[A") // Up arrow
await delay()
stdin.write("\r") // Enter
await delay()
// Should have opened marketplace (wrapped to last item)
expect(mockExec).toHaveBeenCalled()
})
})
describe("skill loading", () => {
it("should call refreshSkills on mount", async () => {
render(<SkillsPanelContent {...defaultProps} />)
await delay()
expect(mockRefreshSkills).toHaveBeenCalled()
})
})
})
-257
View File
@@ -1,257 +0,0 @@
/**
* Skills panel content for inline display in ChatView
* Shows installed skills with toggle and use functionality
*/
import { exec } from "node:child_process"
import os from "node:os"
import { Box, Text, useInput } from "ink"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import type { Controller } from "@/core/controller"
import { refreshSkills } from "@/core/controller/file/refreshSkills"
import { toggleSkill } from "@/core/controller/file/toggleSkill"
import { COLORS } from "../constants/colors"
import { useStdinContext } from "../context/StdinContext"
import { isMouseEscapeSequence } from "../utils/input"
import { Panel } from "./Panel"
const SKILLS_MARKETPLACE_URL = "https://skills.sh/"
interface SkillInfo {
name: string
description: string
path: string
enabled: boolean
}
interface SkillsPanelContentProps {
controller: Controller
onClose: () => void
onUseSkill: (skillPath: string) => void
}
const MAX_VISIBLE = 8
export const SkillsPanelContent: React.FC<SkillsPanelContentProps> = ({ controller, onClose, onUseSkill }) => {
const { isRawModeSupported } = useStdinContext()
const [globalSkills, setGlobalSkills] = useState<SkillInfo[]>([])
const [localSkills, setLocalSkills] = useState<SkillInfo[]>([])
const [selectedIndex, setSelectedIndex] = useState(0)
const [isLoading, setIsLoading] = useState(true)
// Load skills on mount
useEffect(() => {
const loadSkills = async () => {
try {
const skillsData = await refreshSkills(controller)
setGlobalSkills(skillsData.globalSkills || [])
setLocalSkills(skillsData.localSkills || [])
} catch (_error) {
// Skills loading failed, show empty state
} finally {
setIsLoading(false)
}
}
loadSkills()
}, [controller])
// Build flat list of skills with source info (global first, then local, alphabetical within each)
const skillEntries = useMemo(() => {
const entries: { skill: SkillInfo; isGlobal: boolean }[] = []
globalSkills.forEach((skill) => entries.push({ skill, isGlobal: true }))
localSkills.forEach((skill) => entries.push({ skill, isGlobal: false }))
return entries.sort((a, b) => {
if (a.isGlobal !== b.isGlobal) return a.isGlobal ? -1 : 1
return a.skill.name.localeCompare(b.skill.name)
})
}, [globalSkills, localSkills])
// Handle toggle
const handleToggle = useCallback(async () => {
const entry = skillEntries[selectedIndex]
if (!entry) return
const newEnabled = !entry.skill.enabled
const setter = entry.isGlobal ? setGlobalSkills : setLocalSkills
const update = (enabled: boolean) =>
setter((prev) => prev.map((s) => (s.path === entry.skill.path ? { ...s, enabled } : s)))
// Optimistic update
update(newEnabled)
try {
await toggleSkill(controller, {
metadata: undefined,
skillPath: entry.skill.path,
isGlobal: entry.isGlobal,
enabled: newEnabled,
})
} catch {
// Revert on failure
update(!newEnabled)
}
}, [controller, skillEntries, selectedIndex])
// Handle use skill (insert @ mention)
const handleUse = useCallback(() => {
const entry = skillEntries[selectedIndex]
if (!entry) return
onUseSkill(entry.skill.path)
}, [skillEntries, selectedIndex, onUseSkill])
// Handle opening the marketplace URL
const openMarketplace = useCallback(() => {
const platform = os.platform()
let command: string
if (platform === "darwin") {
command = `open "${SKILLS_MARKETPLACE_URL}"`
} else if (platform === "win32") {
command = `start "${SKILLS_MARKETPLACE_URL}"`
} else {
command = `xdg-open "${SKILLS_MARKETPLACE_URL}"`
}
exec(command, (err) => {
if (err) {
// Fallback: show URL in terminal if browser open fails
console.error(`Visit: ${SKILLS_MARKETPLACE_URL}`)
}
})
}, [])
// Total items = skills + 1 for marketplace link
const totalItems = skillEntries.length + 1
const isMarketplaceSelected = selectedIndex === skillEntries.length
useInput(
(input, key) => {
if (isMouseEscapeSequence(input)) {
return
}
if (key.escape) {
onClose()
return
}
// Navigation
if (key.upArrow || input === "k") {
setSelectedIndex((i) => (i > 0 ? i - 1 : totalItems - 1))
return
}
if (key.downArrow || input === "j") {
setSelectedIndex((i) => (i < totalItems - 1 ? i + 1 : 0))
return
}
// Actions
if (key.return) {
if (isMarketplaceSelected) {
openMarketplace()
} else {
handleUse()
}
return
}
if (input === " " && !isMarketplaceSelected) {
handleToggle()
return
}
},
{ isActive: isRawModeSupported },
)
// Scrolling window (includes marketplace row)
const halfVisible = Math.floor(MAX_VISIBLE / 2)
const startIndex = Math.max(0, Math.min(selectedIndex - halfVisible, totalItems - MAX_VISIBLE))
if (isLoading) {
return (
<Panel label="Skills">
<Text color="gray">Loading skills...</Text>
</Panel>
)
}
// Check if marketplace row is in visible window
const marketplaceIndex = skillEntries.length
const showMarketplace = marketplaceIndex >= startIndex && marketplaceIndex < startIndex + MAX_VISIBLE
return (
<Panel label="Skills">
<Box flexDirection="column" gap={1}>
{skillEntries.length === 0 ? (
<Box flexDirection="column" gap={1}>
<Text color="gray">No skills installed.</Text>
<Text>
Install skills with: <Text color="white">npx skills add owner/repo</Text>
</Text>
</Box>
) : (
<Box flexDirection="column">
{skillEntries
.slice(startIndex, Math.min(startIndex + MAX_VISIBLE, skillEntries.length))
.map((entry, idx) => {
const actualIndex = startIndex + idx
const prevEntry = skillEntries[actualIndex - 1]
const showHeader = actualIndex === 0 || (prevEntry && prevEntry.isGlobal !== entry.isGlobal)
return (
<React.Fragment key={entry.skill.path}>
{showHeader && (
<Box marginTop={actualIndex > 0 ? 1 : 0}>
<Text bold color="gray">
{entry.isGlobal ? "Global Skills:" : "Workspace Skills:"}
</Text>
</Box>
)}
<SkillRow isSelected={actualIndex === selectedIndex} skill={entry.skill} />
</React.Fragment>
)
})}
</Box>
)}
{/* Marketplace link - selectable */}
{showMarketplace && (
<Box marginTop={1}>
<Text color={isMarketplaceSelected ? "cyan" : undefined}>
{isMarketplaceSelected ? " " : " "}
<Text color={COLORS.primaryBlue}>Browse more skills at https://skills.sh/</Text>
</Text>
</Box>
)}
{/* Help text */}
<Box marginTop={1}>
<Text color="gray">
/ Navigate Enter {isMarketplaceSelected ? "Open" : "Use"}
{!isMarketplaceSelected && " • Space Toggle"}
</Text>
</Box>
</Box>
</Panel>
)
}
const SkillRow: React.FC<{ skill: SkillInfo; isSelected: boolean }> = ({ skill, isSelected }) => {
return (
<Box flexDirection="column">
<Box>
<Text color={isSelected ? "cyan" : undefined}>
{isSelected ? " " : " "}
<Text color={skill.enabled ? "green" : "red"}>{skill.enabled ? "●" : "○"}</Text>
<Text> </Text>
<Text bold color="white">
{skill.name}
</Text>
</Text>
</Box>
{skill.description && (
<Box marginLeft={4}>
<Text color="gray">
{skill.description.length > 60 ? skill.description.slice(0, 57) + "..." : skill.description}
</Text>
</Box>
)}
</Box>
)
}
-361
View File
@@ -1,361 +0,0 @@
import type { ClineAskUseSubagents, ClineMessage, ClineSaySubagentStatus } from "@shared/ExtensionMessage"
import { Box, Text } from "ink"
import Spinner from "ink-spinner"
import React from "react"
import { COLORS } from "../constants/colors"
import { useTerminalSize } from "../hooks/useTerminalSize"
import { jsonParseSafe } from "../utils/parser"
interface SubagentMessageProps {
message: ClineMessage
isStreaming?: boolean
mode?: "act" | "plan"
}
const TREE_PREFIX_WIDTH = 5
const MIN_PROMPT_WIDTH = 20
const DotRow: React.FC<{ children: React.ReactNode; color?: string; flashing?: boolean }> = ({
children,
color,
flashing = false,
}) => (
<Box flexDirection="row">
<Box width={2}>
{flashing ? (
<Text color={color}>
<Spinner type="toggle8" />
</Text>
) : (
<Text color={color}></Text>
)}
</Box>
<Box flexGrow={1}>{children}</Box>
</Box>
)
function formatCompactTokens(tokens: number | undefined): string {
const value = Number.isFinite(tokens) ? Math.max(0, tokens || 0) : 0
return new Intl.NumberFormat("en-US", {
notation: "compact",
maximumFractionDigits: 1,
})
.format(value)
.toLowerCase()
}
function formatCompactCost(cost: number | undefined): string {
const value = Number.isFinite(cost) ? Math.max(0, cost || 0) : 0
const maximumFractionDigits = value >= 0.01 ? 2 : 4
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
maximumFractionDigits,
}).format(value)
}
function formatSubagentStatsValues(
toolCalls: number | undefined,
contextTokens: number | undefined,
totalCost: number | undefined,
latestToolCall?: string,
) {
const safeToolCalls = Number.isFinite(toolCalls) ? Math.max(0, toolCalls || 0) : 0
const toolUses = safeToolCalls === 1 ? "tool use" : "tool uses"
const tokensUsed = formatCompactTokens(contextTokens || 0)
const formattedCost = formatCompactCost(totalCost || 0)
const stats = `${safeToolCalls} ${toolUses} · ${tokensUsed} tokens · ${formattedCost}`
const latestTool = latestToolCall?.trim()
return latestTool ? `${latestTool} · ${stats}` : stats
}
function wrapPrompt(text: string, width: number): string[] {
if (!text) {
return [""]
}
const normalizedWidth = Math.max(1, width)
const wrappedLines: string[] = []
const paragraphs = text.split("\n")
for (const paragraph of paragraphs) {
const words = paragraph.trim().split(/\s+/).filter(Boolean)
if (words.length === 0) {
wrappedLines.push("")
continue
}
let line = ""
for (const word of words) {
if (!line) {
if (word.length <= normalizedWidth) {
line = word
continue
}
let remaining = word
while (remaining.length > normalizedWidth) {
wrappedLines.push(remaining.slice(0, normalizedWidth))
remaining = remaining.slice(normalizedWidth)
}
line = remaining
continue
}
if (line.length + 1 + word.length <= normalizedWidth) {
line = `${line} ${word}`
continue
}
wrappedLines.push(line)
if (word.length <= normalizedWidth) {
line = word
continue
}
let remaining = word
while (remaining.length > normalizedWidth) {
wrappedLines.push(remaining.slice(0, normalizedWidth))
remaining = remaining.slice(normalizedWidth)
}
line = remaining
}
if (line) {
wrappedLines.push(line)
}
}
return wrappedLines.length > 0 ? wrappedLines : [text]
}
const TreePromptRow: React.FC<{
prefix: React.ReactNode
continuationPrefix: string
prompt: string
promptWidth: number
color?: string
}> = ({ prefix, continuationPrefix, prompt, promptWidth, color }) => {
const lines = wrapPrompt(prompt, promptWidth)
return (
<Box flexDirection="column" width="100%">
{lines.map((line, index) => (
<Box flexDirection="row" key={`${line}-${index}`} width="100%">
<Box flexShrink={0} width={TREE_PREFIX_WIDTH}>
{index === 0 ? prefix : <Text color="gray">{continuationPrefix}</Text>}
</Box>
<Box flexGrow={1}>
<Text color={color}>{line}</Text>
</Box>
</Box>
))}
</Box>
)
}
const TreeStatsRow: React.FC<{ prefix: string; stats: string }> = ({ prefix, stats }) => (
<Box flexDirection="row" width="100%">
<Box flexShrink={0} width={TREE_PREFIX_WIDTH}>
<Text color="gray">{prefix}</Text>
</Box>
<Box flexGrow={1}>
<Text color="gray"> {stats}</Text>
</Box>
</Box>
)
export const SubagentMessage: React.FC<SubagentMessageProps> = ({ message, mode, isStreaming }) => {
const { type, ask, say, text, partial } = message
const toolColor = mode === "plan" ? "yellow" : COLORS.primaryBlue
const { columns } = useTerminalSize()
const promptWidth = Math.max(MIN_PROMPT_WIDTH, columns - 2 - TREE_PREFIX_WIDTH)
if ((type === "ask" && ask === "use_subagents") || say === "use_subagents") {
const parsed = text
? jsonParseSafe<ClineAskUseSubagents>(text, {
prompts: [],
})
: { prompts: [] }
const prompts = (parsed.prompts || []).map((prompt) => prompt?.trim()).filter(Boolean)
if (prompts.length === 0) {
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor}>
<Text color={toolColor}>Cline wants to run subagents:</Text>
</DotRow>
</Box>
)
}
const singular = prompts.length === 1
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text color={toolColor}>{singular ? "Cline wants to run a subagent:" : "Cline wants to run subagents:"}</Text>
</DotRow>
<Box flexDirection="column" marginLeft={2} width="100%">
{prompts.map((prompt, index) => {
const isLastPrompt = index === prompts.length - 1
const branch = isLastPrompt ? "└─" : "├─"
const continuationPrefix = isLastPrompt ? " " : "│ "
const shouldShowPromptStats = partial !== true || !isLastPrompt
return (
<Box flexDirection="column" key={`${prompt}-${index}`}>
<TreePromptRow
color={toolColor}
continuationPrefix={continuationPrefix}
prefix={<Text color={toolColor}>{`${branch} `}</Text>}
prompt={prompt}
promptWidth={promptWidth}
/>
{shouldShowPromptStats && (
<TreeStatsRow
prefix={continuationPrefix}
stats={formatSubagentStatsValues(undefined, undefined, undefined)}
/>
)}
</Box>
)
})}
</Box>
</Box>
)
}
if (say === "subagent" && text) {
const parsed = jsonParseSafe<ClineSaySubagentStatus>(text, {
status: "running",
total: 0,
completed: 0,
successes: 0,
failures: 0,
toolCalls: 0,
inputTokens: 0,
outputTokens: 0,
contextWindow: 0,
maxContextTokens: 0,
maxContextUsagePercentage: 0,
items: [],
})
const items = parsed.items || []
if (items.length === 0) {
return null
}
return (
<Box flexDirection="column" marginBottom={1} width="100%">
<DotRow color={toolColor} flashing={partial === true && isStreaming}>
<Text color={toolColor}>
{items.length === 1 ? "Cline is running a subagent:" : "Cline is running subagents:"}
</Text>
</DotRow>
<Box flexDirection="column" marginLeft={2} width="100%">
{items.map((entry, index) => {
const isLastEntry = index === items.length - 1
const branch = isLastEntry ? "└─" : "├─"
const continuationPrefix = isLastEntry ? " " : "│ "
const key = `${entry.index}-${index}`
const shouldShowStats = true
if (entry.status === "completed") {
return (
<Box flexDirection="column" key={key}>
<TreePromptRow
color="green"
continuationPrefix={continuationPrefix}
prefix={
<Box flexDirection="row">
<Text color="gray">{`${branch} `}</Text>
<Text color="green"></Text>
</Box>
}
prompt={entry.prompt}
promptWidth={promptWidth}
/>
<TreeStatsRow
prefix={continuationPrefix}
stats={formatSubagentStatsValues(
entry.toolCalls,
entry.contextTokens,
entry.totalCost,
entry.latestToolCall,
)}
/>
</Box>
)
}
if (entry.status === "failed") {
return (
<Box flexDirection="column" key={key}>
<TreePromptRow
color="red"
continuationPrefix={continuationPrefix}
prefix={
<Box flexDirection="row">
<Text color="gray">{`${branch} `}</Text>
<Text color="red"></Text>
</Box>
}
prompt={entry.prompt}
promptWidth={promptWidth}
/>
<TreeStatsRow
prefix={continuationPrefix}
stats={formatSubagentStatsValues(
entry.toolCalls,
entry.contextTokens,
entry.totalCost,
entry.latestToolCall,
)}
/>
</Box>
)
}
return (
<Box flexDirection="column" key={key}>
<TreePromptRow
color={toolColor}
continuationPrefix={continuationPrefix}
prefix={
<Box flexDirection="row">
<Text color="gray">{branch} </Text>
{entry.status === "running" ? (
<Text color={toolColor}>
<Spinner type="dots" />
</Text>
) : (
<Text color={toolColor}></Text>
)}
</Box>
}
prompt={entry.prompt}
promptWidth={promptWidth}
/>
{shouldShowStats && (
<TreeStatsRow
prefix={continuationPrefix}
stats={formatSubagentStatsValues(
entry.toolCalls,
entry.contextTokens,
entry.totalCost,
entry.latestToolCall,
)}
/>
)}
</Box>
)
})}
</Box>
</Box>
)
}
return null
}
-12
View File
@@ -1,12 +0,0 @@
import { describe, expect, it } from "vitest"
import { getAllFeaturedModels } from "./featured-models"
describe("featured models", () => {
it("includes display names for all featured models", () => {
const models = getAllFeaturedModels()
for (const model of models) {
expect(model.name).toBeTruthy()
}
})
})
+19 -19
View File
@@ -10,53 +10,53 @@ export interface FeaturedModel {
labels: string[]
}
export const FEATURED_MODELS: { recommended: FeaturedModel[]; free: FeaturedModel[] } = {
export const FEATURED_MODELS = {
recommended: [
{
id: "anthropic/claude-sonnet-4.5",
name: "Claude Sonnet 4.5",
description: "Best balance of speed, cost, and quality",
labels: ["BEST"],
},
{
id: "anthropic/claude-opus-4.6",
name: "Claude Opus 4.6",
description: "State-of-the-art for complex coding",
labels: ["NEW"],
labels: ["BEST"],
},
{
id: "openai/gpt-5.2-codex",
name: "GPT 5.2 Codex",
description: "OpenAI's latest with strong coding abilities",
labels: ["HOT"],
labels: ["NEW"],
},
],
{
id: "google/gemini-3-pro-preview",
name: "Gemini 3 Pro",
description: "1M context window for large codebases",
labels: ["TRENDING"],
},
] as FeaturedModel[],
free: [
{
id: "minimax/minimax-m2.5",
name: "MiniMax M2.5",
description: "MiniMax-M2.5 is a lightweight, state-of-the-art LLM optimized for coding and agentic workflows",
id: "minimax/minimax-m2.1",
name: "MiniMax M2.1",
description: "Exceptional Multi-Programming Language Capabilities",
labels: ["FREE"],
},
{
id: "z-ai/glm-5",
name: "Z-AI GLM5",
description: "Z.AI's latest GLM 5 model with strong coding and agent performance",
id: "moonshotai/kimi-k2.5",
name: "Kimi K2.5",
description: "State-of-the-art model topping benchmarks",
labels: ["FREE"],
},
{
id: "kwaipilot/kat-coder-pro",
name: "KAT Coder Pro",
description: "KwaiKAT's most advanced agentic coding model in the KAT-Coder series",
description: "Advanced agentic coding model",
labels: ["FREE"],
},
{
id: "arcee-ai/trinity-large-preview:free",
name: "Trinity Large Preview",
description: "Arcee AI's advanced large preview model in the Trinity series",
description: "US built open source coding model",
labels: ["FREE"],
},
],
] as FeaturedModel[],
}
export function getAllFeaturedModels(): FeaturedModel[] {
+1 -13
View File
@@ -6,7 +6,6 @@
* - Ctrl+A/E: start/end of line
* - Ctrl+W: delete word backwards
* - Ctrl+U: delete to start of line
* - Ctrl+K: delete to end of line
*
* Note: Home/End keys are handled by useHomeEndKeys hook because Ink doesn't
* expose them in useInput (it sets input='' for these keys).
@@ -153,14 +152,6 @@ export function useTextInput(): UseTextInputReturn {
}
}, [])
const deleteToEnd = useCallback(() => {
const pos = cursorRef.current
if (pos < textRef.current.length) {
setTextState((prev) => prev.slice(0, pos))
// Cursor stays at same position (now at end of text)
}
}, [])
// Cursor movement (internal, used by handlers)
const moveToStart = useCallback(() => setCursorPosState(0), [])
const moveToEnd = useCallback(() => setCursorPosState(textRef.current.length), [])
@@ -199,9 +190,6 @@ export function useTextInput(): UseTextInputReturn {
case "u": // Ctrl+U - delete to start
deleteToStart()
return true
case "k": // Ctrl+K - delete to end
deleteToEnd()
return true
case "w": // Ctrl+W - delete word backwards
deleteWordBefore()
return true
@@ -209,7 +197,7 @@ export function useTextInput(): UseTextInputReturn {
return false
}
},
[moveToStart, moveToEnd, deleteToStart, deleteToEnd, deleteWordBefore],
[moveToStart, moveToEnd, deleteToStart, deleteWordBefore],
)
return {
+14 -40
View File
@@ -15,7 +15,9 @@ import { HostProvider } from "@/hosts/host-provider"
import { FileEditProvider } from "@/integrations/editor/FileEditProvider"
import { openAiCodexOAuthManager } from "@/integrations/openai-codex/oauth"
import { StandaloneTerminalManager } from "@/integrations/terminal/standalone/StandaloneTerminalManager"
import { BannerService } from "@/services/banner/BannerService"
import { ErrorService } from "@/services/error/ErrorService"
import { initializeDistinctId } from "@/services/logging/distinctId"
import { telemetryService } from "@/services/telemetry"
import { PostHogClientProvider } from "@/services/telemetry/providers/posthog/PostHogClientProvider"
import { HistoryItem } from "@/shared/HistoryItem"
@@ -71,27 +73,13 @@ async function disposeTelemetryServices(): Promise<void> {
}
telemetryDisposed = true
await Promise.allSettled([telemetryService.dispose(), PostHogClientProvider.getInstance().dispose()])
}
/**
* Restore yoloModeToggled to its original value from before this CLI session.
* This ensures the --yolo flag is session-only and doesn't leak into future runs.
* Must be called before flushPendingState so the restored value gets persisted.
*/
function restoreYoloState(): void {
if (savedYoloModeToggled !== null) {
try {
StateManager.get().setGlobalState("yoloModeToggled", savedYoloModeToggled)
savedYoloModeToggled = null
} catch {
// StateManager may not be initialized (e.g., early exit before init)
}
}
await Promise.allSettled([
telemetryService.dispose(),
PostHogClientProvider.getInstance().dispose(),
])
}
async function disposeCliContext(ctx: CliContext): Promise<void> {
restoreYoloState()
await ctx.controller.stateManager.flushPendingState()
await ctx.controller.dispose()
await ErrorService.get().dispose()
@@ -204,12 +192,9 @@ function applyTaskOptions(options: TaskOptions): void {
telemetryService.captureHostEvent("max_consecutive_mistakes_flag", String(maxConsecutiveMistakes))
}
// Override yolo mode only if --yolo flag is explicitly passed.
// The original value is saved in initializeCli and restored on exit.
// Set yolo mode based on --yolo flag
if (options.yolo) {
const state = StateManager.get()
savedYoloModeToggled = state.getGlobalSettingsKey("yoloModeToggled") ?? false
state.setGlobalState("yoloModeToggled", true)
StateManager.get().setGlobalState("yoloModeToggled", true)
telemetryService.captureHostEvent("yolo_flag", "true")
}
@@ -314,9 +299,6 @@ let activeContext: CliContext | null = null
let isShuttingDown = false
// Track if we're in plain text mode (no Ink UI) - set by runTask when piped stdin detected
let isPlainTextMode = false
// Track the original yoloModeToggled value from before this CLI session so we can restore it on exit.
// The --yolo flag should only affect the current invocation, not persist across runs.
let savedYoloModeToggled: boolean | null = null
/**
* Wait for stdout to fully drain before exiting.
@@ -358,10 +340,6 @@ function setupSignalHandlers() {
printWarning(`${signal} received, shutting down...`)
try {
// Restore yolo state before any cleanup - this is idempotent and safe
// even if disposeCliContext also calls it (restoreYoloState checks savedYoloModeToggled !== null)
restoreYoloState()
if (activeContext) {
const task = activeContext.controller.task
if (task) {
@@ -369,12 +347,6 @@ function setupSignalHandlers() {
}
await disposeCliContext(activeContext)
} else {
// Best-effort flush of restored yolo state when no active context
try {
await StateManager.get().flushPendingState()
} catch {
// StateManager may not be initialized yet
}
await ErrorService.get().dispose()
await disposeTelemetryServices()
}
@@ -438,6 +410,7 @@ async function initializeCli(options: InitOptions): Promise<CliContext> {
Logger.subscribe(logToChannel)
await ClineEndpoint.initialize(EXTENSION_DIR)
await initializeDistinctId(extensionContext)
// Auto-update check (after endpoints initialized, so we can detect bundled configs)
autoUpdateOnStartup(CLI_VERSION)
@@ -460,14 +433,13 @@ async function initializeCli(options: InitOptions): Promise<CliContext> {
() => new StandaloneTerminalManager(),
createCliHostBridgeProvider(workspacePath),
logToChannel,
async (path: string) => (options.enableAuth ? AuthHandler.getInstance().getCallbackUrl(path) : ""),
async () => (options.enableAuth ? AuthHandler.getInstance().getCallbackUrl() : ""),
getCliBinaryPath,
EXTENSION_DIR,
DATA_DIR,
)
await StateManager.initialize(extensionContext as any)
await ErrorService.initialize()
// Initialize OpenAI Codex OAuth manager with extension context for secrets storage
@@ -476,6 +448,8 @@ async function initializeCli(options: InitOptions): Promise<CliContext> {
const webview = HostProvider.get().createWebviewProvider() as CliWebviewProvider
const controller = webview.controller
BannerService.initialize(webview.controller)
await telemetryService.captureExtensionActivated()
await telemetryService.captureHostEvent("cline_cli", "initialized")
@@ -790,9 +764,9 @@ program
program
.command("auth")
.description("Authenticate a provider and configure what model is used")
.option("-p, --provider <id>", "Provider ID for quick setup (e.g., openai-native, anthropic, moonshot)")
.option("-p, --provider <id>", "Provider ID for quick setup (e.g., openai-native, anthropic)")
.option("-k, --apikey <key>", "API key for the provider")
.option("-m, --modelid <id>", "Model ID to configure (e.g., gpt-4o, claude-sonnet-4-6, kimi-k2.5)")
.option("-m, --modelid <id>", "Model ID to configure (e.g., gpt-4o, claude-sonnet-4-5-20250929)")
.option("-b, --baseurl <url>", "Base URL (optional, only for openai provider)")
.option("-v, --verbose", "Show verbose output")
.option("-c, --cwd <path>", "Working directory for the task")
-28
View File
@@ -1,28 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest"
import { emitTaskStartedMessage } from "./task-start-output"
describe("emitTaskStartedMessage", () => {
afterEach(() => {
vi.restoreAllMocks()
})
it("writes structured task_started JSON to stdout in json mode", () => {
const stdoutWriteSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true)
const stderrWriteSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true)
emitTaskStartedMessage("task-123", true)
expect(stdoutWriteSpy).toHaveBeenCalledWith('{"type":"task_started","taskId":"task-123"}\n')
expect(stderrWriteSpy).not.toHaveBeenCalled()
})
it("writes human-readable task started line to stderr in non-json mode", () => {
const stdoutWriteSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true)
const stderrWriteSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true)
emitTaskStartedMessage("task-456", false)
expect(stderrWriteSpy).toHaveBeenCalledWith("Task started: task-456\n")
expect(stdoutWriteSpy).not.toHaveBeenCalled()
})
})
-18
View File
@@ -17,7 +17,6 @@ import type { Controller } from "@/core/controller"
import { getRequestRegistry } from "@/core/controller/grpc-handler"
import { subscribeToState } from "@/core/controller/state/subscribeToState"
import { showTaskWithId } from "@/core/controller/task/showTaskWithId"
import { emitTaskStartedMessage } from "./task-start-output"
export interface PlainTextTaskOptions {
controller: Controller
@@ -53,7 +52,6 @@ export async function runPlainTextTask(options: PlainTextTaskOptions): Promise<b
})
let hasError = false
let hasEmittedTaskStarted = false
// Track which messages have been processed (by timestamp)
const processedMessages = new Map<number, string>()
@@ -64,20 +62,6 @@ export async function runPlainTextTask(options: PlainTextTaskOptions): Promise<b
// results AFTER this time should trigger task completion.
const completionCutoffTs = Date.now()
const emitTaskStarted = () => {
if (hasEmittedTaskStarted) {
return
}
const taskId = controller.task?.taskId
if (!taskId) {
return
}
emitTaskStartedMessage(taskId, Boolean(jsonOutput))
hasEmittedTaskStarted = true
}
// Helper to process a message and track completion state
const processMessage = (message: ClineMessage) => {
const ts = message.ts || 0
@@ -135,7 +119,6 @@ export async function runPlainTextTask(options: PlainTextTaskOptions): Promise<b
if (options.taskId) {
// Load the existing task
await showTaskWithId(controller, StringRequest.create({ value: options.taskId }))
emitTaskStarted()
// If a prompt was provided, send it as a message to the resumed task
if (prompt && controller.task) {
@@ -148,7 +131,6 @@ export async function runPlainTextTask(options: PlainTextTaskOptions): Promise<b
} else if (prompt) {
// Start a new task with the prompt
await controller.initTask(prompt, imageDataUrls)
emitTaskStarted()
} else {
throw new Error("Either taskId or prompt must be provided")
}
-8
View File
@@ -1,8 +0,0 @@
export function emitTaskStartedMessage(taskId: string, jsonOutput: boolean): void {
if (jsonOutput) {
process.stdout.write(JSON.stringify({ type: "task_started", taskId }) + "\n")
return
}
process.stderr.write(`Task started: ${taskId}\n`)
}
-1
View File
@@ -13,7 +13,6 @@ export default defineConfig({
},
resolve: {
alias: {
vscode: path.resolve(__dirname, "src/vscode-shim.ts"),
// Match tsconfig paths - baseUrl is parent directory
"@": path.resolve(__dirname, "../src"),
"@api": path.resolve(__dirname, "../src/core/api"),
+4 -4
View File
@@ -202,15 +202,15 @@ If Cline can't access files or run commands:
Learn about Cline CLI's core capabilities and use cases.
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="Three Core Flows" icon="route" href="/cline-cli/three-core-flows">
Master interactive mode, headless automation, and multi-instance workflows.
</Card>
<Card title="Skills" icon="graduation-cap" href="/customization/skills">
<Card title="Skills" icon="graduation-cap" href="/features/skills">
Understand how Cline's Skills work across all editors via ACP.
</Card>
<Card title="Hooks" icon="link" href="/customization/hooks">
<Card title="Hooks" icon="link" href="/features/hooks/index">
Learn how to enforce policies with Hooks in any editor.
</Card>
</Columns>
+482
View File
@@ -0,0 +1,482 @@
---
title: "CLI Reference (Deprecated)"
description: "Command reference for Cline CLI versions earlier than 2.0.0 (deprecated). For the latest commands and options, see the current Cline CLI reference."
---
Complete command reference for Cline CLI. Use this for detailed documentation on all commands, options, and configuration.
For quick help in your terminal:
```bash
cline --help # Show all commands
cline task --help # Show task-specific commands
man cline # View the full manual page
```
## Manual Page
The complete manual page for the Cline CLI:
```
CLINE(1) User Commands CLINE(1)
NAME
cline - orchestrate and interact with Cline AI coding agents
SYNOPSIS
cline [prompt] [options]
cline command [subcommand] [options] [arguments]
DESCRIPTION
Try: cat README.md | cline "Summarize this for me:"
cline is a command-line interface for orchestrating multiple Cline AI
coding agents. Cline is an autonomous AI agent who can read, write,
and execute code across your projects. He operates through a
client-server architecture where Cline Core runs as a standalone
service, and the CLI acts as a scriptable interface for managing tasks,
instances, and agent interactions.
The CLI is designed for both interactive use and automation, making it
ideal for CI/CD pipelines, parallel task execution, and terminal-based
workflows. Multiple frontends (CLI, VSCode, JetBrains) can attach to
the same Cline Core instance, enabling seamless task handoff between
environments.
MODES OF OPERATION
Instant Task Mode
The simplest invocation: cline "prompt here" immediately spawns
an instance, creates a task, and enters chat mode. This is
equivalent to running cline instance new && cline task new &&
cline task chat in sequence.
Subcommand Mode
Advanced usage with explicit control: cline <command>
[subcommand] [options] provides fine-grained control over
instances, tasks, authentication, and configuration.
AGENT BEHAVIOR
Cline operates in two primary modes:
ACT MODE
Cline actively uses tools to accomplish tasks. He can read
files, write code, execute commands, use a headless browser, and
more. This is the default mode for task execution.
PLAN MODE
Cline gathers information and creates a detailed plan before
implementation. He explores the codebase, asks clarifying
questions, and presents a strategy for user approval before
switching to ACT MODE.
INSTANT TASK OPTIONS
When using the instant task syntax cline "prompt" the following options
are available:
-o, --oneshot
Full autonomous mode. Cline completes the task and stops
following after completion. Example: cline -o "what's 6 + 8?"
-s, --setting setting value
Override a setting for this task
-y, --no-interactive, --yolo
Enable fully autonomous mode. Disables all interactivity:
• ask_followup_question tool is disabled
• attempt_completion happens automatically
• execute_command runs in non-blocking mode with timeout
• PLAN MODE automatically switches to ACT MODE
-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:
-F, --output-format format
Output format. Options: rich (default), json, plain
-h, --help
Display help information for the command.
-v, --verbose
Enable verbose output for debugging.
COMMANDS
Authentication
cline auth [provider] [key]
cline a [provider] [key]
Configure authentication for AI model providers. Launches an
interactive wizard if no arguments provided. If provider is
specified without a key, prompts for the key or launches the
appropriate OAuth flow.
Instance Management
Cline Core instances are independent agent processes that can run in
the background. Multiple instances can run simultaneously, enabling
parallel task execution.
cline instance
cline i
Display instance management help.
cline instance new [-d|--default]
cline i n [-d|--default]
Spawn a new Cline Core instance. Use --default to set it as
the default instance for subsequent commands.
cline instance list
cline i l
List all running Cline Core instances with their addresses and
status.
cline instance default address
cline i d address
Set the default instance to avoid specifying --address in task
commands.
cline instance kill address [-a|--all]
cline i k address [-a|--all]
Terminate a Cline Core instance. Use --all to kill all running
instances.
Task Management
Tasks represent individual work items that Cline executes. Tasks
maintain conversation history, checkpoints, and settings.
cline task [-a|--address ADDR]
cline t [-a|--address ADDR]
Display task management help. The --address flag specifies
which Cline Core instance to use (e.g., localhost:50052).
cline task new prompt [options]
cline t n prompt [options]
Create a new task in the default or specified instance.
Options:
-s, --setting setting value
Set task-specific settings
-y, --no-interactive, --yolo
Enable autonomous mode
-m, --mode mode
Starting mode (act or plan)
cline task open task-id [options]
cline t o task-id [options]
Resume a previous task from history. Accepts the same options
as task new.
cline task list
cline t l
List all tasks in history with their id and snippet
cline task chat
cline t c
Enter interactive chat mode for the current task. Allows
back-and-forth conversation with Cline.
cline task send [message] [options]
cline t s [message] [options]
Send a message to Cline. If no message is provided, reads from
stdin. Options:
-a, --approve
Approve Cline's proposed action
-d, --deny
Deny Cline's proposed action
-f, --file FILE
Attach a file to the message
-y, --no-interactive, --yolo
Enable autonomous mode
-m, --mode mode
Switch mode (act or plan)
cline task view [-f|--follow] [-c|--follow-complete]
cline t v [-f|--follow] [-c|--follow-complete]
Display the current conversation. Use --follow to stream
updates in real-time, or --follow-complete to follow until task
completion.
cline task restore checkpoint
cline t r checkpoint
Restore the task to a previous checkpoint state.
cline task pause
cline t p
Pause task execution.
Configuration
Configuration can be set globally. Override these global settings for
a task using the --setting flag
cline config
cline c
cline config set key value
cline c s key value
Set a configuration variable.
cline config get key
cline c g key
Read a configuration variable.
cline config list
cline c l
List all configuration variables and their values.
Context Window Configuration
For local model providers, you can configure the context window size:
Ollama
cline config s ollama-api-options-ctx-num=32768
LM Studio
cline config s lm-studio-max-tokens=32768
For other providers (Anthropic, OpenRouter, etc.), the context window
is defined per model in the model metadata and is not user-settable.
Cline uses each model's built-in context limits automatically.
TASK SETTINGS
Task settings are persisted in the ~/.cline/x/tasks directory. When
resuming a task with cline task open, task settings are automatically
restored.
Common settings include:
yolo Enable autonomous mode (true/false)
mode Starting mode (act/plan)
hooks_enabled
Enable or disable hooks for the task (true/false)
HOOKS INTEGRATION
Hooks let you inject custom logic into Cline's workflow at key moments.
They can validate operations before they execute, monitor tool usage,
and shape AI decisions. This allows you to integrate hooks into
automated workflows, CI/CD pipelines, and headless task execution.
Enable hooks for a task:
cline "prompt" -s hooks_enabled=true
Configure hooks globally:
cline config set hooks-enabled=true
cline config get hooks-enabled
Note: Hooks in the CLI are only supported on macOS and Linux.
For complete hooks documentation, see:
<https://docs.cline.bot/features/hooks/index>
NOTES & EXAMPLES
The cline task send and cline task new commands support reading from
stdin, enabling powerful pipeline compositions:
cat requirements.txt | cline task send
echo "Refactor this code" | cline -y
Instance Management
Manage multiple Cline instances:
# Start a new instance and make it default
cline instance new --default
# List all running instances
cline instance list
# Kill a specific instance
cline instance kill localhost:50052
# Kill all CLI instances
cline instance kill --all-cli
Task History
Work with task history:
# List previous tasks
cline task list
# Resume a previous task
cline task open 1760501486669
# View conversation history
cline task view
# Start interactive chat with this task
cline task chat
ARCHITECTURE
Cline operates on a three-layer architecture:
Presentation Layer
User interfaces (CLI, VSCode, JetBrains) that connect to Cline
Core via gRPC
Cline Core
The autonomous agent service handling task management, AI model
integration, state management, tool orchestration, and real-time
streaming updates
Host Provider Layer
Environment-specific integrations (VSCode APIs, JetBrains APIs,
shell APIs) that Cline Core uses to interact with the host
system
BUGS
Report bugs at: <https://github.com/cline/cline/issues>
For real-time help, join the Discord community at:
<https://discord.gg/cline>
SEE ALSO
Full documentation: <https://docs.cline.bot>
AUTHORS
Cline is developed by the Cline Bot Inc. and the open source community.
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:
#### Bash
```bash
# Generate bash completion
cline completion bash > /etc/bash_completion.d/cline
# Or for user-level installation
cline completion bash > ~/.local/share/bash-completion/completions/cline
```
#### Zsh
```bash
# Generate zsh completion
cline completion zsh > "${fpath[1]}/_cline"
# Or add to your .zshrc
echo 'source <(cline completion zsh)' >> ~/.zshrc
```
#### Fish
```bash
# Generate fish completion
cline completion fish > ~/.config/fish/completions/cline.fish
```
#### PowerShell
```powershell
# Generate PowerShell completion
cline completion powershell > cline.ps1
# Add to your PowerShell profile
Add-Content $PROFILE "cline completion powershell | Out-String | Invoke-Expression"
```
### Version Command
```bash
# Show version information
cline version
```
### Environment Variables
#### CLINE_DIR
Override the default Cline directory location:
```bash
# Override default Cline directory
export CLINE_DIR=/custom/path
# Default: ~/.cline
```
This directory is used for:
- Instance registry database
- Configuration files
- Task history
- Checkpoints
+5 -3
View File
@@ -3,6 +3,8 @@ title: "CLI Reference"
description: "Complete command reference for Cline CLI including all commands, flags, and configuration options"
---
# CLI Reference
This page documents all available commands, flags, and configuration options for Cline CLI. For quick help in your terminal, use:
```bash
@@ -314,7 +316,7 @@ When using `--json`, each message is output as a JSON object (one per line):
Cline stores all data in `~/.cline/` by default:
```text
```
~/.cline/
├── data/ # Configuration directory
│ ├── globalState.json # Global settings
@@ -414,8 +416,8 @@ cline auth -p openai -k your-key -b https://api.example.com/v1
Keyboard shortcuts, slash commands, and file mentions.
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="CLI Workflows" icon="route" href="/cline-cli/three-core-flows">
Interactive mode, direct execution, and automation patterns.
</Card>
<Card title="Configuration" icon="gear" href="/cline-cli/configuration">
+6 -6
View File
@@ -38,7 +38,7 @@ Rules help Cline understand your project's conventions, coding standards, and pr
### Workflows Tab
View and manage [workflows](/customization/workflows):
View and manage [workflows](/features/slash-commands/workflows/index):
- List available workflows
- View workflow definitions
@@ -46,7 +46,7 @@ View and manage [workflows](/customization/workflows):
### Hooks Tab
Configure [hooks](/customization/hooks) for custom logic integration:
Configure [hooks](/features/hooks/index) for custom logic integration:
- Enable/disable hooks globally
- View configured hook scripts
@@ -58,7 +58,7 @@ Hooks must be enabled via settings. Use `cline config` to toggle `hooks-enabled`
### Skills Tab
Manage [skills](/customization/skills) that extend Cline's capabilities:
Manage [skills](/features/skills) that extend Cline's capabilities:
- View available skills
- Enable/disable specific skills
@@ -68,7 +68,7 @@ Manage [skills](/customization/skills) that extend Cline's capabilities:
Cline stores configuration in `~/.cline/data/`:
```text
```
~/.cline/
├── data/ # Configuration directory
│ ├── globalState.json # Global settings
@@ -268,8 +268,8 @@ cline auth # Re-authenticate
## Next Steps
<Columns cols={2}>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="CLI Workflows" icon="route" href="/cline-cli/three-core-flows">
Learn about interactive mode, direct execution, and automation patterns.
</Card>
<Card title="CLI Reference" icon="terminal" href="/cline-cli/cli-reference">
-457
View File
@@ -1,457 +0,0 @@
---
title: "Getting Started"
description: "Run Cline AI coding agents directly in your terminal with an interactive CLI or automated workflows"
---
## What is Cline CLI?
Cline CLI brings the full power of Cline to your terminal. Whether you prefer an interactive experience or automated workflows for CI/CD pipelines, the CLI adapts to your needs.
The CLI supports macOS, Linux, and Windows, and works with all the same AI providers as the VS Code extension.
## Two Ways to Use Cline CLI
The CLI operates in two distinct modes, automatically selecting the appropriate one based on how you invoke it:
### Interactive Mode
Interactive mode is designed for **hands-on development sessions** where you want to collaborate with Cline in real-time. It provides a rich terminal interface that feels like chatting with an AI assistant.
**When it activates:** Running `cline` without arguments, or when stdin is a TTY (terminal).
```bash
cline
```
Key features:
- **Real-time conversation** - Type messages, see Cline's responses, and iterate on tasks
- **Visual feedback** - Animated welcome screen, syntax-highlighted code, and progress indicators
- **File mentions** with `@` - Reference workspace files with fuzzy search autocomplete
- **Slash commands** with `/` - Quick access to `/settings`, `/history`, `/models`, and workflows
- **Keyboard shortcuts** - `Tab` to toggle Plan/Act, `Shift+Tab` for auto-approve all
- **Session summaries** - See tasks completed, files modified, and token usage on exit
- **Settings panel** - Configure providers, models, and features without leaving the CLI
Interactive mode keeps you in control. You review Cline's plan, approve or modify actions, and guide the conversation.
[Learn more about interactive mode →](/cline-cli/interactive-mode)
### Headless Mode (Non-Interactive)
Headless mode is designed for **automation, scripting, and CI/CD pipelines** where human interaction isn't possible or desired.
**When it activates:** Using the `-y`/`--yolo` flag, `--json` flag, piping input/output, or when stdin is not a TTY.
```bash
# Headless with auto-approval (YOLO mode)
cline -y "Run tests and fix any failures"
# Headless with JSON output for parsing
cline --json "List all TODO comments" | jq '.text'
# Headless via piped input
cat README.md | cline "Summarize this document"
# Chain multiple headless commands
git diff | cline -y "explain these changes" | cline -y "write a commit message"
```
Key features:
- **No visual interface** - Clean text or JSON output suitable for scripting
- **Automatic execution** - With `-y`, Cline approves all actions and runs autonomously
- **Process control** - Exits automatically when the task completes
- **Piped workflows** - Read from stdin, write to stdout, chain with other commands
- **Machine-readable output** - Use `--json` to get structured output for parsing
<Warning>
Headless mode with `-y` gives Cline full autonomy. Run on a clean git branch so you can easily revert changes if needed.
</Warning>
### Mode Detection Summary
Cline automatically detects which mode to use based on your invocation. This table shows how different command patterns trigger each mode, helping you predict behavior in scripts and interactive sessions.
| Invocation | Mode | Reason |
|------------|------|--------|
| `cline` | Interactive | No arguments, TTY connected |
| `cline "task"` | Interactive | TTY connected |
| `cline -y "task"` | Headless | YOLO flag forces headless |
| `cline --json "task"` | Headless | JSON flag forces headless |
| `cat file \| cline "task"` | Headless | stdin is piped |
| `cline "task" > output.txt` | Headless | stdout is redirected |
[Learn more about headless mode →](/cline-cli/three-core-flows)
## Supported Model Providers
Cline CLI supports all providers available in the VS Code extension:
- **Anthropic** (Claude)
- **OpenAI** (GPT-4o, GPT-4)
- **OpenAI Codex** (ChatGPT subscription)
- **OpenRouter**
- **AWS Bedrock**
- **Google Gemini**
- **X AI (Grok)**
- **Cerebras**
- **DeepSeek**
- **Ollama** (local models)
- **LM Studio** (local models)
- **OpenAI Compatible** (any compatible API)
During setup, authenticate with `cline auth` to configure your preferred provider. [See authentication →](#authenticate)
## What You Can Build
### Automated Code Maintenance
Keep your codebase healthy with automated fixes. Cline scans for issues and applies corrections across multiple files.
```bash
cline -y "Fix all ESLint errors in src/"
```
Finds and fixes linting violations throughout your source directory.
```bash
cline -y "Update all deprecated React lifecycle methods"
```
Migrates legacy code patterns to modern equivalents (e.g., `componentWillMount` → `useEffect`).
```bash
cline -y "Update dependencies with known vulnerabilities"
```
Identifies outdated packages with security issues and updates them to safe versions.
### CI/CD Integration
Integrate Cline into your continuous integration pipelines for automated code review and documentation.
```bash
git diff origin/main | cline -y "Review these changes for issues"
```
Pipes your PR diff to Cline for automated code review, catching bugs and style issues before merge.
```bash
git log --oneline v1.0..v1.1 | cline -y "Write release notes"
```
Generates human-readable release notes from your commit history between two tags.
```bash
cline -y "Run tests and fix failures" --timeout 600
```
Executes your test suite, analyzes failures, and attempts fixes with a 10-minute timeout.
### Development Workflows
From quick edits to complex refactors, Cline adapts to your workflow.
```bash
cline
```
Launches interactive mode for exploratory development and back-and-forth collaboration.
```bash
cline "Refactor this function to use async/await"
```
Executes a focused task directly from the command line with approval prompts at key steps.
```bash
cline "Based on @src/api.ts, add error handling to all endpoints"
```
Uses file mentions (`@`) to give Cline context about specific files in your workspace.
### Custom Shell Pipelines
Chain Cline with other CLI tools to build powerful automation workflows.
```bash
gh pr diff 123 | cline -y "Review this PR"
```
Fetches a GitHub PR diff and pipes it directly to Cline for review.
```bash
cline --json "List all TODO comments" | jq '.text'
```
Outputs structured JSON that you can process with tools like `jq` for scripting.
```bash
git diff | cline -y "explain" | cline -y "write a haiku about these changes"
```
Chains multiple Cline invocations together for creative multi-step workflows.
## Features at a Glance
| Feature | Interactive Mode | Non-Interactive Mode |
|---------|------------------|----------------------|
| Interactive chat | ✓ | - |
| File mentions (@) | ✓ | ✓ (inline) |
| Slash commands (/) | ✓ | - |
| Settings panel | ✓ | `cline config` |
| Plan/Act toggle | ✓ (Tab) | `-p` / `-a` flags |
| Auto-approve | ✓ (Shift+Tab) | `-y` flag |
| Session summary | ✓ | - |
| JSON output | - | `--json` |
| Piped input | - | ✓ |
---
## Installation & Setup
In just a few minutes, you can install the CLI, authenticate with your preferred AI provider, and start running tasks from any directory on your machine.
### Prerequisites
Cline CLI requires **Node.js version 20 or higher**. We recommend Node.js 22 for the best experience.
Check your Node.js version:
```bash
node --version
```
If you need to install or update Node.js, visit [nodejs.org](https://nodejs.org) or use a version manager like [nvm](https://github.com/nvm-sh/nvm).
### Install Cline CLI
Install globally via npm:
```bash
npm install -g cline
```
Verify the installation:
```bash
cline version
```
<Tip>
To install a specific version, use `npm install -g cline@2.0.0`. Check [npm](https://www.npmjs.com/package/cline) for available versions.
</Tip>
### Authenticate
After installation, run the authentication wizard:
```bash
cline auth
```
This launches an interactive wizard with multiple options. Choose the method that works best for your workflow.
#### Option 1: Sign in with Cline (Recommended)
Select **"Sign in with Cline"** to authenticate with your Cline account via OAuth. Your browser opens automatically to complete sign-in.
#### Option 2: Sign in with ChatGPT Subscription
If you have a ChatGPT Plus or Pro subscription, select **"Sign in with ChatGPT Subscription"**. This uses OpenAI's Codex OAuth to authenticate with your existing subscription.
#### Option 3: Import from Existing Tools
Already using another AI coding CLI? Cline can import your existing configuration:
- **Import from Codex CLI** - Imports credentials from `~/.codex/auth.json`
- **Import from OpenCode** - Imports configuration from `~/.local/share/opencode/auth.json`
#### Option 4: Bring Your Own API Key
Select **"Bring your own API key"** to manually configure any supported provider. Or skip the wizard entirely with flags:
```bash
# Anthropic (Claude)
cline auth -p anthropic -k sk-ant-api-xxxxx -m claude-sonnet-4-5-20250929
# OpenAI
cline auth -p openai-native -k sk-xxxxx -m gpt-4o
# OpenRouter
cline auth -p openrouter -k sk-or-xxxxx -m anthropic/claude-sonnet-4-5-20250929
# OpenAI-compatible provider with custom base URL
cline auth -p openai -k your-api-key -b https://api.example.com/v1
```
**Quick Setup Flags:**
| Flag | Description |
|------|-------------|
| `-p, --provider <id>` | Provider ID (e.g., `anthropic`, `openai-native`, `openrouter`) |
| `-k, --apikey <key>` | Your API key |
| `-m, --modelid <id>` | Model ID (e.g., `claude-sonnet-4-5-20250929`, `gpt-4o`) |
| `-b, --baseurl <url>` | Base URL for OpenAI-compatible providers |
<Tip>
Flags are especially useful for scripting, CI/CD environments, or setting up multiple machines.
</Tip>
#### Supported Providers
| Provider | Provider ID | Notes |
|----------|-------------|-------|
| Anthropic | `anthropic` | Direct Claude API access |
| OpenAI | `openai-native` | GPT-4o, GPT-4, etc. |
| OpenAI Codex | `openai-codex` | ChatGPT subscription OAuth |
| OpenRouter | `openrouter` | Access multiple providers |
| AWS Bedrock | `bedrock` | Claude via AWS |
| Google Gemini | `gemini` | Gemini Pro, etc. |
| X AI (Grok) | `xai` | Grok models |
| Cerebras | `cerebras` | Fast inference |
| DeepSeek | `deepseek` | DeepSeek models |
| Ollama | `ollama` | Local models |
| LM Studio | `lmstudio` | Local models |
| OpenAI Compatible | `openai` | Any OpenAI-compatible API |
### Verify Your Setup
Confirm everything is working with a simple test:
```bash
cline "What is 2 + 2?"
```
If Cline responds with an answer, your installation and authentication are complete.
Check your current configuration:
```bash
cline config
```
### Quick Start
Now you're ready to use Cline. Choose how you want to work:
#### Interactive Mode
Launch the interactive CLI for development:
```bash
cline
```
You'll see the Cline welcome screen. Type your task and press Enter. Use:
- `Tab` to toggle between Plan and Act modes
- `Shift+Tab` to enable auto-approve
- `/help` for available commands
[Learn more about interactive mode →](/cline-cli/interactive-mode)
#### Direct Task Execution
Run a task directly from your shell:
```bash
cline "Add error handling to utils.js"
```
For non-interactive execution (perfect for scripts and CI/CD):
```bash
cline -y "Run tests and fix any failures"
```
[Learn more about headless mode →](/cline-cli/three-core-flows)
### Switching Providers
To change your configured provider at any time:
```bash
cline auth
```
You can also use the settings panel in interactive mode:
```bash
cline
# Then type: /settings
# Navigate to the API tab
```
### Updating
Check for updates and install the latest version:
```bash
cline update
```
Or update manually via npm:
```bash
npm update -g cline
```
### Troubleshooting
#### Command Not Found
If `cline` is not found after installation:
1. Ensure npm global bin is in your PATH:
```bash
npm bin -g
```
2. Add the path to your shell configuration (`.bashrc`, `.zshrc`, etc.):
```bash
export PATH="$PATH:$(npm bin -g)"
```
3. Restart your terminal or source your shell config.
#### Permission Errors
If you get permission errors during installation:
```bash
# Option 1: Use a Node version manager (recommended)
# nvm, fnm, or volta handle permissions automatically
# Option 2: Fix npm permissions
# See: https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally
```
#### OAuth Flow Issues
If the browser doesn't open automatically during OAuth:
1. Copy the URL from the terminal
2. Paste it in your browser manually
3. Complete the sign-in flow
4. Return to the terminal
#### API Key Validation
If your API key is rejected:
1. Verify the key is correct and hasn't expired
2. Check that you've selected the correct provider
3. Ensure your API account has the necessary permissions
**Provider-specific tips:**
- **Anthropic**: Keys start with `sk-ant-`
- **OpenAI**: Keys start with `sk-`
- **AWS Bedrock**: Requires AWS credentials configured separately. See [AWS Bedrock documentation](/provider-config/aws-bedrock/api-key).
### Uninstallation
To remove Cline CLI:
```bash
npm uninstall -g cline
```
To also remove configuration data:
```bash
rm -rf ~/.cline
```
## Next Steps
- **[Interactive Mode](/cline-cli/interactive-mode)** - Master the interactive CLI with shortcuts and slash commands
- **[Headless Mode](/cline-cli/three-core-flows)** - Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows
- **[Configuration](/cline-cli/configuration)** - Configure settings, rules, workflows, and environment variables
- **[CLI Reference](/cline-cli/cli-reference)** - Complete command documentation with all flags and options
+4 -8
View File
@@ -74,9 +74,6 @@ cline auth -p openai-native -k sk-xxxxx -m gpt-4o
# OpenRouter
cline auth -p openrouter -k sk-or-xxxxx -m anthropic/claude-sonnet-4-5-20250929
# Moonshot
cline auth -p moonshot -k sk-xxxxx -m kimi-k2.5
# OpenAI-compatible provider with custom base URL
cline auth -p openai -k your-api-key -b https://api.example.com/v1
```
@@ -85,7 +82,7 @@ cline auth -p openai -k your-api-key -b https://api.example.com/v1
| Flag | Description |
|------|-------------|
| `-p, --provider <id>` | Provider ID (e.g., `anthropic`, `openai-native`, `openrouter`, `moonshot`) |
| `-p, --provider <id>` | Provider ID (e.g., `anthropic`, `openai-native`, `openrouter`) |
| `-k, --apikey <key>` | Your API key |
| `-m, --modelid <id>` | Model ID (e.g., `claude-sonnet-4-5-20250929`, `gpt-4o`) |
| `-b, --baseurl <url>` | Base URL for OpenAI-compatible providers |
@@ -107,7 +104,6 @@ Flags are especially useful for scripting, CI/CD environments, or setting up mul
| X AI (Grok) | `xai` | Grok models |
| Cerebras | `cerebras` | Fast inference |
| DeepSeek | `deepseek` | DeepSeek models |
| Moonshot | `moonshot` | Kimi models via Moonshot AI |
| Ollama | `ollama` | Local models |
| LM Studio | `lmstudio` | Local models |
| OpenAI Compatible | `openai` | Any OpenAI-compatible API |
@@ -161,7 +157,7 @@ For non-interactive execution (perfect for scripts and CI/CD):
cline -y "Run tests and fix any failures"
```
[Learn more about headless mode →](/cline-cli/three-core-flows)
[Learn more about CLI workflows →](/cline-cli/three-core-flows)
## Switching Providers
@@ -264,8 +260,8 @@ rm -rf ~/.cline
Master the interactive CLI with shortcuts and slash commands.
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="CLI Workflows" icon="route" href="/cline-cli/three-core-flows">
Learn interactive mode, direct execution, and automation patterns.
</Card>
<Card title="Configuration" icon="gear" href="/cline-cli/configuration">
+10 -10
View File
@@ -65,7 +65,7 @@ Keyboard shortcuts are the primary way to navigate and control the interactive C
Reference files from your workspace by typing `@` followed by the filename:
```text
```
@src/utils.ts can you add error handling to this file?
```
@@ -79,7 +79,7 @@ File search uses ripgrep for fast, fuzzy matching. You can type partial paths li
Include multiple files in a single message:
```text
```
Compare @src/old-api.ts with @src/new-api.ts and list the breaking changes
```
@@ -100,9 +100,9 @@ Type `/` to see available commands. Slash commands provide quick access to setti
### Workflow Commands
If you have [workflows](/customization/workflows) configured, they appear as additional slash commands. For example, if you have a workflow named `code-review`, you can invoke it with:
If you have [workflows](/features/slash-commands/workflows/index) configured, they appear as additional slash commands. For example, if you have a workflow named `code-review`, you can invoke it with:
```text
```
/code-review
```
@@ -120,7 +120,7 @@ Access the settings panel with `/settings`. Navigate between tabs using arrow ke
## Plan and Act Modes
Cline operates in two modes, toggled with `Tab`. These modes work the same way in the CLI as they do in the VS Code extension. For a deeper explanation of how Plan and Act modes work, see the [Plan and Act documentation](/core-workflows/plan-and-act).
Cline operates in two modes, toggled with `Tab`. These modes work the same way in the CLI as they do in the VS Code extension. For a deeper explanation of how Plan and Act modes work, see the [Plan and Act documentation](/features/plan-and-act).
### Plan Mode
@@ -211,7 +211,7 @@ Use terminal multiplexers like tmux or split terminals to run multiple Cline ins
Give Cline context about what you're working on:
```text
```
I'm building a REST API with Express. The routes are in @src/routes/ and models in @src/models/. Help me add user authentication.
```
@@ -219,7 +219,7 @@ I'm building a REST API with Express. The routes are in @src/routes/ and models
When you're unsure about the best approach:
```text
```
[Tab to Plan mode]
How should I structure the database schema for a multi-tenant SaaS app?
```
@@ -228,7 +228,7 @@ How should I structure the database schema for a multi-tenant SaaS app?
The interactive CLI maintains conversation context. Build on previous messages:
```text
```
> Add a login endpoint
[Cline creates the endpoint]
@@ -242,8 +242,8 @@ The interactive CLI maintains conversation context. Build on previous messages:
## Next Steps
<Columns cols={2}>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="CLI Workflows" icon="route" href="/cline-cli/three-core-flows">
Learn about interactive mode, direct execution, and automation patterns.
</Card>
<Card title="Configuration" icon="gear" href="/cline-cli/configuration">
+5 -14
View File
@@ -15,15 +15,6 @@ Ready to get started? Check out the [installation guide](/cline-cli/installation
## Two Ways to Use Cline CLI
<Columns cols={2}>
<Card title="Interactive Mode" icon="terminal" href="/cline-cli/interactive-mode">
**For hands-on development.** Launch `cline` in your terminal and collaborate with Cline in real-time — chat, review plans, approve actions, and iterate on tasks with a rich visual interface.
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
**For automation & CI/CD.** Run `cline -y "task"` to let Cline work autonomously — no interaction needed. Pipe input/output, get JSON results, and chain commands in scripts and pipelines.
</Card>
</Columns>
The CLI operates in two distinct modes, automatically selecting the appropriate one based on how you invoke it:
### Interactive Mode
@@ -95,7 +86,7 @@ Cline automatically detects which mode to use based on your invocation. This tab
| `cat file \| cline "task"` | Headless | stdin is piped |
| `cline "task" > output.txt` | Headless | stdout is redirected |
[Learn more about headless mode →](/cline-cli/three-core-flows)
[Learn more about CLI workflows →](/cline-cli/three-core-flows)
## Supported Model Providers
@@ -219,8 +210,8 @@ Chains multiple Cline invocations together for creative multi-step workflows.
Master the interactive CLI with keyboard shortcuts and slash commands.
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="CLI Workflows" icon="route" href="/cline-cli/three-core-flows">
Learn interactive mode, direct execution, and automation patterns.
</Card>
<Card title="Configuration" icon="gear" href="/cline-cli/configuration">
@@ -231,7 +222,7 @@ Chains multiple Cline invocations together for creative multi-step workflows.
Run Cline as an ACP agent in JetBrains, Neovim, Zed, and more.
</Card>
<Card title="CLI Samples" icon="flask" href="/cline-cli/samples/overview">
Real-world examples of headless workflows and automation patterns.
<Card title="Use in Other Editors" icon="code" href="/cline-cli/acp-editor-integrations">
Run Cline as an ACP agent in JetBrains, Neovim, Zed, and more.
</Card>
</Columns>
@@ -3,6 +3,8 @@ title: "GitHub Actions Integration"
description: "Automatically respond to GitHub issues by mentioning @cline in comments using Cline CLI in GitHub Actions."
---
# GitHub Integration Sample
Automate GitHub issue analysis with AI. Mention `@cline` in any issue comment to trigger an autonomous investigation that reads files, analyzes code, and provides actionable insights - all running automatically in GitHub Actions.
@@ -271,7 +273,7 @@ git push
Once set up, simply mention `@cline` in any issue comment:
```text
```
@cline what's causing this error?
@cline analyze the root cause
+4 -2
View File
@@ -3,6 +3,8 @@ title: "GitHub Issue RCA Sample"
description: "Automated GitHub issue analysis using Cline CLI to identify root causes."
---
# GitHub Root Cause Analysis
Automated GitHub issue analysis using Cline CLI. This script uses Cline's autonomous AI capabilities to fetch, analyze, and identify root causes of GitHub issues, outputting clean, parseable results that can be easily integrated into your development workflows.
<Note>
@@ -201,7 +203,7 @@ fi
This is where the magic happens:
```bash
# Ask Cline for its analysis, showing only the summary
# Ask Cline for his analysis, showing only the summary
cline -y "$PROMPT: $ISSUE_URL" --mode act $ADDRESS -F json | \
sed -n '/^{/,$p' | \
jq -r 'select(.say == "completion_result") | .text' | \
@@ -378,4 +380,4 @@ This pattern can be adapted for many other automation scenarios, from pull reque
- [CLI Installation Guide](https://docs.cline.bot/cline-cli/installation)
- [CLI Reference Documentation](https://docs.cline.bot/cline-cli/cli-reference)
- [Headless Mode](https://docs.cline.bot/cline-cli/three-core-flows)
- [Three Core Flows](https://docs.cline.bot/cline-cli/three-core-flows)
@@ -3,8 +3,14 @@ title: "GitHub PR Review"
description: "Automatically review Pull Requests with AI using Cline CLI in GitHub Actions."
---
# GitHub PR Review Sample
Automate code review for every Pull Request. Detailed analysis, security checks, and code suggestions provided by Cline running autonomously in GitHub Actions.
<Frame>
<img src="https://storage.googleapis.com/cline_public_images/cli-pr-review.png" alt="Cline PR Review Comment" width="600" />
</Frame>
## The Workflow
When a PR is opened or marked ready for review, this workflow:
+13 -8
View File
@@ -3,21 +3,26 @@ title: "Model Orchestration"
description: "Use multiple AI models strategically: optimize costs, reduce bias, and leverage model-specific strengths in your workflows"
---
# Model Orchestration
Cline CLI's `--config` and `--thinking` flags enable sophisticated multi-model workflows. Instead of using a single model for all tasks, you can route different work to different models based on cost, capability, and specialization.
## Why Orchestrate Multiple Models?
**Cost Optimization**
By routing work to the right model for the job, you can dramatically reduce API costs. Fast, inexpensive models like Haiku and Gemini Flash handle simple tasks such as summarization, while expensive models like Opus and O1 are reserved for complex reasoning and planning. This approach can reduce costs by 10-100x on routine operations.
- Use fast, cheap models (Haiku, Gemini Flash) for simple tasks like summarization
- Reserve expensive models (Opus, O1) for complex reasoning and planning
- Reduce API costs by 10-100x on routine operations
**Bias Reduction**
Different models catch different issues, so cross-validating solutions with multiple AI perspectives helps reduce blind spots that come from relying on a single model. In code reviews especially, combining viewpoints surfaces problems that any one model might miss.
- Different models catch different issues in code reviews
- Cross-validate solutions with multiple AI perspectives
- Reduce blind spots from single-model thinking
**Specialization**
Certain models excel in specific domains: Codex and DeepSeek are strong at code generation, while GPT-4 and Claude shine at documentation and prose. Security analysis in particular benefits from combining multiple model viewpoints, since each brings different training data and heuristics to the table.
- Some models excel at code (Codex, DeepSeek)
- Others are better at documentation (GPT-4, Claude)
- Security analysis benefits from multiple viewpoints
## Pattern 1: CI/CD Code Review
@@ -208,8 +213,8 @@ cat *-sec.md | cline -y "find security issues all 3 reviews mentioned"
Complete documentation for --config and --thinking flags
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="Three Core Flows" icon="route" href="/cline-cli/three-core-flows">
Learn about interactive mode, headless automation, and multi-instance workflows
</Card>
<Card title="Model Selection Guide" icon="brain" href="/core-features/model-selection-guide">
+1 -1
View File
@@ -53,4 +53,4 @@ This section provides sample implementations that demonstrate various Cline CLI
- [CLI Installation Guide](/cline-cli/installation)
- [CLI Reference Documentation](/cline-cli/cli-reference)
- [Headless Mode](/cline-cli/three-core-flows)
- [Three Core Flows](/cline-cli/three-core-flows)
@@ -3,6 +3,8 @@ title: "Worktree Workflows"
description: "Use Git worktrees with Cline CLI to run parallel tasks, test different approaches, and pipe context between isolated environments"
---
# Worktree Workflows
Git worktrees let you have multiple branches checked out simultaneously in different folders. Combined with Cline CLI's `--cwd` flag, this enables powerful parallel development workflows and isolated experimentation.
<Tip>
@@ -267,7 +269,7 @@ git worktree remove ~/cline-worktrees/feature-auth
Complete documentation for --cwd and all other CLI flags
</Card>
<Card title="Headless Mode" icon="robot" href="/cline-cli/three-core-flows">
Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows.
<Card title="Three Core Flows" icon="route" href="/cline-cli/three-core-flows">
Learn about interactive mode, task mode, and plain text workflows
</Card>
</Columns>
+129 -81
View File
@@ -1,62 +1,72 @@
---
title: "Headless Mode"
description: "Run Cline autonomously in scripts, CI/CD pipelines, and automated workflows"
title: "CLI Workflows"
description: "Learn the three ways to use Cline CLI: interactive mode, direct task execution, and automation"
---
Headless mode runs Cline without an interactive interface — perfect for automation, scripting, and CI/CD pipelines where human interaction isn't possible or desired. Cline executes tasks, produces clean text or JSON output, and exits when complete.
For collaborative, conversational development, see [Interactive Mode](/cline-cli/interactive-mode) instead.
Cline CLI supports three primary workflows, each optimized for different use cases. Choose the approach that best fits your needs.
<Note>
**Migrating from an older CLI version?** Instance commands (`cline instance new/list/kill`) have been removed in Cline CLI 2.0. The new architecture is simpler — just use `cline -y "task"` for headless execution.
**Migrating from an older CLI version?** Instance commands (`cline instance new/list/kill`) have been removed in Cline CLI 2.0. The new architecture is simpler. Just run `cline` for interactive mode or `cline "task"` for direct execution.
</Note>
## When Headless Mode Activates
## 1. Interactive Mode
Cline automatically enters headless mode when any of these conditions are met:
The interactive CLI provides the richest experience for interactive development.
| Invocation | Reason |
|------------|--------|
| `cline -y "task"` | `-y`/`--yolo` flag forces headless |
| `cline --json "task"` | `--json` flag forces headless |
| `cat file \| cline "task"` | stdin is piped |
| `cline "task" > output.txt` | stdout is redirected |
If none of these apply (e.g., running `cline` or `cline "task"` in a terminal), Cline launches in [interactive mode](/cline-cli/interactive-mode).
## YOLO Mode (Fully Autonomous)
The `-y` or `--yolo` flag enables fully autonomous operation — Cline approves all actions and runs without prompts:
### Getting Started
```bash
cline -y "Run the test suite and fix any failures"
cline
```
In YOLO mode:
- All actions are auto-approved
- Output is plain text (non-interactive)
- Process exits automatically when complete
- Perfect for CI/CD and scripts
This launches an interactive session in your current directory. Type your task, and Cline will analyze and execute it.
<Warning>
YOLO mode gives Cline full autonomy. Run on a clean git branch so you can easily revert changes if needed.
</Warning>
### Key Features
### Mode Selection
**Plan/Act Mode Toggle** - Press `Tab` to switch between modes:
- **Plan Mode**: Cline analyzes your request and presents a strategy
- **Act Mode**: Cline executes actions directly
Control whether Cline plans first or acts immediately:
**Auto-approve Toggle** - Press `Shift+Tab` to enable automatic approval for all actions.
**Slash Commands** - Type `/` for quick access to:
- `/settings` - Configure providers, models, and features
- `/models` - Quick model switching
- `/history` - Browse and resume previous tasks
- `/clear` - Start a fresh task
- `/help` - Show available commands
**File Mentions** - Type `@` to reference workspace files:
```
@src/utils.ts add error handling to this file
```
**Session Summary** - When you exit with `Ctrl+C`, Cline displays a summary of your session including tasks completed, files modified, and token usage.
### When to Use Interactive Mode
- Exploring a new codebase
- Complex refactoring that requires back-and-forth
- Learning how Cline approaches problems
- Tasks where you want to review before executing
[Full Interactive Mode Guide →](/cline-cli/interactive-mode)
## 2. Direct Task Execution
Execute tasks directly from the command line without entering interactive mode.
### Basic Usage
```bash
# Start in Plan mode (analyze before acting)
cline -y -p "Design a REST API for user management"
# Start in Act mode (default)
cline -y -a "Fix the typo in README.md"
cline "Add unit tests to utils.js"
```
## Piping Context
Cline analyzes your task, creates a plan, and executes it. You'll be prompted for approval at key decision points.
Pipe file contents or command output into Cline to provide context:
### Piping Context
Pipe file contents or command output into Cline:
```bash
# Explain a file
@@ -67,16 +77,11 @@ git diff | cline "Review these changes and suggest improvements"
# Analyze command output
npm test 2>&1 | cline "Analyze these test failures and fix them"
# Pipe a GitHub PR diff
gh pr diff 123 | cline -y "Review this PR"
```
When stdin is piped, Cline automatically enters headless mode — the piped content becomes part of the task context.
### Chaining Cline Commands
## Chaining Commands
Pipe Cline's output into another Cline instance for multi-step workflows:
Pipe Cline's output into another Cline instance for creative workflows:
```bash
# Explain changes, then write a commit message
@@ -89,9 +94,59 @@ cline -y "create a fibonacci function" | cline -y "write unit tests for this cod
git diff | cline -y "explain" | cline -y "write a haiku about this"
```
## JSON Output
### Including Images
Use `--json` for machine-readable output that's easy to parse in scripts:
Attach images to your task:
```bash
cline task -i screenshot.png "Fix the layout issue shown in this screenshot"
# Or reference inline
cline "Fix the UI shown in @./design-mockup.png"
```
### Mode Selection
```bash
# Start in Plan mode (analyze before acting)
cline -p "Design a REST API for user management"
# Start in Act mode (default)
cline -a "Fix the typo in README.md"
```
### When to Use Direct Execution
- Quick, well-defined tasks
- Tasks with sufficient context in the prompt
- Scripting and shell workflows
- When you don't need interactive conversation
## 3. Automation & CI/CD
For fully autonomous operation in scripts, CI/CD pipelines, and automated workflows.
### YOLO Mode (Yes Mode)
The `-y` or `--yolo` flag enables fully autonomous operation:
```bash
cline -y "Run the test suite and fix any failures"
```
In YOLO mode:
- All actions are auto-approved
- Output is plain text (non-interactive)
- Process exits automatically when complete
- Perfect for CI/CD and scripts
<Warning>
Run YOLO mode on a clean git branch or directory. You get speed in exchange for oversight, so be ready to revert if needed.
</Warning>
### JSON Output
Use `--json` for machine-readable output:
```bash
cline --json "List all TODO comments in the codebase" | jq '.text'
@@ -109,36 +164,25 @@ JSON output follows the same format as task files in `~/.cline/data/tasks/<id>/u
| `reasoning` | `string` | (Optional) Model reasoning |
| `partial` | `boolean` | (Optional) Streaming flag |
## Including Images
### Timeout Control
Attach images to your headless task:
```bash
cline -y -i screenshot.png "Fix the layout issue shown in this screenshot"
# Or reference inline
cline -y "Fix the UI shown in @./design-mockup.png"
```
## Timeout Control
Set a maximum execution time to prevent runaway tasks:
Set a maximum execution time:
```bash
cline -y --timeout 600 "Run full test suite"
```
## Environment Variables
### Environment Variables
Control Cline behavior via environment variables — useful for CI/CD where you can't use interactive configuration.
Control Cline behavior via environment variables:
**CLINE_DIR** Custom configuration directory:
**CLINE_DIR** - Custom configuration directory:
```bash
export CLINE_DIR=/path/to/config
cline -y "your task"
```
**CLINE_COMMAND_PERMISSIONS** Restrict allowed commands:
**CLINE_COMMAND_PERMISSIONS** - Restrict allowed commands:
```bash
export CLINE_COMMAND_PERMISSIONS='{"allow": ["npm *", "git *"], "deny": ["rm -rf *"]}'
cline -y "your task"
@@ -146,8 +190,6 @@ cline -y "your task"
See [Configuration](/cline-cli/configuration#environment-variables) for full documentation.
## CI/CD Integration
### GitHub Actions Example
Automate PR reviews with Cline:
@@ -190,7 +232,7 @@ jobs:
### Shell Script Example
Create a reusable code review script:
Create a code review script:
```bash
#!/bin/bash
@@ -210,24 +252,30 @@ fi
echo "$DIFF" | cline -y --json "Review this code diff for issues" | jq -r '.text'
```
## Common Use Cases
### When to Use Automation Mode
| Use Case | Example |
|----------|---------|
| Code review | `git diff \| cline -y "Review these changes"` |
| Fix test failures | `cline -y "Run tests and fix any failures"` |
| Generate release notes | `git log --oneline v1.0..v1.1 \| cline -y "Write release notes"` |
| Fix lint errors | `cline -y "Fix all ESLint errors in src/"` |
| Update dependencies | `cline -y "Update dependencies with known vulnerabilities"` |
| Migrate code patterns | `cline -y "Update all deprecated React lifecycle methods"` |
| PR automation | `gh pr diff 123 \| cline -y "Review this PR"` |
| Batch processing | `cline -y --json "List all TODO comments" \| jq '.text'` |
- CI/CD pipelines
- Scheduled maintenance tasks
- Batch processing
- Any workflow requiring non-interactive execution
## Choosing the Right Flow
| Use Case | Recommended Flow |
|----------|------------------|
| Exploring a new codebase | Interactive Mode |
| Complex refactoring | Interactive Mode (Plan first) |
| Quick file edits | Direct Execution |
| Code review | Direct Execution with pipe |
| CI/CD integration | Automation (`-y` flag) |
| Scheduled tasks | Automation (`-y` flag) |
| Learning Cline | Interactive Mode |
## Next Steps
<Columns cols={2}>
<Card title="Interactive Mode" icon="terminal" href="/cline-cli/interactive-mode">
For hands-on development with keyboard shortcuts, slash commands, and file mentions.
Master keyboard shortcuts, slash commands, and file mentions.
</Card>
<Card title="CLI Reference" icon="book" href="/cline-cli/cli-reference">
@@ -238,7 +286,7 @@ echo "$DIFF" | cline -y --json "Review this code diff for issues" | jq -r '.text
Environment variables, rules, and advanced settings.
</Card>
<Card title="CLI Samples" icon="flask" href="/cline-cli/samples/overview">
Real-world examples of headless workflows and automation patterns.
<Card title="YOLO Mode" icon="zap" href="/features/yolo-mode">
Deep dive into autonomous execution and safety considerations.
</Card>
</Columns>
-316
View File
@@ -1,316 +0,0 @@
---
title: "Documentation Templates"
sidebarTitle: "Templates"
description: "Templates for different types of Cline documentation"
---
Use these templates as starting points for new documentation. Each template is designed for a specific purpose. Choose the one that best fits what you're documenting.
## Choosing a Template
| If you're documenting... | Use this template |
|--------------------------|-------------------|
| What a feature does and how to use it | Feature Doc |
| How to accomplish a specific task | How-To Guide |
| Technical specifications or API details | Reference Doc |
| A complete project walkthrough | Tutorial |
## Feature Doc
Use this template when explaining a Cline feature. Focus on what it does, how to use it, and real examples.
````text
---
title: "Feature Name"
sidebarTitle: "Feature Name"
---
[One sentence explaining what this feature does.]
<Frame>
<img src="..." alt="Feature in action" />
</Frame>
[1-2 paragraphs explaining the feature in plain terms. What problem does it
solve? Why would someone use it?]
## How It Works
[Explain the mechanics without jargon. What happens when you use this feature?]
## Using [Feature Name]
[Show how to access and use it. Include the exact UI path.]
### [Option or Variation 1]
[Details with examples]
### [Option or Variation 2]
[Details with examples]
## Inspiration
[Share how you personally use this feature. Use "I" voice. Give 2-3 real
examples that spark imagination about what's possible.]
<Note>
[Important caveat, limitation, or requirement]
</Note>
````
### Example: Checkpoints Feature
Here's how the [Checkpoints](/core-workflows/checkpoints) doc follows this pattern:
- Opens with one clear sentence about what checkpoints do
- Shows a screenshot of the feature in action
- Explains how checkpoints work under the hood
- Shows exact steps to create and restore checkpoints
- Includes real examples of when checkpoints save the day
## How-To Guide
Use this template when showing how to accomplish a specific task. Focus on clear steps and troubleshooting.
````text
---
title: "How to [Accomplish Task]"
sidebarTitle: "[Short Title]"
description: "[One sentence describing what the reader will learn]"
---
[Brief intro explaining what problem this guide solves and what you'll end up
with after following it.]
## Prerequisites
[What the reader needs before starting. Keep it short. Link to other docs
rather than explaining setup here.]
- Cline installed and configured
- [Other requirement]
## Steps
<Steps>
<Step title="[First Action]">
[Clear instructions. Show exactly what to click or type.]
```bash
example command if needed
```
</Step>
<Step title="[Second Action]">
[Next step. Include screenshots for complex UI interactions.]
<Frame>
<img src="..." alt="What you should see" />
</Frame>
</Step>
<Step title="[Final Action]">
[Complete the task. Show the expected result.]
</Step>
</Steps>
## Troubleshooting
Common issues and how to fix them:
- **Problem description**: Solution in one or two sentences.
- **Another problem**: Another solution.
## Next Steps
<Card title="Related Feature" icon="arrow-right" href="/path/to/related">
Continue learning with this related guide.
</Card>
````
### Example: Your First Project
The [Your First Project](/getting-started/your-first-project) guide follows this pattern:
- Clear goal stated upfront
- Prerequisites listed briefly
- Step-by-step instructions with the Steps component
- Troubleshooting section for common issues
## Reference Doc
Use this template for technical specifications, API documentation, or detailed configuration options.
````text
---
title: "[Component/API] Reference"
sidebarTitle: "[Short Title]"
description: "[What this reference covers]"
---
[Brief description of what this reference documents and when you'd need it.]
## Overview
[High-level explanation. What is this component? What role does it play?]
## [Category 1]
### [Item Name]
[What it does in one sentence.]
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `propertyName` | `string` | `"default"` | What this property controls |
| `anotherProp` | `boolean` | `false` | What this does |
**Example:**
```typescript
// Show practical usage
const example = {
propertyName: "custom value",
anotherProp: true
}
```
### [Another Item]
[Continue for each item in this category.]
## [Category 2]
[Continue with other categories as needed.]
## Examples
[Show 2-3 complete, practical examples that combine multiple concepts.]
### [Example 1 Title]
```typescript
// Complete working example
```
### [Example 2 Title]
```typescript
// Another complete example
```
## Related
- [Related Doc 1](/path/to/doc) - Brief description
- [Related Doc 2](/path/to/doc) - Brief description
````
### Example: Cline Tools Guide
The [Cline Tools Guide](/tools-reference/all-cline-tools) follows this pattern:
- Overview of the tool system
- Each tool documented with parameters and examples
- Practical examples showing tools in context
## Tutorial
Use this template for comprehensive project walkthroughs where users build something from start to finish.
````text
---
title: "[Build/Create X] Tutorial"
sidebarTitle: "[Short Title]"
description: "[What the reader will build]"
---
In this tutorial, you'll build [specific outcome]. By the end, you'll have
[tangible result you can see/use].
<Frame>
<img src="..." alt="Preview of what you'll build" />
</Frame>
## What You'll Learn
- [Skill or concept 1]
- [Skill or concept 2]
- [Skill or concept 3]
## Prerequisites
[Required setup. Link to installation guides rather than repeating them.]
- [Prerequisite 1]
- [Prerequisite 2]
## Part 1: [First Major Section]
[Introduction to this section. What are we doing and why?]
### [Subsection]
[Detailed walkthrough with code blocks and explanations.]
```typescript
// Code that the reader should write or understand
```
[Explain what the code does and why.]
## Part 2: [Second Major Section]
[Continue building on Part 1.]
### [Subsection]
[More detailed walkthrough.]
## Part 3: [Final Section]
[Complete the project.]
## Summary
You built [what they built]. Along the way, you learned:
- [Key takeaway 1]
- [Key takeaway 2]
- [Key takeaway 3]
## Next Steps
<CardGroup cols={2}>
<Card title="Go Deeper" icon="book" href="/path/to/advanced">
Learn more advanced techniques.
</Card>
<Card title="Related Tutorial" icon="code" href="/path/to/related">
Build something else with similar concepts.
</Card>
</CardGroup>
````
### Example Structure
A good tutorial:
- Shows the end result upfront so readers know what they're building
- Breaks the work into logical parts
- Explains the "why" alongside the "how"
- Ends with clear next steps
## Quick Tips
When using these templates:
1. **Delete sections you don't need.** Templates are starting points, not rigid structures.
2. **Add sections that make sense.** If your doc needs something not in the template, add it.
3. **Keep the reader moving forward.** Every section should lead naturally to the next.
4. **Test your own instructions.** Follow your guide from scratch to catch missing steps.
<Tip>
Use the `/write-docs` workflow to generate documentation from these templates automatically.
Cline helps you fill in each section based on your project.
</Tip>
-200
View File
@@ -1,200 +0,0 @@
---
title: "Documentation Guide"
sidebarTitle: "Documentation Guide"
description: "How to write and contribute to Cline documentation"
---
Cline's documentation lives in the `docs/` directory and uses [Mintlify](https://mintlify.com) for rendering. This guide covers how to write docs that match Cline's established style.
## Using the Documentation Workflow
The fastest way to create documentation is using the `/write-docs` workflow. Type `/write-docs` in Cline and describe what you want to document. Cline guides you through a 4-step process:
1. **Research**: Examine existing docs structure and patterns
2. **Scope**: Clarify audience, doc type, and key use cases
3. **Outline**: Select a template and create structure
4. **Write**: Generate documentation following style guidelines
The workflow file lives at `.clinerules/workflows/write-docs.md` and contains templates, style rules, and examples.
## Documentation Principles
### Write for Developers
Your audience is developers who value their time. Get to the point. Every sentence should either help them understand something or help them do something.
```markdown
# Good
Switch to bash in Cline Settings → Terminal → Default Terminal Profile.
# Bad
Users who are experiencing issues may find it helpful to navigate to the
Cline settings menu where they can locate the terminal configuration
options and subsequently modify the default terminal profile setting.
```
### Show Real Examples
Abstract descriptions don't help anyone. Show actual code, real file paths, and concrete implementations.
```markdown
# Good
I use `/deep-planning` whenever I'm building features that touch multiple
parts of the codebase. For example, when adding authentication, Cline
mapped every endpoint and created a migration plan that avoided breaking changes.
# Bad
The deep planning feature can be utilized for various complex tasks
that may require careful consideration and planning.
```
### Use Active Voice
Cline does things. Files don't get created by Cline, Cline creates files.
```markdown
# Good
Cline reads your project files and builds context automatically.
# Bad
Project files are read and context is built automatically.
```
### Use Neutral Pronouns for Cline
Refer to Cline as "it" not "he". Cline is software, not a person.
```markdown
# Good
When Cline encounters an error, it suggests fixes.
# Bad
When Cline encounters an error, he suggests fixes.
```
## File Format
All documentation uses MDX format with YAML frontmatter:
```yaml
---
title: "Full Page Title"
sidebarTitle: "Shorter Nav Title" # optional
description: "One sentence for SEO" # optional but recommended
---
```
### Adding New Pages
After creating a new `.mdx` file, add it to `docs/docs.json` in the appropriate navigation group:
```json
{
"group": "Features",
"pages": [
"features/existing-page",
"features/your-new-page"
]
}
```
## Mintlify Components
Use these components appropriately throughout your docs.
### Frame
Wrap all images and videos:
```jsx
<Frame>
<img
src="https://storage.googleapis.com/cline_public_images/docs/assets/filename.png"
alt="Descriptive alt text"
/>
</Frame>
```
### Callouts
Use sparingly and purposefully:
```jsx
<Tip>Helpful suggestions that improve the experience.</Tip>
<Note>Important information the reader needs to know.</Note>
<Warning>Something that could cause problems if ignored.</Warning>
```
### Steps
For sequential procedures:
```jsx
<Steps>
<Step title="Install the Extension">
Search for "Cline" in the VS Code marketplace.
</Step>
<Step title="Configure Your Model">
Open settings and add your API key.
</Step>
</Steps>
```
### Cards
For navigation and feature overviews:
```jsx
<CardGroup cols={2}>
<Card title="Getting Started" icon="rocket" href="/getting-started/installing-cline">
Install Cline and set up your first project.
</Card>
<Card title="Features" icon="wand-magic-sparkles" href="/core-workflows/plan-and-act">
Explore what Cline can do.
</Card>
</CardGroup>
```
## Style Rules
Quick reference for consistent documentation:
| Do | Don't |
|---|---|
| Use "use" | Use "utilize" |
| Keep sentences under 25 words | Write run-on sentences |
| Use bullet points for lists | Write walls of text |
| Show where things are in the UI | Assume users can find features |
| Cross-link related docs | Leave readers stranded |
| Use code blocks with language tags | Use inline code for long snippets |
### Avoid These Patterns
- Em dashes and emojis
- Starting with "This document explains..."
- The **Bold Text**: description pattern
- Explaining obvious things
- Passive voice
## Previewing Changes
Run the docs locally to preview your changes:
```bash
cd docs
npm install # first time only
npm run dev
```
Open `http://localhost:3000` to see your changes in real time.
## Related Resources
<CardGroup cols={2}>
<Card title="Documentation Templates" icon="file-lines" href="/contributing/doc-templates">
Templates for different documentation types.
</Card>
<Card title="Workflows" icon="diagram-project" href="/customization/workflows">
Learn about Cline's workflow system.
</Card>
</CardGroup>
+8 -26
View File
@@ -1,6 +1,6 @@
---
title: "Model Selection Guide"
description: "Choose the right AI model for your workflow based on reliability, speed, cost, and context window size."
description: "Last updated: August 20, 2025."
---
New models drop constantly, so this guide focuses on what's working well with Cline right now. We'll keep it updated as the landscape shifts.
@@ -59,17 +59,12 @@ Choose your preferred AI provider from the dropdown menu.
| **Cline** | Easiest setup | No API keys needed, access to multiple models including stealth models |
| **OpenRouter** | Value seekers | Multiple models, competitive pricing |
| **Anthropic** | Reliability | Claude models, most dependable tool usage |
| **OpenAI** | Latest tech | GPT-5, o3, o4-mini models |
| **OpenAI Codex** | ChatGPT subscribers | Use your ChatGPT subscription — no API key needed |
| **Google Gemini** | Large context | Gemini 3/2.5 with up to 2M context |
| **DeepSeek** | Budget reasoning | V3.2, R1 models at low cost |
| **Alibaba Qwen** | Open source coding | Qwen3 Coder with 1M context |
| **Moonshot** | Agentic coding | Kimi K2.5 with 262K context |
| **Cerebras** | Speed | Up to 2,600 tokens/sec |
| **OpenAI** | Latest tech | GPT models |
| **Google Gemini** | Large context | Google's AI models |
| **AWS Bedrock** | Enterprise | Advanced features |
| **Ollama** | Privacy | Run models locally |
See the [full provider list](/getting-started/authorizing-with-cline) for all 30+ supported providers including xAI Grok, Mistral, Groq, Fireworks, Together, Baseten, SambaNova, Nebius, Hugging Face, and more.
See the [full provider list](/provider-config) for more options including Cerebras, Vertex AI, Azure, and more.
<Info>
**Recommended for beginners:** Start with **Cline** as your provider - no API key management needed, instant access to multiple models, and occasional free inferencing through partner providers.
@@ -86,19 +81,6 @@ The next step depends on which provider you selected.
- You'll be redirected to [app.cline.bot](https://app.cline.bot) to authenticate
- After signing in, return to your IDE
<Note>
For detailed information about the Cline authentication flow, OAuth tokens, and troubleshooting, see [Authorizing with Cline](/getting-started/authorizing-with-cline).
</Note>
#### If you selected **OpenAI Codex** as your provider:
- **No API key needed!** If you have a ChatGPT subscription (Plus, Pro, or Team), you can use it directly in Cline
- Click **"Sign in with OpenAI"** to authenticate via your browser
- Once authorized, all models available on your OpenAI plan will appear automatically
- Usage is governed by your ChatGPT subscription — no separate API billing
See the full [OpenAI Codex setup guide](/provider-config/openai-codex) for details.
#### If you selected any other provider:
You'll need to get an API key from your chosen provider:
@@ -108,7 +90,7 @@ You'll need to get an API key from your chosen provider:
- **OpenRouter**: [openrouter.ai/keys](https://openrouter.ai/keys)
- **OpenAI**: [platform.openai.com/api-keys](https://platform.openai.com/api-keys)
- **Google**: [aistudio.google.com/apikey](https://aistudio.google.com/apikey)
- **Others**: See [Provider Setup Guide](/getting-started/authorizing-with-cline)
- **Others**: See [Provider Setup Guide](/provider-config)
2. **Generate a new API key** on the provider's website
@@ -186,7 +168,8 @@ Selecting the right model involves balancing several factors. Use this framework
## Model Comparison Resources
For detailed model comparisons and performance metrics, see:
For detailed model comparisons, pricing, and performance metrics, see:
- [**Model Comparison & Pricing**](/model-config/model-comparison) - Complete pricing tables and performance benchmarks
- [**Context Window Guide**](/model-config/context-windows) - Understanding and optimizing context usage
## Open Source vs Closed Source
@@ -212,9 +195,8 @@ For detailed model comparisons and performance metrics, see:
| Huge context windows | Gemini 2.5 Pro or Claude Sonnet 4.5 |
| Open source | Qwen3 Coder, Z AI GLM 4.5, or Kimi K2 |
| Latest tech | GPT-5 |
| To use your ChatGPT subscription | [OpenAI Codex](/provider-config/openai-codex) — sign in with your OpenAI account, no API key needed |
| Speed | Qwen3 Coder on Cerebras (fastest available) |
## What Others Are Using
Check [Vercel's leaderboard](https://vercel.com/ai-gateway/leaderboards) to see real usage patterns from the community.
Check [OpenRouter's Cline usage stats](https://openrouter.ai/apps?url=https%3A%2F%2Fcline.bot%2F) to see real usage patterns from the community.
-95
View File
@@ -1,95 +0,0 @@
---
title: "Checkpoints"
sidebarTitle: "Checkpoints"
description: "Roll back code changes while keeping your conversation. Experiment freely."
---
Checkpoints let you undo code changes without losing your conversation. Every time Cline modifies a file or runs a command, it saves a snapshot of your project files. You can restore to any checkpoint, keeping the context you've built while reverting the code.
This changes how you work with Cline. Instead of carefully reviewing every change before approving, you can let Cline move fast and roll back if something goes wrong. The cost of a mistake drops to nearly zero.
<Tip>
Checkpoints are enabled by default. See [Enable or Disable Checkpoints](#enable-or-disable-checkpoints) if you need to turn them off.
</Tip>
## How It Works
Cline maintains a shadow Git repository separate from your project's actual Git history. After each tool use (file edits, commands, etc.), Cline commits the current state of your files to this shadow repo. Your main Git repository stays untouched.
This means:
- Your Git history remains clean and under your control
- Checkpoints capture everything, including files not tracked by Git
- You can restore to any point in a task without affecting commits you've made
- Checkpoints persist across editor sessions
Each checkpoint captures the complete file state at that moment. If Cline edits three files in sequence, you get three checkpoints and can restore to any of them independently.
## Enable or Disable Checkpoints
Checkpoints are enabled by default. To toggle them:
1. Open Cline settings (gear icon in the Cline sidebar)
2. Scroll to the "Feature Settings" section
3. Toggle "Enable Checkpoints"
<Note>
For very large repositories, checkpoints may use significant storage and slow down Cline as it commits file snapshots after each tool use. Consider disabling them if you notice performance issues.
</Note>
## Viewing and Comparing Changes
After each tool use, a checkpoint indicator appears in your conversation. Look for a bookmark icon labeled "Checkpoint" with a dotted line connecting to **Compare** and **Restore** buttons.
Click **Compare** to open a diff view showing exactly what changed at that checkpoint. This opens in your editor's diff viewer, letting you see additions, deletions, and modifications across all affected files.
This is useful when Cline makes changes you want to understand before deciding whether to keep them. You can review the diff, then either continue or restore to undo.
## Restoring Checkpoints
Click **Restore** next to any step to open the restore menu. You have three options:
| Option | What It Does | When to Use It |
|--------|--------------|----------------|
| **Restore Files** | Reverts your project's files to the snapshot at this checkpoint | Undoing code changes while keeping the conversation |
| **Restore Task Only** | Deletes messages after this point, does not affect files | Trying a different prompt while keeping current code |
| **Restore Files & Task** | Reverts files and deletes messages after this point | Starting over completely from a known good state |
The right choice depends on what went wrong:
- If the conversation is productive but the code changes broke something, use **Restore Files**. Cline keeps all the context you've discussed and can try a different implementation.
- If Cline's code changes are good but the conversation went off track, use **Restore Task Only**. You keep the files and can guide the conversation differently.
- If you want to start over from a clean slate, use **Restore Files & Task**. This resets both your files and the conversation to that checkpoint.
## When to Use Checkpoints
| Scenario | Recommended Action |
|----------|-------------------|
| Cline refactored code and broke something | Restore Files, ask for a different approach |
| Experimenting with multiple solutions | Compare each checkpoint, restore to the best one |
| Cline misunderstood your intent | Restore Files & Task, rephrase your request |
| Want to try a different prompt | Restore Task Only, keep the files, resubmit |
| Reviewing changes before committing to Git | Use Compare to inspect, then commit manually |
| Testing risky changes | Let Cline proceed, restore if it fails |
## Working with Auto-Approve
Checkpoints make [auto-approve](/features/auto-approve) practical. Without checkpoints, auto-approve feels risky because Cline can make many changes before you notice a problem. With checkpoints, you can let Cline work autonomously and roll back if needed.
A typical workflow:
1. Enable auto-approve for file edits and commands
2. Let Cline work through your task quickly
3. Review the final result
4. If something is wrong, restore to the last good checkpoint
5. Give Cline more specific guidance
This approach is faster than reviewing every change individually, and checkpoints provide the safety net.
## Checkpoints and Message Editing
The message editing feature integrates with checkpoints. When you edit a previous message and select "Restore All," Cline restores your files to the checkpoint at that point before resubmitting your edited message.
This lets you fix a poorly worded prompt and undo all the changes that resulted from it in one action.
-120
View File
@@ -1,120 +0,0 @@
---
title: "Plan & Act Mode"
sidebarTitle: "Plan & Act Mode"
description: "Think first, then build. Cline's dual-mode system for structured development."
---
Plan & Act modes separate thinking from doing. Plan mode lets you explore and strategize without changing files. Act mode executes against your plan.
<Tip>
**New to Plan & Act?** Watch [Plan & Act Deep Dive](https://youtu.be/b7o6URFPp64) to see it in action.
</Tip>
## Plan Mode
Plan mode is where you and Cline figure out what you're building and how. In this mode, Cline can read your codebase, run searches, and discuss strategy, but cannot modify any files or execute commands.
This constraint is intentional. It keeps the conversation focused on understanding and planning, without the distraction of implementation details. You can explore freely, ask questions, and iterate on the approach before committing to changes.
Use Plan mode to:
- Explore unfamiliar codebases before making changes
- Discuss architecture decisions and tradeoffs
- Identify edge cases and potential issues upfront
- Create a clear implementation strategy
- Review code and understand complex workflows
## Act Mode
Once you have a plan, switch to Act mode. Cline retains the full context from your planning session and can now modify files, run commands, and execute your strategy.
The conversation history carries over when you switch modes. Cline remembers everything you discussed in Plan mode, so you don't need to repeat yourself. This makes the transition seamless.
<Note>
While you can start directly in Act mode, planning first is highly recommended. The planning phase intentionally builds context that Cline needs to implement changes effectively. Without it, Cline may lack the understanding required to make the right decisions.
</Note>
## Typical Workflow
1. Start in Plan mode and describe what you want to build
2. Let Cline explore relevant files and understand the codebase
3. Discuss the approach, considering edge cases and potential issues
4. When confident in the plan, switch to Act mode
5. Cline implements the solution based on your planning session
For complex projects, you may cycle between modes multiple times. Return to Plan mode when you hit unexpected complexity or need to rethink the approach, then switch back to Act mode to continue implementation.
## When to Use Each Mode
| Scenario | Recommended Mode |
|----------|-----------------|
| Starting new features where the approach isn't obvious | Plan |
| Debugging tricky issues where you're unsure what's wrong | Plan |
| Making architectural decisions affecting multiple files | Plan |
| Understanding complex workflows before modifying them | Plan |
| Code review and security analysis | Plan |
| Learning a new codebase | Plan |
| Implementing a solution you've already planned | Act |
| Making routine changes with a clear approach | Act |
| Following established patterns in the codebase | Act |
| Running tests and making adjustments | Act |
| Quick fixes where the solution is obvious | Act |
## Using Different Models for Each Mode
You can configure separate models for Plan and Act modes. This is useful when you want to use a stronger reasoning model for planning and a faster model for implementation.
To enable this:
1. Open Cline Settings
2. Enable "Use different models for Plan and Act"
3. Select your preferred model for each mode
When enabled, switching between Plan and Act mode automatically switches to the configured model for that mode. Your model selection is preserved when you switch back.
**Example configurations:**
| Use Case | Plan Mode | Act Mode |
|----------|-----------|----------|
| Cost optimization | GLM 4.6 | Grok Code Fast |
| Maximum quality | Claude Opus | Claude Sonnet |
| Speed-focused | Gemini 3 Flash | Cerebras |
## Using `/deep-planning`
For complex tasks that need thorough analysis, use the `/deep-planning` slash command. This triggers an extended planning session where Cline:
1. Explores the codebase systematically
2. Identifies all affected files and dependencies
3. Creates a detailed implementation plan
4. Asks clarifying questions before proceeding
The deep planning prompt is optimized for each model family, so it adapts to the strengths of whatever model you're using. See the [Deep Planning docs](/features/deep-planning) for more details.
## Choosing the Right Approach by Task Size
### Small tasks: Act mode only
For quick fixes like typos, simple bug fixes, or following established patterns, start directly in Act mode. Planning adds overhead when the solution is obvious.
**Examples:** Fix a typo, add a missing import, update a config value, rename a variable.
### Medium tasks: Plan → Act
For most development work, start in Plan mode to understand the scope and approach, then switch to Act mode to implement. This is the sweet spot for features that touch a few files and have some complexity.
**Examples:** Add a new API endpoint, implement a UI component, fix a bug that requires investigation, refactor a single module.
### Large tasks: Use `/deep-planning`
For complex features that span multiple files, require architectural decisions, or will take multiple sessions to complete, use the `/deep-planning` slash command. This creates a detailed implementation plan that Cline can reference throughout the work.
**Examples:** Add a new feature across frontend and backend, major refactoring across the codebase, implementing a new system or integration, multi-step migrations.
## Tips
- Have Cline write a markdown file summarizing the plan for future reference
- Use [file mentions](/core-workflows/working-with-files) to point Cline at relevant files during planning
- Switch back to Plan mode when encountering unexpected complexity rather than pushing through
- Enable [Checkpoints](/core-workflows/checkpoints) before Act mode so you can roll back if needed
- For large tasks, ask Cline to create a todo list during planning that you can track in Act mode
-160
View File
@@ -1,160 +0,0 @@
---
title: "Tasks"
sidebarTitle: "Tasks"
description: "Organize your work with tasks - self-contained sessions that capture your conversations, code changes, and decisions."
---
Every interaction with Cline happens within a task. Tasks are self-contained work sessions that capture your entire conversation, code changes, command executions, and decisions.
## What are Tasks?
A task begins when you submit a prompt to Cline. Your prompt defines the goal, and Cline works toward it through conversation, code changes, and tool use. The quality of your initial prompt directly affects how well Cline performs - clear, specific prompts lead to better results.
Each task:
- Starts with your prompt and builds context through the conversation
- Has a unique identifier and dedicated storage directory
- Contains the full conversation history
- Tracks token usage, API costs, and execution time
- Can be interrupted and resumed across sessions
- Creates [checkpoints](/core-workflows/checkpoints) for file changes through Git-based snapshots
<Tip>
Want to get better results from Cline? Learn how to write effective prompts in our [Prompt Module](https://cline.bot/learn).
</Tip>
## Scoping Your Tasks
Each task carries its own context: the conversation history, decisions made, and understanding built up over the session. How you scope your tasks directly affects how well Cline can help you.
Think of it this way: **one task = one goal**. "Implement user authentication" is one task. "Fix an unrelated CSS bug" is a separate task, even if you notice it while working on auth.
A focused task produces better results. When a task tries to cover too many unrelated goals, the context becomes cluttered and responses become less relevant.
<Note>
If you're unsure, err on the side of starting fresh. You can always find previous sessions in your task history.
</Note>
### Context Window
Every AI model has a context window - a limit on how much information it can process at once. Think of it as Cline's working memory for the current task.
As you work, the context window fills up with:
- Your prompts and Cline's responses
- File contents Cline reads or edits
- Command outputs and tool results
- System instructions that guide Cline's behavior (including [Cline Rules](/customization/cline-rules))
When the context window approaches its limit, Cline automatically compresses older parts of the conversation to make room. This means very long tasks may lose some earlier details, though Cline preserves the most important context.
This is why task scoping matters: a focused task keeps relevant information in the context window. A sprawling task fills the window with noise, pushing out useful context.
If your starting context seems high even for simple prompts, add a [`.clineignore`](/customization/clineignore) file to exclude dependencies, build artifacts, and other files Cline doesn't need. This can dramatically reduce your baseline token usage.
<Tip>
For long-running tasks, enable [Auto-Compact](/features/auto-compact) to intelligently manage context as you work.
</Tip>
### New Task vs. Continue
Knowing when to start fresh versus continue can feel unclear at first. As you work with Cline more, you'll develop an intuition for it. Use this table as a starting point:
| Scenario | Action | Why |
|----------|--------|-----|
| Switching to a different feature | **New task** | Clean context, focused responses |
| Building on work Cline just completed | **Continue** | Shared understanding preserved |
| Cline keeps going off-track | **New task** | Fighting context wastes time |
| Iterating on the same files | **Continue** | Conversation history helps |
| Explaining what to ignore | **New task** | Cluttered context hurts quality |
| Refining Cline's last output | **Continue** | Momentum and decisions preserved |
To start a new task, click the **+** button in the Cline sidebar or use the `/newtask` command. Your file changes are preserved through [checkpoints](/core-workflows/checkpoints), and you can reference previous tasks from history anytime.
## Understanding Task Costs
Every cloud-based AI model charges for usage based on tokens, the units of text the model processes. Cline tracks these costs automatically and displays them in the task header so you can monitor spending as you work.
### How Costs Are Calculated
When you interact with Cline, the model processes:
- **Input tokens**: Your prompts, file contents, conversation history, and system instructions
- **Output tokens**: The model's responses, code suggestions, and tool calls
Cloud providers charge per million tokens, with output tokens typically costing more than input. Some providers also support **prompt caching**, which reduces costs when the same context (like your cline rules or large files) appears in multiple requests. Cline automatically tracks cache savings when available.
The estimated cost shown in the task header updates after each API request. This estimate uses the pricing information from your selected provider and may vary slightly from your final bill depending on how your provider rounds or bills usage.
### When You Pay
You pay for AI usage when using cloud providers like Anthropic, OpenAI, OpenRouter, or Google. Costs vary significantly:
| Provider Type | Billing Model |
|--------------|---------------|
| **Cline Provider** | Pay-per-use with credits you purchase |
| **Direct API keys** | Billed by your provider (Anthropic, OpenAI, etc.) |
| **OpenRouter/Requesty** | Aggregated billing across multiple models |
| **Local models** | Free (you provide the hardware) |
If you're using your own API keys, check your provider's pricing page for current rates. Prices change frequently and vary by model.
### Free Options
Not ready to pay? Cline offers several free paths:
- **Free models**: Search "free" in the model selector when using the Cline provider. These models display a **FREE** tag and work well for learning and experimentation.
- **Free tiers**: Some providers offer limited free usage when you use your own API key.
- **Local models**: Run models on your own hardware with zero per-request costs.
### Self-Hosted Models
Running models locally means no API costs, ever. Your only expense is the hardware to run them.
To run local models effectively, you need:
- **32GB RAM minimum** for entry-level models (4-bit quantization)
- **64GB RAM** for better quality (8-bit quantization)
- **128GB+ RAM** for cloud-competitive performance
The trade-off is speed. Local models run at 5-20 tokens per second on typical hardware, compared to hundreds of tokens per second from cloud APIs. They also require more setup and configuration.
<Tip>
If you have the hardware, local models offer unlimited experimentation with complete privacy. See [Running Models Locally](/running-models-locally/overview) to get started.
</Tip>
For most users, starting with free cloud models and moving to paid options as needed provides the best balance of cost, speed, and capability. Check [Selecting Your Model](/getting-started/authorizing-with-cline) for guidance on choosing the right option for your workflow.
## Task History
Every task you work on is saved automatically to your local machine. You can revisit past conversations, resume interrupted work, or reference successful approaches from earlier sessions.
### Finding Your History
Click the **History** button in the Cline sidebar (clock icon at the top-right) to open the history view. You'll see all your past tasks with their initial prompt, timestamp, and token usage. Each task card expands to show a preview of the conversation.
### Searching Tasks
Use the search bar at the top of the history view to find specific tasks. The fuzzy search looks across everything: your prompts, Cline's responses, code snippets, and file names.
Sort results by:
- **Newest/Oldest** for chronological browsing
- **Most Expensive/Most Tokens** to find resource-heavy tasks
- **Most Relevant** when searching for specific content
- **Favorites** to show only starred tasks
<Tip>
Use favorites strategically. Star tasks that represent successful patterns, good prompts, or complex work you might want to reference later. Favorited tasks are protected from deletion.
</Tip>
## Resuming Tasks
Cline can resume interrupted tasks with full context:
1. Open the task from history
2. Cline loads the complete conversation
3. File states are checked against [checkpoints](/core-workflows/checkpoints)
4. The task continues with awareness of the interruption
5. Provide additional context if needed
This works across sessions. Even if you close the editor and return days later, Cline can pick up where you left off.
-75
View File
@@ -1,75 +0,0 @@
---
title: "Using Commands"
sidebarTitle: "Using Commands"
description: "Built-in slash commands to manage context, plan implementations, and create reusable workflows."
---
Cline provides slash commands in chat that help you manage your conversation and plan complex implementations.
<Tip>
**New to slash commands?** Watch our [quick video walkthrough](https://youtu.be/MxS5Jerpf-o) to see these commands in action.
</Tip>
## Slash Commands
Type `/` in the chat input to see available slash commands:
| Command | What It Does |
|---------|--------------|
| `/newtask` | Start fresh task with distilled context from current conversation |
| `/smol` | Compress conversation history while preserving essential context |
| `/newrule` | Create a rule file to teach Cline your preferences |
| `/deep-planning` | Investigate codebase, plan thoroughly, then create implementation task |
| `/explain-changes` | Generate AI explanations for any git diff (VS Code only) |
| `/reportbug` | Report a bug with diagnostic info |
### /newtask
`/newtask` works like a developer handoff. It packages what matters (overall plan, work accomplished, relevant files, next steps) into a fresh task with a clean context window, leaving behind the noise of tool calls and implementation details.
I use `/newtask` when working through complex implementations. If I've completed 3 steps of a 10-step process and my context is already 75% full, I use `/newtask` to extract key decisions, file changes, and progress without all the noise.
### /smol
`/smol` (or its alias `/compact`) compresses your conversation history while preserving essential context. Unlike `/newtask` which creates a new task, `/smol` condenses your current conversation into a comprehensive summary, freeing up context window space while allowing you to continue working in the same task.
Use `/smol` when you're deep into a debugging session or brainstorming and need to continue in the same task without losing the insights you've gained. For more details, see [Smol Command](#smol).
### /newrule
`/newrule` creates a rule file that teaches Cline your preferences. Cline will guide you through setting up guidelines for communication style, coding standards, project context, and workflows. The rule is saved to your `.clinerules` directory and automatically loaded for future conversations.
Use `/newrule` when you find yourself repeating the same instructions across tasks. For more about rules, see [Cline Rules](/customization/cline-rules).
### /deep-planning
Transform Cline into a meticulous architect who investigates your codebase, asks clarifying questions, and creates a comprehensive implementation plan before writing any code. Deep planning follows a four-step process:
1. **Silent Investigation** - Cline explores your codebase structure and patterns
2. **Discussion** - Targeted questions about requirements and approach
3. **Plan Creation** - Generates `implementation_plan.md` with detailed specifications
4. **Task Creation** - Creates a new task with trackable implementation steps
Use `/deep-planning` for features touching multiple parts of your codebase, architectural changes, or complex integrations. For detailed documentation, see [Deep Planning](/features/deep-planning).
### /explain-changes
<Note>
This command is only available in VS Code.
</Note>
`/explain-changes` generates AI-powered explanations for any git diff. You can explain the last commit, uncommitted work, staged changes, specific commits, branches, PRs, or any range of changes.
Use `/explain-changes` when reviewing code, onboarding to a new codebase, or understanding what changed. For the full list of use cases and examples, see [Explain Changes Command](#explain-changes).
### /reportbug
`/reportbug` collects diagnostic information and helps you report issues with Cline. It gathers relevant context like your configuration, recent errors, and system details to make bug reports more useful for the development team.
Use `/reportbug` when you encounter unexpected behavior, crashes, or bugs you want to report.
## Custom Workflows
Beyond the built-in slash commands, you can create your own workflow files that work the same way. Store Markdown files in `.clinerules/workflows/` and invoke them with `/your-workflow.md`.
For a complete guide on creating and managing custom workflows, see [Workflows](/customization/workflows).
-145
View File
@@ -1,145 +0,0 @@
---
title: "Adding Context"
sidebarTitle: "Adding Context"
description: "Use @ mentions and drag & drop to bring files, terminal output, errors, git changes, and web content into your conversations."
---
Cline works best when it has the right context, not just more context. @ mentions let you pull in exactly the files, errors, terminal output, or documentation that matter for your task. No copying, no pasting, no context switching.
You can add context two ways:
- Type `@` in the chat input and select what you want
- Click the **+** button in the bottom left to browse files, images, or mentions
<Tip>
**Want to learn more about managing context?** Watch [Adding Context with @ Mentions](https://youtu.be/7j6R75Dvj1Y) to see it in action.
</Tip>
## Quick Reference
| What you want | Syntax | Example |
|---------------|--------|---------|
| File content | `@/path/to/file` | `@/src/index.ts` |
| Folder contents | `@/path/to/folder/` | `@/src/components/` |
| Workspace errors | `@problems` | `@problems` |
| Terminal output | `@terminal` | `@terminal` |
| Uncommitted changes | `@git-changes` | `@git-changes` |
| Specific commit | `@<commit-hash>` | `@a1b2c3d` |
| Web page | `@<url>` | `@https://react.dev/learn` |
## File Mentions
Reference any file with `@/path/to/file`. Cline sees the complete file content, including imports, related functions, and surrounding context.
```text
Can you refactor the error handling in @/src/api/users.ts?
```
## Folder Mentions
Reference entire directories with `@/path/to/folder/` (note the trailing slash). Cline sees the folder structure and all file contents.
```text
Explain how the components in @/src/components/auth/ work together.
```
<Note>
In multi-root workspaces, prefix paths with the workspace name: `@workspace-name:/path/to/file`
</Note>
## Problem Mentions
Use `@problems` to share all errors and warnings from your workspace's Problems panel.
```text
@problems Can you fix these TypeScript errors?
```
## Terminal Mentions
Use `@terminal` to share recent terminal output. Perfect for debugging build errors or test failures.
```text
@terminal The build is failing. What's wrong?
```
## Git Mentions
Reference uncommitted changes with `@git-changes`:
```text
@git-changes Review my changes before I commit.
```
Reference specific commits with `@<commit-hash>` (7-40 character hex):
```text
What did @a1b2c3d change?
```
## URL Mentions
Reference web content with `@https://example.com`. Cline fetches the page content.
```text
Implement the pattern described in @https://react.dev/learn/scaling-up-with-reducer-and-context
```
## Combining Mentions
Combine multiple @ mentions for comprehensive context:
```text
I'm getting these errors: @problems
Here's my component: @/src/components/Form.jsx
And the API endpoint: @/src/api/users.js
The error happens when I submit: @terminal
I think this commit might have caused it: @a1b2c3d
```
## Drag & Drop
Drag files directly into the chat input to add them to your conversation.
<Note>
In VS Code, hold **Shift** while dragging files into the chat input.
</Note>
Dragging workspace files automatically creates file mentions. You can also drag files from Finder or File Explorer directly into Cline.
### Supported File Types
Cline supports text files from your workspace, plus images, PDFs, CSVs, and Excel files from your file system.
<Note>
Images require a multimodal model. Check the model selector to see which models support image inputs.
</Note>
## Context Menu Commands
Right-click on selected code to access Cline without typing. This is the fastest way to get help with specific code since it automatically includes the selected text and its file location as context.
### Code Editor Commands
| Command | When to Use |
|---------|-------------|
| **Add to Cline** | Ask questions about code, get suggestions, or start a conversation with specific code as context |
| **Fix with Cline** | Quick fixes for errors, bugs, or issues in the selected code |
| **Explain with Cline** | Understand unfamiliar code, complex logic, or code you're reviewing |
| **Improve with Cline** | Get refactoring suggestions, performance improvements, or cleaner implementations |
**Fix with Cline** also appears in the lightbulb menu (Quick Fix) when your cursor is on an error or warning, making it easy to fix issues inline.
### Terminal Commands
Right-click in the terminal to "Add to Cline" and get help with:
- Build errors and failed commands
- Test failures and stack traces
- Configuration issues
- Any terminal output you need help interpreting
### Source Control Commands
In the Source Control panel, use "Generate Commit Message" to create AI-powered commit messages from your staged changes. Cline analyzes the diff and writes a descriptive commit message following conventional commit patterns.
-396
View File
@@ -1,396 +0,0 @@
---
title: "Rules"
sidebarTitle: "Rules"
description: "Define specific instructions and coding standards for Cline."
---
Rules are markdown files that provide persistent instructions across all conversations. Instead of repeating the same preferences every time you start a new task, rules let you define them once and have Cline follow them automatically.
Use rules when you want Cline to:
- Follow your team's coding standards (naming conventions, file organization, error handling patterns)
- Understand project-specific context (tech stack, architecture decisions, dependencies)
- Apply consistent documentation or testing requirements
- Remember constraints like "don't modify files in /legacy" or "always use TypeScript"
<Tip>
**New to Rules?** Watch [Cline Rules Explained](https://youtu.be/xQwsy2vkK5M) to see them in action.
</Tip>
## Supported Rule Types
Cline recognizes rules from multiple sources, so you can use existing rule files from other tools:
| Rule Type | Location | Description |
|-----------|----------|-------------|
| Cline Rules | `.clinerules/` | Primary rule format |
| Cursor Rules | `.cursorrules` | Automatically detected |
| Windsurf Rules | `.windsurfrules` | Automatically detected |
| AGENTS.md | `AGENTS.md` | [Standard format](https://agents.md/) for cross-tool compatibility |
All detected rule types appear in the Rules panel, where you can toggle them individually.
## Where Rules Live
Rules can be stored in two locations: your project workspace or globally on your system.
**Workspace rules** go in `.clinerules/` at your project root. Use these for team standards, project-specific constraints, and anything you want to share with collaborators via version control.
**Global rules** go in your system's Cline Rules directory. Use these for personal preferences that apply across all projects.
```text
your-project/
├── .clinerules/ # Workspace rules
│ ├── coding.md # Coding standards
│ ├── testing.md # Test requirements
│ └── architecture.md # Structural decisions
├── src/
└── ...
```
Cline processes all `.md` and `.txt` files inside `.clinerules/`, combining them into a unified set of rules. Numeric prefixes (like `01-coding.md`) help organize files but are optional.
When both workspace and global rules exist, Cline combines them. Workspace rules take precedence when they conflict with global rules. See [Storage Locations](/customization/overview#storage-locations) for more guidance.
### Global Rules Directory
| Operating System | Default Location |
|------------------|------------------|
| Windows | `Documents\Cline\Rules` |
| macOS | `~/Documents/Cline/Rules` |
| Linux/WSL | `~/Documents/Cline/Rules` |
<Note>
Linux/WSL users: If you don't find global rules in `~/Documents/Cline/Rules`, check `~/Cline/Rules`.
</Note>
## Creating Rules
<Steps>
<Step title="Open the Rules menu">
Click the scale icon at the bottom of the Cline panel, to the left of the model selector.
</Step>
<Step title="Create a new rule file">
Click "New rule file..." and enter a filename (e.g., `coding-standards`). The file will be created with a `.md` extension.
</Step>
<Step title="Write your rule">
Add your instructions in markdown format. Keep each rule file focused on a single concern.
</Step>
</Steps>
You can also use the [`/newrule` slash command](/core-workflows/using-commands#newrule) to have Cline create a rule interactively.
### Toggling Rules
Every rule has a toggle to enable or disable it. This gives you fine-grained control over which rules apply to your current task without deleting the rule file.
For example, you might have a strict testing rule that you want to disable when prototyping, or a client-specific rule you only need when working on that client's features.
## Writing Effective Rules
### Structure
Rules work best when they're scannable and specific. Use markdown structure to organize instructions:
```markdown
# Rule Title
Brief context about why this rule exists (optional but helpful).
## Category 1
- Specific instruction
- Another instruction with example: `like this`
- Reference to file: see /src/utils/example.ts
## Category 2
- More instructions
- Include the "why" when it's not obvious
```
Cline reads rules as context, so formatting matters. Headers help Cline understand the scope of each instruction. Bullet points make individual requirements clear. Code examples show exactly what you want.
### Best Practices
**Be specific, not vague.** "Use descriptive variable names" is too broad. "Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants" gives Cline something concrete to follow.
**Include the why.** When a rule might seem arbitrary, explain the reason. "Don't modify files in /legacy (this code is scheduled for removal in Q2)" helps Cline make better decisions in edge cases.
**Point to examples.** If your codebase already demonstrates the pattern you want, reference it. "Follow the error handling pattern in /src/utils/errors.ts" is more effective than describing the pattern from scratch.
**Keep rules current.** Outdated rules confuse Cline and waste context. If a constraint no longer applies, remove it. If your tech stack changes, update the rules.
**One concern per file.** Split rules by topic: `coding.md` for style, `testing.md` for test requirements, `architecture.md` for structural decisions. This makes it easy to toggle specific rules on or off.
<Warning>
Rules consume context tokens. Avoid lengthy explanations or pasting entire style guides. Keep rules concise and link to external documentation when detailed reference is needed.
</Warning>
## Example
```markdown
# Project Guidelines
## Code Style
- Use TypeScript for all new files
- Prefer composition over inheritance
- Use repository pattern for data access
- Follow error handling pattern in /src/utils/errors.ts
## Documentation
- Update relevant docs when modifying features
- Keep README.md in sync with new capabilities
## Testing
- Unit tests required for business logic
- Integration tests for API endpoints
- E2E tests for critical user flows
```
## Conditional Rules
Conditional rules let you scope rules to specific parts of your codebase. Rules activate only when you're working with matching files, keeping your context focused and relevant.
- **Without conditionals**: every rule loads for every request.
- **With conditionals**, rules activate only when your current files match their defined scope.
For example, documentation style rules should only appear when you're editing docs, not when you're writing application code or tests.
As your rule library grows, loading every rule for every request wastes context tokens and can dilute Cline's focus. Conditional rules solve this by giving Cline only the instructions that matter for the files you're actually touching. This means faster, more accurate responses. Your frontend rules won't compete for attention when you're deep in backend code, and your testing standards appear exactly when you're writing tests. It's the difference between handing someone an entire policy manual versus the one page they need right now.
### How It Works
Conditional rules use YAML frontmatter at the top of your rule files. When Cline processes a request, it gathers context from your current work (open files, visible tabs, mentioned paths, edited files), evaluates each rule's conditions, and activates matching rules.
<Note>
When a conditional rule activates, you'll see a notification: **"Conditional rules applied: workspace:frontend-rules.md"**
</Note>
### Writing Conditional Rules
Add YAML frontmatter to the top of any rule file in your `.clinerules/` directory:
```yaml
---
paths:
- "src/components/**"
- "src/hooks/**"
---
# React Component Guidelines
When creating or modifying React components:
- Use functional components with React hooks
- Extract reusable logic into custom React hooks
- Keep components focused on a single responsibility
```
The `---` markers delimit the frontmatter. Everything after the closing `---` is your rule content.
#### The `paths` Conditional
Currently, `paths` is the supported conditional. It takes an array of glob patterns:
```yaml
---
paths:
- "src/**" # All files under src/
- "*.config.js" # Config files in root
- "packages/*/src/" # Monorepo package sources
---
```
**Glob pattern syntax:**
- `*` matches any characters except `/`
- `**` matches any characters including `/` (recursive)
- `?` matches a single character
- `[abc]` matches any character in the brackets
- `{a,b}` matches either pattern
| Pattern | Matches |
|---------|---------|
| `src/**/*.ts` | All TypeScript files under `src/` |
| `*.md` | Markdown files in root only |
| `**/*.test.ts` | Test files anywhere in the project |
| `packages/{web,api}/**` | Files in web or api packages |
| `src/components/*.tsx` | TSX files directly in components (not nested) |
#### Behavior Details
**Multiple patterns**: A rule activates if any pattern matches any file in your context.
```yaml
---
paths:
- "frontend/**"
- "mobile/**"
---
# Activates when working in frontend OR mobile
```
**No frontmatter**: Rules without frontmatter are always active.
**Empty paths array**: `paths: []` means the rule never activates. Use this to temporarily disable a rule.
**Invalid YAML**: If frontmatter can't be parsed, Cline fails open. The rule activates with raw content visible to help debugging.
### What Counts as "Current Context"
Cline evaluates rules based on:
1. **Your message**: File paths mentioned in your prompt (e.g., "update `src/App.tsx`")
2. **Open tabs**: Files currently open in your editor
3. **Visible files**: Files visible in your active editor panes
4. **Edited files**: Files Cline has created, modified, or deleted during the task
5. **Pending operations**: Files Cline is about to edit
Conditional rules can activate on your first message, when relevant files are open, or mid-task when Cline starts working with matching files.
<Tip>
Be explicit about file paths in your prompts. "Update `src/services/user.ts`" reliably triggers path-based rules; "update the user service" may not.
</Tip>
### Practical Examples
Copy these patterns and adapt them to your project structure.
#### Frontend vs Backend Rules
Keep frontend and backend rules separate to avoid noise. Frontend rules only load when working with UI code, backend rules only load when working with API or service code.
```yaml
# .clinerules/frontend.md
---
paths:
- "src/components/**"
- "src/pages/**"
- "src/hooks/**"
---
# Frontend Guidelines
- Use Tailwind CSS for styling
- Prefer server components where possible
- Keep client components small and focused
```
```yaml
# .clinerules/backend.md
---
paths:
- "src/api/**"
- "src/services/**"
- "src/db/**"
---
# Backend Guidelines
- Use dependency injection for services
- All database queries go through repositories
- Return typed errors, not thrown exceptions
```
#### Test File Rules
Enforce testing standards automatically. This rule activates only when you're writing or modifying tests, so testing guidance appears exactly when you need it.
```yaml
# .clinerules/testing.md
---
paths:
- "**/*.test.ts"
- "**/*.spec.ts"
- "**/__tests__/**"
---
# Testing Standards
- Use descriptive test names: "should [expected behavior] when [condition]"
- One assertion per test when possible
- Mock external dependencies, not internal modules
- Use factories for test data, not fixtures
```
#### Documentation Rules
Apply documentation standards only when editing docs. Prevents style rules from cluttering your context when you're writing code.
```yaml
# .clinerules/docs.md
---
paths:
- "docs/**"
- "**/*.md"
- "**/*.mdx"
---
# Documentation Guidelines
- Use sentence case for headings
- Include code examples for all features
- Keep paragraphs short (3-4 sentences max)
- Link to related documentation
```
### Combining with Rule Toggles
Conditional rules work alongside the rule toggle UI. Toggle off a conditional rule to disable it entirely (it won't activate even if paths match). Toggle on to let it activate when conditions are met.
This provides two levels of control: manual toggles and automatic condition-based activation.
### Tips for Effective Conditional Rules
**Start Broad, Then Narrow.** Begin with broader patterns and refine as you learn what works:
```yaml
# Start here
paths:
- "src/**"
# Then narrow down
paths:
- "src/features/auth/**"
```
**Use Descriptive Filenames.** Name your rule files to indicate their scope:
```text
.clinerules/
├── api-endpoints.md # Rules for API code
├── database-models.md # Rules for DB layer
├── react-components.md # Rules for React
└── universal.md # No frontmatter = always active
```
**Keep Universal Rules Separate.** Put always-on rules (coding standards, project conventions) in files without frontmatter. Reserve conditional rules for context-specific guidance.
**Test Your Patterns.** Not sure if a pattern matches? Create a simple test rule:
```yaml
---
paths:
- "your/pattern/here/**"
---
TEST: This rule should activate for your/pattern/here files.
```
Then work with a file in that path and check if you see the activation notification.
### Troubleshooting Conditional Rules
**Rule not activating:**
- Check that file paths in your context match the glob pattern
- Verify the rule is toggled on in the rules panel
- Ensure YAML frontmatter has proper `---` delimiters
**Rule activating unexpectedly:**
- Review glob patterns. `**` is recursive and may match more than intended
- Check for open files that match the pattern
- File paths mentioned in your message also count as context
**Frontmatter showing in output:**
- YAML couldn't be parsed
- Check for syntax errors (unquoted special characters, improper indentation)
-110
View File
@@ -1,110 +0,0 @@
---
title: ".clineignore"
sidebarTitle: ".clineignore"
description: "Control which files and directories Cline can access in your project."
---
The `.clineignore` file tells Cline which files and directories to skip when analyzing your codebase. It works like `.gitignore`: create a file named `.clineignore` in your project root, add patterns for files you want excluded, and Cline will ignore them.
## Why It Matters
Without a `.clineignore`, Cline may load your entire project into context, including dependencies, build artifacts, and generated files. This wastes tokens, increases costs, and can push useful context out of the window.
Adding a `.clineignore` can cut your starting context from 200k+ tokens to under 50k. That means faster responses, lower costs, and the ability to use smaller, cheaper models effectively.
## Creating a .clineignore
Create a file named `.clineignore` in your project root:
```text
# Dependencies
node_modules/
**/node_modules/
# Build outputs
/build/
/dist/
/.next/
/out/
# Testing artifacts
/coverage/
# Environment variables
.env
.env.*
# Large data files
*.csv
*.xlsx
*.sqlite
# Generated/minified code
*.min.js
*.map
```
## Pattern Syntax
`.clineignore` uses the same pattern syntax as `.gitignore`:
| Pattern | Matches |
|---------|---------|
| `node_modules/` | The `node_modules` directory |
| `**/node_modules/` | `node_modules` at any depth |
| `*.csv` | All CSV files |
| `/build/` | The `build` directory at the project root only |
| `*.env.*` | Files like `.env.local`, `.env.production` |
| `!important.csv` | Exception: do not ignore this file |
Lines starting with `#` are comments. Blank lines are ignored.
## What to Exclude
Start with these categories and adjust for your project:
**Almost always exclude:**
- Package manager directories (`node_modules/`, `vendor/`, `.venv/`)
- Build outputs (`dist/`, `build/`, `.next/`, `out/`)
- Coverage reports (`coverage/`)
- Lock files if large (`package-lock.json`, `yarn.lock`)
**Exclude if present:**
- Large data files (`.csv`, `.xlsx`, `.sqlite`, `.parquet`)
- Binary assets (images, fonts, videos)
- Generated code (API clients, protobuf outputs, minified bundles)
- Environment files with secrets (`.env`, `.env.local`)
**Keep accessible:**
- Source code you actively work on
- Configuration files Cline needs to understand (`tsconfig.json`, `package.json`)
- Documentation and READMEs
- Test files (Cline often needs these for context)
## How It Works
When Cline scans your project to build context, it checks each file path against your `.clineignore` patterns. Matching files are excluded from:
- The file listing Cline sees when starting a task
- Automatic context gathering during conversations
- Search results when Cline looks for relevant code
You can still reference ignored files explicitly using [@ mentions](/core-workflows/working-with-files). If you type `@/node_modules/some-package/index.js`, Cline will read that specific file even though `node_modules/` is in your `.clineignore`. The ignore rules control automatic loading, not explicit access.
<Note>
`.clineignore` is separate from `.gitignore`. Files tracked by Git but irrelevant to Cline (like large test fixtures or data files) should go in `.clineignore` even if they're not in `.gitignore`.
</Note>
## Tips
- Add `.clineignore` early in your project. It's easier to start with broad exclusions and narrow them than to debug why context is bloated later.
- Check your token usage in the task header after adding a `.clineignore`. The difference is often dramatic.
- If Cline seems to be missing context about a file, check whether it's being excluded by your ignore patterns.
- For monorepos or multi-root workspaces, each workspace root can have its own `.clineignore`. See [Multi-Root Workspaces](/features/multiroot-workspace) for details.
## Related
- [Cline Rules](/customization/cline-rules) - Define persistent instructions for Cline
- [Task Management](/core-workflows/task-management#context-window) - Understand how context windows work
- [Auto-Compact](/features/auto-compact) - Automatic context compression during long tasks
- [Memory Bank](/features/memory-bank) - Structured documentation for cross-session context
-470
View File
@@ -1,470 +0,0 @@
---
title: "Hooks"
sidebarTitle: "Hooks"
description: "Inject custom logic into Cline's workflow to validate operations and shape Cline's decisions."
---
Hooks are scripts that run at key moments in Cline's workflow. Because they execute at known points with consistent inputs and outputs, hooks bring determinism to the non-deterministic nature of AI models by enforcing guardrails, validations, and context injection. You can validate operations before they execute, monitor tool usage, and shape how Cline makes decisions.
## What You Can Build
- Stop operations before they cause problems (like creating `.js` files in a TypeScript project)
- Run linters or custom validators before files get saved
- Prevent operations that violate security policies
- Track everything for analytics or compliance
- Trigger external tools or services at the right moments
- Add context to the conversation based on what Cline is doing
## Hook Types
Cline supports 8 hook types that run at different points in the task lifecycle:
| Hook Type | When It Runs |
|-----------|--------------|
| TaskStart | When you start a new task |
| TaskResume | When you resume an interrupted task |
| TaskCancel | When you cancel a running task |
| TaskComplete | When a task finishes successfully |
| PreToolUse | Before Cline executes a tool (read_file, write_to_file, etc.) |
| PostToolUse | After a tool execution completes |
| UserPromptSubmit | When you submit a message to Cline |
| PreCompact | Before Cline truncates conversation history to free up context |
## Hook Lifecycle
```mermaid
flowchart TD
%% Styling
classDef hook fill:#FFB74D,stroke:#E65100,stroke-width:2px,color:black,rx:5,ry:5;
classDef state fill:#E1F5FE,stroke:#0277BD,stroke-width:2px,color:black;
classDef action fill:#FFFFFF,stroke:#333,stroke-width:1px,color:black,stroke-dasharray: 5 5;
%% Entry Points
Start((Start)) --> CheckType{New or<br/>Resume?}
%% Initialization Hooks
CheckType -- New Task --> H_Start[TaskStart]:::hook
CheckType -- Resume --> H_Resume[TaskResume]:::hook
%% Main Loop
H_Start --> Loop(Task Active Loop):::state
H_Resume --> Loop
subgraph Conversation Cycle
direction TB
Loop -- User sends message --> H_Submit[UserPromptSubmit]:::hook
H_Submit --> Thinking[Cline Processes Context]:::state
%% Context Compaction Path
Thinking -. Context Limit Reached .-> H_Compact[PreCompact]:::hook
H_Compact -.-> Thinking
%% Tool Execution Path
Thinking -- Decides to use tool --> H_PreTool[PreToolUse]:::hook
H_PreTool -- Allowed --> ToolExec[Tool Executes]:::action
H_PreTool -- Cancelled --> Thinking
ToolExec --> H_PostTool[PostToolUse]:::hook
H_PostTool --> Thinking
end
%% Termination Paths
Thinking -- Task Successfully Finished --> H_Complete[TaskComplete]:::hook
Loop -- User Cancels Task --> H_Cancel[TaskCancel]:::hook
%% End
H_Complete --> End((End))
H_Cancel --> End
```
The diagram shows the complete hook lifecycle:
1. **Entry**: When you start a task, either **TaskStart** (new task) or **TaskResume** (interrupted task) runs first
2. **Conversation Cycle**: Each time you send a message, **UserPromptSubmit** runs, then Cline processes your request
3. **Tool Execution**: When Cline decides to use a tool, **PreToolUse** runs first-if allowed, the tool executes, then **PostToolUse** runs
4. **Context Management**: If the conversation approaches context limits, **PreCompact** runs before truncation
5. **Exit**: The task ends with either **TaskComplete** (success) or **TaskCancel** (user cancellation)
Orange nodes represent hooks where you can inject custom logic. The cycle repeats as you continue the conversation.
## Hook Locations
Hooks can be stored globally or in a project workspace. See [Storage Locations](/customization/overview#storage-locations) for guidance on when to use each.
- **Global hooks**: `~/Documents/Cline/Hooks/`
- **Project hooks**: `.clinerules/hooks/` in your repo (can be committed to version control)
When both global and workspace hooks exist for the same hook type, both run. Global hooks execute first, then workspace hooks. If either returns `cancel: true`, the operation stops.
## Creating a Hook
<Steps>
<Step title="Open the Hooks tab">
Click the scale icon at the bottom of the Cline panel, to the left of the model selector. Switch to the Hooks tab.
</Step>
<Step title="Create a new hook">
Click **"New hook..."** dropdown and select a hook type (e.g., PreToolUse, TaskStart).
</Step>
<Step title="Review the hook's code">
Click the pencil icon to open and edit the hook script. Cline generates a template with examples.
</Step>
<Step title="Enable the hook">
Toggle the switch to activate the hook once you understand what it does.
</Step>
</Steps>
<Warning>
Always review a hook's code before enabling it. Hooks execute automatically during your workflow and can block operations or run shell commands.
</Warning>
## Quick Start: Your First Hook
Let's create a simple hook that logs every file Cline reads or writes. You'll see results in seconds.
### The Hook
Create a file called `file-logger` in your hooks directory with this content:
```bash
#!/bin/bash
# Logs all file operations to ~/cline-activity.log
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.preToolUse.tool')
FILE_PATH=$(echo "$INPUT" | jq -r '.preToolUse.parameters.path // "N/A"')
# Log to file
echo "$(date '+%H:%M:%S') - $TOOL: $FILE_PATH" >> ~/cline-activity.log
# Always allow the operation
echo '{"cancel":false}'
```
### Setup
<Steps>
<Step title="Create the hook file">
Save the script above as `~/Documents/Cline/Hooks/file-logger` (macOS/Linux) or create it through the Hooks UI.
</Step>
<Step title="Make it executable">
Run `chmod +x ~/Documents/Cline/Hooks/file-logger` in your terminal.
</Step>
<Step title="Enable it">
In Cline's Hooks tab, find "file-logger" under PreToolUse hooks and toggle it on.
</Step>
</Steps>
### Test It
Ask Cline to read any file in your project: "What's in package.json?"
Then check the log:
```bash
cat ~/cline-activity.log
```
You'll see entries like:
```text
14:23:45 - read_file: /path/to/package.json
14:23:47 - search_files: /path/to/src
```
### Customize It
Try modifying the hook to:
- Filter specific file types (only log `.ts` files)
- Add the task ID to each log entry
- Send notifications for write operations
- Block operations on certain paths
The sections below explain how hooks receive input and return output, plus more examples.
## How Hooks Work
Hooks are executable scripts that receive JSON input via stdin and return JSON output via stdout.
### Input Structure
Every hook receives a JSON object with common fields plus hook-specific data:
```json
{
"taskId": "abc123",
"clineVersion": "3.17.0",
"timestamp": 1736654400000,
"workspacePath": "/path/to/project",
// Hook-specific field (name matches hook type in camelCase)
"taskStart": {
"task": "Add authentication to the API"
}
}
```
The hook-specific field name matches the hook type:
- `taskStart`, `taskResume`, `taskCancel`, `taskComplete` contain `{ task: string }`
- `preToolUse` contains `{ tool: string, parameters: object }`
- `postToolUse` contains `{ tool: string, parameters: object, result: string, success: boolean, durationMs: number }`
- `userPromptSubmit` contains `{ prompt: string }`
- `preCompact` contains `{ conversationLength: number, estimatedTokens: number }`
### Output Structure
Hooks return a JSON object to stdout:
```json
{
"cancel": false,
"contextModification": "Optional text to add to the conversation",
"errorMessage": ""
}
```
| Field | Type | Description |
|-------|------|-------------|
| `cancel` | boolean | If `true`, stops the operation (blocks the tool, cancels the task start, etc.) |
| `contextModification` | string | Optional text that gets injected into the conversation as context for Cline |
| `errorMessage` | string | Shown to the user if `cancel` is `true` |
### Context Modification
The `contextModification` field lets hooks inject information into the conversation. This is useful for:
- Adding project-specific context when a task starts
- Providing validation results that Cline should consider
- Injecting environment information before tool execution
For example, a PreToolUse hook could add: `"Note: This file is auto-generated. Edits may be overwritten."`
## Hook Reference
### Task Lifecycle Hooks
#### TaskStart
Runs when you start a new task. Use it to:
- Log task start time for analytics
- Add project context to the conversation
- Check prerequisites before work begins
- Notify external systems (Slack, issue trackers)
```bash
#!/bin/bash
INPUT=$(cat)
TASK=$(echo "$INPUT" | jq -r '.taskStart.task')
echo "[TaskStart] Starting: $TASK" >&2
echo '{"cancel":false,"contextModification":"","errorMessage":""}'
```
#### TaskResume
Runs when you resume an interrupted task (instead of TaskStart). Use it to:
- Check for changes since the task was paused
- Refresh context with latest project state
- Notify that work is resuming
#### TaskCancel
Runs when you cancel a running task. Use it to:
- Clean up temporary files or resources
- Notify external systems about cancellation
- Log cancellation for analytics
#### TaskComplete
Runs when a task completes successfully. Use it to:
- Run tests or validation after changes
- Generate reports or summaries
- Notify stakeholders
- Trigger CI/CD pipelines
### Tool Hooks
#### PreToolUse
Runs before any tool executes. This is the most powerful hook for validation and safety. Use it to:
- Block dangerous operations
- Validate parameters before execution
- Add context about the file or resource being accessed
- Log tool usage
The input includes the tool name and its parameters:
```json
{
"preToolUse": {
"tool": "write_to_file",
"parameters": {
"path": "src/config.ts",
"content": "..."
}
}
}
```
Example that blocks `.js` files in a TypeScript project:
```bash
#!/bin/bash
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.preToolUse.tool')
FILE_PATH=$(echo "$INPUT" | jq -r '.preToolUse.parameters.path // empty')
if [[ "$TOOL" == "write_to_file" && "$FILE_PATH" == *.js ]]; then
echo '{"cancel":true,"errorMessage":"Use .ts files instead of .js in this TypeScript project"}'
exit 0
fi
echo '{"cancel":false}'
```
#### PostToolUse
Runs after a tool completes (success or failure). Use it to:
- Audit tool usage
- Validate results
- Trigger follow-up actions
- Monitor performance
The input includes execution results:
```json
{
"postToolUse": {
"tool": "execute_command",
"parameters": { "command": "npm test" },
"result": "All tests passed",
"success": true,
"durationMs": 3450
}
}
```
<Note>
PostToolUse hooks can return `cancel: true` to stop the task, but they cannot undo the tool execution that already happened.
</Note>
### Other Hooks
#### UserPromptSubmit
Runs when you send a message to Cline. Use it to:
- Log prompts for analytics
- Add context based on prompt content
- Validate or sanitize prompts
#### PreCompact
Runs before Cline truncates conversation history to stay within context limits. Use it to:
- Archive important conversation parts before they're removed
- Log compaction events
- Add a summary of what's being removed
The input includes context metrics:
```json
{
"preCompact": {
"conversationLength": 45,
"estimatedTokens": 125000
}
}
```
## Examples
### TypeScript Enforcement
Block creation of `.js` files in a TypeScript project:
```bash
#!/bin/bash
# PreToolUse hook
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.preToolUse.tool')
FILE_PATH=$(echo "$INPUT" | jq -r '.preToolUse.parameters.path // empty')
if [[ "$TOOL" == "write_to_file" && "$FILE_PATH" == *.js ]]; then
echo '{"cancel":true,"errorMessage":"Use .ts files instead of .js in this TypeScript project"}'
exit 0
fi
echo '{"cancel":false}'
```
### Tool Usage Logging
Log all tool executions to a file:
```bash
#!/bin/bash
# PostToolUse hook
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.postToolUse.tool')
SUCCESS=$(echo "$INPUT" | jq -r '.postToolUse.success')
DURATION=$(echo "$INPUT" | jq -r '.postToolUse.durationMs')
echo "$(date -Iseconds) | $TOOL | success=$SUCCESS | ${DURATION}ms" >> ~/.cline-tool-log.txt
echo '{"cancel":false}'
```
### Add Project Context on Task Start
Inject project-specific information when a task begins:
```bash
#!/bin/bash
# TaskStart hook
INPUT=$(cat)
WORKSPACE=$(echo "$INPUT" | jq -r '.workspacePath')
# Read project info if available
if [[ -f "$WORKSPACE/.project-context" ]]; then
CONTEXT=$(cat "$WORKSPACE/.project-context")
echo "{\"cancel\":false,\"contextModification\":\"Project context: $CONTEXT\"}"
else
echo '{"cancel":false}'
fi
```
## CLI Support
Hooks are available in the [Cline CLI](/cline-cli/getting-started):
```bash
# Enable hooks for a task
cline "What does this repo do?" -s hooks_enabled=true
# Configure hooks globally
cline config set hooks-enabled=true
```
<Note>
CLI hooks are only supported on macOS and Linux.
</Note>
## Troubleshooting
**Hook not running?**
- Check that the file is executable (`chmod +x hookname`)
- Verify the hook is enabled (toggle is on in the Hooks tab)
- Check that Hooks are enabled globally in Settings
**Hook output not parsed?**
- Ensure output is valid JSON on a single line to stdout
- Use stderr (`>&2`) for debug logging, not stdout
- Check for trailing characters or newlines before the JSON
**Hook blocking unexpectedly?**
- Review the hook's logic and test with sample input
- Check both global and workspace hooks (both run if they exist)
## Related Features
- [Rules](/customization/cline-rules) define high-level guidance that hooks can enforce programmatically
- [Checkpoints](/core-workflows/checkpoints) let you roll back if a hook didn't catch an issue
- [Auto-Approve](/features/auto-approve) works well with hooks as safety nets
-86
View File
@@ -1,86 +0,0 @@
---
title: "Overview"
sidebarTitle: "Overview"
description: "Understand how Rules, Skills, Workflows, Hooks, and .clineignore work together to customize Cline."
---
Out of the box, Cline is a general-purpose AI assistant. Customizations transform it into an expert on your codebase, your team's conventions, and your workflows. Instead of repeating the same instructions every task, you define them once and Cline follows them automatically.
Cline offers five systems for this: Rules, Skills, Workflows, Hooks, and .clineignore. Each serves a different purpose and activates at different times.
## Quick Comparison
| Feature | Purpose | When Active | Best For |
|---------|---------|-------------|----------|
| **[Rules](/customization/cline-rules)** | Define how Cline behaves | Always (or contextually) | Coding standards, project constraints, team conventions |
| **[Skills](/customization/skills)** | Domain expertise loaded on-demand | Triggered by matching requests | Specialized knowledge, complex procedures, institutional expertise |
| **[Workflows](/customization/workflows)** | Step-by-step task automation | Invoked with `/workflow.md` | Repetitive processes, release procedures, setup scripts |
| **[Hooks](/customization/hooks)** | Inject custom logic at key moments | Automatically on specific events | Validation, enforcement, monitoring, automation triggers |
| **[.clineignore](/customization/clineignore)** | Control file access | Always | Excluding dependencies, build artifacts, large data files |
## Understanding Each Tool
**[Rules](/customization/cline-rules)** are always-on guidance. Use them when you want Cline to consistently follow certain patterns: coding standards, naming conventions, architectural constraints, or project-specific context. Rules shape *how* Cline works across all tasks. For example, a rule might say "always use TypeScript" or "follow the repository pattern for data access."
**[Skills](/customization/skills)** are domain expertise that loads only when relevant. Use them when you have extensive knowledge that would waste context if always active. Cline sees skill descriptions at startup and activates the full instructions only when your request matches. A data analysis skill might include pandas patterns, visualization preferences, and output formats that Cline only loads when you're working with data files.
**[Workflows](/customization/workflows)** are explicit task scripts you invoke on demand. Use them when you have a repeatable multi-step process that should run the same way every time. Type `/release.md` and Cline executes your release sequence: bump version, run tests, update changelog, commit, tag, push. Workflows define *what* to do, step by step.
**[Hooks](/customization/hooks)** are programmatic guardrails that run automatically at key moments. Use them when you need to validate, enforce, or extend Cline's behavior with custom code. A hook might block `.js` file creation in a TypeScript project, run linters before saves, or notify external services after deployments.
**[.clineignore](/customization/clineignore)** controls which files and directories Cline can access. Use it to exclude dependencies, build artifacts, generated files, and large data files from Cline's context. This reduces token usage, lowers costs, and keeps Cline focused on the code that matters. It works like `.gitignore`: add patterns to a `.clineignore` file in your project root and matching files are automatically excluded.
### Example: A Release Process
Consider how all five work together for releasing a new version:
1. **Rules** ensure Cline follows your team's commit message format and versioning policy
2. **Skills** offer deep knowledge about your CI/CD system that Cline loads when deployment questions arise
3. **Workflows** provide the explicit `/release.md` sequence: bump version, update changelog, tag, push
4. **Hooks** validate that tests pass before allowing any commit or that the changelog was actually updated
5. **.clineignore** keeps build artifacts, `node_modules/`, and generated files out of Cline's context so it stays focused
## Storage Locations
All five systems support both global and project-specific configurations:
| System | Global Location | Project Location |
|--------|-----------------|------------------|
| Rules | `~/Documents/Cline/Rules/` | `.clinerules/` |
| Skills | `~/.cline/skills/` | `.cline/skills/` |
| Workflows | `~/Documents/Cline/Workflows/` | `.clinerules/workflows/` |
| Hooks | `~/Documents/Cline/Hooks/` | `.clinerules/hooks/` |
| .clineignore | N/A | `.clineignore` |
### When to Use Each
**Start with project storage.** Most customizations belong in your project's directory because they're tied to that specific codebase. Team coding standards, deployment workflows, and architectural constraints all live with the code they describe. This also means your customizations travel with the repository, so collaborators get them automatically and changes can be reviewed in pull requests.
**Use global storage for personal preferences.** If you find yourself adding the same customization to every project, move it to global storage. Your preferred communication style, personal productivity workflows, and tools you use everywhere belong here. Global customizations apply to all projects but stay out of version control, so they won't affect your teammates.
When names conflict, project-specific configurations take precedence (except for Skills, where global takes precedence). This lets you override global defaults for specific projects when needed.
## Security Considerations
<Warning>
Always review customizations before adding them to your projects. Only use customizations from sources you trust.
</Warning>
Customizations are powerful. They shape how Cline writes code, execute commands automatically, and influence every interaction. Treat customization files with the same scrutiny you'd give any code running in your environment.
### Best Practices
Review any customization file before adding it to your project or global configuration. Understand what it does and why.
When downloading customizations from GitHub repositories, community shares, or other external sources, verify the source:
- Is the author reputable?
- Has the community reviewed it?
- Does the code do what it claims?
Look for dangerous commands:
- Shell commands that delete files (`rm`, `del`)
- Commands that transmit data (`curl`, `wget` with POST)
- File operations outside your project directory
- Commands that modify system configuration
Keep your customizations in version control so you can track changes, review diffs, and roll back if something goes wrong. When creating hooks, use the most restrictive event triggers necessary. Don't run hooks on every file save if you only need them before commits.
-261
View File
@@ -1,261 +0,0 @@
---
title: "Skills"
sidebarTitle: "Skills"
description: "Modular instruction sets that extend Cline's capabilities for specific 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.
Install multiple skills and Cline only loads what it needs. A deployment skill stays dormant until you ask about deploying. Unlike [rules](/customization/cline-rules) (which are always active), skills load on-demand so they don't consume context when you're working on something unrelated.
<Note>
Skills is an experimental feature. Enable it in **Settings → Features → Enable Skills**.
</Note>
## How Skills Work
Skills use progressive loading to maximize efficiency:
| Level | When Loaded | Token Cost | Content |
|-------|-------------|------------|---------|
| Metadata | Always (at startup) | ~100 tokens per skill | `name` and `description` from YAML frontmatter |
| Instructions | When skill is triggered | Under 5k tokens | SKILL.md body with instructions and guidance |
| Resources | As needed | Effectively unlimited | Bundled files accessed via `read_file` or executed scripts |
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 from SKILL.md.
## Skill Structure
Every skill is a directory containing a `SKILL.md` file with YAML frontmatter.
```text title="Skill directory structure"
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.
```markdown title="SKILL.md"
---
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)
## Creating a Skill
<Steps>
<Step title="Open the Skills menu">
Click the scale icon at the bottom of the Cline panel, to the left of the model selector. Switch to the Skills tab.
</Step>
<Step title="Create a new skill">
Click "New skill..." and enter a name for your skill (e.g., `aws-deploy`). Cline creates a skill directory with a template `SKILL.md` file.
</Step>
<Step title="Write your skill instructions">
Edit the `SKILL.md` file:
- Update the `description` field to specify when this skill should trigger
- Add detailed instructions in the body
- Optionally add supporting files in `docs/`, `templates/`, or `scripts/` subdirectories
</Step>
</Steps>
You can also create skills manually by creating the directory structure in your file system. Place skill directories in `.cline/skills/` (workspace) or `~/.cline/skills/` (global) and Cline will detect them automatically.
Put the important information first in your SKILL.md. Cline reads the file sequentially, so front-load the common cases. Use clear section headers like "## Error Handling" or "## Configuration" so Cline can scan for relevant sections.
### Toggling Skills
Every skill has a toggle to enable or disable it. This lets you control which skills are active without deleting the skill directory. Skills are enabled by default when discovered.
For example, you might disable a CI/CD skill when working on local development, or enable a client-specific skill only when working on that client's project.
## Writing Your SKILL.md
### Naming Conventions
The skill name appears in the `name` field and must match the directory name exactly. Use lowercase with hyphens (kebab-case) and be descriptive about what the skill does.
Good names:
- `aws-cdk-deploy`
- `pr-review-checklist`
- `database-migration`
- `api-client-generator`
Avoid:
- `aws` (too vague)
- `my_skill` (underscores, not descriptive)
- `DeployToAWS` (use kebab-case, not PascalCase)
- `misc-helpers` (too generic)
### Writing Effective Descriptions
The description determines when Cline activates the skill. A vague description means the skill won't trigger when you expect it to.
Good descriptions are specific and actionable:
```yaml
description: Deploy applications to AWS using CDK. Use when deploying, updating infrastructure, or managing AWS resources.
description: Generate release notes from git commits. Use when preparing releases, writing changelogs, or summarizing recent changes.
description: Analyze CSV and Excel data files. Use when exploring datasets, generating statistics, or creating visualizations from tabular data.
```
Weak descriptions leave too much ambiguity:
```yaml
description: Helps with AWS stuff.
description: Data analysis helper.
description: Useful for releases.
```
Start with what the skill does (action verbs), include trigger phrases users might say, and mention specific file types, tools, or domains. Test your descriptions by trying different phrasings of requests to see if the skill triggers.
### Keeping Skills Focused
Keep SKILL.md under 5k tokens. If your skill needs more content, split it into separate files in a `docs/` directory and reference them from the main instructions. Cline loads referenced files only when needed.
Include real examples. Show what commands to run, what output to expect, and what the result should look like. Abstract instructions are harder to follow than concrete examples.
## Where Skills Live
Skills can be stored globally or in a project workspace. See [Storage Locations](/customization/overview#storage-locations) for guidance on when to use each.
Project skills:
- `.cline/skills/` (recommended)
- `.clinerules/skills/`
- `.claude/skills/`
Global skills:
- `~/.cline/skills/` (macOS/Linux)
- `C:\Users\USERNAME\.cline\skills\` (Windows)
When a global skill and project skill have the same name, the global skill takes precedence. This lets you keep general-purpose skills globally while using project-specific skills in `.cline/skills/` so the whole team can use them.
Version control your project skills by committing `.cline/skills/`. Your team can share, review, and improve them together.
## Bundling Supporting Files
Skills can include additional files that Cline accesses only when needed.
```text title="Directory structure"
complex-skill/
├── SKILL.md
├── docs/
│ ├── setup.md
│ └── troubleshooting.md
├── templates/
│ └── config.yaml
└── scripts/
└── validate.py
```
### docs/
Use docs for information that's too detailed for SKILL.md or only relevant in specific situations:
- Advanced configuration options
- Troubleshooting guides for edge cases
- Reference material (API schemas, database schemas)
- Platform-specific instructions
A deployment skill might have `docs/aws.md`, `docs/gcp.md`, and `docs/azure.md`. Cline loads only the relevant platform guide based on your request.
### templates/
Use templates when your skill creates configuration files, boilerplate code, or structured documents:
- Config files (Terraform, Docker Compose, CI/CD pipelines)
- Code scaffolding (component templates, test fixtures)
- Documentation templates (README, API docs)
A project setup skill could include `templates/dockerfile`, `templates/docker-compose.yml`, and `templates/.env.example` that Cline customizes for each new project.
### scripts/
Use scripts for deterministic operations where you want consistent behavior:
- Validation (linting configs, checking prerequisites)
- Data processing (parsing, formatting, transforming)
- Complex calculations (cost estimation, resource sizing)
- API interactions (fetching data, running health checks)
Scripts are token-efficient because only their output enters context, not the code itself. A 500-line validation script produces a simple "Passed" or detailed error messages without consuming any context for the script logic.
### Referencing Bundled Files
Reference these files in your SKILL.md instructions:
```markdown title="SKILL.md (referencing bundled files)"
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:
python scripts/validate.py
```
Cline reads documentation files using `read_file` when the instructions reference them. Scripts can be executed directly, and only the script's output enters the context window.
| Use Scripts For | Use Instructions For |
|-----------------|---------------------|
| Deterministic operations (validation, formatting) | Flexible guidance that adapts to context |
| Complex computations | Decision-making workflows |
| Operations that need reliability | Steps that might vary by situation |
| Anything you'd rather not consume tokens explaining | Best practices and patterns |
## Example: Data Analysis Skill
Here's a practical skill for data analysis tasks. Create a directory called `data-analysis/` with this `SKILL.md`:
```markdown title="data-analysis/SKILL.md"
---
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.
---
# 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:
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.
```
Skills transform Cline from a general-purpose assistant into a specialist that knows your domain. Start with one skill for a task you repeat often, test it, and iterate on the description until it triggers reliably.
-221
View File
@@ -1,221 +0,0 @@
---
title: "Workflows"
sidebarTitle: "Workflows"
description: "Automate repetitive tasks with Markdown-based workflow files."
---
Workflows are Markdown files that define a series of steps to guide Cline through repetitive or complex tasks. Type `/` followed by the workflow's filename to invoke it (e.g., `/deploy.md`).
Deploying, setting up a new project, running through a release checklist: these tasks often require remembering a dozen steps, running commands in the right order, and updating files manually. Mess up one step and you're debugging for an hour. Workflows turn those multi-step processes into one command. Type `/release.md` and Cline handles the version bump, runs tests, updates the changelog, commits, tags, and pushes. You just review and approve.
## Workflow Structure
A workflow is a markdown file with a title and steps. The filename becomes the command: `demo-workflow.md` is invoked with `/demo-workflow.md`.
````markdown title="demo-workflow.md"
# Demo Workflow
Brief description of what this workflow accomplishes.
## Step 1: Check prerequisites
Verify the environment is ready. Look for required tools and dependencies.
## Step 2: Run the build
Execute the build command:
```bash
npm run build
```
## Step 3: Verify results
Check that the build completed successfully and report any issues.
````
Steps can be written at different levels of detail:
- **High-level**: "Run the test suite and fix any failures" lets Cline decide how to accomplish the goal
- **Specific**: Use XML tool syntax or exact commands when you need precise control
## Creating Workflows
<Steps>
<Step title="Open the Workflows menu">
Click the scale icon at the bottom of the Cline panel, to the left of the model selector. Switch to the Workflows tab.
</Step>
<Step title="Create a new workflow file">
Click "New workflow file..." and enter a filename (e.g., `deploy`). The file will be created with a `.md` extension.
</Step>
<Step title="Write your workflow">
Add a title and numbered steps in markdown format. Describe what each step should accomplish.
</Step>
</Steps>
<Tip>
**Create workflows from completed tasks.** After finishing something you'll need to repeat, tell Cline: "Create a workflow for the process I just completed." Cline analyzes the conversation, identifies the steps, and generates the workflow file. Your accumulated context becomes reusable automation.
</Tip>
### Invoking Workflows
Type `/` in the chat input to see available workflows. Cline shows autocomplete suggestions as you type, so `/rel` would match `release-prep.md`. Select a workflow and press Enter to start it.
Cline executes each step in sequence, pausing for your approval when needed. You can stop a workflow at any point by rejecting a step.
### Toggling Workflows
Every workflow has a toggle to enable or disable it. This lets you control which workflows appear in the `/` menu without deleting the file.
## Where Workflows Live
Workflows can be stored in two locations: your project workspace or globally on your system.
**Workspace workflows** go in `.clinerules/workflows/` at your project root. Use these for project-specific automation like deployment scripts, release processes, or setup procedures that your team shares.
**Global workflows** go in your system's Cline Workflows directory. Use these for personal productivity workflows you use across all projects.
### Global Workflows Directory
| Operating System | Default Location |
|------------------|------------------|
| Windows | `Documents\Cline\Workflows` |
| macOS | `~/Documents/Cline/Workflows` |
| Linux/WSL | `~/Documents/Cline/Workflows` |
Workspace workflows take precedence when names match global workflows. See [Storage Locations](/customization/overview#storage-locations) for more guidance.
## What Workflows Can Use
Workflows can combine natural language instructions with specific tool calls. This flexibility lets you write workflows that are as simple or as precise as your task requires.
### Natural Language
Write steps as plain instructions. Cline interprets them and figures out which tools to use:
```markdown
## Step 1: Check for uncommitted changes
Look at the git status. If there are uncommitted changes, ask whether to continue or abort.
## Step 2: Run the test suite
Execute all tests. If any fail, show the failures and stop.
```
This approach works well when you want Cline to adapt to the situation rather than follow rigid steps.
### Cline Tools
For precise control, use Cline's built-in tools with XML syntax. This guarantees specific actions:
```xml
<execute_command>
<command>npm run test</command>
<requires_approval>false</requires_approval>
</execute_command>
```
```xml
<read_file>
<path>src/config.json</path>
</read_file>
```
```xml
<ask_followup_question>
<question>Deploy to production or staging?</question>
<options>["Production", "Staging", "Cancel"]</options>
</ask_followup_question>
```
See the full list in the [Cline Tools Reference](/tools-reference/all-cline-tools).
### CLI Tools
Reference any command-line tool installed on your machine. Git, npm, docker, gh, make, curl: whatever you have available.
```bash
git log --author="$(git config user.name)" --since="yesterday" --oneline
```
### MCP Tools
If you have [MCP servers](/mcp/mcp-overview) connected, use them in your workflows with the `use_mcp_tool` syntax. This lets you integrate with external services like GitHub, Slack, databases, or custom internal tools.
```xml
<use_mcp_tool>
<server_name>github-server</server_name>
<tool_name>create_release</tool_name>
<arguments>{"tag": "v1.2.0", "name": "Release v1.2.0", "body": "Changelog content here"}</arguments>
</use_mcp_tool>
```
Or describe the intent in natural language and let Cline figure out the tool call:
```markdown
## Step 3: Create GitHub release
Use the GitHub MCP server to create a release tagged with the version from package.json.
Include the changelog as the release body.
```
## Writing Effective Workflows
**Start simple.** Write natural language steps first. Only add XML tool calls when you need guaranteed behavior.
**Be specific about decisions.** If a step requires user input, make that explicit: "Ask whether to deploy to production or staging."
**Include failure handling.** Tell Cline what to do when something goes wrong: "If tests fail, show the failures and stop the workflow."
**Keep workflows focused.** A `deploy.md` should deploy. A `setup-db.md` should set up the database. Split complex processes into multiple workflows that can be run independently.
**Version control your workflows.** Store workflows in `.clinerules/workflows/` and commit them. Your team can share, review, and improve them together.
<Warning>
Workflows execute with your permissions. Review workflows before running them, especially those from external sources.
</Warning>
## Example: Release Preparation
This workflow automates the tedious pre-release checklist. It verifies your working directory is clean, runs tests and builds, prompts you for the version bump, and generates a changelog from recent commits.
The workflow demonstrates both approaches: XML tool syntax (`<execute_command>`, `<ask_followup_question>`) for steps that need precise control, and natural language for steps where Cline should adapt to the situation.
````markdown title="release-prep.md"
# Release Preparation
Prepare a new release by running tests, building, and updating version info.
## Step 1: Check for clean working directory
<execute_command>
<command>git status --porcelain</command>
</execute_command>
If there are uncommitted changes, ask whether to continue or stash them first.
## Step 2: Run the test suite
<execute_command>
<command>npm run test</command>
</execute_command>
If any tests fail, stop the workflow and report the failures.
## Step 3: Build the project
<execute_command>
<command>npm run build</command>
</execute_command>
Verify the build completes without errors.
## Step 4: Ask for new version
<ask_followup_question>
<question>What should the new version be?</question>
<options>["Patch (x.x.X)", "Minor (x.X.0)", "Major (X.0.0)", "Custom"]</options>
</ask_followup_question>
## Step 5: Update version
Update the version in `package.json` to the new version specified by the user.
## Step 6: Generate changelog entry
<execute_command>
<command>git log --oneline $(git describe --tags --abbrev=0)..HEAD</command>
</execute_command>
Use these commits to write a changelog entry for the new version.
````
Invoke it with `/release-prep.md` and Cline walks through each step.
+154 -312
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://mintlify.com/docs.json",
"theme": "mint",
"theme": "linden",
"name": "Cline",
"description": "AI-powered coding agent for complex work",
"colors": {
@@ -60,130 +60,169 @@
"icon": "square-terminal",
"groups": [
{
"group": "Home",
"group": "Introduction",
"pages": [
"home",
"getting-started/quick-start"
"introduction/welcome",
"introduction/overview"
]
},
{
"group": "Getting Started",
"pages": [
"getting-started/what-is-cline",
"getting-started/installing-cline",
"getting-started/authorizing-with-cline",
"getting-started/selecting-your-model",
"getting-started/your-first-project"
]
},
{
"group": "Core Workflows",
"group": "Best Practices",
"pages": [
"core-workflows/task-management",
"core-workflows/plan-and-act",
"core-workflows/working-with-files",
"core-workflows/using-commands",
"core-workflows/checkpoints"
"prompting/understanding-context-management",
"prompting/prompt-engineering-guide",
"prompting/cline-memory-bank"
]
},
{
"group": "Customization",
"pages": [
"customization/overview",
"customization/cline-rules",
"customization/skills",
"customization/workflows",
"customization/hooks",
"customization/clineignore"
]
},
{
"group": "Cline CLI",
"group": "CLI",
"pages": [
"cline-cli/overview",
"cline-cli/installation",
"cline-cli/interactive-mode",
"cline-cli/configuration",
"cline-cli/three-core-flows",
"cline-cli/acp-editor-integrations",
{
"group": "Headless Mode",
"group": "CLI Samples",
"pages": [
"cline-cli/three-core-flows",
"cline-cli/samples/overview",
"cline-cli/samples/model-orchestration",
"cline-cli/samples/worktree-workflows",
"cline-cli/samples/github-issue-rca",
"cline-cli/samples/github-integration",
"cline-cli/samples/github-pr-review",
"cline-cli/samples/model-orchestration",
"cline-cli/samples/worktree-workflows"
"cline-cli/samples/github-pr-review"
]
},
"cline-cli/configuration",
"cline-cli/acp-editor-integrations",
"cline-cli/cli-reference"
]
},
{
"group": "Features",
"pages": [
"features/memory-bank",
"features/focus-chain",
{
"group": "@ Mentions",
"pages": [
"features/at-mentions/overview",
"features/at-mentions/file-mentions",
"features/at-mentions/terminal-mentions",
"features/at-mentions/problem-mentions",
"features/at-mentions/git-mentions",
"features/at-mentions/url-mentions"
]
},
"features/auto-approve",
"features/auto-compact",
"features/multiroot-workspace",
"features/subagents",
"features/background-edit",
"features/jupyter-notebooks",
"features/deep-planning",
"features/web-tools",
"features/worktrees"
]
},
{
"group": "Models & Providers",
"pages": [
"features/checkpoints",
{
"group": "Choosing & Configuring Models",
"group": "Cline Rules",
"pages": [
"core-features/model-selection-guide",
"model-config/context-windows"
"features/cline-rules/overview",
"features/cline-rules/conditional-rules"
]
},
{
"group": "Running Models Locally",
"group": "Commands & Shortcuts",
"pages": [
"running-models-locally/overview",
"running-models-locally/ollama",
"running-models-locally/lm-studio"
"features/commands-and-shortcuts/overview",
"features/commands-and-shortcuts/code-commands",
"features/commands-and-shortcuts/terminal-integration",
"features/commands-and-shortcuts/git-integration",
"features/commands-and-shortcuts/keyboard-shortcuts"
]
},
{
"group": "Customization",
"pages": [
"features/customization/opening-cline-in-sidebar",
"features/customization/disable-terminal-pagers"
]
},
"features/dictation",
"features/drag-and-drop",
"features/editing-messages",
"features/explain-changes",
"features/focus-chain",
{
"group": "Hooks",
"pages": [
"features/hooks/index",
"features/hooks/hook-reference",
"features/hooks/samples"
]
},
"features/jupyter-notebooks",
"features/multiroot-workspace",
"features/plan-and-act",
"features/skills",
{
"group": "Slash Commands",
"pages": [
"features/slash-commands/new-task",
"features/slash-commands/new-rule",
"features/slash-commands/explain-changes",
"features/slash-commands/smol",
"features/slash-commands/report-bug",
"features/slash-commands/deep-planning"
]
},
{
"group": "Workflows",
"pages": [
"features/slash-commands/workflows/index",
"features/slash-commands/workflows/quickstart",
"features/slash-commands/workflows/best-practices"
]
},
{
"group": "Task Management",
"pages": [
"features/tasks/understanding-tasks",
"features/tasks/task-management"
]
},
"features/worktrees",
"features/yolo-mode"
]
},
{
"group": "Model & Provider Configuration",
"pages": [
{
"group": "Model Selection",
"pages": [
"core-features/model-selection-guide",
"model-config/model-comparison",
"model-config/context-windows"
]
},
{
"group": "Cloud Providers",
"pages": [
"provider-config/qwen",
"provider-config/anthropic",
"provider-config/asksage",
"provider-config/baseten",
"provider-config/cerebras",
"provider-config/claude-code",
"provider-config/deepseek",
"provider-config/doubao",
"provider-config/fireworks",
"provider-config/gcp-vertex-ai",
"provider-config/google-gemini",
"provider-config/groq",
"provider-config/huawei-cloud-maas",
"provider-config/huggingface",
"provider-config/minimax",
"provider-config/mistral-ai",
"provider-config/moonshot",
"provider-config/nebius",
"provider-config/nousresearch",
"provider-config/openai",
"provider-config/openai-codex",
"provider-config/openrouter",
"provider-config/oracle-code-assist",
"provider-config/qwen-code",
"provider-config/sambanova",
"provider-config/together",
"provider-config/cerebras",
"provider-config/deepseek",
"provider-config/groq",
"provider-config/xai-grok",
"provider-config/mistral-ai",
"provider-config/doubao",
"provider-config/fireworks",
"provider-config/zai",
"provider-config/gcp-vertex-ai",
"provider-config/baseten",
{
"group": "AWS Bedrock",
"pages": [
@@ -194,53 +233,55 @@
}
]
},
{
"group": "Running Models Locally",
"pages": [
"running-models-locally/overview",
"running-models-locally/ollama",
"running-models-locally/lm-studio"
]
},
{
"group": "Advanced Configuration",
"pages": [
"provider-config/aihubmix",
"provider-config/dify",
"provider-config/hicap",
"provider-config/litellm-and-cline-using-codestral",
"provider-config/openai-compatible",
"provider-config/requesty",
"provider-config/litellm-and-cline-using-codestral",
"provider-config/vscode-language-model-api",
"provider-config/sap-aicore",
"provider-config/vercel-ai-gateway",
"provider-config/vscode-language-model-api"
"provider-config/requesty"
]
}
]
},
{
"group": "MCP (Extending Cline)",
"group": "MCP Integration",
"pages": [
"mcp/mcp-overview",
"mcp/mcp-marketplace",
"mcp/adding-and-configuring-servers",
"mcp/mcp-server-development-protocol",
"mcp/adding-mcp-servers-from-github",
"mcp/configuring-mcp-servers",
"mcp/connecting-to-a-remote-server",
"mcp/mcp-marketplace",
"mcp/mcp-server-development-protocol",
"mcp/mcp-transport-mechanisms"
]
},
{
"group": "Tools Reference",
"group": "Cline Tools Reference",
"pages": [
"tools-reference/all-cline-tools",
"tools-reference/browser-automation"
"exploring-clines-tools/cline-tools-guide",
"exploring-clines-tools/new-task-tool",
"exploring-clines-tools/remote-browser-support"
]
},
{
"group": "Troubleshooting",
"group": "Reference",
"pages": [
"troubleshooting/terminal-quick-fixes",
"troubleshooting/networking-and-proxies",
"troubleshooting/task-history-recovery"
]
},
{
"group": "Contributing",
"pages": [
"contributing/documentation-guide",
"contributing/doc-templates"
"troubleshooting/terminal-quick-fixes",
"troubleshooting/terminal-integration-guide",
"troubleshooting/task-history-recovery",
"more-info/telemetry"
]
}
]
@@ -294,7 +335,8 @@
"pages": [
"enterprise-solutions/monitoring/overview",
"enterprise-solutions/monitoring/telemetry",
"enterprise-solutions/monitoring/opentelemetry"
"enterprise-solutions/monitoring/opentelemetry",
"enterprise-solutions/monitoring/opentelemetry_override"
]
}
]
@@ -319,7 +361,7 @@
{
"name": "Overview",
"icon": "house",
"url": "getting-started/what-is-cline"
"url": "introduction/overview"
}
],
"redirects": [
@@ -327,21 +369,17 @@
"source": "/getting-started/installing-cline-jetbrains",
"destination": "/getting-started/installing-cline"
},
{
"source": "/getting-started/what-is-cline",
"destination": "/introduction/overview"
},
{
"source": "/getting-started/overview",
"destination": "/getting-started/what-is-cline"
"destination": "/introduction/overview"
},
{
"source": "/introduction",
"destination": "/getting-started/what-is-cline"
},
{
"source": "/introduction/welcome",
"destination": "/getting-started/what-is-cline"
},
{
"source": "/introduction/overview",
"destination": "/getting-started/what-is-cline"
"destination": "/introduction/welcome"
},
{
"source": "/getting-started/model-selection-guide",
@@ -357,39 +395,11 @@
},
{
"source": "/getting-started/understanding-context-management",
"destination": "/model-config/context-windows"
"destination": "/prompting/understanding-context-management"
},
{
"source": "/best-practices/understanding-context-management",
"destination": "/model-config/context-windows"
},
{
"source": "/prompting/understanding-context-management",
"destination": "/model-config/context-windows"
},
{
"source": "/prompting/prompt-engineering-guide",
"destination": "/customization/cline-rules"
},
{
"source": "/prompting/cline-memory-bank",
"destination": "/features/memory-bank"
},
{
"source": "/customization/memory-bank",
"destination": "/features/memory-bank"
},
{
"source": "/customization/focus-chain",
"destination": "/features/focus-chain"
},
{
"source": "/customization/auto-approve",
"destination": "/features/auto-approve"
},
{
"source": "/customization/auto-compact",
"destination": "/features/auto-compact"
"destination": "/prompting/understanding-context-management"
},
{
"source": "/getting-started/your-first-task",
@@ -399,149 +409,9 @@
"source": "/cline-cli/samples",
"destination": "/cline-cli/samples/overview"
},
{
"source": "/cline-cli/overview",
"destination": "/cline-cli/getting-started"
},
{
"source": "/features/hooks/real-world-examples",
"destination": "/customization/hooks"
},
{
"source": "/features/hooks/index",
"destination": "/customization/hooks"
},
{
"source": "/features/hooks/hook-reference",
"destination": "/customization/hooks"
},
{
"source": "/features/hooks/samples",
"destination": "/customization/hooks"
},
{
"source": "/features/plan-and-act",
"destination": "/core-workflows/plan-and-act"
},
{
"source": "/features/checkpoints",
"destination": "/core-workflows/checkpoints"
},
{
"source": "/features/tasks/understanding-tasks",
"destination": "/core-workflows/task-management"
},
{
"source": "/features/tasks/task-management",
"destination": "/core-workflows/task-management"
},
{
"source": "/features/at-mentions/overview",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/at-mentions/file-mentions",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/at-mentions/folder-mentions",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/at-mentions/terminal-mentions",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/at-mentions/problem-mentions",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/at-mentions/git-mentions",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/at-mentions/url-mentions",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/drag-and-drop",
"destination": "/core-workflows/working-with-files"
},
{
"source": "/features/yolo-mode",
"destination": "/features/auto-approve"
},
{
"source": "/features/cline-rules",
"destination": "/customization/cline-rules"
},
{
"source": "/features/cline-rules/overview",
"destination": "/customization/cline-rules"
},
{
"source": "/features/cline-rules/conditional-rules",
"destination": "/customization/cline-rules"
},
{
"source": "/features/commands-and-shortcuts/overview",
"destination": "/core-workflows/using-commands"
},
{
"source": "/features/commands-and-shortcuts/code-commands",
"destination": "/core-workflows/using-commands"
},
{
"source": "/features/commands-and-shortcuts/terminal-integration",
"destination": "/core-workflows/using-commands"
},
{
"source": "/features/commands-and-shortcuts/git-integration",
"destination": "/core-workflows/using-commands"
},
{
"source": "/features/commands-and-shortcuts/keyboard-shortcuts",
"destination": "/core-workflows/using-commands"
},
{
"source": "/features/slash-commands/new-task",
"destination": "/core-workflows/using-commands"
},
{
"source": "/features/slash-commands/workflows/index",
"destination": "/customization/workflows"
},
{
"source": "/features/slash-commands/workflows/quickstart",
"destination": "/customization/workflows"
},
{
"source": "/features/slash-commands/workflows/best-practices",
"destination": "/customization/workflows"
},
{
"source": "/exploring-clines-tools/cline-tools-guide",
"destination": "/tools-reference/all-cline-tools"
},
{
"source": "/exploring-clines-tools/new-task-tool",
"destination": "/tools-reference/all-cline-tools"
},
{
"source": "/exploring-clines-tools/remote-browser-support",
"destination": "/tools-reference/browser-automation"
},
{
"source": "/mcp/adding-mcp-servers-from-github",
"destination": "/mcp/adding-and-configuring-servers"
},
{
"source": "/mcp/configuring-mcp-servers",
"destination": "/mcp/adding-and-configuring-servers"
},
{
"source": "/more-info/telemetry",
"destination": "/enterprise-solutions/monitoring/telemetry"
"destination": "/features/hooks/samples"
},
{
"source": "/enterprise-solutions/configure-AWS-Bedrock-Admin",
@@ -568,44 +438,16 @@
"destination": "/enterprise-solutions/team-management/managing-members"
},
{
"source": "/features/customization/opening-cline-in-sidebar",
"destination": "/getting-started/installing-cline"
"source": "/features/cline-rules",
"destination": "/features/cline-rules/overview"
},
{
"source": "/prompting/prompt-engineering-guide/clineignore-file-guide",
"destination": "/customization/clineignore"
"source": "/features/conditional-rules",
"destination": "/features/cline-rules/conditional-rules"
},
{
"source": "/getting-started/selecting-your-model",
"destination": "/getting-started/authorizing-with-cline"
},
{
"source": "/model-config/model-comparison",
"destination": "/core-features/model-selection-guide"
},
{
"source": "/troubleshooting/terminal-integration-guide",
"destination": "/troubleshooting/terminal-quick-fixes"
},
{
"source": "/features/slash-commands/deep-planning",
"destination": "/features/deep-planning"
},
{
"source": "/features/slash-commands/smol",
"destination": "/core-workflows/using-commands#smol"
},
{
"source": "/features/slash-commands/explain-changes",
"destination": "/core-workflows/using-commands#explain-changes"
},
{
"source": "/features/slash-commands/new-rule",
"destination": "/core-workflows/using-commands#newrule"
},
{
"source": "/features/skills",
"destination": "/customization/skills"
"source": "/cline-cli/authentication",
"destination": "/cline-cli/installation"
}
],
"search": {
@@ -0,0 +1,287 @@
---
title: "Bundled Endpoints Configuration"
description: "Enterprise guide for distributing Cline with pre-configured endpoints"
---
# Bundled Endpoints Configuration
This guide explains how enterprise customers can distribute Cline with pre-configured endpoints bundled directly into the installation packages.
## Overview
Cline supports bundling custom endpoint configurations directly into distribution packages (VSIX, NPM, or JetBrains). This eliminates the need for end users to manually configure endpoints, ensuring consistent configuration across your organization.
### Configuration Priority
When Cline starts, it checks for endpoints configuration in this order:
1. **Bundled endpoints.json** (in extension installation directory) - Highest priority
2. **User endpoints.json** (`~/.cline/endpoints.json`) - Fallback
3. **Built-in endpoints** (standard Cline URLs) - Default
When a bundled `endpoints.json` is found, Cline automatically switches to self-hosted mode and uses those endpoints exclusively.
## Prerequisites
- Official Cline release package (VSIX, TGZ, or ZIP)
- Your `endpoints.json` configuration file
- `jq` command-line tool (for JSON validation)
- `unzip`, `zip`, `tar` utilities
## Creating endpoints.json
Create a JSON file with your organization's endpoints:
```json
{
"appBaseUrl": "https://cline.yourcompany.com",
"apiBaseUrl": "https://api-cline.yourcompany.com",
"mcpBaseUrl": "https://api-cline.yourcompany.com/v1/mcp"
}
```
### Required Fields
All three fields are required and must be valid URLs:
- **appBaseUrl**: Web application base URL
- **apiBaseUrl**: API server base URL
- **mcpBaseUrl**: MCP (Model Context Protocol) server URL
### Validation
The packaging scripts automatically validate:
- Valid JSON syntax
- All required fields present
- Non-empty string values
- Valid URL format (must start with `http://` or `https://`)
## Packaging Scripts
Cline provides three scripts for adding bundled endpoints to packages:
### VSCode Extension (VSIX)
```bash
./scripts/add-endpoints-to-vsix.sh \
cline-3.55.0.vsix \
cline-3.55.0-enterprise.vsix \
endpoints.json
```
This script:
1. Extracts the VSIX package
2. Adds `endpoints.json` to the `extension/` directory
3. Repackages as a new VSIX file
### NPM Package (CLI)
```bash
./scripts/add-endpoints-to-npm.sh \
cline-3.55.0.tgz \
cline-3.55.0-enterprise.tgz \
endpoints.json
```
This script:
1. Extracts the NPM tarball
2. Adds `endpoints.json` to the package root
3. Repackages as a new tarball
### JetBrains Plugin (ZIP)
```bash
./scripts/add-endpoints-to-jetbrains.sh \
cline-jetbrains-3.55.0.zip \
cline-jetbrains-3.55.0-enterprise.zip \
endpoints.json
```
This script:
1. Extracts the ZIP package
2. Adds `endpoints.json` to the plugin directory
3. Repackages as a new ZIP file
## Distribution Workflow
### 1. Download Official Release
Download the official Cline package for your platform:
```bash
# VSCode - from marketplace or GitHub releases
curl -LO https://github.com/cline/cline/releases/download/v3.55.0/cline-3.55.0.vsix
# NPM - from npm registry
npm pack @cline/cline@3.55.0
# JetBrains - from marketplace or GitHub releases
curl -LO https://github.com/cline/cline/releases/download/v3.55.0/cline-jetbrains-3.55.0.zip
```
### 2. Create Endpoints Configuration
Create your `endpoints.json` file:
```json
{
"appBaseUrl": "https://cline.internal.company.com",
"apiBaseUrl": "https://cline-api.internal.company.com",
"mcpBaseUrl": "https://cline-api.internal.company.com/v1/mcp"
}
```
### 3. Run Packaging Script
Choose the appropriate script for your platform:
```bash
# VSCode
./scripts/add-endpoints-to-vsix.sh \
cline-3.55.0.vsix \
cline-3.55.0-yourcompany.vsix \
endpoints.json
# CLI
./scripts/add-endpoints-to-npm.sh \
cline-3.55.0.tgz \
cline-3.55.0-yourcompany.tgz \
endpoints.json
# JetBrains
./scripts/add-endpoints-to-jetbrains.sh \
cline-jetbrains-3.55.0.zip \
cline-jetbrains-3.55.0-yourcompany.zip \
endpoints.json
```
### 4. Distribute to Users
Distribute the enterprise package to your users through your internal channels:
- **VSCode**: Install via `code --install-extension cline-3.55.0-yourcompany.vsix`
- **CLI**: Install via `npm install -g cline-3.55.0-yourcompany.tgz`
- **JetBrains**: Install through IDE plugin manager from disk
## Verification
After installation, verify the configuration is active:
1. Launch Cline
2. Check the logs for: `"Cline running in self-hosted mode with custom endpoints"`
3. Confirm that environment switching is disabled (as expected in self-hosted mode)
## User Experience
### What Users See
- Cline automatically uses the bundled endpoints
- No manual configuration required
- Environment switching is disabled (prevents accidental misconfiguration)
- All API calls route to your organization's infrastructure
### User Override
Users **cannot** override bundled endpoints through the UI. The bundled configuration takes absolute precedence. This ensures:
- Consistent configuration across the organization
- No accidental connections to external services
- Simplified deployment and support
If users have a `~/.cline/endpoints.json` file, it will be ignored when bundled configuration is present.
## Troubleshooting
### Invalid Configuration Error
If users see an error about invalid configuration on startup:
```
ClineConfigurationError: Invalid JSON in bundled endpoints configuration file
```
**Solution**: The bundled `endpoints.json` is malformed. Repackage with a valid JSON file.
### Missing Required Field Error
```
ClineConfigurationError: Missing required field "apiBaseUrl" in endpoints configuration file
```
**Solution**: Ensure all three required fields are present in `endpoints.json`.
### Invalid URL Error
```
ClineConfigurationError: Field "appBaseUrl" must be a valid URL. Got: "not-a-url"
```
**Solution**: All URLs must start with `http://` or `https://`.
## Security Considerations
1. **Bundle Validation**: The packaging scripts validate JSON structure and required fields
2. **Read-Only Configuration**: Users cannot modify bundled endpoints through the UI
3. **Self-Hosted Mode**: Automatic switch to self-hosted mode prevents external connections
4. **Audit Trail**: All endpoint access is logged with configuration source
## Updating Endpoints
To update endpoints for existing installations:
1. Create updated `endpoints.json`
2. Repackage the same Cline version with new endpoints
3. Distribute updated package
4. Users reinstall/update the package
The version number remains the same since only configuration changed, not the Cline code.
## Support
For questions or issues with bundled endpoints:
1. Verify your `endpoints.json` is valid JSON with all required fields
2. Check that URLs are accessible from user networks
3. Review Cline logs for configuration loading messages
4. Contact your Cline support representative for assistance
## Example: Complete Workflow
Here's a complete example for VSCode deployment:
```bash
# 1. Download official release
curl -LO https://github.com/cline/cline/releases/download/v3.55.0/cline-3.55.0.vsix
# 2. Create endpoints configuration
cat > endpoints.json << 'EOF'
{
"appBaseUrl": "https://cline.acme.internal",
"apiBaseUrl": "https://cline-api.acme.internal",
"mcpBaseUrl": "https://cline-api.acme.internal/v1/mcp"
}
EOF
# 3. Validate JSON
jq empty endpoints.json # Should succeed silently
# 4. Run packaging script
./scripts/add-endpoints-to-vsix.sh \
cline-3.55.0.vsix \
cline-3.55.0-acme.vsix \
endpoints.json
# 5. Verify output
unzip -l cline-3.55.0-acme.vsix | grep endpoints.json
# Should show: extension/endpoints.json
# 6. Test installation (on test machine)
code --install-extension cline-3.55.0-acme.vsix
# 7. Distribute to organization
# Upload to internal package repository
# or distribute via configuration management system
```
## Changelog
- **v3.55.0**: Initial release of bundled endpoints support
@@ -0,0 +1,105 @@
---
title: "Choosing Your Configuration Path"
sidebarTitle: "Deployment Guide"
description: "Decide between SaaS and Self-Hosted configuration for your Cline Enterprise deployment"
---
Choose the right configuration approach for your organization. Most teams start with SaaS for quick deployment, while enterprises with complex requirements opt for self-hosted infrastructure.
## Configuration Paths
<CardGroup cols={2}>
<Card title="SaaS Provider Configuration" icon="cloud" href="/enterprise-solutions/configuration/remote-configuration/overview">
### Quick Setup via Web Console
✅ No infrastructure required
✅ 5-10 minute configuration
✅ Web-based admin console
✅ Automatic updates
✅ Simplified credential management
**Best for:**
- Small to medium teams (5-50 developers)
- Quick deployment needs
- Limited DevOps resources
- Standard security requirements
- Single region deployments
</Card>
<Card title="Self-Hosted Configuration" icon="server" href="/enterprise-solutions/configuration/infrastructure-configuration/overview">
### Full Infrastructure Control
✅ Your own AWS/GCP/K8s
✅ VPC endpoints & private connectivity
✅ Multi-account setups
✅ Advanced compliance & audit
✅ GitOps workflows
**Best for:**
- Large enterprises (50+ developers)
- Complex security requirements
- Existing cloud infrastructure
- Multi-region deployments
- Custom compliance needs
</Card>
</CardGroup>
## Detailed Comparison
### Feature Comparison
| Feature | SaaS | Self-Hosted |
|---------|------|-------------|
| **Configuration** | Web UI | YAML + Helm/Kubernetes |
| **Infrastructure** | None required | Full AWS/GCP/K8s |
| **VPC Endpoints** | Basic | Full private connectivity |
| **Multi-Account** | ❌ | ✅ |
| **IAM** | Standard RBAC roles | Standard RBAC roles |
| **Compliance** | Standard | Custom frameworks |
| **GitOps** | ❌ | ✅ |
| **Maintenance** | Managed by Cline | Self-managed |
| **Updates** | Automatic (extension) | Automatic (extension) + Infrastructure control |
### Security & Compliance
| Capability | SaaS | Self-Hosted |
|------------|------|-------------|
| **Network Encryption** | HTTPS/TLS | HTTPS/TLS |
| **Network** | Public internet | Private VPC endpoints |
| **Access Control** | Standard RBAC | Standard RBAC |
| **Audit Logs** | OpenTelemetry traces | OpenTelemetry traces + Infrastructure logs |
| **Data Residency** | Cline-managed deployment | Customer-controlled deployment |
### Cost Structure
| Cost Category | SaaS | Self-Hosted |
|---------------|------|-------------|
| **Cline Subscription** | Fixed enterprise fee | Fixed enterprise fee |
| **Inference Provider Costs** | Usage-based | Usage-based |
| **Infrastructure** | ✅ None required | Kubernetes, networking, storage |
| **Personnel** | ✅ None required | DevOps team needed |
| **Total Cost Profile** | Predictable and simple | Variable based on scale |
## Migration Path
<Note>
Most organizations start with SaaS configuration for quick deployment, then migrate to self-hosted later as requirements grow. This minimizes risk and ensures your infrastructure meets actual usage patterns.
</Note>
## Getting Started
<CardGroup cols={2}>
<Card title="Start with SaaS" icon="rocket" href="/enterprise-solutions/configuration/remote-configuration/overview">
Begin with quick SaaS setup
</Card>
<Card title="Deploy Self-Hosted" icon="server" href="/enterprise-solutions/configuration/infrastructure-configuration/overview">
Plan your infrastructure deployment
</Card>
</CardGroup>
## Need Help Deciding?
- [**Contact Cline Enterprise Sales**](https://cline.bot/contact-sales) for a consultation on your specific requirements
- [**Start with SaaS**](/enterprise-solutions/configuration/remote-configuration/overview) if unsure - it's lower risk and you can always migrate later
- [**Review Self-Hosted Requirements**](/enterprise-solutions/configuration/infrastructure-configuration/overview) if you have existing infrastructure that could benefit from self-hosted deployment
@@ -0,0 +1,35 @@
---
title: "Overview"
sidebarTitle: "Overview"
description: "Configure Cline settings for your enterprise deployment"
---
This section covers configuration options for controlling Cline's behavior in enterprise deployments.
## Available Settings
<Card title="YOLO Mode" icon="rocket" href="/enterprise-solutions/configuration/infrastructure-configuration/control-other-cline-features/yolo-mode">
Control enterprise access to autonomous operation mode with complete auto-approval
</Card>
## Configuration Methods
These settings can be configured through:
### Individual Users
- Users can toggle settings in their local Cline interface
- Enterprise policies can restrict certain settings
- Changes apply immediately to new tasks
## Enterprise Controls
Administrators can enforce policies through remote configuration:
```json
{
"yoloModeAllowed": false
}
```
When `yoloModeAllowed` is set to `false`, users cannot enable YOLO Mode in their local Cline interface.
@@ -0,0 +1,565 @@
---
title: "MCP Marketplace"
sidebarTitle: "MCP Marketplace"
description: "Deploy pre-built enterprise MCP servers from the Cline marketplace with one-click configuration"
---
The MCP Marketplace provides curated, enterprise-ready integrations with popular development tools and services. All marketplace servers are built with enterprise security, compliance, and scalability in mind.
## Enterprise Marketplace Benefits
<CardGroup cols={2}>
<Card title="One-Click Deployment" icon="rocket">
Deploy complex integrations instantly with pre-configured enterprise settings.
</Card>
<Card title="Security Hardened" icon="shield-check">
All servers include enterprise security features, audit logging, and compliance controls.
</Card>
<Card title="Maintained & Updated" icon="sync">
Regular security updates and feature enhancements managed by Cline Enterprise team.
</Card>
<Card title="Enterprise Support" icon="headset">
Dedicated support channels for marketplace integration issues and customization.
</Card>
</CardGroup>
## Available Integrations
### Development Tools
<CardGroup cols={3}>
<Card title="GitHub Enterprise" icon="github">
Repository management, issue tracking, PR workflows, and code analysis
</Card>
<Card title="GitLab Enterprise" icon="gitlab">
Project management, CI/CD pipelines, merge requests, and security scanning
</Card>
<Card title="Bitbucket Enterprise" icon="bitbucket">
Source code management, build pipelines, and deployment automation
</Card>
</CardGroup>
### Project Management
<CardGroup cols={3}>
<Card title="Jira Enterprise" icon="jira">
Issue tracking, sprint management, custom fields, and workflow automation
</Card>
<Card title="Azure DevOps" icon="microsoft">
Work items, boards, repos, pipelines, and test management
</Card>
<Card title="Linear" icon="linear">
Issue tracking, project planning, and development workflow integration
</Card>
</CardGroup>
### Communication & Collaboration
<CardGroup cols={3}>
<Card title="Slack Enterprise Grid" icon="slack">
Notifications, bot interactions, file sharing, and workflow automation
</Card>
<Card title="Microsoft Teams" icon="microsoft-teams">
Chat notifications, meeting integration, and collaborative workflows
</Card>
<Card title="Discord" icon="discord">
Community management, bot interactions, and developer notifications
</Card>
</CardGroup>
### Cloud Services
<CardGroup cols={3}>
<Card title="AWS Services" icon="aws">
EC2, S3, Lambda, RDS, CloudWatch, and other AWS service integrations
</Card>
<Card title="Google Cloud" icon="google-cloud">
Compute Engine, Cloud Storage, BigQuery, and GCP service management
</Card>
<Card title="Azure Services" icon="azure">
Virtual Machines, Storage Accounts, Functions, and Azure resource management
</Card>
</CardGroup>
## Installing Marketplace Servers
### Via Cline Enterprise Dashboard
1. **Access Marketplace**: Navigate to `Settings > Enterprise > MCP Marketplace`
2. **Browse Integrations**: Filter by category, popularity, or search by name
3. **Review Details**: Check compatibility, permissions, and configuration requirements
4. **Install**: Click "Install" and configure required settings
5. **Deploy**: Approve deployment to your selected environment
### Via Configuration File
Install marketplace servers through enterprise configuration:
```yaml
# enterprise-mcp-config.yaml
mcp:
marketplace_servers:
- name: "github-enterprise"
package: "@cline/mcp-github-enterprise"
version: "2.1.0"
environment: "production"
config:
github:
base_url: "https://github.company.com/api/v3"
token: "${GITHUB_ENTERPRISE_TOKEN}"
organization: "company"
features:
issue_management: true
pull_request_automation: true
code_analysis: true
security_scanning: true
permissions:
repositories: "read-write"
issues: "write"
pull_requests: "write"
compliance:
audit_logging: true
data_retention_days: 365
encryption_at_rest: true
- name: "jira-enterprise"
package: "@cline/mcp-jira-enterprise"
version: "1.8.3"
environment: "production"
config:
jira:
base_url: "https://company.atlassian.net"
username: "${JIRA_USERNAME}"
api_token: "${JIRA_API_TOKEN}"
projects:
- key: "DEV"
permissions: ["read", "write", "transition"]
- key: "OPS"
permissions: ["read", "comment"]
compliance:
field_encryption: ["description", "comments"]
audit_trail: true
```
### Via CLI
Deploy using the Cline Enterprise CLI:
```bash
# Install GitHub Enterprise integration
cline-enterprise mcp install github-enterprise \
--version 2.1.0 \
--config-file github-config.yaml \
--environment production
# Install Slack Enterprise Grid integration
cline-enterprise mcp install slack-enterprise-grid \
--version 1.5.2 \
--config workspace_id=T1234567890 \
--config bot_token=${SLACK_BOT_TOKEN} \
--environment production
# List installed marketplace servers
cline-enterprise mcp list --environment production
# Check server status
cline-enterprise mcp status github-enterprise --environment production
```
## Configuration Examples
### GitHub Enterprise Integration
```yaml
# github-enterprise-config.yaml
github:
base_url: "https://github.company.com/api/v3"
token: "${GITHUB_ENTERPRISE_TOKEN}"
organization: "company"
# Repository access controls
repositories:
allowed_patterns:
- "company/*"
- "internal/*"
blocked_patterns:
- "*/secrets"
- "*/private-keys"
# Feature configuration
features:
issue_management:
enabled: true
auto_assign: true
labels:
- "ai-generated"
- "cline-task"
pull_requests:
enabled: true
auto_review_request: true
required_approvals: 2
enforce_branch_protection: true
code_analysis:
enabled: true
languages: ["typescript", "python", "go", "rust"]
security_scan: true
# Security and compliance
security:
webhook_secret: "${GITHUB_WEBHOOK_SECRET}"
rate_limiting:
requests_per_hour: 5000
burst_limit: 100
ip_whitelist:
- "10.0.0.0/8"
- "192.168.0.0/16"
audit:
log_level: "INFO"
include_payloads: false
retention_days: 365
destinations: ["datadog", "splunk"]
```
### Jira Enterprise Integration
```yaml
# jira-enterprise-config.yaml
jira:
base_url: "https://company.atlassian.net"
username: "${JIRA_USERNAME}"
api_token: "${JIRA_API_TOKEN}"
# Project access configuration
projects:
- key: "DEV"
name: "Development"
permissions: ["read", "write", "transition", "assign"]
issue_types: ["Story", "Bug", "Task", "Subtask"]
- key: "OPS"
name: "Operations"
permissions: ["read", "comment", "watch"]
# Custom field mappings
custom_fields:
story_points: "customfield_10002"
epic_link: "customfield_10014"
sprint: "customfield_10020"
# Workflow automation
automation:
auto_transition:
enabled: true
rules:
- from_status: "To Do"
to_status: "In Progress"
condition: "assignee_changed"
auto_assign:
enabled: true
rules:
- issue_type: "Bug"
component: "Frontend"
assignee: "frontend-team-lead"
# Security and compliance
security:
encrypt_fields: ["description", "comment"]
mask_sensitive_data: true
audit_changes: true
compliance:
gdpr_compliant: true
data_retention_policy: "365_days"
audit_log_retention: "7_years"
```
### Slack Enterprise Grid Integration
```yaml
# slack-enterprise-config.yaml
slack:
workspace_id: "T1234567890"
bot_token: "${SLACK_BOT_TOKEN}"
signing_secret: "${SLACK_SIGNING_SECRET}"
# Channel management
channels:
notifications:
- name: "#dev-alerts"
types: ["deployments", "errors", "security"]
- name: "#ai-activity"
types: ["cline-tasks", "completions"]
private_channels:
- name: "#security-incidents"
members: ["security-team"]
types: ["security-alerts", "compliance-issues"]
# Bot behavior
bot:
display_name: "Cline Enterprise"
default_channel: "#general"
response_delay_ms: 1000
commands:
- command: "/cline-status"
description: "Check Cline Enterprise status"
permission: "all"
- command: "/cline-deploy"
description: "Trigger deployment"
permission: "admin"
# Enterprise features
enterprise:
app_approval_required: true
data_residency: "US"
compliance_export: true
dlp:
enabled: true
scan_messages: true
block_sensitive_data: true
# Security settings
security:
require_app_approval: true
audit_api_calls: true
encrypt_messages: true
retain_audit_logs_days: 2555 # 7 years
```
## Enterprise Management
### Multi-Environment Deployment
Deploy marketplace servers across environments:
```yaml
# environments-config.yaml
environments:
development:
marketplace_servers:
- github-enterprise:
version: "2.1.0-beta"
config_override:
github:
base_url: "https://github-dev.company.com/api/v3"
organization: "company-dev"
staging:
marketplace_servers:
- github-enterprise:
version: "2.1.0-rc1"
config_override:
github:
base_url: "https://github-staging.company.com/api/v3"
organization: "company-staging"
production:
marketplace_servers:
- github-enterprise:
version: "2.1.0"
config_override:
github:
base_url: "https://github.company.com/api/v3"
organization: "company"
```
### Version Management
Control marketplace server versions:
```bash
# List available versions
cline-enterprise mcp versions github-enterprise
# Upgrade to latest version
cline-enterprise mcp upgrade github-enterprise --version 2.2.0 --environment staging
# Rollback to previous version
cline-enterprise mcp rollback github-enterprise --version 2.1.0 --environment staging
# Pin to specific version (disable auto-updates)
cline-enterprise mcp pin github-enterprise --version 2.1.0
```
### Health Monitoring
Monitor marketplace server health:
```yaml
# monitoring-config.yaml
monitoring:
marketplace_servers:
health_checks:
interval_seconds: 30
timeout_seconds: 10
metrics:
- server_status
- request_latency
- error_rate
- resource_usage
alerts:
- name: "marketplace-server-down"
condition: "server_status != 1"
severity: "critical"
- name: "high-error-rate"
condition: "error_rate > 0.05"
severity: "warning"
- name: "performance-degradation"
condition: "request_latency > 5s"
severity: "warning"
```
## Security & Compliance
### Enterprise Security Features
All marketplace servers include:
- **Authentication Integration**: SSO, SAML, OAuth2 support
- **Authorization Controls**: RBAC and fine-grained permissions
- **Audit Logging**: Comprehensive activity tracking
- **Data Encryption**: At-rest and in-transit encryption
- **Network Security**: VPN, IP whitelisting, private endpoints
- **Compliance**: SOC2, GDPR, HIPAA compliance frameworks
### Data Governance
Configure data handling policies:
```yaml
# data-governance-config.yaml
data_governance:
classification:
public:
retention_days: 90
backup_required: false
internal:
retention_days: 365
backup_required: true
encryption_required: false
confidential:
retention_days: 2555 # 7 years
backup_required: true
encryption_required: true
audit_access: true
restricted:
retention_days: 2555
backup_required: true
encryption_required: true
audit_access: true
approval_required: true
privacy:
pii_detection: true
pii_masking: true
gdpr_compliance: true
data_subject_requests: true
compliance:
frameworks: ["SOC2", "GDPR", "CCPA", "HIPAA"]
audit_frequency: "quarterly"
certification_renewal: "annual"
```
## Best Practices
### Installation
1. **Review Permissions**: Always review required permissions before installation
2. **Test in Staging**: Deploy to staging environment first
3. **Configuration Validation**: Validate configuration files before deployment
4. **Backup Current State**: Create configuration backups before changes
5. **Monitor Deployment**: Watch health metrics during rollout
### Configuration
1. **Environment Separation**: Use different configurations per environment
2. **Secret Management**: Store sensitive data in secure secret stores
3. **Version Pinning**: Pin versions for production deployments
4. **Access Controls**: Implement least-privilege access policies
5. **Regular Updates**: Schedule regular security and feature updates
### Monitoring
1. **Health Checks**: Monitor server health continuously
2. **Performance Metrics**: Track latency and throughput
3. **Error Tracking**: Alert on error rates and failure patterns
4. **Resource Usage**: Monitor CPU, memory, and network usage
5. **Audit Reviews**: Regular review of audit logs and access patterns
## Troubleshooting
### Common Issues
**Installation Failures**:
```bash
# Check marketplace connectivity
cline-enterprise mcp marketplace-status
# Verify authentication
cline-enterprise auth verify --service marketplace
# Check installation logs
cline-enterprise logs mcp-installer --lines 100
```
**Configuration Errors**:
```bash
# Validate configuration
cline-enterprise mcp validate-config --file config.yaml
# Test connectivity
cline-enterprise mcp test-connection github-enterprise --environment staging
# Check server status
cline-enterprise mcp status --all
```
**Performance Issues**:
```bash
# Check server metrics
cline-enterprise mcp metrics github-enterprise --duration 1h
# View recent error logs
cline-enterprise logs github-enterprise --level error --lines 50
```
## Support
For marketplace server issues:
- **Documentation**: Check server-specific documentation in the dashboard
- **Community**: Join the Cline Enterprise community forum
- **Support Tickets**: Create support tickets for critical issues
- **Professional Services**: Engage professional services for custom configurations
Enterprise customers have access to dedicated support channels with SLA guarantees.
@@ -0,0 +1,571 @@
---
title: "MCP Integration"
sidebarTitle: "Overview"
description: "Configure Model Context Protocol (MCP) servers and marketplace integrations for enterprise Cline deployments"
---
Model Context Protocol (MCP) provides standardized communication between AI models and external data sources, tools, and services. Enterprise MCP integration allows you to securely connect Cline to your organization's systems while maintaining governance and compliance.
## Enterprise MCP Benefits
<CardGroup cols={2}>
<Card title="Extensible Architecture" icon="puzzle-piece">
Connect to unlimited external tools, databases, APIs, and services through standardized MCP servers.
</Card>
<Card title="Enterprise Security" icon="shield-alt">
Secure authentication, authorization, and audit trails for all MCP server communications.
</Card>
<Card title="Centralized Management" icon="network-wired">
Manage and deploy MCP servers enterprise-wide with version control and configuration management.
</Card>
<Card title="Compliance Ready" icon="clipboard-check">
Built-in logging, monitoring, and data governance for regulatory compliance requirements.
</Card>
</CardGroup>
## MCP Architecture Overview
```mermaid
graph TB
A[Cline Enterprise] --> B[MCP Hub]
B --> C[MCP Marketplace]
B --> D[Remote MCP Servers]
B --> E[Internal MCP Servers]
C --> F[GitHub Integration]
C --> G[Slack Integration]
C --> H[Jira Integration]
D --> I[Custom APIs]
D --> J[Databases]
D --> K[Cloud Services]
E --> L[Internal Tools]
E --> M[Legacy Systems]
E --> N[Security Systems]
O[Enterprise Admin] --> B
P[Audit Logging] --> B
Q[Authentication] --> B
```
## Core Components
<CardGroup cols={2}>
<Card title="MCP Marketplace" icon="store" href="/enterprise-solutions/configuration/infrastructure-configuration/mcp/mcp-marketplace">
Pre-built, enterprise-ready MCP servers for popular tools and services with one-click deployment.
</Card>
<Card title="Remote MCP Servers" icon="server" href="/enterprise-solutions/configuration/infrastructure-configuration/mcp/remote-mcp-servers">
Deploy and manage custom MCP servers across your infrastructure with centralized configuration.
</Card>
</CardGroup>
## Enterprise Configuration
### Basic MCP Hub Setup
Configure the central MCP hub for your enterprise deployment:
```yaml
# mcp-hub-config.yaml
mcp:
hub:
enabled: true
port: 8080
authentication:
method: "enterprise-sso"
jwt_secret: "${MCP_JWT_SECRET}"
# Server discovery
discovery:
methods: ["marketplace", "remote", "local"]
marketplace_url: "https://mcp.cline.bot/marketplace"
# Security settings
security:
enforce_tls: true
allowed_origins: ["https://*.company.com"]
rate_limiting:
requests_per_minute: 1000
burst_size: 100
# Audit and compliance
audit:
enabled: true
log_level: "INFO"
destinations: ["file", "syslog", "datadog"]
retention_days: 90
```
### Multi-Environment Configuration
Deploy MCP configurations across environments:
<Tabs>
<Tab title="Development">
```yaml
# mcp-dev-config.yaml
mcp:
environment: "development"
servers:
- name: "github-dev"
type: "marketplace"
package: "@cline/mcp-github"
version: "latest"
config:
github_token: "${GITHUB_DEV_TOKEN}"
org: "company-dev"
- name: "local-db"
type: "remote"
url: "http://localhost:3001"
auth:
type: "api-key"
key: "${DEV_DB_API_KEY}"
policies:
allow_experimental: true
auto_update: true
rate_limits:
relaxed: true
```
</Tab>
<Tab title="Production">
```yaml
# mcp-prod-config.yaml
mcp:
environment: "production"
servers:
- name: "github-prod"
type: "marketplace"
package: "@cline/mcp-github"
version: "1.2.3" # Pinned version
config:
github_token: "${GITHUB_PROD_TOKEN}"
org: "company"
- name: "crm-integration"
type: "remote"
url: "https://mcp-crm.internal.company.com"
auth:
type: "mtls"
cert_path: "/certs/mcp-client.pem"
key_path: "/certs/mcp-client-key.pem"
- name: "security-scanner"
type: "remote"
url: "https://security-mcp.company.com"
auth:
type: "oauth2"
client_id: "${SECURITY_CLIENT_ID}"
client_secret: "${SECURITY_CLIENT_SECRET}"
policies:
allow_experimental: false
auto_update: false
strict_versioning: true
monitoring:
metrics: true
health_checks: true
alert_on_failure: true
```
</Tab>
</Tabs>
## Server Management
### Lifecycle Management
Manage MCP server deployments with GitOps:
```yaml
# mcp-server-manifest.yaml
apiVersion: mcp.cline.bot/v1
kind: MCPServer
metadata:
name: custom-api-server
namespace: cline-enterprise
spec:
image: company/custom-mcp-server:v1.0.0
replicas: 3
config:
api_endpoint: "https://api.internal.company.com"
timeout: 30s
retry_attempts: 3
auth:
type: service-account
service_account: mcp-custom-api
resources:
requests:
memory: "256Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
monitoring:
enabled: true
metrics_port: 9090
health_endpoint: "/health"
security:
network_policy: strict
pod_security_standard: restricted
```
### Configuration Management
Use Helm charts for enterprise MCP deployments:
```yaml
# values-prod.yaml
mcp:
hub:
replicaCount: 3
image:
repository: cline/mcp-hub-enterprise
tag: "1.5.2"
servers:
marketplace:
enabled: true
catalog_url: "https://enterprise-catalog.company.com"
custom:
- name: "salesforce"
enabled: true
image: "company/mcp-salesforce:1.0.0"
config:
instance_url: "https://company.my.salesforce.com"
- name: "jira"
enabled: true
image: "company/mcp-jira:2.1.0"
config:
base_url: "https://company.atlassian.net"
ingress:
enabled: true
className: nginx
annotations:
cert-manager.io/cluster-issuer: "letsencrypt-prod"
hosts:
- host: mcp.company.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: mcp-tls
hosts:
- mcp.company.com
```
## Security & Governance
### Authentication & Authorization
Configure enterprise authentication for MCP servers:
```yaml
# mcp-auth-config.yaml
authentication:
providers:
- name: "enterprise-sso"
type: "oidc"
issuer: "https://sso.company.com"
client_id: "${SSO_CLIENT_ID}"
client_secret: "${SSO_CLIENT_SECRET}"
- name: "service-accounts"
type: "jwt"
signing_key: "${SERVICE_ACCOUNT_KEY}"
authorization:
policies:
- name: "developers"
subjects: ["group:developers"]
resources: ["mcp:servers:read", "mcp:servers:execute"]
- name: "admins"
subjects: ["group:mcp-admins"]
resources: ["mcp:*"]
- name: "security-team"
subjects: ["group:security"]
resources: ["mcp:audit:*", "mcp:servers:security-*"]
rbac:
enabled: true
default_role: "viewer"
```
### Network Security
Implement network policies for MCP communications:
```yaml
# mcp-network-policy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: mcp-server-policy
namespace: cline-enterprise
spec:
podSelector:
matchLabels:
app: mcp-server
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: cline-enterprise
- podSelector:
matchLabels:
app: cline-core
ports:
- protocol: TCP
port: 8080
egress:
# Allow DNS
- to: []
ports:
- protocol: UDP
port: 53
# Allow HTTPS to external APIs
- to: []
ports:
- protocol: TCP
port: 443
```
## Monitoring & Observability
### Metrics Collection
Configure comprehensive MCP monitoring:
```yaml
# mcp-monitoring.yaml
monitoring:
metrics:
enabled: true
interval: 30s
collectors:
- name: "server-health"
metrics:
- mcp_server_status
- mcp_server_response_time
- mcp_server_error_rate
- name: "hub-performance"
metrics:
- mcp_hub_requests_total
- mcp_hub_request_duration
- mcp_hub_active_connections
- name: "resource-usage"
metrics:
- mcp_memory_usage
- mcp_cpu_usage
- mcp_network_io
alerts:
- name: "server-down"
condition: "mcp_server_status == 0"
severity: "critical"
notification_channels: ["pagerduty", "slack"]
- name: "high-error-rate"
condition: "mcp_server_error_rate > 0.05"
severity: "warning"
notification_channels: ["slack"]
- name: "performance-degradation"
condition: "mcp_server_response_time > 5s"
severity: "warning"
notification_channels: ["email"]
```
### Audit Logging
Implement comprehensive audit trails:
```json
{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "mcp_server_call",
"user_id": "john.doe@company.com",
"session_id": "sess_abc123",
"server_name": "github-prod",
"method": "github.create_issue",
"request": {
"repository": "company/project",
"title": "Bug fix required",
"sensitive_data_detected": false
},
"response": {
"status": "success",
"issue_id": "12345",
"duration_ms": 234
},
"compliance": {
"data_classification": "internal",
"retention_required": true,
"pii_detected": false
}
}
```
## Custom MCP Server Development
### Development Framework
Create custom MCP servers using the enterprise SDK:
```typescript
// custom-mcp-server.ts
import { MCPServer, Tool, Resource } from '@cline/mcp-enterprise-sdk';
class CustomAPIServer extends MCPServer {
constructor() {
super({
name: 'custom-api-server',
version: '1.0.0',
description: 'Custom API integration server'
});
this.addTool(new DatabaseQueryTool());
this.addResource(new UserDataResource());
}
}
class DatabaseQueryTool implements Tool {
name = 'query_database';
description = 'Query the company database';
async execute(params: any) {
// Implement database query logic
const result = await this.database.query(params.sql);
// Audit log the query
await this.auditLog({
action: 'database_query',
query: params.sql,
user: params.user_id,
results_count: result.length
});
return result;
}
async validate(params: any): Promise<boolean> {
// Implement query validation
return params.sql && !this.containsMaliciousSQL(params.sql);
}
}
```
### Deployment Pipeline
Automate MCP server deployments:
```yaml
# .github/workflows/deploy-mcp-server.yml
name: Deploy MCP Server
on:
push:
branches: [main]
paths: ['mcp-servers/**']
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build MCP Server
run: |
docker build -t company/mcp-server:${{ github.sha }} .
docker push company/mcp-server:${{ github.sha }}
- name: Deploy to Staging
run: |
helm upgrade mcp-server-staging ./helm-chart \
--set image.tag=${{ github.sha }} \
--namespace mcp-staging
- name: Run Integration Tests
run: |
kubectl wait --for=condition=ready pod -l app=mcp-server -n mcp-staging
npm run test:integration
- name: Deploy to Production
if: success()
run: |
helm upgrade mcp-server-prod ./helm-chart \
--set image.tag=${{ github.sha }} \
--namespace mcp-prod
```
## Best Practices
### Security
1. **Authentication**: Always require authentication for MCP servers
2. **Encryption**: Use TLS for all MCP communications
3. **Validation**: Validate all inputs and sanitize outputs
4. **Least Privilege**: Grant minimal required permissions
5. **Audit**: Log all MCP server interactions
### Performance
1. **Caching**: Implement response caching where appropriate
2. **Connection Pooling**: Reuse connections to external services
3. **Async Operations**: Use non-blocking operations for I/O
4. **Resource Limits**: Set appropriate CPU and memory limits
5. **Load Balancing**: Scale MCP servers based on demand
### Reliability
1. **Health Checks**: Implement comprehensive health endpoints
2. **Circuit Breakers**: Fail fast when external services are down
3. **Retry Logic**: Implement exponential backoff for failures
4. **Graceful Degradation**: Provide fallback behavior
5. **Monitoring**: Set up proactive alerting and monitoring
## Production Checklist
Before deploying MCP servers to production:
- [ ] Security review completed
- [ ] Authentication and authorization configured
- [ ] Network policies implemented
- [ ] Monitoring and alerting set up
- [ ] Audit logging enabled
- [ ] Resource limits configured
- [ ] Health checks implemented
- [ ] Integration tests passing
- [ ] Disaster recovery plan documented
- [ ] Compliance requirements validated
## Getting Started
Ready to implement enterprise MCP integration? Start with:
1. [MCP Marketplace](/enterprise-solutions/configuration/infrastructure-configuration/mcp/mcp-marketplace) - Deploy pre-built integrations
2. [Remote MCP Servers](/enterprise-solutions/configuration/infrastructure-configuration/mcp/remote-mcp-servers) - Configure custom servers
3. Review our [MCP Development Guide](/mcp/mcp-overview) for building custom integrations
@@ -0,0 +1,95 @@
---
title: "Self-Hosted Configuration"
sidebarTitle: "Overview"
description: "Deploy and configure Cline on your own infrastructure with enterprise-grade security and compliance"
---
<Warning>
**Self-Hosted Configuration Path**
This section is for enterprises deploying **self-hosted Cline infrastructure** with complex security, compliance, and multi-environment requirements. Configuration is done through YAML files, Kubernetes/Helm deployments, and infrastructure-as-code.
**Looking for simple setup?** See [SaaS Provider Configuration](/enterprise-solutions/configuration/remote-configuration/overview) for quick configuration through the app.cline.bot admin console - no infrastructure deployment required, just web-based settings.
</Warning>
Self-Hosted Configuration provides centralized control over all aspects of your Cline deployment on your own infrastructure, from AI providers to custom workflows. This section covers how to configure, manage, and optimize your enterprise Cline installation with advanced security, compliance, and operational features.
## Configuration Categories
<CardGroup cols={2}>
<Card title="Providers" icon="cloud" href="/enterprise-solutions/configuration/infrastructure-configuration/providers/overview">
Configure AI providers including AWS Bedrock, LiteLLM, and Google Vertex AI with enterprise-grade security and governance.
</Card>
<Card title="MCP Integration" icon="plug" href="/enterprise-solutions/configuration/infrastructure-configuration/mcp/overview">
Manage Model Context Protocol servers, marketplace integrations, and remote MCP server configurations.
</Card>
<Card title="Rules Engine" icon="shield-check" href="/enterprise-solutions/configuration/infrastructure-configuration/rules">
Define and enforce enterprise governance rules, security policies, and compliance requirements.
</Card>
<Card title="Workflows" icon="workflow" href="/enterprise-solutions/configuration/infrastructure-configuration/workflows">
Create automated workflows for development processes, approval chains, and integration pipelines.
</Card>
</CardGroup>
## Advanced Controls
<CardGroup cols={2}>
<Card title="Control Other Cline Features" icon="toggles" href="/enterprise-solutions/configuration/infrastructure-configuration/control-other-cline-features/overview">
Enable or disable specific Cline features across your organization with granular permission controls.
</Card>
<Card title="Monitoring" icon="chart-line" href="/enterprise-solutions/monitoring/overview">
Configure OpenTelemetry integration for comprehensive monitoring, logging, and analytics.
</Card>
</CardGroup>
## Getting Started
1. **Assessment**: Review your current infrastructure and integration requirements
2. **Provider Setup**: Configure your preferred AI providers with enterprise credentials
3. **Security Configuration**: Implement rules and access controls
4. **Monitoring Setup**: Enable telemetry and monitoring for operational visibility
5. **User Onboarding**: Deploy configurations to your development teams
## Enterprise Architecture Considerations
### Security & Compliance
- **Zero Trust Architecture**: All configurations support zero-trust security models
- **Audit Logging**: Complete audit trails for all configuration changes
- **Role-Based Access**: Granular permissions for different administrative roles
- **Data Sovereignty**: Keep sensitive data within your infrastructure boundaries
### Scalability & Performance
- **Multi-Region Support**: Deploy configurations across multiple geographic regions
- **Load Balancing**: Distribute AI provider requests across multiple endpoints
- **Caching Strategies**: Optimize performance with intelligent caching
- **Rate Limiting**: Prevent abuse with configurable rate limits
### Integration & Automation
- **GitOps Integration**: Version control your configurations alongside code
- **CI/CD Pipeline Integration**: Automate configuration deployment
- **Webhook Support**: React to configuration changes with custom automation
- **API-First Design**: Programmatically manage all configurations
## Configuration Management
All enterprise configurations support:
- **Version Control**: Track changes with full revision history
- **Environment Promotion**: Deploy configurations from dev → staging → production
- **Rollback Capabilities**: Quickly revert problematic configurations
- **Configuration Validation**: Automated testing of configuration changes
- **Drift Detection**: Monitor and alert on configuration drift
## Next Steps
Ready to configure your enterprise deployment? Start with:
1. [Provider Configuration](/enterprise-solutions/configuration/infrastructure-configuration/providers/overview) - Set up your AI providers
2. [Security Rules](/enterprise-solutions/configuration/infrastructure-configuration/rules) - Implement governance policies
3. [Monitoring Setup](/enterprise-solutions/monitoring/overview) - Enable operational visibility
For hands-on configuration assistance, contact your Cline Enterprise support team or refer to our implementation guides.
@@ -0,0 +1,182 @@
---
title: "AWS Bedrock Configuration"
sidebarTitle: "AWS Bedrock"
description: "Configure AWS Bedrock for your Cline deployment"
---
<Info>
**Configuration Path: Self-Hosted**
This guide covers Bedrock configuration for self-hosted deployments. For simple web-based setup, see [AWS Bedrock SaaS Configuration](/enterprise-solutions/configuration/remote-configuration/aws-bedrock/admin-configuration).
</Info>
Configure Cline to use AWS Bedrock for enterprise access to Claude and other foundation models through Amazon's managed service.
## Configuration Format
Configure Bedrock through your remote configuration JSON using the `providerSettings.AwsBedrock` section:
```json
{
"providerSettings": {
"AwsBedrock": {
"models": [
{
"id": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"name": "Claude 3.5 Sonnet"
}
],
"awsRegion": "us-east-1"
}
}
}
```
## Configuration Fields
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| `models` | Array | List of model configurations | Yes |
| `awsRegion` | String | AWS region (e.g., `us-east-1`) | Yes |
| `awsUseCrossRegionInference` | Boolean | Enable cross-region inference | No |
| `awsUseGlobalInference` | Boolean | Enable global inference routing | No |
| `awsBedrockUsePromptCache` | Boolean | Enable prompt caching | No |
| `awsBedrockEndpoint` | String | Custom Bedrock endpoint URL | No |
| `customModels` | Array | Custom model configurations | No |
### Model Configuration
Each model in the `models` array requires:
```json
{
"id": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"name": "Claude 3.5 Sonnet",
"info": {
"maxTokens": 8192,
"contextWindow": 200000,
"supportsImages": true,
"supportsPromptCache": true
}
}
```
## Common Model IDs
| Model ID | Description | Context Window |
|----------|-------------|----------------|
| `anthropic.claude-3-5-sonnet-20241022-v2:0` | Latest Claude Sonnet | 200K tokens |
| `anthropic.claude-3-5-haiku-20241022-v1:0` | Latest Claude Haiku | 200K tokens |
| `anthropic.claude-3-opus-20240229-v1:0` | Claude Opus | 200K tokens |
<Note>
Model availability varies by region. See [AWS Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html) for region-specific model availability.
</Note>
## Example Configurations
### Basic Configuration
```json
{
"providerSettings": {
"AwsBedrock": {
"models": [
{
"id": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"name": "Claude 3.5 Sonnet"
}
],
"awsRegion": "us-east-1"
}
}
}
```
### With Prompt Caching
```json
{
"providerSettings": {
"AwsBedrock": {
"models": [
{
"id": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"name": "Claude 3.5 Sonnet"
}
],
"awsRegion": "us-east-1",
"awsBedrockUsePromptCache": true
}
}
}
```
### Multiple Models
```json
{
"providerSettings": {
"AwsBedrock": {
"models": [
{
"id": "anthropic.claude-3-5-sonnet-20241022-v2:0",
"name": "Claude 3.5 Sonnet"
},
{
"id": "anthropic.claude-3-5-haiku-20241022-v1:0",
"name": "Claude 3.5 Haiku"
}
],
"awsRegion": "us-east-1"
}
}
}
```
## Prerequisites
Before configuring Cline to use Bedrock, you need:
1. **AWS Account** with Bedrock access enabled
2. **IAM Permissions** for Bedrock API calls (`bedrock:InvokeModel`, `bedrock:InvokeModelWithResponseStream`)
3. **Model Access** enabled for desired models in the Bedrock console
4. **AWS Credentials** configured (IAM role, access keys, or AWS profile)
<Tip>
For AWS account setup and IAM configuration, see the [AWS Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html).
</Tip>
## Troubleshooting
**"Access Denied" Errors**
Ensure your AWS credentials have the required Bedrock permissions. See [AWS IAM documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html) for permission requirements.
**"Model Not Found" Errors**
Verify model access is enabled in the AWS Bedrock console and the model is available in your configured region.
**High Latency**
Consider using a region closer to your users or enabling cross-region inference for better performance.
## Related Resources
<CardGroup cols={2}>
<Card title="AWS Bedrock Docs" icon="book" href="https://docs.aws.amazon.com/bedrock/">
Complete AWS Bedrock documentation
</Card>
<Card title="Model Access" icon="key" href="https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html">
How to enable model access
</Card>
<Card title="IAM Permissions" icon="shield" href="https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam.html">
Required IAM permissions
</Card>
<Card title="Pricing" icon="dollar-sign" href="https://aws.amazon.com/bedrock/pricing/">
AWS Bedrock pricing details
</Card>
</CardGroup>
@@ -0,0 +1,254 @@
---
title: "Custom Provider Configuration"
sidebarTitle: "Custom Providers"
description: "Configure custom OpenAI-compatible providers for your Cline deployment"
---
<Info>
**Configuration Path: Self-Hosted**
This guide covers custom provider configuration for self-hosted deployments.
</Info>
Configure Cline to use any OpenAI-compatible API provider, including Azure OpenAI, self-hosted inference servers, and other third-party services.
## What are Custom Providers?
Custom providers include any API that implements the OpenAI API format:
- **Azure OpenAI Service**: Microsoft's managed OpenAI models
- **vLLM**: Self-hosted inference server
- **Ollama**: Local model runner
- **Text Generation Inference (TGI)**: Hugging Face's inference server
- **LocalAI**: Local OpenAI API replacement
- **Other OpenAI-compatible APIs**: Any custom implementation
## Configuration Format
Configure custom providers through your remote configuration JSON using the `providerSettings.OpenAiCompatible` section:
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "gpt-4-turbo",
"name": "GPT-4 Turbo"
}
],
"openAiBaseUrl": "https://your-api.company.com/v1"
}
}
}
```
## Configuration Fields
| Field | Type | Description | Required |
|-------|------|-------------|----------|
| `models` | Array | List of model configurations | Yes |
| `openAiBaseUrl` | String | API endpoint base URL | Yes |
| `openAiApiKey` | String | API key for authentication | No |
| `openAiModelId` | String | Default model identifier | No |
### Azure OpenAI Specific Fields
For Azure OpenAI, additional fields are available:
| Field | Type | Description |
|-------|------|-------------|
| `azureApiVersion` | String | Azure API version (e.g., `2024-02-15-preview`) |
## Example Configurations
### Azure OpenAI
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "gpt-4-turbo",
"name": "GPT-4 Turbo"
}
],
"openAiBaseUrl": "https://your-resource.openai.azure.com/openai/deployments/gpt-4-turbo",
"openAiApiKey": "your-azure-api-key",
"azureApiVersion": "2024-02-15-preview"
}
}
}
```
### Self-Hosted vLLM
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "meta-llama/Llama-2-70b-chat-hf",
"name": "Llama 2 70B"
}
],
"openAiBaseUrl": "http://vllm.company.com:8000/v1"
}
}
}
```
### Local Ollama
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "codellama",
"name": "Code Llama"
}
],
"openAiBaseUrl": "http://localhost:11434/v1"
}
}
}
```
### Text Generation Inference (TGI)
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "mistralai/Mistral-7B-Instruct-v0.2",
"name": "Mistral 7B Instruct"
}
],
"openAiBaseUrl": "http://tgi.company.com:8080/v1",
"openAiApiKey": "your-tgi-api-key"
}
}
}
```
### LocalAI
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "gpt-3.5-turbo",
"name": "Local GPT-3.5"
}
],
"openAiBaseUrl": "http://localhost:8080/v1"
}
}
}
```
### Internal Network (No Auth)
```json
{
"providerSettings": {
"OpenAiCompatible": {
"models": [
{
"id": "custom-model",
"name": "Custom Model"
}
],
"openAiBaseUrl": "http://internal.api:8000/v1"
}
}
}
```
## Model Configuration
Each model requires basic information:
```json
{
"id": "model-identifier",
"name": "Display Name",
"info": {
"maxTokens": 4096,
"contextWindow": 128000,
"supportsImages": true,
"supportsPromptCache": false
}
}
```
## Prerequisites
Before configuring a custom provider, you need:
1. **API Endpoint**: URL of your OpenAI-compatible API
2. **API Key** (if required): Authentication credentials
3. **Model IDs**: Names of available models
4. **Network Access**: Connectivity from where Cline is being used
## Troubleshooting
**Connection Errors**
Verify the endpoint is accessible:
```bash
curl https://your-api.company.com/v1/models
```
**Authentication Errors**
Test authentication with your API key:
```bash
curl -H "Authorization: Bearer your-api-key" \
https://your-api.company.com/v1/models
```
**Model Not Found**
Ensure the model ID in your configuration matches what the API expects. Check available models:
```bash
curl -H "Authorization: Bearer your-api-key" \
https://your-api.company.com/v1/models
```
**Timeout Issues**
If responses are slow:
- Check network latency
- Verify server has adequate resources
- Consider using faster models
## Provider Documentation
For setup and deployment of these services, see their official documentation:
<CardGroup cols={2}>
<Card title="Azure OpenAI" icon="microsoft" href="https://learn.microsoft.com/en-us/azure/ai-services/openai/">
Microsoft's managed OpenAI service
</Card>
<Card title="vLLM" icon="server" href="https://docs.vllm.ai/">
High-performance inference engine
</Card>
<Card title="Ollama" icon="download" href="https://ollama.ai/">
Run models locally
</Card>
<Card title="Text Generation Inference" icon="code" href="https://huggingface.co/docs/text-generation-inference/">
Hugging Face inference server
</Card>
</CardGroup>

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