Merge branch 'main' of https://github.com/continuedev/continue into dallin/cli-git-branch

This commit is contained in:
Dallin Romney 2025-09-08 19:39:16 -07:00
commit 70e79dc9c6
145 changed files with 4290 additions and 1420 deletions

View file

@ -1,25 +1,25 @@
name: 'Run VS Code E2E Test'
description: 'Run a single VS Code E2E test with all required setup'
name: "Run VS Code E2E Test"
description: "Run a single VS Code E2E test with all required setup"
inputs:
test_file:
description: 'E2E test file to run'
description: "E2E test file to run"
required: true
command:
description: 'Command to run (e2e:ci:run or e2e:ci:run-yaml)'
description: "Command to run (e2e:ci:run or e2e:ci:run-yaml)"
required: true
ssh_key:
description: 'SSH private key for testing'
description: "SSH private key for testing"
required: false
ssh_host:
description: 'SSH host for testing'
description: "SSH host for testing"
required: false
is_fork:
description: 'Whether this is a fork (affects SSH tests)'
description: "Whether this is a fork (affects SSH tests)"
required: false
default: 'false'
default: "false"
runs:
using: 'composite'
using: "composite"
steps:
- uses: actions/setup-node@v4
with:
@ -58,6 +58,7 @@ runs:
cd core
npm ci
cd ../extensions/vscode
npm ci
npm run e2e:ci:download
else
cd core
@ -131,4 +132,4 @@ runs:
uses: actions/upload-artifact@v4
with:
name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ inputs.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }}
path: extensions/vscode/e2e.log
path: extensions/vscode/e2e.log

View file

@ -0,0 +1,170 @@
name: Auto Fix Failed Tests
on:
workflow_run:
workflows: ["PR Checks", "CLI PR Checks"]
types:
- completed
permissions:
contents: write
pull-requests: write
issues: write
actions: read
jobs:
fix-failed-tests:
# Only run if the workflow failed
# DISABLED: Remove 'false && ' on the next line to enable auto-fixing
if: false && github.event.workflow_run.conclusion == 'failure'
runs-on: ubuntu-latest
steps:
- name: Get workflow run details
id: workflow-details
uses: actions/github-script@v7
with:
script: |
const workflowRun = context.payload.workflow_run;
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflowRun.id
});
// Find all failed jobs since we're only monitoring specific test workflows
const failedJobs = jobs.jobs.filter(job => job.conclusion === 'failure');
if (failedJobs.length === 0) {
core.info('No failed jobs found');
return null;
}
core.setOutput('has_failed_tests', 'true');
core.setOutput('workflow_name', workflowRun.name);
core.setOutput('workflow_run_id', workflowRun.id);
core.setOutput('head_branch', workflowRun.head_branch);
core.setOutput('head_sha', workflowRun.head_sha);
core.setOutput('failed_jobs', JSON.stringify(failedJobs.map(j => j.name)));
return failedJobs;
- name: Get job logs for failed tests
if: steps.workflow-details.outputs.has_failed_tests == 'true'
id: get-logs
uses: actions/github-script@v7
with:
script: |
const workflowRunId = ${{ github.event.workflow_run.id }};
const { data: jobs } = await github.rest.actions.listJobsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: workflowRunId
});
let errorLogs = '';
for (const job of jobs.jobs) {
if (job.conclusion === 'failure') {
try {
const { data: logData } = await github.rest.actions.downloadJobLogsForWorkflowRun({
owner: context.repo.owner,
repo: context.repo.repo,
job_id: job.id
});
errorLogs += `\n\n=== Job: ${job.name} ===\n`;
errorLogs += logData;
} catch (error) {
core.warning(`Could not fetch logs for job ${job.name}: ${error.message}`);
}
}
}
// Store logs in environment file for next step
const fs = require('fs');
fs.writeFileSync('/tmp/test_failure_logs.txt', errorLogs);
core.setOutput('has_logs', errorLogs.length > 0 ? 'true' : 'false');
- name: Checkout repository
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ steps.workflow-details.outputs.head_sha }}
- name: Setup Node.js
if: steps.workflow-details.outputs.has_failed_tests == 'true'
uses: actions/setup-node@v5
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.workflow-details.outputs.has_failed_tests == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session to fix failed tests
if: steps.workflow-details.outputs.has_failed_tests == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create a detailed prompt for fixing the failed tests
cat > /tmp/fix_tests_prompt.txt << 'PROMPT_EOF'
🔧 **Auto Test Fix Request**
The following tests failed in workflow "${{ steps.workflow-details.outputs.workflow_name }}" (Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}):
**Failed Jobs:** ${{ steps.workflow-details.outputs.failed_jobs }}
**Branch:** ${{ steps.workflow-details.outputs.head_branch }}
**Commit:** ${{ steps.workflow-details.outputs.head_sha }}
**Your Task:**
1. Analyze the test failure logs and error messages
2. Identify the root cause of the test failures
3. Fix the failing tests by updating the test code or the underlying implementation
4. Ensure all tests pass after your changes
5. Commit your fixes with a descriptive message
**Test Failure Context:**
Please examine the repository structure, run the failing tests locally to understand the errors, and implement appropriate fixes.
Focus on:
- Understanding what the tests are trying to validate
- Identifying why they're failing (code changes, environment issues, test logic errors)
- Making minimal, targeted fixes that address the root cause
- Ensuring the fixes don't break other functionality
Please start by examining the failing tests and their error messages, then proceed with the necessary fixes.
PROMPT_EOF
echo "Starting Continue CLI remote session for test fixes..."
echo "Prompt content:"
cat /tmp/fix_tests_prompt.txt
# Start remote session and capture JSON output
SESSION_OUTPUT=$(cat /tmp/fix_tests_prompt.txt | cn remote -s --branch ${{ steps.workflow-details.outputs.head_branch }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Log session details
if: steps.workflow-details.outputs.has_failed_tests == 'true'
run: |
echo "✅ Successfully started auto-fix session for failed tests"
echo "Workflow: ${{ steps.workflow-details.outputs.workflow_name }}"
echo "Run ID: ${{ steps.workflow-details.outputs.workflow_run_id }}"
echo "Branch: ${{ steps.workflow-details.outputs.head_branch }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Failed jobs: ${{ steps.workflow-details.outputs.failed_jobs }}"

View file

@ -24,7 +24,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
registry-url: "https://registry.npmjs.org"

View file

@ -25,7 +25,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
cache: "npm"
@ -59,6 +59,7 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22, 24]
fail-fast: false
runs-on: ${{ matrix.os }}
steps:
@ -66,7 +67,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node-version }}

View file

@ -41,7 +41,7 @@ jobs:
- name: Add PR title guidance comment
if: always() && steps.pr-title-check.outputs.valid == 'false'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: comments } = await github.rest.issues.listComments({
@ -104,7 +104,7 @@ jobs:
uses: actions/checkout@v5
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
cache: "npm"

View file

@ -152,7 +152,7 @@ jobs:
# # Setup Node.js
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -370,7 +370,7 @@ jobs:
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -44,7 +44,7 @@ jobs:
- name: Determine and apply tier label
if: steps.check-author.outputs.should_label == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const pr = context.payload.pull_request;

View file

@ -20,7 +20,7 @@ jobs:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v1.0.*-vscode ]]; then
if [[ "${{ github.event.release.tag_name }}" == v1.2.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
@ -70,7 +70,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -23,7 +23,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -224,7 +224,7 @@ jobs:
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -342,7 +342,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version: 20

View file

@ -70,7 +70,7 @@ jobs:
with:
fetch-depth: 0
- uses: actions/setup-node@v4
- uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"
@ -165,7 +165,7 @@ jobs:
# 4. Create PR with version bump
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -29,7 +29,7 @@ jobs:
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForIssueComment({
@ -49,7 +49,7 @@ jobs:
- name: Get PR information
if: steps.check-mention.outputs.contains_mention == 'true'
id: pr-info
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const { data: pr } = await github.rest.pulls.get({
@ -69,7 +69,7 @@ jobs:
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: "20"
@ -107,7 +107,7 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
@ -144,7 +144,7 @@ jobs:
- name: Add eyes reaction to comment
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
await github.rest.reactions.createForPullRequestReviewComment({
@ -164,7 +164,7 @@ jobs:
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: "20"
@ -172,21 +172,59 @@ jobs:
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Get review context
if: steps.check-mention.outputs.contains_mention == 'true'
id: review-context
uses: actions/github-script@v8
with:
script: |
let reviewContext = '';
// Check if this comment is a reply to another review comment
if (context.payload.comment.in_reply_to_id) {
try {
const { data: originalComment } = await github.rest.pulls.getReviewComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.in_reply_to_id
});
reviewContext = `**Original review comment by @${originalComment.user.login}:**
${originalComment.body}
**Reply by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
} catch (error) {
console.log('Could not fetch original comment, using current comment only');
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
} else {
reviewContext = `**Review comment by @${{ github.event.comment.user.login }}:**
${{ github.event.comment.body }}`;
}
core.setOutput('context', reviewContext);
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Debug: Echo the branch we're starting the session on
echo "Starting remote session on branch: ${{ github.event.pull_request.head.ref }}"
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
Please help with the following code review discussion from PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
**Comment:** ${{ github.event.comment.body }}
Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
${{ steps.review-context.outputs.context }}
Please analyze the specific file and line mentioned, understand the review feedback and any discussion context, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
@ -211,7 +249,7 @@ jobs:
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:

View file

@ -55,7 +55,7 @@ jobs:
uses: ./.github/actions/setup-packages
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -31,7 +31,7 @@ jobs:
path: deja-view
- name: Setup Python
uses: actions/setup-python@v5
uses: actions/setup-python@v6
with:
python-version: "3.11"
@ -190,7 +190,7 @@ jobs:
echo "confidence=$CONFIDENCE" >> $GITHUB_OUTPUT
- name: Comment with analysis
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
let comment = '';
@ -307,7 +307,7 @@ jobs:
- name: Add labels
if: github.event_name == 'issues'
uses: actions/github-script@v7
uses: actions/github-script@v8
with:
script: |
const labels = [];

View file

@ -40,7 +40,7 @@ jobs:
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: 20
registry-url: "https://registry.npmjs.org"

View file

@ -10,7 +10,7 @@ jobs:
pull-requests: write
runs-on: ubuntu-latest
steps:
- uses: actions/stale@v9
- uses: actions/stale@v10
with:
close-issue-message: "This issue was closed because it wasn't updated for 10 days after being marked stale. If it's still important, please reopen + comment and we'll gladly take another look!"
stale-issue-message: "This issue hasn't been updated in 90 days and will be closed after an additional 10 days without activity. If it's still important, please leave a comment and share any new information that would help us address the issue."

View file

@ -21,7 +21,7 @@ jobs:
gh auth login --with-token <<< "${{ github.token }}"
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version-file: ".nvmrc"

View file

@ -176,9 +176,9 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
`main` branch titled `v1.3.x-vscode`, which automatically triggers the workflow
in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
a release has been sufficiently tested, we will create a new release titled `v1.2.x-vscode`, triggering a similar
workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
is well explained by <http://releaseflow.org>.

5
core/index.d.ts vendored
View file

@ -1070,11 +1070,6 @@ export interface ToolExtras {
codeBaseIndexer?: CodebaseIndexer;
}
export type ToolPolicy =
| "allowedWithPermission"
| "allowedWithoutPermission"
| "disabled";
export interface Tool {
type: "function";
function: {

View file

@ -370,8 +370,17 @@ export abstract class BaseLLM implements ILLM {
},
});
if (error !== undefined) {
if (error === "cancel" || error.name === "AbortError") {
if (typeof error === "undefined") {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
} else {
if (error === "cancel" || error?.name?.includes("AbortError")) {
interaction?.logItem({
kind: "cancel",
promptTokens,
@ -393,15 +402,6 @@ export abstract class BaseLLM implements ILLM {
});
return "error";
}
} else {
interaction?.logItem({
kind: "success",
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
}
}
@ -615,6 +615,7 @@ export abstract class BaseLLM implements ILLM {
kind: "chunk",
chunk: formattedContent,
});
completion += formattedContent;
yield content;
}
@ -630,6 +631,7 @@ export abstract class BaseLLM implements ILLM {
kind: "chunk",
chunk,
});
completion += chunk;
yield chunk;
}

View file

@ -150,7 +150,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
constructor(options: LLMOptions) {
super(options);
if (options.isFromAutoDetect) {
if (options.model === "AUTODETECT") {
return;
}
const headers: Record<string, string> = {

View file

@ -7,16 +7,23 @@ class Scaleway extends OpenAI {
static providerName = "scaleway";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.scaleway.ai/v1/",
model: "qwen2.5-coder-32b-instruct",
model: "qwen3-coder-30b-a3b-instruct",
useLegacyCompletionsEndpoint: false,
};
private static MODEL_IDS: { [name: string]: string } = {
"llama3.1-8b": "llama-3.1-8b-instruct",
"llama3.3-70b": "llama-3.3-70b-instruct",
"pixtral-12b": "pixtral-12b-2409",
"mistral-small3.1": "mistral-small-3.1-24b-instruct-2503",
"mistral-small3.2": "mistral-small-3.2-24b-instruct-2506",
"devstral-small": "devstral-small-2505",
"deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b",
"qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
"qwen3-coder-30b-a3b": "qwen3-coder-30b-a3b-instruct",
"qwen3-235b-a22b": "qwen3-235b-a22b-instruct-2507",
"gemma-3-27b": "gemma-3-27b-it",
"gpt-oss-120b": "gpt-oss-120b",
};
protected _convertModelName(model: string) {

19
core/package-lock.json generated
View file

@ -17,6 +17,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -238,6 +239,20 @@
"vitest": "^3.2.4"
}
},
"../packages/terminal-security": {
"name": "@continuedev/terminal-security",
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
"shell-quote": "^1.8.1"
},
"devDependencies": {
"@types/node": "^20.11.19",
"@types/shell-quote": "^1.7.5",
"typescript": "^5.5.2",
"vitest": "^1.6.0"
}
},
"node_modules/@75lb/deep-merge": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
@ -2957,6 +2972,10 @@
"resolved": "../packages/openai-adapters",
"link": true
},
"node_modules/@continuedev/terminal-security": {
"resolved": "../packages/terminal-security",
"link": true
},
"node_modules/@dabh/diagnostics": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz",

View file

@ -62,6 +62,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -4,6 +4,7 @@ import {
DevDataLogEvent,
ModelRole,
} from "@continuedev/config-yaml";
import { ToolPolicy } from "@continuedev/terminal-security";
import {
AutocompleteInput,
@ -39,7 +40,6 @@ import {
SlashCommandDescWithSource,
StreamDiffLinesPayload,
ToolCall,
ToolPolicy,
} from "../";
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
import { GetLspDefinitionsFunction } from "../autocomplete/types";

View file

@ -8,7 +8,7 @@ export interface EditToolArgs {
}
export const NO_PARALLEL_TOOL_CALLING_INTSRUCTION =
"Note this tool CANNOT be called in parallel with other tools.";
"This tool CANNOT be called in parallel with other tools.";
const CHANGES_DESCRIPTION =
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INTSRUCTION } from "./editFile";
import { singleFindAndReplaceTool } from "./singleFindAndReplace";
export interface EditOperation {
old_string: string;
@ -24,60 +25,41 @@ export const multiEditTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.MultiEdit,
description: `This is a tool for making multiple edits to a single file in one operation. It
is built on top of the single find and replace tool and allows you to perform multiple
find-and-replace operations efficiently. Prefer this tool over the single find and replace tool
when you need to make multiple edits to the same file.
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${singleFindAndReplaceTool.function.name} and allows you to perform multiple find-and-replace operations efficiently.
Prefer this tool over the ${singleFindAndReplaceTool.function.name} tool when you need to make multiple edits to the same file.
Before using this tool:
1. Use the read_file tool to understand the file's contents and context
2. Verify the directory path is correct
To make multiple file edits, provide the following:
1. filepath: The path to the file to modify (relative to the root of the workspace)
To make multiple edits to a file, provide the following:
1. filepath: The path to the file to modify, RELATIVE to the project/workspace root (verify the directory path is correct)
2. edits: An array of edit operations to perform, where each edit contains:
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
- old_string: The text to replace (must match the old file contents exactly, including all whitespace/indentation)
- new_string: The edited text to replace the old_string
- replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
IMPORTANT:
- All edits are applied in sequence, in the order they are provided
- Each edit operates on the result of the previous edit
- All edits must be valid for the operation to succeed - if any edit fails,
none will be applied
- This tool is ideal when you need to make several changes to different parts
of the same file
- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
- This tool is ideal when you need to make several changes to different parts of the same file
CRITICAL REQUIREMENTS:
1. All edits follow the same requirements as the single find and replace tool
2. The edits are atomic - either all succeed or none are applied
3. Plan your edits carefully to avoid conflicts between sequential operations
4. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
WARNING:
- The tool will fail if edits.old_string doesn't match the file contents
exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same
- Since edits are applied in sequence, ensure that earlier edits don't affect
the text that later edits are trying to find
When making edits:
1. ALWAYS use the ${BuiltInToolNames.ReadFile} tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
2. ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
3. When making edits:
- Ensure all edits result in idiomatic, correct code
- Do not leave the code in a broken state
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- Use replace_all for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked
- Use replace_all for replacing and renaming all matches for a string across the file. This parameter is useful if you want to rename a variable, for instance
If you want to create a new file, use:
- A new file path
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits are not allowed - there is no need since you are creating`,
- Subsequent edits are not allowed - there is no need since you are creating
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different`,
parameters: {
type: "object",
required: ["filepath", "edits"],
@ -97,16 +79,18 @@ If you want to create a new file, use:
properties: {
old_string: {
type: "string",
description: "The text to replace",
description:
"The text to replace (exact match including whitespace/indentation)",
},
new_string: {
type: "string",
description: "The text to replace it with",
description:
"The text to replace it with. MUST be different than old_string.",
},
replace_all: {
type: "boolean",
description:
"Replace all occurrences of old_string (default false)",
"Replace all occurrences of old_string (default false) in the file",
},
},
},

View file

@ -1,7 +1,10 @@
import os from "os";
import { Tool, ToolPolicy } from "../..";
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { evaluateTerminalCommandSecurity } from "../security/terminalCommandSecurity";
import {
evaluateTerminalCommandSecurity,
ToolPolicy,
} from "@continuedev/terminal-security";
/**
* Get the preferred shell for the current platform

View file

@ -20,33 +20,18 @@ export const singleFindAndReplaceTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.SingleFindAndReplace,
description: `Performs exact string replacements in files.
Usage:
- You must use your \`read_file\` tool at least once in the conversation before
editing. This tool will error if you attempt an edit without reading the file.
- When editing text from read_file tool output, ensure you preserve the exact
indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
number prefix format is: spaces + line number + tab. Everything after that tab
is the actual file content to match. Never include any part of the line number
prefix in the old_string or new_string.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files
unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
description: `Performs exact string replacements in a file.
IMPORTANT:
- ALWAYS use the \`${BuiltInToolNames.ReadFile}\` tool just before making edits, to understand the file's up-to-date contents and context. The user can also edit the file while you are working with it.
- ${NO_PARALLEL_TOOL_CALLING_INTSRUCTION}
- When editing text from \`${BuiltInToolNames.ReadFile}\` tool output, ensure you preserve exact whitespace/indentation.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
a larger string with more surrounding context to make it unique or use
\`replace_all\` to change every instance of \`old_string\`.
- Use \`replace_all\` for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.`,
WARNINGS:
- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
- The edit will likely fail if you have not recently used the \`${BuiltInToolNames.ReadFile}\` tool to view up-to-date file contents.`,
parameters: {
type: "object",
required: ["filepath", "old_string", "new_string"],
@ -58,12 +43,13 @@ parameter is useful if you want to rename a variable for instance.`,
},
old_string: {
type: "string",
description: "The text to replace",
description:
"The text to replace - must be exact including whitespace/indentation",
},
new_string: {
type: "string",
description:
"The text to replace it with (must be different from old_string)",
"The text to replace it with (MUST be different from old_string)",
},
replace_all: {
type: "boolean",

View file

@ -2,7 +2,7 @@
title: "Chat"
sidebarTitle: "How To Use AI Chat"
icon: "circle-question"
description: "Learn how to use Continue's AI chat assistant to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
description: "Learn how to use Continue's AI chat agent to solve coding problems without leaving your IDE, including code context sharing, applying generated solutions, and switching between models"
---
<Frame>

View file

@ -1,6 +1,6 @@
---
title: "Customization Overview"
description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding assistant"
description: "Learn how to customize Continue with model providers, context providers, slash commands, and tools to create your perfect AI coding agent"
---
Continue can be deeply customized to fit your specific development workflow and preferences. This guide covers the main ways you can customize Continue to enhance your coding experience.
@ -21,15 +21,15 @@ Slash commands allow you to easily add custom functionality to Continue. You can
Unchain your LLM with the power of tools using [Agent](/features/agent/quick-start). Add custom tools using [MCP Servers](/customization/mcp-tools)
Whatever you choose, you'll probably start by editing your Assistant.
Whatever you choose, you'll probably start by editing your Agent.
## Edit Your Assistant
## Edit Your Agent
You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing `cmd/ctrl` + `L` (VS Code) or `cmd/ctrl` + `J` (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon.
![configure an assistant](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png)
![configure an agent](/images/customization/images/configure-continue-a5c8c79f3304c08353f3fc727aa5da7e.png)
## Manage Your Assistant
## Manage Your Agent
- See [Editing Hub Assistants](/hub/assistants/edit-an-assistant) for more details on managing your hub assistant
- See the [Config Deep Dive](/reference) for more details on configuring local assistants.
- See [Editing Hub Agents](/hub/agents/edit-an-agent) for more details on managing your hub agent
- See the [Config Deep Dive](/reference) for more details on configuring local agents.

View file

@ -1,18 +1,18 @@
---
title: "Rules"
description: "Rules allow you to provide specific instructions that guide how the AI assistant behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses."
description: "Rules allow you to provide specific instructions that guide how the AI agent behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses."
---
Think of these as the guardrails for your AI coding assistants:
Think of these as the guardrails for your AI coding agents:
- **Enforce company-specific coding standards** and security practices
- **Implement quality checks** that match your engineering culture
- **Create paved paths** for developers to follow organizational best practices
By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints.
By implementing rules, you transform the AI from a generic coding agent into a knowledgeable team member that understands your project's unique requirements and constraints.
## How Rules Work
Your assistant detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
Your agent detects rules and applies the specified rules while in [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) modes.
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.

View file

@ -1,26 +1,26 @@
---
title: "How to Configure Continue Assistants"
description: Learn how to access and manage Continue assistant configurations through Hub or local YAML files
title: "How to Configure Continue Agents"
description: Learn how to access and manage Continue agent configurations through Hub or local YAML files
keywords: [config, settings, customize]
sidebarTitle: "Assistant Configuration"
sidebarTitle: "Agent Configuration"
---
You can easily access your assistant configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the Assistant selector above the main chat input. Then, you can hover over an assistant and click the `new window` (hub assistants) or `gear` (local assistants) icon.
You can easily access your agent configuration from the Continue Chat sidebar. Open the sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains) and click the Agent selector above the main chat input. Then, you can hover over an agent and click the `new window` (hub agents) or `gear` (local agents) icon.
![configure an assistant](/images/configure-continue.png)
![configure an agent](/images/configure-continue.png)
## How to Manage Hub Assistants
## How to Manage Hub Agents
Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editing an Assistant](../../hub/assistants/edit-an-assistant.md)
Hub Agents can be managed in [the Hub](https://hub.continue.dev). See [Editing an Agent](../../hub/agents/edit-an-agent.md)
## How to Configure Local Assistants with YAML
## How to Configure Local Agents with YAML
Local user-level configuration is stored and can be edited in your home directory in `config.yaml`:
- `~/.continue/config.yaml` (MacOS / Linux)
- `%USERPROFILE%\.continue\config.yaml` (Windows)
To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`.
To open this `config.yaml`, you need to open the agents dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Agent" option, select the cog icon. It will open the local `config.yaml`.
![local-config-open-steps](/images/local-config-open-steps.png)

View file

@ -19,7 +19,7 @@ that can be set up with custom tools.
Currently custom tools can be configured using the Model Context
Protocol standard to unify prompts, context, and tool use.
MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can
MCP Servers can be added to hub Agents using `mcpServers` blocks. You can
explore available MCP server blocks
[here](https://hub.continue.dev/explore/mcp).
@ -27,7 +27,7 @@ explore available MCP server blocks
## Quick Start: How to Set Up Your First MCP Server
Below is a quick example of setting up a new MCP server for use in your assistant:
Below is a quick example of setting up a new MCP server for use in your agent:
1. Create a folder called `.continue/mcpServers` at the top level of your workspace
2. Add a file called `playwright-mcp.yaml` to this folder.

View file

@ -42,7 +42,7 @@ Now test your rules by asking a question about a file in chat.
## How to Create Rules Blocks
Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules.
Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules.
![add local rules button](/images/add-local-rules.png)
@ -53,7 +53,7 @@ For example, you can say "Create a rule for this", and a rule will be created fo
</Info>
Rules can also be added to an Assistant on the Continue Hub.
Rules can also be added to an Agent on the Continue Hub.
Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.

View file

@ -39,7 +39,7 @@ Now test your rules by asking a question about a file in chat.
## Creating `rules` blocks
Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules.
Rules can be added locally using the "Add Rules" button while viewing the Local Agent's rules.
![add local rules button](/images/add-local-rules.png)
@ -49,7 +49,7 @@ Automatically create local rule blocks: When in Agent mode, you can prompt the a
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
</Info>
Rules can also be added to an Assistant on the Continue Hub.
Rules can also be added to an Agent on the Continue Hub.
Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
@ -133,7 +133,7 @@ name: New rule
Always give concise responses
```
This is also done when selecting "Add Rule" in the Assistant settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`.
This is also done when selecting "Add Rule" in the Agent settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.md`.
### Examples

View file

@ -21,9 +21,9 @@ Slash commands can be combined with additional instructions, including highlight
## Ways to Create Slash Commands in Continue
### Assistant Prompt Blocks
### Agent Prompt Blocks
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works).
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your agent, which show up as slash commands in [Chat](../../features/chat/how-it-works).
### Prompt Files

View file

@ -2,7 +2,7 @@
title: "Model roles"
sidebarTitle: Overview
icon: "circle-info"
description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding assistant's capabilities"
description: "Learn about the different model roles in Continue including chat, autocomplete, edit, apply, embeddings, and reranking for customizing your AI coding agent's capabilities"
---
<CardGroup>

View file

@ -23,7 +23,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See
## Selecting model roles
You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
![Settings Active Models Section](/images/settings-model-roles.png)

View file

@ -16,7 +16,7 @@ These roles can be specified for a `config.yaml` model block using `roles`. See
## Selecting model roles
You can control which of the models in your assistant for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
You can control which of the models in your agent for a given role will be currently used for that role. Above the main input, click the 3 dots and then the cube icon to expand the `Models` section. Then you can use the dropdowns to select an active model for each role.
<Frame>
<img src="/images/settings-model-roles-5e5f8a6bd9137b70cf94178a7e45847c.png" />

View file

@ -179,13 +179,13 @@
"pages": [
"hub/introduction",
{
"group": "Assistants",
"group": "agents",
"icon": "robot",
"pages": [
"hub/assistants/intro",
"hub/assistants/use-an-assistant",
"hub/assistants/create-an-assistant",
"hub/assistants/edit-an-assistant"
"hub/agents/intro",
"hub/agents/use-an-agent",
"hub/agents/create-an-agent",
"hub/agents/edit-an-agent"
]
},
{
@ -228,7 +228,7 @@
"group": "Guides",
"pages": [
"guides/overview",
"guides/understanding-assistants",
"guides/understanding-agents",
"guides/codebase-documentation-awareness",
"guides/cli",
"guides/continuous-ai",
@ -348,17 +348,13 @@
"source": "/hub/secrets",
"destination": "/hub/secrets/secret-types"
},
{
"source": "/hub/assistants",
"destination": "/hub/assistants/intro"
},
{
"source": "/hub/blocks",
"destination": "/hub/blocks/intro"
},
{
"source": "/hub/agents/intro",
"destination": "/hub/assistants/intro"
"destination": "/hub/agents/intro"
},
{
"source": "/customize",
@ -1106,7 +1102,7 @@
},
{
"source": "/troubleshooting#changes-to-assistants-not-showing-in-vs-code",
"destination": "/faqs#changes-to-assistants-not-showing-in-vs-code"
"destination": "/faqs#changes-to-agents-not-showing-in-vs-code"
},
{
"source": "/troubleshooting#i-installed-continue-but-dont-see-the-sidebar-window",
@ -1175,6 +1171,26 @@
{
"source": "/features/edit/next-edit",
"destination": "/features/autocomplete/next-edit"
},
{
"source": "/hub/assistants/intro",
"destination": "/hub/agents/intro"
},
{
"source": "/hub/assistants/use-an-assistant",
"destination": "/hub/agents/use-an-agent"
},
{
"source": "/hub/assistants/create-an-assistant",
"destination": "/hub/agents/create-an-agent"
},
{
"source": "/hub/assistants/edit-an-assistant",
"destination": "/hub/agents/edit-an-agent"
},
{
"source": "/guides/understanding-assistants",
"destination": "/guides/understanding-agents"
}
]
}

View file

@ -48,15 +48,15 @@ If you are using VS Code and require requests to be made through a proxy, you ar
Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server).
## Changes to assistants not showing in VS Code
## Changes to agents not showing in VS Code
If you've made changes to assistants (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window:
If you've made changes to agents (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window:
1. Open the command palette (`cmd/ctrl` + `shift` + `P`)
2. Type "Reload Window"
3. Select the reload option
This will restart VS Code and reload all extensions, which should make your assistant changes visible.
This will restart VS Code and reload all extensions, which should make your agent changes visible.
## I installed Continue, but don't see the sidebar window
@ -256,7 +256,7 @@ If you're getting parse errors with remote Ollama:
3. **Check URL format**: Ensure you're using `http://` not `https://` for local network addresses
## Local Assistant
## Local Agent
### Managing Local Secrets and Environment Variables
@ -318,7 +318,7 @@ If your API keys aren't being recognized:
### Using Model Addons Locally
You can leverage model addons from the Continue Hub in your local assistant configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration.
You can leverage model addons from the Continue Hub in your local agent configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration.
#### Requirements
@ -330,7 +330,7 @@ You can leverage model addons from the Continue Hub in your local assistant conf
In your local `config.yaml`, reference model addons using the format `provider/model-name`:
```yaml
name: My Local Assistant
name: My Local Agent
version: 0.0.1
schema: v1
models:
@ -344,7 +344,7 @@ models:
You can combine hub model addons with local models:
```yaml
name: My Local Assistant
name: My Local Agent
version: 0.0.1
schema: v1
models:

View file

@ -6,7 +6,7 @@ sidebarTitle: "Customize Agent"
## How to Add Rules Blocks
Adding Rules can be done in your assistant locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
Adding Rules can be done in your agent locally or in the Hub. You can explore Rules on the Continue Hub and refer to the [Rules deep dive](/customize/deep-dives/rules) for more details.
## How to Customize System Messages
@ -18,14 +18,14 @@ models:
provider: openai
model: gpt-4o
chatOptions:
baseSystemMessage: "You are a helpful coding assistant."
baseAgentSystemMessage: "You are a systematic coding assistant. Break down problems methodically."
basePlanSystemMessage: "You are a planning assistant. Create clear, actionable steps."
baseSystemMessage: "You are a helpful coding agent."
baseAgentSystemMessage: "You are a systematic coding agent. Break down problems methodically."
basePlanSystemMessage: "You are a planning agent. Create clear, actionable steps."
```
## How to Add MCP Tools
You can add MCP servers to your assistant to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
You can add MCP servers to your agent to give Agent access to more tools. Explore [MCP Servers on the Hub](https://hub.continue.dev) and consult the [MCP guide](/customize/deep-dives/mcp) for more details.
## How to Configure Tool Policies

View file

@ -3,6 +3,6 @@ title: “Customize Autocomplete Settings in Continue”
description: “Learn how to customize autocomplete behavior in Continue, including user settings, configuration options, and adjustments to improve AI code suggestions in your IDE.”
---
Continue offers a handful of settings to customize autocomplete behavior. Visit the [User Settings Page](/customize/settings) to manage these settings.
Continue offers a handful of settings to customize autocomplete behavior. Visit the User Settings Page (Gear Icon) to manage these settings.
For a comprehensive guide on all configuration options and their impacts, see the [Autocomplete deep dive](/customize/deep-dives/autocomplete).

View file

@ -6,7 +6,7 @@ sidebarTitle: "Customize Edit"
## How to Set Active Edit/Apply Model
You can configure particular models from your Assistant to be used for Edit and Apply requests.
You can configure particular models from your Agent to be used for Edit and Apply requests.
1. Click the 3 dots above the main input
2. Click the cube icon to expand the "Models" section

View file

@ -1,6 +1,6 @@
---
title: "Understanding Assistants"
title: "Understanding Agents"
description: "Continue offers two ways to configure your AI assistants"
---
This content has moved to our comprehensive guide: [Understanding Assistants: Hub vs Local Configuration](/guides/understanding-assistants)
This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-assistants)

View file

@ -24,7 +24,7 @@ The Continue logo will appear on the left sidebar. For a better experience, move
</Step>
<Step title="Sign In">
[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant
[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent
</Step>
</Steps>
@ -54,7 +54,7 @@ Click `Install`, which will cause the Continue logo to show up on the right tool
</Step>
<Step title="Sign In">
[Sign in to the hub](https://auth.continue.dev/) to get started with your first assistant
[Sign in to the hub](https://auth.continue.dev/) to get started with your first agent
</Step>
</Steps>
@ -68,6 +68,6 @@ Click `Install`, which will cause the Continue logo to show up on the right tool
## Signing in
Click "Get started" to sign in to the hub and start using assistants.
Click "Get started" to sign in to the hub and start using agents.
![Hub Onboarding in the Extension](/images/getting-started/images/hub-onboarding-card-81abd457b6d131c4b0aa89a5a6d647d3.png)

View file

@ -57,6 +57,6 @@ description: "To quickly understand what you can do with Continue, check out eac
</Tab>
</Tabs>
## AI Coding Assistants
## AI Coding Agents
Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Assistants** for easy setup and synchronization, or **Local Assistants** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).
Continue offers flexible AI assistants that enhance your development workflow. You can choose between cloud-managed **Hub Agents** for easy setup and synchronization, or **Local Agents** for complete control and privacy. Learn more about [understanding and configuring assistants](/guides/understanding-assistants).

View file

@ -247,12 +247,12 @@ Ready to master specific features? Check out these detailed guides:
<Accordion title="Chat & Agent Best Practices">
Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub
v. local assistants](/guides/understanding-assistants), and [custom slash
v. local agents](/guides/understanding-agents), and [custom slash
commands](/customize/deep-dives/slash-commands).
</Accordion>
<Accordion title="Enterprise & Teams">
Explore [Hub Assistants](/hub/assistants/intro), [organization
Explore [Hub Agents](/hub/agents/intro), [organization
management](/hub/governance/creating-an-org), and [sharing
configurations](/hub/sharing).
</Accordion>

View file

@ -123,8 +123,8 @@ Track how often you need to correct AI output. Lower intervention rates mean hig
Imagine setting up an AI agent that checks new GitHub issues every morning and leaves the first helpful response. This lightens the load for maintainers and ensures community members feel heard quickly.
</Accordion>
<Accordion title="Pattern 2: The PR Review Assistant">
AI can automatically review new pull requests for security, performance, and style issues. The reviewer still has the final say, but the assistant highlights common problems and speeds up the feedback loop.
<Accordion title="Pattern 2: The PR Review Agent">
AI can automatically review new pull requests for security, performance, and style issues. The reviewer still has the final say, but the agent highlights common problems and speeds up the feedback loop.
</Accordion>
<Accordion title="Pattern 3: The Documentation Guardian">
@ -203,5 +203,5 @@ Ready to amplify your development workflow with Continuous AI? Start with one si
<Card title="Want to dive deeper?" icon="rocket">
Check out our guides on [Continue CLI](/guides/cli) and [Understanding
Assistants](/guides/understanding-assistants).
Agents](/guides/understanding-agents).
</Card>

View file

@ -86,8 +86,8 @@ There are multiple ways to configure Ollama models in Continue:
The easiest way is to use [pre-configured model blocks](/reference#local-blocks) from the Continue Hub in your local configuration:
```yaml title="~/.continue/assistants/My Local Assistant.yaml"
name: My Local Assistant
```yaml title="~/.continue/agents/My Local Agent.yaml"
name: My Local Agent
version: 0.0.1
schema: v1
models:
@ -309,11 +309,11 @@ ollama pull deepseek-r1:32b
#### Using Hub Blocks in Local Config
**Problem**: Unclear how to use hub models locally
**Solution**: Create a local assistant file:
**Solution**: Create a local agent file:
```yaml
# ~/.continue/assistants/Local.yaml
name: Local Assistant
# ~/.continue/agents/Local.yaml
name: Local Agent
version: 0.0.1
schema: v1
models:

View file

@ -1,63 +1,63 @@
---
title: "How to Understand Assistants: Hub vs Local Configuration"
description: "Learn how to choose between cloud-managed Hub assistants and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
title: "How to Understand Agents: Hub vs Local Configuration"
description: "Learn how to choose between cloud-managed Hub agents and local configuration for AI development assistance in Continue, including setup, management, and best practices for each approach"
---
Every developer has unique needs when it comes to AI assistance. Some prefer the convenience of cloud-managed configurations, while others need the control and privacy of local setups. Continue offers both paths, and this guide will help you choose the right one for your workflow.
## What Are the Two Paths to AI Assistance?
Continue provides two distinct ways to configure your AI assistant:
Continue provides two distinct ways to configure your AI agent:
Think of Continue's configuration options like choosing between a managed service and self-hosting. Both get you to the same destination—powerful AI assistance in your IDE—but the journey and control level differ significantly.
### How to Access Your Assistant Configuration
### How to Access Your Agent Configuration
Before we dive into the specifics, let's understand how to access your configuration:
1. Open the Continue Chat sidebar by pressing <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)
2. Click the Assistant selector above the main chat input
3. Hover over an assistant and click:
- `new window` icon for Hub assistants
- `gear` icon for Local assistants
2. Click the Agent selector above the main chat input
3. Hover over an agent and click:
- `new window` icon for Hub agents
- `gear` icon for Local agents
![configure an assistant](/images/configure-continue.png)
![configure an agent](/images/configure-continue.png)
## What Are Hub Assistants: The Managed Experience
## What Are Hub Agents: The Managed Experience
Hub Assistants represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured assistants that sync seamlessly across all your development environments.
Hub Agents represent the "it just works" philosophy. When you [sign in to Continue Hub](https://auth.continue.dev/), you gain access to a curated ecosystem of pre-configured agents that sync seamlessly across all your development environments.
### Why Should You Choose Hub Assistants?
### Why Should You Choose Hub Agents?
**The Power of Simplicity**
- **Instant Setup**: Browse the [assistant marketplace](https://hub.continue.dev/explore/assistants) and add any assistant to your account with a single click
- **Instant Setup**: Browse the [agent marketplace](https://hub.continue.dev) and add any agent to your account with a single click
- **Web-Based Management**: Configure models, add secrets, and customize settings through an intuitive web interface—no JSON editing required
- **Automatic Synchronization**: Make a change on the hub, and it reflects immediately across all your IDE instances
- **Team Collaboration**: Share custom assistants with your team, ensuring everyone uses the same optimized configurations
- **Team Collaboration**: Share custom agents with your team, ensuring everyone uses the same optimized configurations
![nextjs assistant](/images/nextjs-assistant.png)
![nextjs agent](/images/nextjs-assistant.png)
### How to Get Started with Hub Assistants
### How to Get Started with Hub Agents
The journey from zero to AI-powered coding takes just four steps:
1. **Select Your Assistant**: Click the assistant selector in your IDE's Continue panel
2. **Explore or Create**: Browse community assistants or craft your own specialized helper
1. **Select Your Agent**: Click the agent selector in your IDE's Continue panel
2. **Explore or Create**: Browse community agents or craft your own specialized helper
3. **Secure Your Keys**: Add API keys as [User Secrets](https://hub.continue.dev/settings/secrets) in the hub—they're encrypted and never exposed
4. **Sync and Code**: Click "Reload config" to pull your latest settings
Pro tip: Hub Assistants are perfect for teams. Create a custom assistant with your team's coding standards, preferred models, and context sources, then share it with a simple link.
Pro tip: Hub Agents are perfect for teams. Create a custom agent with your team's coding standards, preferred models, and context sources, then share it with a simple link.
### How to Manage Hub Assistants
### How to Manage Hub Agents
All Hub Assistant management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Assistant](/hub/assistants/edit-an-assistant).
All Hub Agent management happens through [the Hub](https://hub.continue.dev). For detailed customization, see our guide on [Editing an Agent](/hub/agents/edit-an-agent).
## What Are Local Assistants: The Power User's Choice
## What Are Local Agents: The Power User's Choice
Local Assistants put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI assistant's behavior, with all configuration stored directly on your machine.
Local Agents put you in the driver's seat. Using a `config.yaml` file, you have complete control over every aspect of your AI agent's behavior, with all configuration stored directly on your machine.
### Why Should You Choose Local Assistants?
### Why Should You Choose Local Agents?
**Complete Control and Privacy**
@ -66,7 +66,7 @@ Local Assistants put you in the driver's seat. Using a `config.yaml` file, you h
- **Offline Capability**: Once configured, no internet connection needed (assuming you're using local models)
- **Unlimited Customization**: Access every configuration option, experimental feature, and advanced setting
### How to Set Up Local Assistants
### How to Set Up Local Agents
Local configuration lives in a single YAML file in your home directory:
@ -77,13 +77,13 @@ Local configuration lives in a single YAML file in your home directory:
**Quick Access Method:**
1. Open the assistants dropdown in your IDE
2. Click the gear icon next to "Local Assistant"
1. Open the agents dropdown in your IDE
2. Click the gear icon next to "Local Agent"
3. The `config.yaml` file opens in your editor
![local-config-open-steps](/images/local-config-open-steps.png)
### The Local Assistant Experience
### The Local Agent Experience
When you edit your `config.yaml`, Continue provides intelligent autocomplete for all available options. Save the file, and Continue automatically reloads your configuration—no restart required.
@ -93,9 +93,9 @@ For the complete configuration reference, see our [config.yaml documentation](/r
## How to Make the Right Choice
The decision between Hub and Local assistants often comes down to your specific needs and constraints. Here's a framework to help you decide:
The decision between Hub and Local agents often comes down to your specific needs and constraints. Here's a framework to help you decide:
### Choose Hub Assistants When You:
### Choose Hub Agents When You:
**Value Convenience Over Control**
@ -106,7 +106,7 @@ The decision between Hub and Local assistants often comes down to your specific
**Need Advanced Collaboration**
- Want to share custom assistants with teammates
- Want to share custom agents with teammates
- Need centralized API key management
- Require quick updates across your entire organization
@ -116,7 +116,7 @@ The decision between Hub and Local assistants often comes down to your specific
- Want to experiment with different models and configurations
- Prefer guided setup experiences
### Choose Local Assistants When You:
### Choose Local Agents When You:
**Require Maximum Control**
@ -140,21 +140,21 @@ The decision between Hub and Local assistants often comes down to your specific
Here's a secret: you don't have to choose just one. Many developers use both approaches:
- **Hub Assistants** for general development and experimentation
- **Local Assistants** for production work or client projects with specific requirements
- **Hub Agents** for general development and experimentation
- **Local Agents** for production work or client projects with specific requirements
You can switch between them seamlessly using the assistant selector in your IDE.
You can switch between them seamlessly using the agent selector in your IDE.
## Common Patterns and Best Practices
### For Hub Assistant Users
### For Hub Agent Users
1. **Start with Community Assistants**: Before creating your own, explore what others have built
1. **Start with Community Agents**: Before creating your own, explore what others have built
2. **Use Secrets Properly**: Never hardcode API keys—always use the User Secrets feature
3. **Create Specialized Assistants**: Make different assistants for different contexts (frontend, backend, DevOps)
3. **Create Specialized Agents**: Make different agents for different contexts (frontend, backend, DevOps)
4. **Share Liberally**: If you create something useful, share it with the community
### For Local Assistant Users
### For Local Agent Users
1. **Version Control Your Config**: Treat your `config.yaml` like code—commit it, review changes, and maintain history
2. **Use Environment Variables**: For sensitive data, reference environment variables instead of hardcoding values
@ -163,7 +163,7 @@ You can switch between them seamlessly using the assistant selector in your IDE.
## Troubleshooting and Tips
### Hub Assistant Issues
### Hub Agent Issues
**Changes Not Reflecting?**
@ -171,12 +171,12 @@ You can switch between them seamlessly using the assistant selector in your IDE.
- Check your internet connection
- Ensure you're signed in to the correct account
**Assistant Not Available?**
**Agent Not Available?**
- Verify it's added to your account on the hub
- Check if it requires specific API keys
### Local Assistant Issues
### Local Agent Issues
**Config Not Loading?**
@ -193,7 +193,7 @@ You can switch between them seamlessly using the assistant selector in your IDE.
Now that you understand both configuration approaches, you're ready to dive deeper:
- **For Hub Users**: [Create Your First Assistant](/hub/assistants/create-an-assistant)
- **For Hub Users**: [Create Your First Agent](/hub/agents/create-an-agent)
- **For Local Users**: [Explore the Config Reference](/reference)
- **For Everyone**: [Discover Available Models](/customize/model-providers/overview)

View file

@ -0,0 +1,34 @@
---
title: "How to Create an AI Agent"
description: "Learn how to create custom AI coding agents in Continue Hub by remixing existing agents or building new ones from scratch with reusable blocks and YAML configuration."
sidebarTitle: "Create an AI Agent"
---
## How to Create an AI Agent from Scratch
To create an agent from scratch, select “New agent” in the top bar.
![New agent button](/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png)
Choose a name, slug, description, and icon for your agent.
The easiest way to create an agent is to click "Create agent" with the default configuration and then add / remove blocks using the sidebar.
Alternatively, you can edit the agent YAML directly before clicking "Create agent". Refer to examples of agents on [hub.continue.dev](https://hub.continue.dev) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
![New agent YAML](/images/hub/assistants/images/assistant-create-yaml-a991e5a81506f1c3ba611a664a50734c.png)
## How to Remix an Agent
You can also create an agent by remixing an existing one. This is useful if you want to start with a pre-configured agent and make modifications.
By clicking the “remix” button, you’ll be taken to the “Create a remix” page.
![Remix Agent Button](/images/hub/assistants/images/assistant-remix-button-728ececa73983140eeab42e33cc3903b.png)
Once here, you’ll be able to
1. add or remove blocks in YAML configuration
2. change the name, description, icon, etc.
Clicking “Create agent” will make this agent available for use.

View file

@ -0,0 +1,20 @@
---
title: "How to Edit an Agent"
description: "New versions of an agent can be created and published using the sidebar."
---
![Remix Agent Button](/images/hub/assistants/images/assistant-create-sidebar-608be49973f2a7723212adeb52dbcafb.png)
First, select an agent from the dropdown at the top.
While editing an agent, you can explore the hub and click "Add Block" from a block page to add it to your agent.
For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed.
To delete a block, click the trash icon.
If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block).
When you are done editing, click "Publish" to publish a new version of the agent.
Click "Open VS Code" or "Open JetBrains" to open your IDE for using the agent.

View file

@ -0,0 +1,8 @@
---
title: "Introduction to Agents"
description: "Custom AI code agents are configurations of building blocks that enable a coding experience tailored to your specific use cases."
---
`config.yaml` is a format for defining custom AI code agents. An agent has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an agent.
The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom agent experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your agents will automatically be synced with the IDE extensions.

View file

@ -0,0 +1,19 @@
---
title: "How to Use an Agent"
description: "Learn how to add, configure, and use an AI agent in Continue, including setting required inputs and selecting it in your IDE extension."
---
## Steps to Use an AI Agent in Continue
Once you've found the agent you want to use on Continue Hub:
1. Click “Add Agent” on its page
2. Add any required inputs (e.g. secrets like API keys)
3. Select “Save changes” in agent sidebar on the right hand side
After saving, open your IDE extension and:
- Select the agent from the **agent dropdown** in the Continue extension.
- Begin using it for chat, code generation, or other configured capabilities.
![Extension Agent Selector](/images/hub/assistants/images/assistant-extension-select.png)

View file

@ -1,34 +0,0 @@
---
title: "How to Create an AI Assistant"
description: "Learn how to create custom AI coding assistants in Continue Hub by remixing existing assistants or building new ones from scratch with reusable blocks and YAML configuration."
sidebarTitle: "Create an AI Assistant"
---
## How to Create an AI Assistant from Scratch
To create an assistant from scratch, select “New assistant” in the top bar.
![New assistant button](/images/hub/assistants/images/assistant-new-button-16070e2cff9ce25ec9ebfeecb0e2f2b5.png)
Choose a name, slug, description, and icon for your assistant.
The easiest way to create an assistant is to click "Create assistant" with the default configuration and then add / remove blocks using the sidebar.
Alternatively, you can edit the assistant YAML directly before clicking "Create assistant". Refer to examples of assistants on [hub.continue.dev](https://hub.continue.dev/explore/assistants) and visit the [YAML Reference](/reference#complete-yaml-config-example) docs for more details.
![New assistant YAML](/images/hub/assistants/images/assistant-create-yaml-a991e5a81506f1c3ba611a664a50734c.png)
## How to Remix an Assistant
You can also create an assistant by remixing an existing one. This is useful if you want to start with a pre-configured assistant and make modifications.
By clicking the “remix” button, you’ll be taken to the “Create a remix” page.
![Remix Assistant Button](/images/hub/assistants/images/assistant-remix-button-728ececa73983140eeab42e33cc3903b.png)
Once here, you’ll be able to
1. add or remove blocks in YAML configuration
2. change the name, description, icon, etc.
Clicking “Create assistant” will make this assistant available for use.

View file

@ -1,20 +0,0 @@
---
title: "How to Edit an Assistant"
description: "New versions of an assistant can be created and published using the sidebar."
---
![Remix Assistant Button](/images/hub/assistants/images/assistant-create-sidebar-608be49973f2a7723212adeb52dbcafb.png)
First, select an assistant from the dropdown at the top.
While editing an assistant, you can explore the hub and click "Add Block" from a block page to add it to your assistant.
For blocks that require secret values like API keys, you will see a small notification on the block's tile in the sidebar that will indicate if action is needed.
To delete a block, click the trash icon.
If a block you want to use does not exist yet, you can [create a new block](/hub/blocks/create-a-block).
When you are done editing, click "Publish" to publish a new version of the assistant.
Click "Open VS Code" or "Open JetBrains" to open your IDE for using the assistant.

View file

@ -1,8 +0,0 @@
---
title: "Introduction to Assistants"
description: "Custom AI code assistants are configurations of building blocks that enable a coding experience tailored to your specific use cases."
---
`config.yaml` is a format for defining custom AI code assistants. An assistant has some top-level properties (e.g. `name`, `version`), but otherwise consists of composable lists of **blocks** such as `models` and `rules`, which are the atomic building blocks of an assistant.
The `config.yaml` is parsed by the open-source Continue IDE extensions to create custom assistant experiences. When you log in to [hub.continue.dev](https://hub.continue.dev/), your assistants will automatically be synced with the IDE extensions.

View file

@ -1,19 +0,0 @@
---
title: "How to Use an Assistant"
description: "Learn how to add, configure, and use an AI assistant in Continue, including setting required inputs and selecting it in your IDE extension."
---
## Steps to Use an AI Assistant in Continue
Once you've found the assistant you want to use on Continue Hub:
1. Click “Add Assistant” on its page
2. Add any required inputs (e.g. secrets like API keys)
3. Select “Save changes” in assistant sidebar on the right hand side
After saving, open your IDE extension and:
- Select the assistant from the **assistant dropdown** in the Continue extension.
- Begin using it for chat, code generation, or other configured capabilities.
![Extension Assistant Selector](/images/hub/assistants/images/assistant-extension-select.png)

View file

@ -20,7 +20,7 @@ Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServ
## Rules
Rules blocks are instructions that your custom AI code assistant will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub.
Rules blocks are instructions that your custom AI code agent will always keep in mind - the contents of rules are inserted into the system message for all Chat requests. [Explore rules](https://hub.continue.dev/explore/rules) on the hub.
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.

View file

@ -12,7 +12,7 @@ By clicking the “remix” button, you’ll be taken to the “Create a remix
![Remix block button](/images/hub/blocks/images/block-remix-button-913beb80672662855acc7013561c78d0.png)
Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an assistant.
Once here, you’ll be able to 1) edit YAML configuration for the block and 2) change name, description, icon, etc. Clicking “Create block” will make this block available for use in an agent.
## How to Create a Block from Scratch
@ -26,4 +26,4 @@ After filling out information on the block, you will want to create a block foll
### Block Inputs
Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their assistant.
Blocks can receive values, including secrets, as inputs through templating. For values that the user of the block needs to set, you can use template variables (e.g. `${{ inputs.API_KEY}}`). Then, the user can set `API_KEY: ${{ secrets.MY_API_KEY }}` in the `with` clause of their agent.

View file

@ -1,6 +1,6 @@
---
title: "Introduction"
description: "Blocks are the components you use to build a custom AI code assistant. These include Models, MCP Servers, Rules, and Prompts."
description: "Blocks are the components you use to build a custom AI code agent. These include Models, MCP Servers, Rules, and Prompts."
---
Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code assistant.
Blocks follow the [`config.yaml`](/reference) format. When combined with other blocks into a complete `config.yaml`, they form a custom AI code agent.

View file

@ -1,12 +1,12 @@
---
title: "How to Use a Block"
description: "Learn how to use blocks in Continue Hub to enhance your AI code assistant."
description: "Learn how to use blocks in Continue Hub to enhance your AI code agent."
---
Blocks are used to build custom AI code assistants in Continue Hub. Learn more:
Blocks are used to build custom AI code agents in Continue Hub. Learn more:
- [Create an assistant](/hub/assistants/create-an-assistant)
- [Edit an assistant](/hub/assistants/edit-an-assistant)
- [Create an agent](/hub/agents/create-an-agent)
- [Edit an agent](/hub/agents/edit-an-agent)
Some blocks require inputs. If you are missing an input for a block, a notification icon will show up in the sidebar next to the block. Click the notification to select which secret to use for the block input:

View file

@ -6,7 +6,7 @@ description: "To Create an Organization, click the organization selector in the
![create an org selector](/images/hub/governance/images/org-selector-4ea627afc7c0765633780920a0fbe16e.png)
1. Choose a name, which will be used as the display name for your organization throughout the hub
2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and assistant slugs
2. Add a slug, which will be used for your org URL and as the prefix to all organization blocks and agent slugs
3. Select an icon for your organization using the image uploader
4. Finally, add a Biography, which will be displayed on your org Home Page

View file

@ -1,16 +1,16 @@
---
title: "Secret Types"
description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across assistants and within organizations."
description: "The Continue Hub comes with secrets management built-in. Secrets are values such as API keys or endpoints that can be shared across agents and within organizations."
---
## User secrets
User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the assistant `config.yaml`.
User secrets are defined by the user for themselves. This means that user secrets are available only to the user that created them. User secrets are assumed to be safe for the user to know, so they will be sent to the IDE extensions alongside the agent `config.yaml`.
This allows API requests to be made directly from the IDE extensions. You can use user secrets with [Solo](/hub/governance/pricing#solo), [Teams](/hub/governance/pricing#teams), and [Enterprise](/hub/governance/pricing#enterprise). User secrets can be managed [here](https://hub.continue.dev/settings/secrets) in the hub.
## Org secrets
Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with assistants in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys).
Org secrets are defined by admins for their organization. Org secrets are available to anyone in the organization to use with agents in that organization. Org secrets are assumed to not be shareable with the user (e.g. you are a team lead who wants to give team members access to models without passing out API keys).
This is why LLM requests are proxied through api.continue.dev / on-premise proxy and secrets are never sent to the IDE extensions. You can only use org secrets on [Teams](/hub/governance/pricing#teams) and [Enterprise](/hub/governance/pricing#enterprise). If you are an admin, you can manage secrets for your organization from the org settings page.

View file

@ -15,17 +15,17 @@ Share your custom assistants, blocks, and configurations with the Continue commu
[Visit the Hub →](https://hub.continue.dev)
## Browse Assistants
## Browse Agents
Explore assistants created by the community for specific use cases and workflows.
[Browse Assistants →](https://hub.continue.dev)
[Browse Agents →](https://hub.continue.dev)
## Using Assistants
## Using Agents
Learn how to discover, install, and use community-created assistants in your projects.
[Learn About Assistants →](/hub/assistants/intro)
[Learn About Agents →](/hub/assistants/intro)
---

View file

@ -1,6 +1,6 @@
---
title: "Source Control"
description: "When managing your custom assistants within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on ."
description: "When managing your custom agents within an organization, you might want to take advantage of your usual source control workflows. Continue makes this easy with a that automatically syncs your YAML files with hub.continue.dev. We are also planning on adding automations for GitLab, BitBucket, Gitee, and others. If you are interested, please reach out to us on ."
---
## Quickstart
@ -34,11 +34,11 @@ This is the only configuration necessary, but you can view the full list of opti
### 4. Commit and push
Add the [YAML for your assistants and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the assistant/block.
Add the [YAML for your agents and blocks](/reference) to the appropriate directories. The name of the file will be the slug of the agent/block.
- `assistants/public` for public assistants
- `assistants/private` for private (visible only within your organization) assistants
- `assistants/public` for public agents
- `assistants/private` for private (visible only within your organization) agents
- `blocks/public` for public blocks
- `blocks/private` for private blocks
Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the assistants within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s).
Then, commit and push your changes. Once the GitHub Action has completed running, you should be able to view the agents within your organization on hub.continue.dev. For subsequent changes, make sure to increment the `version` property of your updated YAML file(s).

View file

@ -1,43 +1,43 @@
---
title: "config.yaml Reference"
description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding assistants. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration."
description: "Comprehensive guide to the config.yaml format used by Continue.dev for building custom coding agents. Learn how to define models, context providers, rules, prompts, and more using reusable blocks and YAML configuration."
---
## Introduction
Continue hub assistants are defined using the `config.yaml` specification. Assistants can be loaded from [the Hub](https://hub.continue.dev/explore/assistants) or locally
Continue hub agents are defined using the `config.yaml` specification. Agents can be loaded from [the Hub](https://hub.continue.dev/explore/agents) or locally
- [Continue Hub](https://hub.continue.dev/explore/assistants) - YAML is stored on the hub and automatically synced to the extension
- [Continue Hub](https://hub.continue.dev/explore/agents) - YAML is stored on the hub and automatically synced to the extension
- Locally
- in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/assistants`. The name of the file will be used as the display name of the assistant, e.g. `My Assistant.yaml`
- in your workspace in a `/.continue/assistants` folder, with the same naming convention
- in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) within `.continue/agents`. The name of the file will be used as the display name of the agent, e.g. `My Agent.yaml`
- in your workspace in a `/.continue/agents` folder, with the same naming convention
<Info>
Config YAML replaces `config.json`, which is deprecated. View the **[Migration
Guide](/reference/yaml-migration)**.
</Info>
An assistant is made up of:
An agent is made up of:
1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the assistant
2. **Block lists**, which are composable arrays of coding assistant building blocks available to the assistant, such as models, docs, and context providers.
1. **Top level properties**, which specify the `name`, `version`, and `config.yaml` `schema` for the agent
2. **Block lists**, which are composable arrays of coding agent building blocks available to the agent, such as models, docs, and context providers.
A block is a single standalone building block of a coding assistants, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as assistants (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is.
A block is a single standalone building block of a coding agents, e.g., one model or one documentation source. In `config.yaml` syntax, a block consists of the same top-level properties as agents (`name`, `version`, and `schema`), but only has **ONE** item under whichever block type it is.
Examples of blocks and assistants can be found on the [Continue hub](https://hub.continue.dev/explore/assistants).
Examples of blocks and agents can be found on the [Continue Hub](https://hub.continue.dev).
Assistants can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks.
Agents can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks.
### Using Blocks
Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev).
Hub blocks and agents are identified with a slug in the format `owner-slug/block-or-agent-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev).
Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
Blocks can be imported into an agent by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type.
For example, the following assistant imports an Anthropic model and defines an Ollama DeepSeek one.
For example, the following agent imports an Anthropic model and defines an Ollama DeepSeek one.
Assistant models section
Agent models section
```yaml
name: Team Agent
@ -52,13 +52,13 @@ models:
### Local Blocks
It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all assistants when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally).
It is also possible to define blocks locally in a `.continue` folder. This folder can be located at either the root of your workspace (these will automatically be applied to all agents when you are in that workspace) or in your home directory at `~/.continue` (these will automatically be applied globally).
Place your YAML files in the following folders:
Assistants:
Agents:
- `.continue/assistants` - for assistants
- `.continue/agents` - for agents
Blocks:
@ -100,7 +100,7 @@ models:
Which can then be imported like this:
```yaml title="config.yaml"
name: myprofile/custom-assistant
name: myprofile/custom-agent
version: 1.0.0
schema: v1
@ -118,7 +118,7 @@ Note that hub secrets can be passed as inputs, using a similar mustache format:
Block properties can be also be directly overriden using `override`. For example:
```yaml title="config.yaml"
name: myprofile/custom-assistant
name: myprofile/custom-agent
version: 1.0.0
schema: v1

View file

@ -45,7 +45,7 @@ What context providers are available in Continue?
### Customization
```
How do I add custom rules to my assistant in Continue?
How do I add custom rules to my agent in Continue?
```
## Troubleshooting

View file

@ -408,4 +408,4 @@ The following configuration example includes:
</Tab>
</Tabs>
This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings).
This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon).

View file

@ -50,8 +50,8 @@ export const ModelRecommendations = ({ role = "all" }) => {
"[Kimi K2 (1T)](https://hub.continue.dev/openrouter/kimi-k2)",
"[gpt-oss (120B)](https://hub.continue.dev/openrouter/gpt-oss-120b)",
"[gpt-oss (20B)](https://hub.continue.dev/ollama/gpt-oss-20b)",
"GLM 4.5 (355B)",
"GLM 4.5 Air (106B)",
"[GLM 4.5 (355B)](https://hub.continue.dev/openrouter/glm-4-5)",
"[GLM 4.5 Air (106B)](https://hub.continue.dev/openrouter/glm-4-5-air)",
],
closed: [
"[Claude Opus 4.1](https://hub.continue.dev/anthropic/claude-4-1-opus)",
@ -83,7 +83,7 @@ export const ModelRecommendations = ({ role = "all" }) => {
],
closed: [
"[Codestral](https://hub.continue.dev/mistral/codestral)",
"[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)",
"[Mercury Coder](https://hub.continue.dev/inception/mercury-coder)",
],
notes: "Closed models are slightly better than open models",
},
@ -119,7 +119,7 @@ export const ModelRecommendations = ({ role = "all" }) => {
next_edit: {
open: ["[Instinct](https://hub.continue.dev/continuedev/instinct)"],
closed: [
"[Mercury Coder](https://hub.continue.dev/inceptionlabs/mercury-coder)",
"[Mercury Coder](https://hub.continue.dev/inception/mercury-coder)",
],
notes: "Closed models are better than open models",
},

View file

@ -1,215 +0,0 @@
name: Respond to @continuedev Comments
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
permissions:
contents: write
pull-requests: write
issues: write
jobs:
respond-to-comment:
# Only run on pull request comments
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
- name: Get PR information
if: steps.check-mention.outputs.contains_mention == 'true'
id: pr-info
uses: actions/github-script@v7
with:
script: |
const { data: pr } = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: context.issue.number
});
core.setOutput('head_ref', pr.head.ref);
core.setOutput('head_sha', pr.head.sha);
return pr;
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
git checkout ${{ steps.pr-info.outputs.head_ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create the prompt for remote session
PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}:
${{ github.event.comment.body }}
Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch."
# Start remote session and capture JSON output
SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: commentBody
});
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "Original comment: ${{ github.event.comment.body }}"
respond-to-review-comment:
# Only run on pull request review comments
if: github.event_name == 'pull_request_review_comment'
runs-on: ubuntu-latest
steps:
- name: Check if comment contains @continuedev
id: check-mention
run: |
if echo "${{ github.event.comment.body }}" | grep -q "@continuedev"; then
echo "contains_mention=true" >> $GITHUB_OUTPUT
else
echo "contains_mention=false" >> $GITHUB_OUTPUT
fi
- name: Checkout PR branch
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
- name: Setup Node.js
if: steps.check-mention.outputs.contains_mention == 'true'
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
id: remote-session
env:
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
run: |
# Create a temporary file for the prompt to handle special characters and newlines properly
cat > /tmp/prompt.txt << 'PROMPT_EOF'
Please help with the following code review comment from @${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}:
**File:** ${{ github.event.comment.path }}
**Line:** ${{ github.event.comment.line || github.event.comment.original_line || 'N/A' }}
**Comment:** ${{ github.event.comment.body }}
Please analyze the specific file and line mentioned, understand the review feedback, implement the necessary changes, and commit them to this branch.
PROMPT_EOF
# Debug output
echo "PROMPT content:"
cat /tmp/prompt.txt
# Start remote session and capture JSON output
echo "Starting cn with prompt..."
SESSION_OUTPUT=$(cat /tmp/prompt.txt | cn remote -s --branch ${{ github.event.pull_request.head.ref }})
echo "Raw session output: $SESSION_OUTPUT"
# Extract URL from JSON output
SESSION_URL=$(echo "$SESSION_OUTPUT" | jq -r '.url // empty')
if [ -z "$SESSION_URL" ] || [ "$SESSION_URL" = "null" ]; then
echo "Failed to extract session URL from output: $SESSION_OUTPUT"
exit 1
fi
echo "session_url=$SESSION_URL" >> $GITHUB_OUTPUT
echo "✅ Started remote session: $SESSION_URL"
- name: Comment with session URL
if: steps.check-mention.outputs.contains_mention == 'true' && steps.remote-session.outputs.session_url
uses: actions/github-script@v7
with:
script: |
const commentBody = `I've started [a remote session](${{ steps.remote-session.outputs.session_url }}) to help with your request:
> ${{ github.event.comment.body }}`;
const commentParams = {
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: ${{ github.event.pull_request.number }},
body: commentBody,
commit_id: '${{ github.event.pull_request.head.sha }}',
path: '${{ github.event.comment.path }}',
in_reply_to: ${{ github.event.comment.id }}
};
await github.rest.pulls.createReviewComment(commentParams);
- name: Log session details
if: steps.check-mention.outputs.contains_mention == 'true'
run: |
echo "✅ Successfully started remote session for review comment from ${{ github.event.comment.user.login }} on PR #${{ github.event.pull_request.number }}"
echo "Session URL: ${{ steps.remote-session.outputs.session_url }}"
echo "File: ${{ github.event.comment.path }}"
echo "Line: ${{ github.event.comment.line }}"
echo "Original comment: ${{ github.event.comment.body }}"

View file

@ -68,6 +68,10 @@ try {
__dirname,
"../../packages/llm-info/dist/index.js",
),
"@continuedev/terminal-security": resolve(
__dirname,
"../../packages/terminal-security/dist/index.js",
),
},
// Add banner to create require for CommonJS packages

View file

@ -18,6 +18,7 @@
"@continuedev/config-yaml": "file:../../packages/config-yaml",
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
"@continuedev/sdk": "^0.0.13",
"@continuedev/terminal-security": "file:../../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",
@ -123,6 +124,7 @@
"@continuedev/fetch": "file:../packages/fetch",
"@continuedev/llm-info": "file:../packages/llm-info",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@continuedev/terminal-security": "file:../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -173,6 +175,7 @@
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
"shell-quote": "^1.8.3",
"socket.io-client": "^4.7.3",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
@ -207,6 +210,7 @@
"@types/pg": "^8.11.6",
"@types/plist": "^3.0.5",
"@types/request": "^2.48.12",
"@types/shell-quote": "^1.7.5",
"@types/tar": "^6.1.13",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
@ -294,6 +298,21 @@
"vitest": "^3.2.4"
}
},
"../../packages/terminal-security": {
"name": "@continuedev/terminal-security",
"version": "1.0.0",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"shell-quote": "^1.8.1"
},
"devDependencies": {
"@types/node": "^20.11.19",
"@types/shell-quote": "^1.7.5",
"typescript": "^5.5.2",
"vitest": "^1.6.0"
}
},
"node_modules/@alcalzone/ansi-tokenize": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.0.tgz",
@ -386,6 +405,10 @@
"openai": "^4.96.2"
}
},
"node_modules/@continuedev/terminal-security": {
"resolved": "../../packages/terminal-security",
"link": true
},
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",

View file

@ -15,7 +15,7 @@
"test:e2e": "vitest run --config vitest.e2e.config.ts",
"test:smoke": "node smoke-test.mjs",
"build:tsc": "tsc -p tsconfig.build.json",
"build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i",
"build:local-deps": "cd ../../packages/config-types && npm i && npm run build && cd ../fetch && npm i && npm run build && cd ../llm-info && npm i && npm run build && cd ../terminal-security && npm i && npm run build && cd ../config-yaml && npm i && npm run build && cd ../openai-adapters && npm i && npm run build && cd ../../core && npm i && npm run build && cd ../extensions/cli && npm i",
"build:validate": "node validate-aliases.mjs",
"build:bundle": "node build.mjs",
"build": "npm run build:validate && npm run build:bundle",
@ -50,6 +50,7 @@
"@continuedev/config-yaml": "file:../../packages/config-yaml",
"@continuedev/openai-adapters": "file:../../packages/openai-adapters",
"@continuedev/sdk": "^0.0.13",
"@continuedev/terminal-security": "file:../../packages/terminal-security",
"@modelcontextprotocol/sdk": "^1.17.2",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.203.0",

View file

@ -0,0 +1,138 @@
shell Mode (CLI TUI)
Overview
- shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
- It is intended for quick terminal command execution without leaving the TUI.
Activation
- shell mode is activated when the current input (trimmed) starts with !
- Example: "!git status" or " !ls -la" both activate shell mode.
- Visual indicator:
- Input border color changes to yellow.
- The input prompt indicator changes to a yellow "$".
- The input placeholder includes "! for shell mode".
Deactivation / Exiting shell Mode
- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
Interaction with other input helpers
- When in shell mode (input starts with !):
- "@" file search suggestions are disabled.
- "/" slash command UI is disabled.
- When in slash command mode (input starts with /):
- "@" file search suggestions are disabled.
Submission behavior
- On submit (Enter) with a shell-mode input:
- The leading ! is removed and the remainder is treated as the shell command to run.
- The TUI immediately appends an assistant message representing a shell tool call, with status set to calling, so users can see that the command is in progress.
- The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
Execution semantics
- The command is executed in the same way as terminal tool commands, minus permissions
Output handling
- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
- Output is truncated to the first 5000 lines if exceeded.
- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
"[Command timed out after 30 seconds of no output]".
Keyboard behaviors (summary)
- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending shell tool call immediately.
- Shift+Enter: new line.
- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
Scope / Modes
- shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
Error handling
- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
Examples
- "!git status" → shows a shell tool call immediately, then populates with the git status output.
- "!echo hello" → shows a shell tool call immediately, then output "hello".
- "!some-unknown-cmd" → shows a shell tool call immediately, then sets status to error with an error message.
Shell Mode (CLI TUI)
Overview
- Shell mode lets users run shell commands directly from the chat input by starting their input with an exclamation mark (!).
- It is intended for quick terminal command execution without leaving the TUI.
Activation
- Shell mode is activated when the current input (trimmed) starts with !
- Example: "!git status" or " !ls -la" both activate Shell mode.
- Visual indicator:
- Input border color changes to yellow.
- The input prompt indicator changes to a yellow "$".
- The input placeholder includes "! for shell mode".
Deactivation / Exiting Shell Mode
- Pressing Enter to submit the input exits shell mode immediately after submission, regardless of the command result.
- Pressing Esc when the input (trimmed) is exactly ! clears the input and exits shell mode.
- Editing the input so it no longer starts with ! also exits shell mode and restores normal input behavior.
Interaction with other input helpers
- When in shell mode (input starts with !):
- "@" file search suggestions are disabled.
- "/" slash command UI is disabled.
- When in slash command mode (input starts with /):
- "@" file search suggestions are disabled.
Submission behavior
- On submit (Enter) with a shell-mode input:
- The leading ! is removed and the remainder is treated as the shell command to run.
- The TUI immediately appends an assistant message representing a Shell tool call, with status set to calling, so users can see that the command is in progress.
- The shell command is executed asynchronously; when it completes, the tool call status is updated to done (or error) and the output is populated.
Execution semantics
- The command is executed in the same way as terminal tool commands, minus permissions, and inserted into the chat history the same.
Output handling
- Stdout is streamed into memory; Stderr is captured and appended as a trailing "Stderr: ..." section on success.
- If the process exits non-zero and Stderr contains content, the tool call is marked as error and the error text is shown.
- Output is truncated to the first 5000 lines if exceeded.
- Timeout behavior: If no output is received for 30 seconds (configurable in tests), the process is terminated and the result includes a note like:
"[Command timed out after 30 seconds of no output]".
Keyboard behaviors (summary)
- Enter: submit input. If in shell mode, exits shell mode after submission and shows the pending Shell tool call immediately.
- Shift+Enter: new line.
- Backslash (\) at end-of-line: inserts a new line (line continuation) as usual.
- Esc: if only ! (trimmed) is present, clears input and exits shell mode; otherwise cancels streaming or closes suggestions depending on context.
Scope / Modes
- Shell mode applies to interactive (TUI/standard) CLI usage. It is not part of headless (-p/--print) processing.
Error handling
- Command execution errors are captured and surfaced in the tool call as status error with human-readable error text (including Stderr when available).
Examples
- "!git status" → shows a Shell tool call immediately, then populates with the git status output.
- "!echo hello" → shows a Shell tool call immediately, then output "hello".
- "!some-unknown-cmd" → shows a Shell tool call immediately, then sets status to error with an error message.

View file

@ -47,6 +47,42 @@ export function setExitMessageCallback(callback: () => void) {
exitMessageCallback = callback;
}
// Sets up SIGINT handler that requires double Ctrl+C within 1 second to exit
export function enableSigintHandler() {
// Remove all existing SIGINT listeners first
process.removeAllListeners("SIGINT");
process.on("SIGINT", async () => {
const now = Date.now();
const timeSinceLastCtrlC = now - lastCtrlCTime;
if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) {
// Second Ctrl+C within 1 second - exit
showExitMessage = false;
if (tuiUnmount) {
tuiUnmount();
}
await sentryService.flush();
process.exit(0);
} else {
// First Ctrl+C or too much time elapsed - show exit message
lastCtrlCTime = now;
showExitMessage = true;
if (exitMessageCallback) {
exitMessageCallback();
}
// Hide message after 1 second
setTimeout(() => {
showExitMessage = false;
if (exitMessageCallback) {
exitMessageCallback();
}
}, 1000);
}
});
}
// Check if "ctrl+c to exit" message should be displayed
export function shouldShowExitMessage(): boolean {
return showExitMessage;
@ -294,41 +330,6 @@ try {
process.exit(1);
}
// Graceful shutdown with two-stage Ctrl+C exit
// Remove all existing SIGINT listeners first
process.removeAllListeners("SIGINT");
process.on("SIGINT", async () => {
const now = Date.now();
const timeSinceLastCtrlC = now - lastCtrlCTime;
if (timeSinceLastCtrlC <= 1000 && lastCtrlCTime !== 0) {
// Second Ctrl+C within 1 second - exit
showExitMessage = false;
if (tuiUnmount) {
tuiUnmount();
}
await sentryService.flush();
process.exit(0);
} else {
// First Ctrl+C or too much time elapsed - show exit message
lastCtrlCTime = now;
showExitMessage = true;
if (exitMessageCallback) {
exitMessageCallback();
}
// Hide message after 1 second
setTimeout(() => {
showExitMessage = false;
if (exitMessageCallback) {
exitMessageCallback();
}
}, 1000);
}
});
process.on("SIGTERM", async () => {
await sentryService.flush();
process.exit(0);

View file

@ -1,3 +1,7 @@
import { vi, describe, it, expect, beforeEach, afterEach } from "vitest";
import * as toolsModule from "../tools/index.js";
import {
checkToolPermission,
filterExcludedTools,
@ -593,4 +597,373 @@ describe("Permission Checker", () => {
expect(filtered).toEqual(tools);
});
});
describe("Hybrid Permission Model with Dynamic Evaluation", () => {
// Mock the runTerminalCommand tool with evaluateToolCallPolicy
const mockBashTool = {
name: "Bash",
displayName: "Bash",
description: "Execute bash commands",
parameters: {},
isBuiltIn: true,
evaluateToolCallPolicy: vi.fn(),
run: vi.fn(),
};
beforeEach(() => {
vi.clearAllMocks();
// Mock getAllBuiltinTools to return our test tool
vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([
mockBashTool,
]);
// Reset mock between tests
mockBashTool.evaluateToolCallPolicy.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("User has Bash in 'allow' mode", () => {
const permissions: ToolPermissions = {
policies: [
{ tool: "Bash", permission: "allow" },
{ tool: "*", permission: "ask" },
],
};
it("should allow safe commands (echo hello)", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithoutPermission",
);
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "echo hello" } },
permissions,
);
expect(result.permission).toBe("allow"); // User preference wins
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithoutPermission", // converted from "allow"
{ command: "echo hello" },
);
});
it("should allow risky commands based on user preference (curl)", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithPermission",
);
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "curl https://example.com" } },
permissions,
);
expect(result.permission).toBe("allow"); // User preference wins over "ask"
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithoutPermission", // converted from "allow"
{ command: "curl https://example.com" },
);
});
it("should block dangerous commands despite user preference (eval)", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "eval 'echo safe'" } },
permissions,
);
expect(result.permission).toBe("exclude"); // Security wins
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithoutPermission", // converted from "allow"
{ command: "eval 'echo safe'" },
);
});
it("should block sudo commands despite user preference", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "sudo rm -rf /" } },
permissions,
);
expect(result.permission).toBe("exclude"); // Security wins
});
});
describe("User has Bash in 'ask' mode (default)", () => {
const permissions: ToolPermissions = {
policies: [
{ tool: "Bash", permission: "ask" },
{ tool: "*", permission: "ask" },
],
};
it("should ask for safe commands based on user preference (echo)", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithoutPermission",
);
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "echo hello" } },
permissions,
);
expect(result.permission).toBe("ask"); // User preference wins
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithPermission", // converted from "ask"
{ command: "echo hello" },
);
});
it("should ask for risky commands (curl)", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithPermission",
);
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "curl https://example.com" } },
permissions,
);
expect(result.permission).toBe("ask"); // Both agree on "ask"
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithPermission", // converted from "ask"
{ command: "curl https://example.com" },
);
});
it("should block dangerous commands (eval)", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "eval 'echo safe'" } },
permissions,
);
expect(result.permission).toBe("exclude"); // Security wins
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithPermission", // converted from "ask"
{ command: "eval 'echo safe'" },
);
});
it("should block rm -rf commands", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "rm -rf /tmp/important" } },
permissions,
);
expect(result.permission).toBe("exclude"); // Security wins
});
});
describe("User has Bash in 'exclude' mode", () => {
const permissions: ToolPermissions = {
policies: [{ tool: "Bash", permission: "exclude" }],
};
it("should always exclude regardless of dynamic evaluation", () => {
// Even if dynamic evaluation would allow it
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithoutPermission",
);
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "echo hello" } },
permissions,
);
expect(result.permission).toBe("exclude"); // User excluded the tool entirely
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"disabled", // converted from "exclude"
{ command: "echo hello" },
);
});
});
describe("Comprehensive command testing", () => {
const permissions: ToolPermissions = {
policies: [{ tool: "Bash", permission: "allow" }],
};
const testCases = [
// Safe commands
{
command: "ls",
dynamicResult: "allowedWithoutPermission",
expected: "allow",
},
{
command: "pwd",
dynamicResult: "allowedWithoutPermission",
expected: "allow",
},
{
command: "date",
dynamicResult: "allowedWithoutPermission",
expected: "allow",
},
{
command: "echo test",
dynamicResult: "allowedWithoutPermission",
expected: "allow",
},
{
command: "git status",
dynamicResult: "allowedWithoutPermission",
expected: "allow",
},
// Risky commands (user preference wins when not disabled)
{
command: "npm install pkg",
dynamicResult: "allowedWithPermission",
expected: "allow",
},
{
command: "rm file.txt",
dynamicResult: "allowedWithPermission",
expected: "allow",
},
{
command: "curl https://api.example.com",
dynamicResult: "allowedWithPermission",
expected: "allow",
},
{
command: "wget https://example.com/file",
dynamicResult: "allowedWithPermission",
expected: "allow",
},
// Dangerous commands (always blocked)
{
command: "sudo rm -rf /",
dynamicResult: "disabled",
expected: "exclude",
},
{
command: "exec bash",
dynamicResult: "disabled",
expected: "exclude",
},
{
command: "eval 'malicious code'",
dynamicResult: "disabled",
expected: "exclude",
},
{ command: "rm -rf /", dynamicResult: "disabled", expected: "exclude" },
];
testCases.forEach(({ command, dynamicResult, expected }) => {
it(`should handle '${command}' correctly`, () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult);
const result = checkToolPermission(
{ name: "Bash", arguments: { command } },
permissions,
);
expect(result.permission).toBe(expected);
});
});
});
describe("Edge cases", () => {
it("should handle tools without dynamic evaluation", () => {
// Mock a Read tool without evaluateToolCallPolicy
const mockReadTool = {
name: "Read",
displayName: "Read",
description: "Read files",
parameters: {},
isBuiltIn: true,
run: vi.fn(),
// No evaluateToolCallPolicy
};
vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([
mockReadTool,
mockBashTool,
]);
const permissions: ToolPermissions = {
policies: [{ tool: "Read", permission: "allow" }],
};
const result = checkToolPermission(
{ name: "Read", arguments: { path: "/tmp/file.txt" } },
permissions,
);
expect(result.permission).toBe("allow");
expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled();
});
it("should use default 'ask' when no policy matches", () => {
const permissions: ToolPermissions = {
policies: [],
};
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithPermission",
);
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "echo test" } },
permissions,
);
expect(result.permission).toBe("ask"); // Default fallback, user preference wins
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithPermission", // converted from default "ask"
{ command: "echo test" },
);
});
it("should handle null/undefined arguments gracefully", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithPermission",
);
const permissions: ToolPermissions = {
policies: [{ tool: "Bash", permission: "allow" }],
};
const result = checkToolPermission(
{ name: "Bash", arguments: {} },
permissions,
);
expect(result.permission).toBe("allow");
expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
"allowedWithoutPermission",
{},
);
});
it("should maintain matched policy information", () => {
mockBashTool.evaluateToolCallPolicy.mockReturnValue(
"allowedWithoutPermission",
);
const policy = { tool: "Bash", permission: "allow" as const };
const permissions: ToolPermissions = {
policies: [policy],
};
const result = checkToolPermission(
{ name: "Bash", arguments: { command: "ls" } },
permissions,
);
expect(result.matchedPolicy).toBe(policy);
});
});
});
});

View file

@ -1,10 +1,14 @@
import type { ToolPolicy } from "@continuedev/terminal-security";
import { getServiceSync } from "../services/index.js";
import type { ToolPermissionServiceState } from "../services/types.js";
import { SERVICE_NAMES } from "../services/types.js";
import { getAllBuiltinTools } from "../tools/index.js";
import { DEFAULT_TOOL_POLICIES } from "./defaultPolicies.js";
import {
PermissionCheckResult,
PermissionPolicy,
ToolCallRequest,
ToolPermissions,
} from "./types.js";
@ -103,6 +107,24 @@ export function matchesArguments(
return true;
}
/**
* Converts CLI's PermissionPolicy to core's ToolPolicy
*/
function permissionPolicyToToolPolicy(
permission: PermissionPolicy,
): ToolPolicy {
switch (permission) {
case "allow":
return "allowedWithoutPermission";
case "ask":
return "allowedWithPermission";
case "exclude":
return "disabled";
default:
return "allowedWithPermission";
}
}
/**
* Evaluates a tool call request against a set of permission policies.
* Returns the permission for the first matching policy.
@ -129,21 +151,54 @@ export function checkToolPermission(
}
}
// First, get the base permission from static policies
let basePermission: PermissionPolicy = "ask";
let matchedPolicy = undefined;
for (const policy of policies) {
if (
matchesToolPattern(toolCall.name, policy.tool, toolCall.arguments) &&
matchesArguments(toolCall.arguments, policy.argumentMatches)
) {
return {
permission: policy.permission,
matchedPolicy: policy,
};
basePermission = policy.permission;
matchedPolicy = policy;
break;
}
}
// Fallback to "ask" if no policy matches
// Check if tool has dynamic policy evaluation
const builtinTools = getAllBuiltinTools();
const tool = builtinTools.find((t) => t.name === toolCall.name);
if (tool?.evaluateToolCallPolicy) {
// Convert CLI permission to core policy
const basePolicy = permissionPolicyToToolPolicy(basePermission);
// Evaluate the dynamic policy
const evaluatedPolicy = tool.evaluateToolCallPolicy(
basePolicy,
toolCall.arguments,
);
// If dynamic evaluation says disabled, that ALWAYS takes precedence
if (evaluatedPolicy === "disabled") {
return {
permission: "exclude",
matchedPolicy,
};
}
// Otherwise, user preference wins - return the original base permission
return {
permission: basePermission,
matchedPolicy,
};
}
// No dynamic evaluation, return static result
return {
permission: "ask",
permission: basePermission,
matchedPolicy,
};
}

View file

@ -28,6 +28,7 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
` ${chalk.cyan("Enter")} Submit message`,
` ${chalk.cyan("Shift+Enter")} New line`,
` ${chalk.cyan("\\")} Line continuation (at end of line)`,
` ${chalk.cyan("!")} Shell mode - run shell commands`,
"",
chalk.white("Controls:"),
` ${chalk.cyan("Ctrl+C")} Clear input`,
@ -39,9 +40,11 @@ async function handleHelp(_args: string[], _assistant: AssistantConfig) {
chalk.white("Special Characters:"),
` ${chalk.cyan("@")} Search and attach files for context`,
` ${chalk.cyan("/")} Access slash commands`,
` ${chalk.cyan("!")} Execute bash commands directly`,
"",
chalk.white("Available Commands:"),
` Type ${chalk.cyan("/")} to see available slash commands`,
` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
].join("\n");
posthogService.capture("useSlashCommand", { name: "help" });
return { output: helpMessage };

View file

@ -25,11 +25,17 @@ export function handlePermissionDenied(
toolCall: PreprocessedToolCall,
chatHistoryEntries: ChatCompletionToolMessageParam[],
callbacks?: StreamCallbacks,
reason: "user" | "policy" = "user",
): void {
const deniedMessage = `Permission denied by user`;
const deniedMessage =
reason === "policy"
? `Command blocked by security policy`
: `Permission denied by user`;
logger.info("Tool call denied", {
name: toolCall.name,
arguments: toolCall.arguments,
reason,
});
chatHistoryEntries.push({
@ -39,7 +45,7 @@ export function handlePermissionDenied(
});
callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled");
logger.debug("Tool call rejected - stopping stream");
logger.debug(`Tool call rejected (${reason}) - stopping stream`);
}
// Helper function to handle headless mode permission
@ -114,22 +120,25 @@ export async function checkToolPermissionApproval(
toolCall: PreprocessedToolCall,
callbacks?: StreamCallbacks,
isHeadless?: boolean,
): Promise<boolean> {
): Promise<{ approved: boolean; denialReason?: "user" | "policy" }> {
const permissionCheck = checkToolPermission(toolCall);
if (permissionCheck.permission === "allow") {
return true;
return { approved: true };
} else if (permissionCheck.permission === "ask") {
if (isHeadless) {
handleHeadlessPermission(toolCall);
}
return await requestUserPermission(toolCall, callbacks);
const userApproved = await requestUserPermission(toolCall, callbacks);
return userApproved
? { approved: true }
: { approved: false, denialReason: "user" };
} else if (permissionCheck.permission === "exclude") {
// This shouldn't happen as excluded tools are filtered out earlier
return false;
// Tool blocked by security policy
return { approved: false, denialReason: "policy" };
}
return false;
return { approved: false, denialReason: "policy" };
}
// Helper function to track first token time
@ -401,18 +410,25 @@ export async function executeStreamedToolCalls(
// Notify tool start before permission check to display in UI fallbacks
callbacks?.onToolStart?.(call.name, call.arguments);
const approved = await checkToolPermissionApproval(
// Check tool permissions using helper
const permissionResult = await checkToolPermissionApproval(
call,
callbacks,
isHeadless,
);
if (!approved) {
if (!permissionResult.approved) {
// Permission denied: record and mark rejection
const denialReason = permissionResult.denialReason || "user";
const deniedMessage =
denialReason === "policy"
? `Command blocked by security policy`
: `Permission denied by user`;
const deniedEntry: ChatCompletionToolMessageParam = {
role: "tool",
tool_call_id: call.id,
content: `Permission denied by user`,
content: deniedMessage,
};
entriesByIndex.set(index, deniedEntry);
callbacks?.onToolResult?.(

View file

@ -176,6 +176,13 @@ export async function constructSystemMessage(
if (currentMode === "plan") {
systemMessage +=
'\n<context name="planMode">You are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.</context>\n';
} else {
// TODO - make including this coauthor commit configurable
systemMessage += `\n<context name="commitSignature">When creating commits using any CLI or tool, include the following in the commit message:
Generated with [Continue](https://continue.dev)
Co-Authored-By: Continue <noreply@continue.dev>
</context>\n`;
}
// In headless mode, add instructions to be concise and only provide final answers

View file

@ -1,3 +1,4 @@
import dns from "dns/promises";
import os from "node:os";
import node_machine_id from "node-machine-id";
@ -15,13 +16,36 @@ export class PosthogService {
this.uniqueId = this.getEventUserId();
}
private _hasInternetConnection: boolean | undefined = undefined;
private async hasInternetConnection() {
const refetchConnection = async () => {
try {
await dns.lookup("app.posthog.com");
this._hasInternetConnection = true;
} catch {
this._hasInternetConnection = false;
}
};
if (typeof this._hasInternetConnection !== "undefined") {
void refetchConnection(); // check in background if connection became available
return this._hasInternetConnection;
}
await refetchConnection();
return this._hasInternetConnection;
}
get isEnabled() {
return process.env.CONTINUE_CLI_ENABLE_TELEMETRY !== "0";
}
private _client: PostHogType | undefined;
private async getClient() {
if (this.isEnabled) {
if (!(await this.hasInternetConnection())) {
this._client = undefined;
logger.warn("No internet connection, skipping telemetry");
} else if (this.isEnabled) {
if (!this._client) {
const { PostHog } = await import("posthog-node");
this._client = new PostHog(
@ -30,6 +54,7 @@ export class PosthogService {
host: "https://app.posthog.com",
},
);
logger.debug("Initialized telemetry");
}
} else {
this._client = undefined;
@ -83,7 +108,13 @@ export class PosthogService {
try {
const client = await this.getClient();
if (client) {
await client.shutdown();
// Set a timeout for shutdown to prevent hanging
const shutdownPromise = client.shutdown();
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Shutdown timeout")), 5000),
);
await Promise.race([shutdownPromise, timeoutPromise]);
}
} catch (e) {
logger.debug(`Failed to shutdown PostHog client: ${e}`);

View file

@ -1,8 +1,9 @@
import * as fs from "fs";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { editTool, markFileAsRead, readFilesSet } from "./edit.js";
import { editTool } from "./edit.js";
import { markFileAsRead, readFilesSet } from "./readFile.js";
// Mock the dependencies
vi.mock("../telemetry/telemetryService.js");
@ -21,6 +22,7 @@ vi.mock("fs", async () => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
unlinkSync: vi.fn(),
realpathSync: vi.fn(),
};
});
@ -34,6 +36,7 @@ describe("editTool", () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
});
afterEach(() => {
@ -126,7 +129,7 @@ describe("editTool", () => {
const result = await editTool.preprocess!(args);
expect(result.args).toEqual({
file_path: testFilePath,
resolvedPath: testFilePath,
newContent: "Hi there\nThis is a test file\nGoodbye world",
oldContent: originalContent,
});
@ -163,7 +166,7 @@ describe("editTool", () => {
it("should successfully write file and return success message", async () => {
const newContent = "Hi there\nThis is a test file\nGoodbye world";
const args = {
file_path: testFilePath,
resolvedPath: testFilePath,
newContent,
oldContent: originalContent,
};
@ -186,7 +189,7 @@ describe("editTool", () => {
});
const args = {
file_path: testFilePath,
resolvedPath: testFilePath,
newContent: "new content",
oldContent: originalContent,
};

View file

@ -8,6 +8,7 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
@ -18,40 +19,23 @@ export interface EditArgs {
replace_all?: boolean;
}
// Track files that have been read in the current session
export const readFilesSet = new Set<string>();
export const editTool: Tool = {
name: "Edit",
displayName: "Edit",
readonly: false,
isBuiltIn: true,
description: `Performs exact string replacements in files.
description: `Performs exact string replacements in a file.
USAGE:
- ALWAYS use the \`${readFileTool.name}\` tool just before making edits, to understand the file's up-to-date contents and context.
- When editing text from ${readFileTool.name} tool output, ensure you preserve exact whitespace/indentation.
- Always prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use \`replace_all\` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable, for instance.
Usage:
- You must use your \`Read\` tool at least once in the conversation before
editing. This tool will error if you attempt an edit without reading the file.
- When editing text from Read tool output, ensure you preserve the exact
indentation (tabs/spaces) as it appears AFTER the line number prefix. The line
number prefix format is: spaces + line number + tab. Everything after that tab
is the actual file content to match. Never include any part of the line number
prefix in the old_string or new_string.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files
unless explicitly required.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- The edit will FAIL if \`old_string\` is not unique in the file. Either provide
a larger string with more surrounding context to make it unique or use
\`replace_all\` to change every instance of \`old_string\`.
- Use \`replace_all\` for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.`,
WARNINGS:
- When not using \`replace_all\`, the edit will FAIL if \`old_string\` is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use \`replace_all\` to change every instance of \`old_string\`.
- The edit will FAIL if you have not recently used the \`${readFileTool.name}\` tool to view up-to-date file contents.`,
parameters: {
file_path: {
type: "string",
@ -60,13 +44,14 @@ parameter is useful if you want to rename a variable for instance.`,
},
old_string: {
type: "string",
description: "The text to replace",
description:
"The text to replace - must be exact including whitespace/indentation",
required: true,
},
new_string: {
type: "string",
description:
"The text to replace it with (must be different from old_string)",
"The text to replace it with (MUST be different from old_string)",
required: true,
},
replace_all: {
@ -82,18 +67,12 @@ parameter is useful if you want to rename a variable for instance.`,
new_string,
replace_all = false,
} = args as EditArgs;
throwIfFileIsSecurityConcern(file_path);
// Check if file has been read
if (!readFilesSet.has(file_path)) {
throw new Error(
`You must use the Read tool to read ${file_path} before editing it.`,
);
}
// Validate arguments
if (!file_path) {
throw new Error("file_path is required");
}
if (!old_string) {
throw new Error("old_string is required");
}
@ -104,13 +83,24 @@ parameter is useful if you want to rename a variable for instance.`,
throw new Error("old_string and new_string must be different");
}
const resolvedPath = fs.realpathSync(file_path);
// Check if file has been read
if (!readFilesSet.has(resolvedPath)) {
throw new Error(
`You must use the ${readFileTool.name} tool to read ${file_path} before editing it.`,
);
}
throwIfFileIsSecurityConcern(resolvedPath);
// Check if file exists
if (!fs.existsSync(file_path)) {
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File ${file_path} does not exist`);
}
// Read current file content
const oldContent = fs.readFileSync(file_path, "utf-8");
const oldContent = fs.readFileSync(resolvedPath, "utf-8");
// Check if old_string exists in the file
if (!oldContent.includes(old_string)) {
@ -134,11 +124,11 @@ parameter is useful if you want to rename a variable for instance.`,
}
// Generate diff for preview
const diff = generateDiff(oldContent, newContent, file_path);
const diff = generateDiff(oldContent, newContent, resolvedPath);
return {
args: {
file_path,
resolvedPath,
newContent,
oldContent,
},
@ -155,19 +145,19 @@ parameter is useful if you want to rename a variable for instance.`,
};
},
run: async (args: {
file_path: string;
resolvedPath: string;
newContent: string;
oldContent: string;
}) => {
try {
fs.writeFileSync(args.file_path, args.newContent, "utf-8");
fs.writeFileSync(args.resolvedPath, args.newContent, "utf-8");
// Get lines for telemetry
const { added, removed } = calculateLinesOfCodeDiff(
args.oldContent,
args.newContent,
);
const language = getLanguageFromFilePath(args.file_path);
const language = getLanguageFromFilePath(args.resolvedPath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
@ -184,21 +174,16 @@ parameter is useful if you want to rename a variable for instance.`,
const diff = generateDiff(
args.oldContent,
args.newContent,
args.file_path,
args.resolvedPath,
);
return `Successfully edited ${args.file_path}\nDiff:\n${diff}`;
return `Successfully edited ${args.resolvedPath}\nDiff:\n${diff}`;
} catch (error) {
throw new Error(
`Error: failed to edit ${args.file_path}: ${
`Error: failed to edit ${args.resolvedPath}: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
},
};
// Function to mark a file as read (to be called from the read tool)
export function markFileAsRead(filePath: string) {
readFilesSet.add(filePath);
}

View file

@ -1,9 +1,10 @@
import * as fs from "fs";
import * as path from "path";
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { multiEditTool, markFileAsRead } from "./multiEdit.js";
import { multiEditTool } from "./multiEdit.js";
import { markFileAsRead } from "./readFile.js";
// Mock the dependencies
vi.mock("../telemetry/telemetryService.js");
@ -22,6 +23,7 @@ vi.mock("fs", async () => {
readFileSync: vi.fn(),
writeFileSync: vi.fn(),
unlinkSync: vi.fn(),
realpathSync: vi.fn(),
};
});
@ -35,6 +37,7 @@ describe("multiEditTool", () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
vi.mocked(fs.writeFileSync).mockImplementation(() => {});
vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
});
afterEach(() => {

View file

@ -9,12 +9,11 @@ import {
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { markFileAsRead, readFilesSet } from "./edit.js";
import { editTool } from "./edit.js";
import { readFilesSet, readFileTool } from "./readFile.js";
import { Tool } from "./types.js";
import { generateDiff } from "./writeFile.js";
export { markFileAsRead };
export interface EditOperation {
old_string: string;
new_string: string;
@ -26,15 +25,10 @@ export interface MultiEditArgs {
edits: EditOperation[];
}
// Function to check if file has been read (shared with edit tool)
function hasFileBeenRead(filePath: string): boolean {
return readFilesSet.has(filePath);
}
// Helper functions for multiEdit validation
function validateMultiEditArgs(args: any): {
original_path: string;
file_path: string;
resolved_path: string;
edits: EditOperation[];
} {
const { file_path, edits } = args as MultiEditArgs;
@ -53,7 +47,9 @@ function validateMultiEditArgs(args: any): {
? file_path
: path.resolve(process.cwd(), file_path);
return { original_path: file_path, file_path: absolutePath, edits };
const resolvedPath = fs.realpathSync(absolutePath);
return { original_path: file_path, resolved_path: resolvedPath, edits };
}
function validateEdits(edits: EditOperation[]): void {
@ -74,26 +70,25 @@ function validateEdits(edits: EditOperation[]): void {
}
function validateFileAccess(
original_path: string,
file_path: string,
resolvedPath: string,
isCreatingNewFile: boolean,
): void {
if (isCreatingNewFile) {
// For new file creation, check if parent directory exists
const parentDir = path.dirname(file_path);
const parentDir = path.dirname(resolvedPath);
if (parentDir && !fs.existsSync(parentDir)) {
throw new Error(`Parent directory does not exist: ${parentDir}`);
}
} else {
// For existing files, check if file has been read
// Check with the original path first, then with absolute path
if (!hasFileBeenRead(original_path) && !hasFileBeenRead(file_path)) {
if (!readFilesSet.has(resolvedPath)) {
throw new Error(
`You must use the Read tool to read ${original_path} before editing it.`,
`You must use the ${readFileTool.name} tool to read ${resolvedPath} before editing it.`,
);
}
if (!fs.existsSync(file_path)) {
throw new Error(`File ${file_path} does not exist`);
if (!fs.existsSync(resolvedPath)) {
throw new Error(`File ${resolvedPath} does not exist`);
}
}
}
@ -138,87 +133,42 @@ export const multiEditTool: Tool = {
displayName: "MultiEdit",
readonly: false,
isBuiltIn: true,
description: `This is a tool for making multiple edits to a single file in one operation. It
is built on top of the Edit tool and allows you to perform multiple
find-and-replace operations efficiently. Prefer this tool over the Edit tool
when you need to make multiple edits to the same file.
Before using this tool:
1. Use the Read tool to understand the file's contents and context
2. Verify the directory path is correct
To make multiple file edits, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not
relative)
description: `This is a tool for making multiple edits to a single file in one operation. It is built on top of the ${editTool.name} tool and allows you to perform multiple find-and-replace operations efficiently.
Prefer this tool over the ${editTool.name} tool when you need to make multiple edits to the same file.
To make multiple edits to a file, provide the following:
1. file_path: The absolute path to the file to modify (must be absolute, not relative)
2. edits: An array of edit operations to perform, where each edit contains:
- old_string: The text to replace (must match the file contents exactly, including all whitespace and indentation)
- old_string: The text to replace (must match the file contents exactly, including all whitespace/indentation)
- new_string: The edited text to replace the old_string
- replace_all: Replace all occurences of old_string. This parameter is optional and defaults to false.
IMPORTANT:
- All edits are applied in sequence, in the order they are provided
- Each edit operates on the result of the previous edit
- All edits must be valid for the operation to succeed - if any edit fails,
none will be applied
- This tool is ideal when you need to make several changes to different parts
of the same file
- For Jupyter notebooks (.ipynb files), use the NotebookEdit instead
- Each edit operates on the result of the previous edit, so plan your edits carefully to avoid conflicts between sequential operations
- Edits are atomic - all edits must be valid for the operation to succeed - if any edit fails, none will be applied
- This tool is ideal when you need to make several changes to different parts of the same file
CRITICAL REQUIREMENTS:
1. All edits follow the same requirements as the single Edit tool
2. The edits are atomic - either all succeed or none are applied
3. Plan your edits carefully to avoid conflicts between sequential operations
WARNING:
- The tool will fail if edits.old_string doesn't match the file contents
exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same
- Since edits are applied in sequence, ensure that earlier edits don't affect
the text that later edits are trying to find
When making edits:
1. ALWAYS use the ${readFileTool.name} tool just before making edits, to understand the file's up-to-date contents and context
2. When making edits:
- Ensure all edits result in idiomatic, correct code
- Do not leave the code in a broken state
- Always use absolute file paths (starting with /)
- Only use emojis if the user explicitly requests it. Avoid adding emojis to
files unless asked.
- Use replace_all for replacing and renaming strings across the file. This
parameter is useful if you want to rename a variable for instance.
- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.
- Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.
If you want to create a new file, use:
- A new file path, including dir name if needed
- A new file path, including new directory if needed
- First edit: empty old_string and the new file's contents as new_string
- Subsequent edits: normal edit operations on the created content
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required
- Subsequent edits: normal edit operations on the created content`,
WARNINGS:
- If earlier edits affect the text that later edits are trying to find, files can become mangled
- The tool will fail if edits.old_string doesn't match the file contents exactly (including whitespace)
- The tool will fail if edits.old_string and edits.new_string are the same - they MUST be different
- The tool will fail if you have not used the ${readFileTool.name} tool to read the file in this session`,
parameters: {
file_path: {
type: "string",
@ -237,9 +187,9 @@ If you want to create a new file, use:
},
preprocess: async (args) => {
// Validate and extract arguments
const { original_path, file_path, edits } = validateMultiEditArgs(args);
const { resolved_path, edits } = validateMultiEditArgs(args);
throwIfFileIsSecurityConcern(file_path);
throwIfFileIsSecurityConcern(resolved_path);
// Validate each edit operation
validateEdits(edits);
@ -248,12 +198,12 @@ If you want to create a new file, use:
const isCreatingNewFile = edits[0].old_string === "";
// Validate file access
validateFileAccess(original_path, file_path, isCreatingNewFile);
validateFileAccess(resolved_path, isCreatingNewFile);
// Read current file content (or start with empty for new files)
let currentContent = "";
if (!isCreatingNewFile) {
currentContent = fs.readFileSync(file_path, "utf-8");
currentContent = fs.readFileSync(resolved_path, "utf-8");
}
const originalContent = currentContent;
@ -266,11 +216,11 @@ If you want to create a new file, use:
}
// Generate diff for preview
const diff = generateDiff(originalContent, newContent, file_path);
const diff = generateDiff(originalContent, newContent, resolved_path);
return {
args: {
file_path,
file_path: resolved_path,
newContent,
originalContent,
isCreatingNewFile,
@ -279,7 +229,7 @@ If you want to create a new file, use:
preview: [
{
type: "text",
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${file_path}:`,
content: `Will apply ${edits.length} edit${edits.length === 1 ? "" : "s"} to ${isCreatingNewFile ? "create" : "modify"} ${resolved_path}:`,
},
{
type: "diff",

View file

@ -2,10 +2,15 @@ import * as fs from "fs";
import { throwIfFileIsSecurityConcern } from "core/indexing/ignore.js";
import { markFileAsRead } from "./edit.js";
import { formatToolArgument } from "./formatters.js";
import { Tool } from "./types.js";
// Track files that have been read in the current session
export const readFilesSet = new Set<string>();
export function markFileAsRead(filePath: string) {
readFilesSet.add(filePath);
}
export const readFileTool: Tool = {
name: "Read",
displayName: "Read",
@ -20,13 +25,17 @@ export const readFileTool: Tool = {
readonly: true,
isBuiltIn: true,
preprocess: async (args) => {
throwIfFileIsSecurityConcern(args.filepath);
let { filepath } = args;
if (filepath.startsWith("./")) {
filepath = filepath.slice(2);
}
throwIfFileIsSecurityConcern(filepath);
return {
args,
preview: [
{
type: "text",
content: `Will read ${formatToolArgument(args.filepath)}`,
content: `Will read ${formatToolArgument(filepath)}`,
},
],
};
@ -41,9 +50,10 @@ export const readFileTool: Tool = {
if (!fs.existsSync(filepath)) {
return `Error: File does not exist: ${filepath}`;
}
const content = fs.readFileSync(filepath, "utf-8");
const realPath = fs.realpathSync(filepath);
const content = fs.readFileSync(realPath, "utf-8");
// Mark this file as read for the edit tool
markFileAsRead(filepath);
markFileAsRead(realPath);
const lines = content.split("\n");
if (lines.length > 5000) {

View file

@ -1,5 +1,10 @@
import { spawn } from "child_process";
import {
evaluateTerminalCommandSecurity,
type ToolPolicy,
} from "@continuedev/terminal-security";
import { telemetryService } from "../telemetry/telemetryService.js";
import {
isGitCommitCommand,
@ -28,7 +33,7 @@ export const runTerminalCommandTool: Tool = {
displayName: "Bash",
description: `Executes a terminal command and returns the output
The command will be executed from the current working directory: ${process.cwd()}
Commands are automatically executed from the current working directory (${process.cwd()}), so there's no need to change directories with 'cd' commands.
`,
parameters: {
command: {
@ -39,6 +44,15 @@ The command will be executed from the current working directory: ${process.cwd()
},
readonly: false,
isBuiltIn: true,
evaluateToolCallPolicy: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
): ToolPolicy => {
return evaluateTerminalCommandSecurity(
basePolicy,
parsedArgs.command as string,
);
},
preprocess: async (args) => {
const command = args.command;
if (!command || typeof command !== "string") {

View file

@ -1,3 +1,5 @@
import type { ToolPolicy } from "@continuedev/terminal-security";
export type ToolParameters = Record<
string,
{
@ -31,6 +33,10 @@ export interface Tool {
run: (args: any) => Promise<string>;
readonly?: boolean; // Indicates if the tool is readonly
isBuiltIn: boolean;
evaluateToolCallPolicy?: (
basePolicy: ToolPolicy,
parsedArgs: Record<string, unknown>,
) => ToolPolicy;
}
export interface ToolCall {

View file

@ -20,6 +20,77 @@ import {
import { SlashCommandUI } from "./SlashCommandUI.js";
import { TextBuffer } from "./TextBuffer.js";
// Small presentational helpers to reduce cyclomatic complexity in UserInput
const InterruptedBanner: React.FC<{ wasInterrupted: boolean }> = ({
wasInterrupted,
}) => {
if (!wasInterrupted) return null;
return (
<Box paddingX={1} marginBottom={0}>
<Text color="yellow">⚠ Interrupted by user - Press enter to resume</Text>
</Box>
);
};
const SlashCommandsMaybe: React.FC<{
show: boolean;
inputMode: boolean;
hideNormalUI: boolean;
isRemoteMode: boolean;
assistant?: AssistantConfig;
filter: string;
selectedIndex: number;
}> = ({
show,
inputMode,
hideNormalUI,
isRemoteMode,
assistant,
filter,
selectedIndex,
}) => {
if (!show || !inputMode || hideNormalUI || !(isRemoteMode || assistant))
return null;
return (
<SlashCommandUI
assistant={assistant}
filter={filter}
selectedIndex={selectedIndex}
isRemoteMode={isRemoteMode}
/>
);
};
const FileSearchMaybe: React.FC<{
show: boolean;
inputMode: boolean;
hideNormalUI: boolean;
isRemoteMode: boolean;
filter: string;
selectedIndex: number;
onSelect: (path: string) => void | Promise<void>;
onFilesUpdated: (files: Array<{ path: string; displayName: string }>) => void;
}> = ({
show,
inputMode,
hideNormalUI,
isRemoteMode,
filter,
selectedIndex,
onSelect,
onFilesUpdated,
}) => {
if (!show || !inputMode || hideNormalUI || isRemoteMode) return null;
return (
<FileSearchUI
filter={filter}
selectedIndex={selectedIndex}
onSelect={onSelect}
onFilesUpdated={onFilesUpdated}
/>
);
};
interface UserInputProps {
onSubmit: (message: string, imageMap?: Map<string, Buffer>) => void;
isWaitingForResponse: boolean;
@ -78,10 +149,13 @@ const UserInput: React.FC<UserInputProps> = ({
setCursorPosition(0);
setShowSlashCommands(false);
setShowFileSearch(false);
setShowBashMode(false);
inputHistory.resetNavigation();
}, [textBuffer]);
const [slashCommandFilter, setSlashCommandFilter] = useState("");
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0);
const [showBashMode, setShowBashMode] = useState(false);
const [showFileSearch, setShowFileSearch] = useState(false);
const [fileSearchFilter, setFileSearchFilter] = useState("");
const [selectedFileIndex, setSelectedFileIndex] = useState(0);
@ -131,6 +205,18 @@ const UserInput: React.FC<UserInputProps> = ({
return nextMode;
};
// Update shell mode state based on input
const updateBashModeState = (text: string) => {
const trimmed = text.trimStart();
const isBash = trimmed.startsWith("!");
setShowBashMode(isBash);
if (isBash) {
// Disable other helpers while in shell mode
setShowSlashCommands(false);
setShowFileSearch(false);
}
};
// Update slash command UI state based on input
const updateSlashCommandState = (text: string, cursor: number) => {
// Only show slash commands if slash is the very first character
@ -139,6 +225,9 @@ const UserInput: React.FC<UserInputProps> = ({
return;
}
// When using slash commands, disable file search
setShowFileSearch(false);
const trimmedText = text.trimStart();
const beforeCursor = trimmedText.slice(
0,
@ -196,6 +285,13 @@ const UserInput: React.FC<UserInputProps> = ({
return;
}
// Disable file search if we're in shell mode or slash command mode
const trimmed = text.trimStart();
if (trimmed.startsWith("!") || trimmed.startsWith("/")) {
setShowFileSearch(false);
return;
}
// Check if we're in a file search context
const beforeCursor = text.slice(0, cursor);
const lastAtIndex = beforeCursor.lastIndexOf("@");
@ -234,6 +330,7 @@ const UserInput: React.FC<UserInputProps> = ({
setFileSearchFilter(afterAt);
setSelectedFileIndex(0);
setShowSlashCommands(false);
setShowBashMode(false);
}
}
};
@ -278,6 +375,7 @@ const UserInput: React.FC<UserInputProps> = ({
setInputText(newText);
setCursorPosition(newCursorPos);
setShowSlashCommands(false);
setShowBashMode(false);
}
};
@ -437,6 +535,7 @@ const UserInput: React.FC<UserInputProps> = ({
setInputText("");
setCursorPosition(0);
setShowSlashCommands(false);
setShowBashMode(false);
}
return true;
}
@ -462,6 +561,15 @@ const UserInput: React.FC<UserInputProps> = ({
const handleEscapeKey = (key: any): boolean => {
if (!key.escape) return false;
// If only "!" is present, clear shell mode
if (inputMode && showBashMode && inputText.trim() === "!") {
textBuffer.clear();
setInputText("");
setCursorPosition(0);
setShowBashMode(false);
return true;
}
// Handle escape key to interrupt streaming
if (isWaitingForResponse && onInterrupt) {
onInterrupt();
@ -491,6 +599,7 @@ const UserInput: React.FC<UserInputProps> = ({
setCursorPosition(newCursor);
updateSlashCommandState(newText, newCursor);
updateFileSearchState(newText, newCursor);
updateBashModeState(newText);
inputHistory.resetNavigation();
};
@ -587,14 +696,16 @@ const UserInput: React.FC<UserInputProps> = ({
setCursorPosition,
updateSlashCommandState,
updateFileSearchState,
updateBashModeState,
inputHistory,
});
});
const renderInputText = () => {
const placeholderText = isRemoteMode
? "Ask anything, / for slash commands"
: placeholder || "Ask anything, @ for context, / for slash commands";
? "Ask anything, / for slash commands, ! for shell mode"
: placeholder ||
"Ask anything, @ for context, / for slash commands, ! for shell mode";
if (inputText.length === 0) {
return (
<>
@ -677,50 +788,44 @@ const UserInput: React.FC<UserInputProps> = ({
return (
<Box flexDirection="column">
{/* Interruption message - shown just above the input box */}
{wasInterrupted && (
<Box paddingX={1} marginBottom={0}>
<Text color="yellow">
⚠ Interrupted by user - Press enter to resume
</Text>
</Box>
)}
<InterruptedBanner wasInterrupted={!!wasInterrupted} />
{/* Input box */}
<Box
borderStyle="round"
borderTop={true}
paddingX={1}
borderColor={isRemoteMode ? "cyan" : "gray"}
borderColor={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "gray"}
>
<Text color={isRemoteMode ? "cyan" : "blue"} bold>
{isRemoteMode ? "◉" : "●"}{" "}
<Text
color={showBashMode ? "yellow" : isRemoteMode ? "cyan" : "blue"}
bold
>
{showBashMode ? "$ " : isRemoteMode ? "◉ " : "● "}
</Text>
{renderInputText()}
</Box>
{/* Slash command UI - show in remote mode OR when assistant is available */}
{showSlashCommands &&
inputMode &&
!hideNormalUI &&
(isRemoteMode || assistant) && (
<SlashCommandUI
assistant={assistant}
filter={slashCommandFilter}
selectedIndex={selectedCommandIndex}
isRemoteMode={isRemoteMode}
/>
)}
<SlashCommandsMaybe
show={showSlashCommands}
inputMode={inputMode}
hideNormalUI={!!hideNormalUI}
isRemoteMode={!!isRemoteMode}
assistant={assistant}
filter={slashCommandFilter}
selectedIndex={selectedCommandIndex}
/>
{/* File search UI - only show in local mode */}
{showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && (
<FileSearchUI
filter={fileSearchFilter}
selectedIndex={selectedFileIndex}
onSelect={selectFile}
onFilesUpdated={setCurrentFiles}
/>
)}
<FileSearchMaybe
show={showFileSearch}
inputMode={inputMode}
hideNormalUI={!!hideNormalUI}
isRemoteMode={!!isRemoteMode}
filter={fileSearchFilter}
selectedIndex={selectedFileIndex}
onSelect={selectFile}
onFilesUpdated={setCurrentFiles}
/>
</Box>
);
};

View file

@ -140,6 +140,7 @@ export const ScreenContent: React.FC<ScreenContentProps> = ({
toolArgs={activePermissionRequest.toolArgs}
requestId={activePermissionRequest.requestId}
toolCallPreview={activePermissionRequest.toolCallPreview}
hasDynamicEvaluation={activePermissionRequest.hasDynamicEvaluation}
onResponse={handleToolPermissionResponse}
/>
);

View file

@ -74,14 +74,12 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
}, [chatHistory]);
// Split chat history into stable and pending items
// Only put items in pending if they contain tool calls with "calling" status
// Everything else goes into static content
// The last two items may have pending tool calls
const { staticItems, pendingItems } = React.useMemo(() => {
const items: React.ReactElement[] = [];
// Add intro message as first item if it should be shown
const staticItems: React.ReactElement[] = [];
if (showIntroMessage) {
items.push(
staticItems.push(
<IntroMessage
key="intro"
config={config}
@ -91,48 +89,27 @@ export const StaticChatContent: React.FC<StaticChatContentProps> = ({
);
}
// Helper function to check if an item has pending tool calls
const hasPendingToolCalls = (item: ChatHistoryItem): boolean => {
return !!(
item.toolCallStates &&
item.toolCallStates.some(
(toolState) =>
toolState.status === "calling" ||
toolState.status === "generating" ||
toolState.status === "generated",
)
);
};
// Find the first message with pending tool calls from the end
let pendingStartIndex = filteredChatHistory.length;
for (let i = filteredChatHistory.length - 1; i >= 0; i--) {
if (hasPendingToolCalls(filteredChatHistory[i])) {
pendingStartIndex = i;
// If there's a message after this one, include it too as it might be related
if (i + 1 < filteredChatHistory.length) {
// Keep the pending start index as is, so we include the next message
}
break;
}
}
const stableHistory = filteredChatHistory.slice(0, pendingStartIndex);
const pendingHistory = filteredChatHistory.slice(pendingStartIndex);
const PENDING_ITEMS_COUNT = 2;
const stableCount = Math.max(
0,
filteredChatHistory.length - PENDING_ITEMS_COUNT,
);
const stableHistory = filteredChatHistory.slice(0, stableCount);
const pendingHistory = filteredChatHistory.slice(stableCount);
// Add stable messages to static items
stableHistory.forEach((item, index) => {
items.push(renderMessage(item, index));
staticItems.push(renderMessage(item, index));
});
// Pending items will be rendered dynamically outside Static
const pendingElements = pendingHistory.map((item, index) =>
renderMessage(item, pendingStartIndex + index),
const pendingItems = pendingHistory.map((item, index) =>
renderMessage(item, stableCount + index),
);
return {
staticItems: items,
pendingItems: pendingElements,
staticItems,
pendingItems,
};
}, [
showIntroMessage,

View file

@ -22,6 +22,7 @@ interface ToolPermissionSelectorProps {
toolArgs: any;
requestId: string;
toolCallPreview?: ToolCallPreview[];
hasDynamicEvaluation?: boolean;
onResponse: (
requestId: string,
approved: boolean,
@ -30,36 +31,40 @@ interface ToolPermissionSelectorProps {
) => void;
}
const PERMISSION_OPTIONS: PermissionOption[] = [
{ id: "approve", name: "Continue", color: "green", approved: true },
{
id: "approve_policy",
name: "Continue + don't ask again",
color: "cyan",
approved: true,
createPolicy: true,
},
{
id: "deny_stop",
name: "No, and tell Continue what to do differently",
color: "yellow",
approved: false,
stopStream: true,
},
];
const getPermissionOptions = (): PermissionOption[] => {
return [
{ id: "approve", name: "Continue", color: "green", approved: true },
{
id: "approve_policy",
name: "Continue + don't ask again",
color: "cyan",
approved: true,
createPolicy: true,
},
{
id: "deny_stop",
name: "No, and tell Continue what to do differently",
color: "yellow",
approved: false,
stopStream: true,
},
];
};
export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
toolName,
toolArgs,
requestId,
toolCallPreview,
hasDynamicEvaluation = false,
onResponse,
}) => {
const permissionOptions = getPermissionOptions();
const [selectedIndex, setSelectedIndex] = useState(0);
useInput((input, key) => {
if (key.return) {
const selectedOption = PERMISSION_OPTIONS[selectedIndex];
const selectedOption = permissionOptions[selectedIndex];
onResponse(
requestId,
selectedOption.approved,
@ -91,7 +96,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
setSelectedIndex(Math.max(0, selectedIndex - 1));
} else if (key.downArrow) {
setSelectedIndex(
Math.min(PERMISSION_OPTIONS.length - 1, selectedIndex + 1),
Math.min(permissionOptions.length - 1, selectedIndex + 1),
);
}
@ -120,7 +125,15 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
<Box marginTop={1} flexDirection="column">
<Text color="dim">Would you like to continue?</Text>
{PERMISSION_OPTIONS.map((option, index) => {
{hasDynamicEvaluation && (
<Box marginTop={1}>
<Text color="yellow" dimColor>
Note: Dangerous commands will be blocked regardless of your
preference.
</Text>
</Box>
)}
{permissionOptions.map((option, index) => {
const isSelected = index === selectedIndex;
let shortcut = "";
if (option.id === "approve") shortcut = "(tab)";

View file

@ -15,7 +15,6 @@ vi.mock("../../session.js", () => ({
describe("useChat clear command", () => {
let mockSetChatHistory: ReturnType<typeof vi.fn>;
let mockExit: ReturnType<typeof vi.fn>;
let mockOnClear: ReturnType<typeof vi.fn>;
beforeEach(() => {
@ -23,7 +22,6 @@ describe("useChat clear command", () => {
vi.clearAllMocks();
mockSetChatHistory = vi.fn();
mockExit = vi.fn();
mockOnClear = vi.fn();
});
@ -44,7 +42,6 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
exit: mockExit,
onShowConfigSelector: vi.fn(),
onClear: mockOnClear,
});
@ -91,7 +88,6 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
exit: mockExit,
onShowConfigSelector: vi.fn(),
// onClear is not provided
});
@ -127,7 +123,6 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
exit: mockExit,
onShowConfigSelector: vi.fn(),
onClear: mockOnClear,
});
@ -149,7 +144,6 @@ describe("useChat clear command", () => {
result,
chatHistory,
setChatHistory: mockSetChatHistory,
exit: mockExit,
onShowConfigSelector: vi.fn(),
onClear: mockOnClear,
});

View file

@ -46,7 +46,6 @@ interface ProcessSlashCommandResultOptions {
result: SlashCommandResult;
chatHistory: ChatHistoryItem[];
setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>;
exit: () => void;
onShowConfigSelector: () => void;
onShowModelSelector?: () => void;
onShowMCPSelector?: () => void;
@ -61,7 +60,6 @@ export function processSlashCommandResult({
result,
chatHistory,
setChatHistory,
exit,
onShowConfigSelector,
onShowModelSelector,
onShowMCPSelector,
@ -69,8 +67,7 @@ export function processSlashCommandResult({
onClear,
}: ProcessSlashCommandResultOptions): string | null {
if (result.exit) {
exit();
return null;
process.exit(0);
}
if (result.openMcpSelector) {

View file

@ -0,0 +1,148 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js";
import { services } from "../../services/index.js";
import { handleBashModeProcessing } from "./useChat.shellMode.js";
// Mock the runTerminalCommandTool with the correct path for the import in shellMode.ts
vi.mock("src/tools/runTerminalCommand.js", () => ({
runTerminalCommandTool: {
run: vi.fn(),
},
}));
// Mock the services
vi.mock("../../services/index.js", () => ({
services: {
chatHistory: {
addAssistantMessage: vi.fn(),
updateToolStatus: vi.fn(),
addToolResult: vi.fn(),
},
},
}));
describe("handleBashModeProcessing", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("should detect bash mode when message starts with !", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
mockRun.mockResolvedValue(
"total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..",
);
const result = await handleBashModeProcessing("!ls -la");
expect(result).toBe(null); // Processed, no further handling needed
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith(
expect.any(String),
"calling",
);
// Use vi.waitFor to wait for async operations in the void expression
await vi.waitFor(
() => {
expect(mockRun).toHaveBeenCalledWith({ command: "ls -la" });
},
{ timeout: 1000 },
);
await vi.waitFor(
() => {
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
expect.any(String),
"total 5\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 12:00 ..",
"done",
);
},
{ timeout: 1000 },
);
});
it("should handle bash command errors", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
mockRun.mockRejectedValue(new Error("Command not found"));
const result = await handleBashModeProcessing("!invalidcommand");
expect(result).toBe(null); // Processed, no further handling needed
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
expect(services.chatHistory.updateToolStatus).toHaveBeenCalledWith(
expect.any(String),
"calling",
);
// Use vi.waitFor to wait for async operations in the void expression
await vi.waitFor(
() => {
expect(mockRun).toHaveBeenCalledWith({ command: "invalidcommand" });
},
{ timeout: 1000 },
);
await vi.waitFor(
() => {
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
expect.any(String),
"Bash command failed: Command not found",
"errored",
);
},
{ timeout: 1000 },
);
});
it("should not trigger bash mode for regular messages", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
const result = await handleBashModeProcessing("Hello! How are you?");
expect(result).toBe("Hello! How are you?"); // Pass through unchanged
expect(mockRun).not.toHaveBeenCalled();
expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled();
});
it("should handle empty bash command", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
const result = await handleBashModeProcessing("!");
expect(result).toBe("!"); // Pass through unchanged for empty command
expect(mockRun).not.toHaveBeenCalled();
expect(services.chatHistory.addAssistantMessage).not.toHaveBeenCalled();
});
it("should handle bash command with leading whitespace", async () => {
const mockRun = vi.mocked(runTerminalCommandTool.run);
mockRun.mockResolvedValue("echo test output");
const result = await handleBashModeProcessing(" !echo hello");
expect(result).toBe(null); // Processed, no further handling needed
expect(services.chatHistory.addAssistantMessage).toHaveBeenCalled();
// Use vi.waitFor to wait for async operations in the void expression
await vi.waitFor(
() => {
expect(mockRun).toHaveBeenCalledWith({ command: "echo hello" });
},
{ timeout: 1000 },
);
await vi.waitFor(
() => {
expect(services.chatHistory.addToolResult).toHaveBeenCalledWith(
expect.any(String),
"echo test output",
"done",
);
},
{ timeout: 1000 },
);
});
});

View file

@ -0,0 +1,51 @@
import { runTerminalCommandTool } from "src/tools/runTerminalCommand.js";
import { getErrorString } from "src/util/error.js";
import { services } from "../../services/index.js";
export const handleBashModeProcessing = async (
message: string,
): Promise<string | null> => {
// Handle shell mode commands (starting with !)
if (!message.trimStart().startsWith("!")) {
return message;
}
// Extract the command after the !
const bashCommand = message.trimStart().slice(1).trim();
if (!bashCommand) {
return message; // No command provided, treat as regular message
}
// Show tool call immediately, then run asynchronously and populate result
const toolCallId = `shell-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
const toolCall = {
id: toolCallId,
type: "function" as const,
function: {
name: "Bash",
arguments: JSON.stringify({ command: bashCommand }),
},
};
// Add assistant message with tool call immediately
services.chatHistory.addAssistantMessage("", [toolCall]);
// Mark as calling for immediate UI feedback
services.chatHistory.updateToolStatus(toolCallId, "calling");
// Execute the bash command asynchronously - don't block UI
void runTerminalCommandTool
.run({
command: bashCommand,
})
.then((result) => {
services.chatHistory.addToolResult(toolCallId, result, "done");
})
.catch((error) => {
const errorMessage = `Bash command failed: ${getErrorString(error)}`;
services.chatHistory.addToolResult(toolCallId, errorMessage, "errored");
});
return null; // Processed, no further message handling needed
};

View file

@ -1,5 +1,6 @@
import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js";
import { getAllBuiltinTools } from "src/tools/index.js";
import { logger } from "src/util/logger.js";
import { services } from "../../services/index.js";
@ -201,11 +202,16 @@ export function createStreamCallbacks(
requestId: string,
toolCallPreview?: any[],
) => {
// Check if this tool has dynamic evaluation
const tool = getAllBuiltinTools().find((t: any) => t.name === toolName);
const hasDynamicEvaluation = !!tool?.evaluateToolCallPolicy;
setActivePermissionRequest({
toolName,
toolArgs,
requestId,
toolCallPreview,
hasDynamicEvaluation,
});
},

View file

@ -30,6 +30,7 @@ import {
handleRemoteMessage,
setupRemotePolling,
} from "./useChat.remote.helpers.js";
import { handleBashModeProcessing } from "./useChat.shellMode.js";
import {
createStreamCallbacks,
executeStreaming,
@ -369,7 +370,6 @@ export function useChat({
result: commandResult,
chatHistory,
setChatHistory,
exit,
onShowConfigSelector,
onShowModelSelector,
onShowMCPSelector,
@ -423,6 +423,13 @@ export function useChat({
if (handled) return;
// Handle shell mode commands (before slash commands)
const bashProcessedMessage = await handleBashModeProcessing(message);
if (bashProcessedMessage === null) {
return; // Bash command was handled and no further processing needed
}
message = bashProcessedMessage;
// Handle slash commands
const processedMessage = await handleSlashCommandProcessing(message);
if (processedMessage === null) {

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