diff --git a/.github/actions/run-vscode-e2e-test/action.yml b/.github/actions/run-vscode-e2e-test/action.yml index 1fcba5245..d9ac252af 100644 --- a/.github/actions/run-vscode-e2e-test/action.yml +++ b/.github/actions/run-vscode-e2e-test/action.yml @@ -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 \ No newline at end of file + path: extensions/vscode/e2e.log diff --git a/.github/workflows/auto-fix-failed-tests.yml b/.github/workflows/auto-fix-failed-tests.yml new file mode 100644 index 000000000..e11676229 --- /dev/null +++ b/.github/workflows/auto-fix-failed-tests.yml @@ -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 }}" diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.yml index 6c1a7f517..a52daa05b 100644 --- a/.github/workflows/beta-release.yml +++ b/.github/workflows/beta-release.yml @@ -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" diff --git a/.github/workflows/cli-pr-checks.yml b/.github/workflows/cli-pr-checks.yml index 43a78d06e..93922dd31 100644 --- a/.github/workflows/cli-pr-checks.yml +++ b/.github/workflows/cli-pr-checks.yml @@ -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 }} diff --git a/.github/workflows/compliance.yaml b/.github/workflows/compliance.yaml index 76c21d6b1..2a1819fa5 100644 --- a/.github/workflows/compliance.yaml +++ b/.github/workflows/compliance.yaml @@ -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" diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 23e434ff3..6ed9292b7 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -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" diff --git a/.github/workflows/label-merged-prs.yml b/.github/workflows/label-merged-prs.yml index d6f83eba8..b434d07fd 100644 --- a/.github/workflows/label-merged-prs.yml +++ b/.github/workflows/label-merged-prs.yml @@ -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; diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 785044868..8be01696a 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -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" diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 1599f525e..12ac77caf 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -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 diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 7e054eb59..fa24eb2bf 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -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" diff --git a/.github/workflows/respond-to-cubic.yaml b/.github/workflows/respond-to-cubic.yaml index f69ed0790..cb607033c 100644 --- a/.github/workflows/respond-to-cubic.yaml +++ b/.github/workflows/respond-to-cubic.yaml @@ -27,6 +27,18 @@ jobs: echo "contains_mention=false" >> $GITHUB_OUTPUT fi + - name: Add eyes reaction to comment + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForIssueComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: ${{ github.event.comment.id }}, + content: 'eyes' + }); + - name: Checkout PR branch if: steps.check-mention.outputs.contains_mention == 'true' uses: actions/checkout@v5 @@ -37,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({ @@ -57,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" @@ -95,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: @@ -130,6 +142,18 @@ jobs: echo "contains_mention=false" >> $GITHUB_OUTPUT fi + - name: Add eyes reaction to comment + if: steps.check-mention.outputs.contains_mention == 'true' + uses: actions/github-script@v8 + with: + script: | + await github.rest.reactions.createForPullRequestReviewComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: ${{ github.event.comment.id }}, + content: 'eyes' + }); + - name: Checkout PR branch if: steps.check-mention.outputs.contains_mention == 'true' uses: actions/checkout@v5 @@ -140,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" @@ -148,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 @@ -187,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: diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index 6dbd55817..5f243f6bc 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -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" diff --git a/.github/workflows/similar-issues.yml b/.github/workflows/similar-issues.yml index 9873a0585..4abf1cdd3 100644 --- a/.github/workflows/similar-issues.yml +++ b/.github/workflows/similar-issues.yml @@ -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 = []; diff --git a/.github/workflows/stable-release.yml b/.github/workflows/stable-release.yml index 6c5dd209a..b97970da2 100644 --- a/.github/workflows/stable-release.yml +++ b/.github/workflows/stable-release.yml @@ -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" diff --git a/.github/workflows/stale-issue-helper.yaml b/.github/workflows/stale-issue-helper.yaml index 067f4c60f..1309cd624 100644 --- a/.github/workflows/stale-issue-helper.yaml +++ b/.github/workflows/stale-issue-helper.yaml @@ -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." diff --git a/.github/workflows/vscode-version-bump.yml b/.github/workflows/vscode-version-bump.yml index 961fa50ba..dbf258f35 100644 --- a/.github/workflows/vscode-version-bump.yml +++ b/.github/workflows/vscode-version-bump.yml @@ -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" diff --git a/.prettierignore b/.prettierignore index 97c951ccc..51cd37d83 100644 --- a/.prettierignore +++ b/.prettierignore @@ -23,5 +23,5 @@ CHANGELOG.md **/CODEOWNERS core/vendor coverage -e2e +# e2e packages/continue-sdk \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3993294b4..21c645480 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 . diff --git a/actions/detailed-review/action.yml b/actions/detailed-review/action.yml index 97c47018f..f8273cc50 100644 --- a/actions/detailed-review/action.yml +++ b/actions/detailed-review/action.yml @@ -73,7 +73,7 @@ runs: - name: Install Continue CLI if: env.SKIP_REVIEW != 'true' shell: bash - run: npm install -g @continuedev/cli@1.4.25 + run: npm install -g @continuedev/cli@1.4.30 - name: Build Inline Review Prompt if: env.SKIP_REVIEW != 'true' @@ -194,6 +194,21 @@ runs: exit 1 fi + # Validate API key + if [ -z "$CONTINUE_API_KEY" ]; then + echo "Warning: CONTINUE_API_KEY environment variable is not set" + # Create fallback review and continue + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review skipped: CONTINUE_API_KEY not configured.", + "comments": [] + } + EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "SKIP_CLI=false" >> $GITHUB_ENV + fi + # Log the prompt for debugging echo "===== START REVIEW PROMPT =====" head -n 50 inline_review_prompt.txt @@ -201,23 +216,67 @@ runs: tail -n 20 inline_review_prompt.txt echo "===== END REVIEW PROMPT =====" - # Run the CLI and capture JSON output - cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json - - # Log the output for debugging - echo "Initial Continue CLI output:" - cat inline_review_raw.json - - # Validate JSON output and use it directly - if ! jq empty inline_review_raw.json 2>/dev/null; then - echo "Error: Invalid JSON output from Continue CLI" - exit 1 + # Test Continue CLI availability + if [ "$SKIP_CLI" != "true" ]; then + echo "Testing Continue CLI..." + if ! cn --version; then + echo "Warning: Continue CLI not found or not working" + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review skipped: Continue CLI installation failed.", + "comments": [] + } + EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "Continue CLI version: $(cn --version)" + fi + fi + + # Run the CLI and capture JSON output with error handling + if [ "$SKIP_CLI" != "true" ]; then + echo "Executing Continue CLI with config: ${{ inputs.continue-org }}/${{ inputs.continue-config }}" + + # Write prompt to temp file for better handling + PROMPT_FILE="/tmp/continue-prompt-$.txt" + cp inline_review_prompt.txt "$PROMPT_FILE" + + # Use timeout to prevent hanging (240 seconds = 4 minutes) + if ! timeout 240 cn --config "${{ inputs.continue-org }}/${{ inputs.continue-config }}" -p "@$PROMPT_FILE" --allow Bash --format json > inline_review_raw.json 2>cli_error.log; then + echo "Warning: Continue CLI command failed" + echo "CLI error log:" + cat cli_error.log + + # Create fallback review + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review failed due to service initialization issues. Please check the Continue API key and configuration.", + "comments": [] + } + EOF + echo "Created fallback review due to CLI failure" + else + # Log the output for debugging + echo "Initial Continue CLI output:" + cat inline_review_raw.json + + # Validate JSON output and use it directly + if ! jq empty inline_review_raw.json 2>/dev/null; then + echo "Warning: Invalid JSON output from Continue CLI, using fallback" + cat > inline_review.json << 'EOF' + { + "review_summary": "AI review completed but failed to parse output correctly.", + "comments": [] + } + EOF + else + # Use the JSON output directly + cp inline_review_raw.json inline_review.json + echo "Review output:" + cat inline_review.json + fi + fi fi - - # Use the JSON output directly - cp inline_review_raw.json inline_review.json - echo "Review output:" - cat inline_review.json - name: Post Inline Review Comments if: env.SKIP_REVIEW != 'true' diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index bf5e221e1..dd18c447a 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -68,7 +68,7 @@ runs: - name: Install Continue CLI if: env.SHOULD_RUN == 'true' shell: bash - run: npm install -g @continuedev/cli@1.4.25 + run: npm install -g @continuedev/cli@1.4.30 - name: Build PR Review Prompt if: env.SHOULD_RUN == 'true' @@ -157,6 +157,24 @@ runs: echo "==================================" echo "" + # Validate API key + if [ -z "$CONTINUE_API_KEY" ]; then + echo "Warning: CONTINUE_API_KEY environment variable is not set" + # Create fallback review and continue + cat > code_review.md << 'EOF' +## Code Review Summary + +⚠️ AI review skipped: CONTINUE_API_KEY not configured. + +### Configuration Required +- Please set the CONTINUE_API_KEY secret in repository settings +- Verify that the organization and config path are valid +EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "SKIP_CLI=false" >> $GITHUB_ENV + fi + # Validate inputs to prevent command injection if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores." @@ -168,8 +186,55 @@ runs: exit 1 fi - # Run the CLI with validated config - cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md + # Test Continue CLI availability + if [ "$SKIP_CLI" != "true" ]; then + echo "Testing Continue CLI..." + if ! cn --version; then + echo "Warning: Continue CLI not found or not working" + cat > code_review.md << 'EOF' +## Code Review Summary + +⚠️ AI review skipped: Continue CLI installation failed. + +### Troubleshooting +- Check that npm installation succeeded +- Verify @continuedev/cli package is available +EOF + echo "SKIP_CLI=true" >> $GITHUB_ENV + else + echo "Continue CLI version: $(cn --version)" + fi + fi + + # Run the CLI with validated config and error handling + if [ "$SKIP_CLI" != "true" ]; then + echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG" + + # Write prompt to temp file for better handling + PROMPT_FILE="/tmp/continue-prompt-$.txt" + cp review_prompt.txt "$PROMPT_FILE" + + # Use timeout to prevent hanging (240 seconds = 4 minutes) + if ! timeout 240 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review.md 2>cli_error.log; then + echo "Error: Continue CLI command failed" + echo "CLI error log:" + cat cli_error.log + + # Create fallback review + cat > code_review.md << 'EOF' +## Code Review Summary + +⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration. + +### Troubleshooting +- Verify the CONTINUE_API_KEY secret is set correctly +- Check that the organization and config path are valid +- Ensure the Continue service is accessible +EOF + else + echo "Review generated successfully" + fi + fi - name: Upload Review Results if: env.SHOULD_RUN == 'true' && always() diff --git a/binary/package-lock.json b/binary/package-lock.json index 37f2d865d..92756d546 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -106,6 +106,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", @@ -140,6 +141,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", diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 837bb2a39..2e7a65ca3 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -202,6 +202,8 @@ export class ConfigHandler { message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`, }); } + } else { + PolicySingleton.getInstance().policy = null; } // Load local org if not signed in or hub orgs fail try { diff --git a/core/config/load.ts b/core/config/load.ts index 065842052..370695bd3 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -57,6 +57,7 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { PolicySingleton } from "../control-plane/PolicySingleton"; import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import { getBaseToolDefinitions } from "../tools"; import { resolveRelativePathInDir } from "../util/ideUtils"; @@ -544,16 +545,21 @@ async function intermediateToFinalConfig({ // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.setConnections( - (config.experimental?.modelContextProtocolServers ?? []).map( - (server, index) => ({ - id: `continue-mcp-server-${index + 1}`, - name: `MCP Server`, - ...server, - }), - ), - false, - ); + const orgPolicy = PolicySingleton.getInstance().policy; + if (orgPolicy?.policy?.allowMcpServers === false) { + await mcpManager.shutdown(); + } else { + mcpManager.setConnections( + (config.experimental?.modelContextProtocolServers ?? []).map( + (server, index) => ({ + id: `continue-mcp-server-${index + 1}`, + name: `MCP Server`, + ...server, + }), + ), + false, + ); + } // Handle experimental modelRole config values for apply and edit const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title; diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0b39489eb..fcb5f30bc 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -332,12 +332,14 @@ export default async function doLoadConfig(options: { } } - if ( - PolicySingleton.getInstance().policy?.policy?.allowAnonymousTelemetry === - false - ) { + // Org policies + const policy = PolicySingleton.getInstance().policy?.policy; + if (policy?.allowAnonymousTelemetry === false) { newConfig.allowAnonymousTelemetry = false; } + if (policy?.allowCodebaseIndexing === false) { + newConfig.disableIndexing = true; + } // Setup telemetry only after (and if) we know it is enabled await Telemetry.setup( diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 7a9c9f634..65cb5e0ff 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -25,6 +25,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand"; import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand"; import { getControlPlaneEnvSync } from "../../control-plane/env"; +import { PolicySingleton } from "../../control-plane/PolicySingleton"; import { getBaseToolDefinitions } from "../../tools"; import { getCleanUriPath } from "../../util/uri"; import { loadConfigContextProviders } from "../loadContextProviders"; @@ -378,21 +379,26 @@ async function configYamlToContinueConfig(options: { // Trigger MCP server refreshes (Config is reloaded again once connected!) const mcpManager = MCPManagerSingleton.getInstance(); - mcpManager.setConnections( - (config.mcpServers ?? []).map((server) => ({ - id: server.name, - name: server.name, - sourceFile: server.sourceFile, - transport: { - type: "stdio", - args: [], - ...(server as any), // TODO: fix the types on mcpServers in config-yaml - }, - timeout: server.connectionTimeout, - })), - false, - { ide }, - ); + const orgPolicy = PolicySingleton.getInstance().policy; + if (orgPolicy?.policy?.allowMcpServers === false) { + await mcpManager.shutdown(); + } else { + mcpManager.setConnections( + (config.mcpServers ?? []).map((server) => ({ + id: server.name, + name: server.name, + sourceFile: server.sourceFile, + transport: { + type: "stdio", + args: [], + ...(server as any), // TODO: fix the types on mcpServers in config-yaml + }, + timeout: server.connectionTimeout, + })), + false, + { ide }, + ); + } return { config: continueConfig, errors: localErrors }; } diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 22495bef4..c9dc41929 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -48,6 +48,21 @@ export class MCPManagerSingleton { this.connections.delete(id); } + async shutdown() { + if (this.connections.size > 0) { + await Promise.allSettled( + Array.from(this.connections.entries()).map(([id, connection]) => { + try { + connection.abortController.abort(); + void connection.client.close(); + } finally { + this.connections.delete(id); + } + }), + ); + } + } + setConnections( servers: MCPOptions[], forceRefresh: boolean, diff --git a/core/core.ts b/core/core.ts index 65f2e4ede..6d8738f20 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1009,6 +1009,37 @@ export class Core { this.handleToolCall(toolCall), ); + on( + "tools/evaluatePolicy", + async ({ data: { toolName, basePolicy, args } }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + const tool = config.tools.find((t) => t.function.name === toolName); + if (!tool) { + // Tool not found, return base policy + return { policy: basePolicy }; + } + + // Extract display value for specific tools + let displayValue: string | undefined; + if (toolName === "runTerminalCommand" && args.command) { + displayValue = args.command as string; + } + + // If tool has evaluateToolCallPolicy function, use it + if (tool.evaluateToolCallPolicy) { + const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args); + return { policy: evaluatedPolicy, displayValue }; + } + + // Otherwise return base policy unchanged + return { policy: basePolicy, displayValue }; + }, + ); + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); diff --git a/core/index.d.ts b/core/index.d.ts index 7c3f4a121..a31e02c67 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1070,11 +1070,6 @@ export interface ToolExtras { codeBaseIndexer?: CodebaseIndexer; } -export type ToolPolicy = - | "allowedWithPermission" - | "allowedWithoutPermission" - | "disabled"; - export interface Tool { type: "function"; function: { @@ -1099,6 +1094,10 @@ export interface Tool { exampleArgs?: Array<[string, string | number]>; }; defaultToolPolicy?: ToolPolicy; + evaluateToolCallPolicy?: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ) => ToolPolicy; } interface ToolChoice { diff --git a/core/llm/index.ts b/core/llm/index.ts index 6602be1f1..f8fefd381 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -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; } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index d08bf7bc6..1d069ff71 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -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 = { diff --git a/core/llm/llms/Scaleway.ts b/core/llm/llms/Scaleway.ts index 93fc599db..4f308dc0c 100644 --- a/core/llm/llms/Scaleway.ts +++ b/core/llm/llms/Scaleway.ts @@ -7,16 +7,23 @@ class Scaleway extends OpenAI { static providerName = "scaleway"; static defaultOptions: Partial = { 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) { diff --git a/core/package-lock.json b/core/package-lock.json index 974a50300..bf948e8a9 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -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", @@ -67,6 +68,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", @@ -101,6 +103,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", @@ -236,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", @@ -2955,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", @@ -6892,6 +6913,13 @@ "node": ">= 0.12" } }, + "node_modules/@types/shell-quote": { + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@types/shell-quote/-/shell-quote-1.7.5.tgz", + "integrity": "sha512-+UE8GAGRPbJVQDdxi16dgadcBfQ+KG2vgZhV1+3A1XmHbmwcdwhCUwIdy+d3pAGrbvgRoVSjeI9vOWyq376Yzw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/shimmer": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@types/shimmer/-/shimmer-1.2.0.tgz", @@ -17459,6 +17487,18 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/shiki": { "version": "3.7.0", "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.7.0.tgz", diff --git a/core/package.json b/core/package.json index c7ca9158d..db53c661a 100644 --- a/core/package.json +++ b/core/package.json @@ -34,6 +34,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", @@ -61,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", @@ -111,6 +113,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", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index b6d3ffe96..5add878be 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -4,6 +4,7 @@ import { DevDataLogEvent, ModelRole, } from "@continuedev/config-yaml"; +import { ToolPolicy } from "@continuedev/terminal-security"; import { AutocompleteInput, @@ -293,6 +294,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { { toolCall: ToolCall }, { contextItems: ContextItem[]; errorMessage?: string }, ]; + "tools/evaluatePolicy": [ + { toolName: string; basePolicy: ToolPolicy; args: Record }, + { policy: ToolPolicy; displayValue?: string }, + ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getEnvironment": [undefined, ControlPlaneEnv]; diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index db1b9eb9a..91819a33d 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -78,6 +78,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedProfile", "didChangeSelectedOrg", "tools/call", + "tools/evaluatePolicy", "controlPlane/getEnvironment", "controlPlane/getFreeTrialStatus", "controlPlane/getModelsAddOnUpgradeUrl", diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 3f740da1c..47cd6769f 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -1,5 +1,6 @@ export enum BuiltInToolNames { ReadFile = "read_file", + ReadFileRange = "read_file_range", EditExistingFile = "edit_existing_file", SingleFindAndReplace = "single_find_and_replace", MultiEdit = "multi_edit", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index f24210511..c1d203972 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -12,6 +12,8 @@ import { grepSearchImpl } from "./implementations/grepSearch"; import { lsToolImpl } from "./implementations/lsTool"; import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile"; import { readFileImpl } from "./implementations/readFile"; + +import { readFileRangeImpl } from "./implementations/readFileRange"; import { requestRuleImpl } from "./implementations/requestRule"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; @@ -145,6 +147,8 @@ export async function callBuiltInTool( switch (functionName) { case BuiltInToolNames.ReadFile: return await readFileImpl(args, extras); + case BuiltInToolNames.ReadFileRange: + return await readFileRangeImpl(args, extras); case BuiltInToolNames.CreateNewFile: return await createNewFileImpl(args, extras); case BuiltInToolNames.GrepSearch: diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 1b12af8fb..b04c9196f 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -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 ...'"; diff --git a/core/tools/definitions/index.ts b/core/tools/definitions/index.ts index 413157e4d..bf3dc02d9 100644 --- a/core/tools/definitions/index.ts +++ b/core/tools/definitions/index.ts @@ -9,6 +9,8 @@ export { lsTool } from "./ls"; export { multiEditTool } from "./multiEdit"; export { readCurrentlyOpenFileTool } from "./readCurrentlyOpenFile"; export { readFileTool } from "./readFile"; + +export { readFileRangeTool } from "./readFileRange"; export { requestRuleTool } from "./requestRule"; export { runTerminalCommandTool } from "./runTerminalCommand"; export { searchWebTool } from "./searchWeb"; diff --git a/core/tools/definitions/multiEdit.ts b/core/tools/definitions/multiEdit.ts index 09a26be5b..913961737 100644 --- a/core/tools/definitions/multiEdit.ts +++ b/core/tools/definitions/multiEdit.ts @@ -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", }, }, }, diff --git a/core/tools/definitions/readFileRange.ts b/core/tools/definitions/readFileRange.ts new file mode 100644 index 000000000..91e94d574 --- /dev/null +++ b/core/tools/definitions/readFileRange.ts @@ -0,0 +1,51 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const readFileRangeTool: Tool = { + type: "function", + displayTitle: "Read File Range", + wouldLikeTo: + "read lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", + isCurrently: + "reading lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", + hasAlready: + "viewed lines {{{ startLine }}}-{{{ endLine }}} of {{{ filepath }}}", + readonly: true, + isInstant: true, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.ReadFileRange, + description: + "Use this tool to read a specific range of lines from an existing file. Only supports positive line numbers (1-based from start). For reading from the end of a file, use the terminal tool with 'tail' command instead.", + parameters: { + type: "object", + required: ["filepath", "startLine", "endLine"], + properties: { + filepath: { + type: "string", + description: + "The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)", + }, + startLine: { + type: "number", + description: + "The starting line number (1-based from start). Must be a positive integer. Example: 1 = first line, 10 = tenth line", + }, + endLine: { + type: "number", + description: + "The ending line number (1-based from start). Must be a positive integer greater than or equal to startLine. Example: 10 = tenth line, 20 = twentieth line", + }, + }, + }, + }, + systemMessageDescription: { + prefix: `To read a specific range of lines from a file, use the ${BuiltInToolNames.ReadFileRange} tool. Only supports positive line numbers (1-based from start). For reading from the end of files, use the terminal tool with 'tail' command instead:`, + exampleArgs: [ + ["filepath", "path/to/the_file.txt"], + ["startLine", 10], + ["endLine", 20], + ], + }, + defaultToolPolicy: "allowedWithoutPermission", +}; diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index b2dc74316..dbeaa5c05 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,6 +1,10 @@ import os from "os"; import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { + evaluateTerminalCommandSecurity, + ToolPolicy, +} from "@continuedev/terminal-security"; /** * Get the preferred shell for the current platform @@ -56,6 +60,15 @@ export const runTerminalCommandTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", + evaluateToolCallPolicy: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ): ToolPolicy => { + return evaluateTerminalCommandSecurity( + basePolicy, + parsedArgs.command as string, + ); + }, systemMessageDescription: { prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool ${RUN_COMMAND_NOTES} diff --git a/core/tools/definitions/singleFindAndReplace.ts b/core/tools/definitions/singleFindAndReplace.ts index a8a9fc15b..d0b172ad7 100644 --- a/core/tools/definitions/singleFindAndReplace.ts +++ b/core/tools/definitions/singleFindAndReplace.ts @@ -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", diff --git a/core/tools/implementations/readFileRange.integration.vitest.ts b/core/tools/implementations/readFileRange.integration.vitest.ts new file mode 100644 index 000000000..945d03e41 --- /dev/null +++ b/core/tools/implementations/readFileRange.integration.vitest.ts @@ -0,0 +1,204 @@ +import { expect, test, vi } from "vitest"; +import { ToolExtras } from "../.."; +import { readFileRangeImpl } from "./readFileRange"; + +// Mock the dependencies +vi.mock("../../util/ideUtils", () => ({ + resolveRelativePathInDir: vi.fn(), +})); + +vi.mock("../../util/uri", () => ({ + getUriPathBasename: vi.fn(), +})); + +vi.mock("./readFileLimit", () => ({ + throwIfFileExceedsHalfOfContext: vi.fn(), +})); + +test("readFileRangeImpl handles out-of-bounds ranges gracefully", async () => { + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); + const { getUriPathBasename } = await import("../../util/uri"); + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); + + // Mock the utility functions + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); + + // Test case 1: Start line beyond end of file + const mockIdeOutOfBounds = { + readRangeInFile: vi.fn().mockResolvedValue(""), // IDE returns empty string + }; + + const mockExtras1 = { + ide: mockIdeOutOfBounds, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + const result1 = await readFileRangeImpl( + { + filepath: "test.txt", + startLine: 100, // Beyond end of file + endLine: 105, + }, + mockExtras1, + ); + + expect(result1).toHaveLength(1); + expect(result1[0].content).toBe(""); + expect(result1[0].description).toBe("test.txt (lines 100-105)"); + + // Test case 2: End line beyond end of file + const mockIdePartialRange = { + readRangeInFile: vi.fn().mockResolvedValue("line5\nline6"), // IDE returns available content + }; + + const mockExtras2 = { + ide: mockIdePartialRange, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + const result2 = await readFileRangeImpl( + { + filepath: "test.txt", + startLine: 5, + endLine: 100, // Beyond end of file + }, + mockExtras2, + ); + + expect(result2).toHaveLength(1); + expect(result2[0].content).toBe("line5\nline6"); + expect(result2[0].description).toBe("test.txt (lines 5-100)"); + + // Verify that IDE methods were called with correct 0-based ranges + expect(mockIdeOutOfBounds.readRangeInFile).toHaveBeenCalledWith( + "file:///test.txt", + { + start: { line: 99, character: 0 }, // 100 - 1 + end: { line: 104, character: Number.MAX_SAFE_INTEGER }, // 105 - 1 + }, + ); + + expect(mockIdePartialRange.readRangeInFile).toHaveBeenCalledWith( + "file:///test.txt", + { + start: { line: 4, character: 0 }, // 5 - 1 + end: { line: 99, character: Number.MAX_SAFE_INTEGER }, // 100 - 1 + }, + ); +}); + +test("readFileRangeImpl validates line number constraints", async () => { + const mockExtras = { + ide: { readRangeInFile: vi.fn(), readFile: vi.fn() }, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + // Test startLine < 1 (invalid) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 0, + endLine: 5, + }, + mockExtras, + ), + ).rejects.toThrow("startLine must be 1 or greater"); + + // Test negative startLine (no longer supported) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: -1, + endLine: 5, + }, + mockExtras, + ), + ).rejects.toThrow("Negative line numbers are not supported"); + + // Test endLine < 1 (invalid) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 1, + endLine: 0, + }, + mockExtras, + ), + ).rejects.toThrow("endLine must be 1 or greater"); + + // Test negative endLine (no longer supported) + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 1, + endLine: -1, + }, + mockExtras, + ), + ).rejects.toThrow("Negative line numbers are not supported"); + + // Test endLine < startLine + await expect( + readFileRangeImpl( + { + filepath: "test.txt", + startLine: 10, + endLine: 5, + }, + mockExtras, + ), + ).rejects.toThrow( + "endLine (5) must be greater than or equal to startLine (10)", + ); +}); + +test("readFileRangeImpl handles normal ranges correctly", async () => { + const { resolveRelativePathInDir } = await import("../../util/ideUtils"); + const { getUriPathBasename } = await import("../../util/uri"); + const { throwIfFileExceedsHalfOfContext } = await import("./readFileLimit"); + + vi.mocked(resolveRelativePathInDir).mockResolvedValue("file:///test.txt"); + vi.mocked(getUriPathBasename).mockReturnValue("test.txt"); + vi.mocked(throwIfFileExceedsHalfOfContext).mockResolvedValue(undefined); + + const mockIde = { + readRangeInFile: vi.fn().mockResolvedValue("line2\nline3\nline4"), + }; + + const mockExtras = { + ide: mockIde, + config: { selectedModelByRole: { chat: { contextLength: 8192 } } }, + } as unknown as ToolExtras; + + const result = await readFileRangeImpl( + { + filepath: "src/test.py", + startLine: 2, + endLine: 4, + }, + mockExtras, + ); + + expect(result).toHaveLength(1); + expect(result[0]).toEqual({ + name: "test.txt", + description: "src/test.py (lines 2-4)", + content: "line2\nline3\nline4", + uri: { + type: "file", + value: "file:///test.txt", + }, + }); + + // Verify correct 0-based conversion + expect(mockIde.readRangeInFile).toHaveBeenCalledWith("file:///test.txt", { + start: { line: 1, character: 0 }, // 2 - 1 + end: { line: 3, character: Number.MAX_SAFE_INTEGER }, // 4 - 1 + }); +}); diff --git a/core/tools/implementations/readFileRange.ts b/core/tools/implementations/readFileRange.ts new file mode 100644 index 000000000..c313f4bff --- /dev/null +++ b/core/tools/implementations/readFileRange.ts @@ -0,0 +1,68 @@ +import { resolveRelativePathInDir } from "../../util/ideUtils"; +import { getUriPathBasename } from "../../util/uri"; + +import { ToolImpl } from "."; +import { getNumberArg, getStringArg } from "../parseArgs"; +import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; + +export const readFileRangeImpl: ToolImpl = async (args, extras) => { + const filepath = getStringArg(args, "filepath"); + const startLine = getNumberArg(args, "startLine"); + const endLine = getNumberArg(args, "endLine"); + + // Validate that line numbers are positive integers + if (startLine < 1) { + throw new Error( + "startLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", + ); + } + if (endLine < 1) { + throw new Error( + "endLine must be 1 or greater. Negative line numbers are not supported - use the terminal tool with 'tail' command for reading from file end.", + ); + } + if (endLine < startLine) { + throw new Error( + `endLine (${endLine}) must be greater than or equal to startLine (${startLine})`, + ); + } + + const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); + if (!firstUriMatch) { + throw new Error( + `File "${filepath}" does not exist. You might want to check the path and try again.`, + ); + } + + // Use the IDE's readRangeInFile method with 0-based range (IDE expects 0-based internally) + const content = await extras.ide.readRangeInFile(firstUriMatch, { + start: { + line: startLine - 1, // Convert from 1-based to 0-based + character: 0, + }, + end: { + line: endLine - 1, // Convert from 1-based to 0-based + character: Number.MAX_SAFE_INTEGER, // Read to end of line + }, + }); + + await throwIfFileExceedsHalfOfContext( + filepath, + content, + extras.config.selectedModelByRole.chat, + ); + + const rangeDescription = `${filepath} (lines ${startLine}-${endLine})`; + + return [ + { + name: getUriPathBasename(firstUriMatch), + description: rangeDescription, + content, + uri: { + type: "file", + value: firstUriMatch, + }, + }, + ]; +}; diff --git a/core/tools/implementations/readFileRange.vitest.ts b/core/tools/implementations/readFileRange.vitest.ts new file mode 100644 index 000000000..b8a172d1c --- /dev/null +++ b/core/tools/implementations/readFileRange.vitest.ts @@ -0,0 +1,60 @@ +import { expect, test } from "vitest"; +import { getNumberArg } from "../parseArgs"; + +test("readFileRange should validate positive line number arguments", () => { + // Test positive startLine validation + expect(() => getNumberArg({ startLine: 1 }, "startLine")).not.toThrow(); + expect(() => getNumberArg({ startLine: "1" }, "startLine")).not.toThrow(); + expect(() => getNumberArg({ startLine: 100 }, "startLine")).not.toThrow(); + + // Test positive endLine validation + expect(() => getNumberArg({ endLine: 5 }, "endLine")).not.toThrow(); + expect(() => getNumberArg({ endLine: "10" }, "endLine")).not.toThrow(); + expect(() => getNumberArg({ endLine: 1000 }, "endLine")).not.toThrow(); + + // Test missing arguments + expect(() => getNumberArg({}, "startLine")).toThrow( + "Argument `startLine` is required (type number)", + ); + expect(() => getNumberArg({}, "endLine")).toThrow( + "Argument `endLine` is required (type number)", + ); + + // Test invalid arguments + expect(() => + getNumberArg({ startLine: "not-a-number" }, "startLine"), + ).toThrow("Argument `startLine` must be a valid number"); + expect(() => getNumberArg({ endLine: true }, "endLine")).toThrow( + "Argument `endLine` must be a valid number", + ); +}); + +test("readFileRange should handle line number conversion", () => { + // Test that our parsing function converts correctly + expect(getNumberArg({ line: 1 }, "line")).toBe(1); + expect(getNumberArg({ line: "5" }, "line")).toBe(5); + expect(getNumberArg({ line: 10.7 }, "line")).toBe(10); // Should floor + expect(getNumberArg({ line: "15.9" }, "line")).toBe(15); // Should floor +}); + +test("readFileRange parses negative numbers (validation happens in implementation)", () => { + // The parseArgs function should parse negative numbers correctly + // but the implementation will reject them with helpful error messages + expect(getNumberArg({ line: -1 }, "line")).toBe(-1); + expect(getNumberArg({ line: -10 }, "line")).toBe(-10); + expect(getNumberArg({ line: "-5" }, "line")).toBe(-5); +}); + +test("readFileRange handles out-of-bounds ranges gracefully", () => { + // IDE implementations handle out-of-bounds gracefully: + // - VS Code: Uses array.slice() which handles out-of-bounds gracefully + // - IntelliJ: Uses lines.getOrNull() which returns null for out-of-bounds + // Both return empty content or available content without throwing errors + + expect(() => { + const startLine = getNumberArg({ startLine: 1000 }, "startLine"); + const endLine = getNumberArg({ endLine: 2000 }, "endLine"); + expect(startLine).toBe(1000); + expect(endLine).toBe(2000); + }).not.toThrow(); +}); diff --git a/core/tools/implementations/runTerminalCommand.test.ts b/core/tools/implementations/runTerminalCommand.vitest.ts similarity index 76% rename from core/tools/implementations/runTerminalCommand.test.ts rename to core/tools/implementations/runTerminalCommand.vitest.ts index e744ea4f1..659163eb8 100644 --- a/core/tools/implementations/runTerminalCommand.test.ts +++ b/core/tools/implementations/runTerminalCommand.vitest.ts @@ -1,4 +1,12 @@ -import { jest } from "@jest/globals"; +import { + describe, + it, + expect, + beforeEach, + afterEach, + afterAll, + vi, +} from "vitest"; import * as childProcess from "node:child_process"; import * as fs from "node:fs"; import * as os from "node:os"; @@ -6,17 +14,18 @@ import * as path from "node:path"; import { IDE, ToolExtras } from "../.."; import * as processBackgroundStates from "../../util/processTerminalBackgroundStates"; import { runTerminalCommandImpl } from "./runTerminalCommand"; +import { runTerminalCommandTool } from "../definitions/runTerminalCommand"; // We're using real child processes, so ensure these aren't mocked -jest.unmock("node:child_process"); -jest.unmock("node:util"); +vi.unmock("node:child_process"); +vi.unmock("node:util"); describe("runTerminalCommandImpl", () => { // Setup mocks and spies - const mockGetIdeInfo = jest.fn(); - const mockGetWorkspaceDirs = jest.fn(); - const mockOnPartialOutput = jest.fn(); - const mockRunCommand = jest.fn(); + const mockGetIdeInfo = vi.fn(); + const mockGetWorkspaceDirs = vi.fn(); + const mockOnPartialOutput = vi.fn(); + const mockRunCommand = vi.fn(); // Use a simple approach to ensure background processes are terminated let testPid: number | null = null; @@ -27,7 +36,7 @@ describe("runTerminalCommandImpl", () => { ); beforeEach(() => { - jest.resetAllMocks(); + vi.resetAllMocks(); // Setup backgrounded processes handling - don't mock, just make sure it's empty // Get any processes that might be already tracked and clear them @@ -73,7 +82,7 @@ describe("runTerminalCommandImpl", () => { // Helper function to create a ToolExtras object const createMockExtras = ( overrides: Partial<{ - onPartialOutput?: jest.Mock; + onPartialOutput?: any; remoteName?: string; }> = {}, ): ToolExtras => { @@ -90,16 +99,16 @@ describe("runTerminalCommandImpl", () => { getWorkspaceDirs: mockGetWorkspaceDirs, runCommand: mockRunCommand, // Add stubs for other required IDE methods - getIdeSettings: jest.fn(), - getDiff: jest.fn(), - getClipboardContent: jest.fn(), - isTelemetryEnabled: jest.fn(), - readFile: jest.fn(), - writeFile: jest.fn(), - renameFile: jest.fn(), - deleteFile: jest.fn(), - globFiles: jest.fn(), - ls: jest.fn(), + getIdeSettings: vi.fn(), + getDiff: vi.fn(), + getClipboardContent: vi.fn(), + isTelemetryEnabled: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + renameFile: vi.fn(), + deleteFile: vi.fn(), + globFiles: vi.fn(), + ls: vi.fn(), }; // Create a base ToolExtras object with required properties @@ -147,7 +156,7 @@ describe("runTerminalCommandImpl", () => { "`; const args = { command, waitForCompletion: true }; - const mockOutputFn = jest.fn(); + const mockOutputFn = vi.fn(); const extras = createMockExtras({ onPartialOutput: mockOutputFn }); // Execute the command with streaming @@ -191,7 +200,7 @@ describe("runTerminalCommandImpl", () => { "`; const args = { command, waitForCompletion: false }; - const mockOutputFn = jest.fn(); + const mockOutputFn = vi.fn(); const extras = createMockExtras({ onPartialOutput: mockOutputFn }); const result = await runTerminalCommandImpl(args, extras); @@ -355,25 +364,25 @@ describe("runTerminalCommandImpl", () => { it("should handle missing workspace directory gracefully", async () => { // Mock IDE to return empty workspace directories - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); // Create IDE mock with empty workspace const mockIde = { - getIdeInfo: jest + getIdeInfo: vi .fn() .mockReturnValue(Promise.resolve({ remoteName: "local" })), getWorkspaceDirs: mockEmptyWorkspace, - runCommand: jest.fn(), - getIdeSettings: jest.fn(), - getDiff: jest.fn(), - getClipboardContent: jest.fn(), - isTelemetryEnabled: jest.fn(), - readFile: jest.fn(), - writeFile: jest.fn(), - renameFile: jest.fn(), - deleteFile: jest.fn(), - globFiles: jest.fn(), - ls: jest.fn(), + runCommand: vi.fn(), + getIdeSettings: vi.fn(), + getDiff: vi.fn(), + getClipboardContent: vi.fn(), + isTelemetryEnabled: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + renameFile: vi.fn(), + deleteFile: vi.fn(), + globFiles: vi.fn(), + ls: vi.fn(), }; const extras = { @@ -402,7 +411,7 @@ describe("runTerminalCommandImpl", () => { it("should handle case where cwd fallbacks all fail", async () => { // Mock IDE to return empty workspace directories - const mockEmptyWorkspace = jest.fn().mockReturnValue(Promise.resolve([])); + const mockEmptyWorkspace = vi.fn().mockReturnValue(Promise.resolve([])); // Save original environment variables and process.cwd const originalHome = process.env.HOME; @@ -413,27 +422,27 @@ describe("runTerminalCommandImpl", () => { // Mock all fallbacks to fail delete process.env.HOME; delete process.env.USERPROFILE; - process.cwd = jest.fn().mockImplementation(() => { + process.cwd = vi.fn().mockImplementation(() => { throw new Error("Current directory unavailable"); - }) as jest.MockedFunction<() => string>; + }) as any; // Create IDE mock with empty workspace const mockIde = { - getIdeInfo: jest + getIdeInfo: vi .fn() .mockReturnValue(Promise.resolve({ remoteName: "local" })), getWorkspaceDirs: mockEmptyWorkspace, - runCommand: jest.fn(), - getIdeSettings: jest.fn(), - getDiff: jest.fn(), - getClipboardContent: jest.fn(), - isTelemetryEnabled: jest.fn(), - readFile: jest.fn(), - writeFile: jest.fn(), - renameFile: jest.fn(), - deleteFile: jest.fn(), - globFiles: jest.fn(), - ls: jest.fn(), + runCommand: vi.fn(), + getIdeSettings: vi.fn(), + getDiff: vi.fn(), + getClipboardContent: vi.fn(), + isTelemetryEnabled: vi.fn(), + readFile: vi.fn(), + writeFile: vi.fn(), + renameFile: vi.fn(), + deleteFile: vi.fn(), + globFiles: vi.fn(), + ls: vi.fn(), }; const extras = { @@ -472,3 +481,125 @@ describe("runTerminalCommandImpl", () => { } }); }); + +describe("runTerminalCommandTool.evaluateToolCallPolicy", () => { + it("should return base policy for safe commands like echo", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "echo hello world" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should respect disabled policy even for non-echo commands", () => { + const basePolicy = "disabled"; + const args = { command: "ls -la" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("disabled"); + }); + + it("should respect disabled policy even for safe commands", () => { + const basePolicy = "disabled"; + const args = { command: "echo test" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("disabled"); + }); + + it("should return base policy for non-echo commands", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "ls -la" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should return base policy for git commands", () => { + const basePolicy = "allowedWithPermission"; + const args = { command: "git status" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithPermission"); + }); + + it("should handle undefined command gracefully", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: undefined }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should handle null command gracefully", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: null }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should handle empty command string", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithoutPermission"); + }); + + it("should disable dangerous commands like rm -rf /", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "rm -rf /" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("disabled"); + }); + + it("should require permission for high-risk network commands", () => { + const basePolicy = "allowedWithoutPermission"; + const args = { command: "curl http://example.com" }; + + const result = runTerminalCommandTool.evaluateToolCallPolicy!( + basePolicy, + args, + ); + + expect(result).toBe("allowedWithPermission"); + }); +}); diff --git a/core/tools/index.ts b/core/tools/index.ts index 0277da6a7..3a45ea295 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -4,6 +4,7 @@ import * as toolDefinitions from "./definitions"; // I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads. export const getBaseToolDefinitions = () => [ toolDefinitions.readFileTool, + toolDefinitions.createNewFileTool, toolDefinitions.runTerminalCommandTool, toolDefinitions.globSearchTool, @@ -33,6 +34,7 @@ export const getConfigDependentToolDefinitions = ( toolDefinitions.viewRepoMapTool, toolDefinitions.viewSubdirectoryTool, toolDefinitions.codebaseTool, + toolDefinitions.readFileRangeTool, ); } diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index a31267854..543e6ba53 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -40,6 +40,24 @@ export function getOptionalStringArg( return getStringArg(args, argName, allowEmpty); } +export function getNumberArg(args: any, argName: string): number { + if (!args || !(argName in args)) { + throw new Error(`Argument \`${argName}\` is required (type number)`); + } + const value = args[argName]; + if (typeof value === "string") { + const parsed = parseInt(value, 10); + if (isNaN(parsed)) { + throw new Error(`Argument \`${argName}\` must be a valid number`); + } + return parsed; + } + if (typeof value !== "number" || isNaN(value)) { + throw new Error(`Argument \`${argName}\` must be a valid number`); + } + return Math.floor(value); // Ensure integer for line numbers (supports negative numbers) +} + export function getBooleanArg(args: any, argName: string, required = false) { if (!args || !(argName in args)) { if (required) { diff --git a/core/tools/parseArgs.vitest.ts b/core/tools/parseArgs.vitest.ts index b2cee9fc5..71bfc0cc5 100644 --- a/core/tools/parseArgs.vitest.ts +++ b/core/tools/parseArgs.vitest.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest"; import { ToolCallDelta } from ".."; import { getBooleanArg, + getNumberArg, getOptionalStringArg, getStringArg, safeParseToolCallArgs, @@ -246,3 +247,86 @@ describe("getBooleanArg", () => { ); }); }); + +describe("getNumberArg", () => { + it("should return number argument when valid", () => { + const args = { count: 42 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should parse string numbers", () => { + const args = { count: "42" }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should floor decimal numbers", () => { + const args = { count: 42.7 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should parse and floor string decimal numbers", () => { + const args = { count: "42.7" }; + const result = getNumberArg(args, "count"); + expect(result).toBe(42); + }); + + it("should throw error when argument is missing", () => { + const args = { otherArg: 42 }; + expect(() => getNumberArg(args, "count")).toThrowError( + "Argument `count` is required (type number)", + ); + }); + + it("should throw error when argument is not a number", () => { + const argsString = { count: "not-a-number" }; + const argsBoolean = { count: true }; + const argsObject = { count: {} }; + + expect(() => getNumberArg(argsString, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + expect(() => getNumberArg(argsBoolean, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + expect(() => getNumberArg(argsObject, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + }); + + it("should throw error when argument is NaN", () => { + const args = { count: NaN }; + expect(() => getNumberArg(args, "count")).toThrowError( + "Argument `count` must be a valid number", + ); + }); + + it("should handle negative numbers", () => { + const args = { count: -5 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(-5); + }); + + it("should handle negative string numbers", () => { + const args = { count: "-10" }; + const result = getNumberArg(args, "count"); + expect(result).toBe(-10); + }); + + it("should handle zero", () => { + const args = { count: 0 }; + const result = getNumberArg(args, "count"); + expect(result).toBe(0); + }); + + it("should handle null or undefined args", () => { + expect(() => getNumberArg(null, "count")).toThrowError( + "Argument `count` is required (type number)", + ); + expect(() => getNumberArg(undefined, "count")).toThrowError( + "Argument `count` is required (type number)", + ); + }); +}); diff --git a/docs/chat/how-to-use-it.mdx b/docs/chat/how-to-use-it.mdx index 3acf5f1b5..94257fdb7 100644 --- a/docs/chat/how-to-use-it.mdx +++ b/docs/chat/how-to-use-it.mdx @@ -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" --- diff --git a/docs/customization/overview.mdx b/docs/customization/overview.mdx index 1889806d6..edbeeee16 100644 --- a/docs/customization/overview.mdx +++ b/docs/customization/overview.mdx @@ -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. diff --git a/docs/customization/rules.mdx b/docs/customization/rules.mdx index 37ab76ff9..75dbfc811 100644 --- a/docs/customization/rules.mdx +++ b/docs/customization/rules.mdx @@ -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. \ No newline at end of file diff --git a/docs/customize/deep-dives/configuration.mdx b/docs/customize/deep-dives/configuration.mdx index 4291dfbd8..7b3a302a9 100644 --- a/docs/customize/deep-dives/configuration.mdx +++ b/docs/customize/deep-dives/configuration.mdx @@ -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 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/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) diff --git a/docs/customize/deep-dives/mcp.mdx b/docs/customize/deep-dives/mcp.mdx index 7b6230923..074448104 100644 --- a/docs/customize/deep-dives/mcp.mdx +++ b/docs/customize/deep-dives/mcp.mdx @@ -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. diff --git a/docs/customize/deep-dives/rules.mdx b/docs/customize/deep-dives/rules.mdx index 2f9411bc9..f2dd04166 100644 --- a/docs/customize/deep-dives/rules.mdx +++ b/docs/customize/deep-dives/rules.mdx @@ -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 -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. diff --git a/docs/customize/deep-dives/rules.mdx.backup b/docs/customize/deep-dives/rules.mdx.backup index 0971568a8..5338df40d 100644 --- a/docs/customize/deep-dives/rules.mdx.backup +++ b/docs/customize/deep-dives/rules.mdx.backup @@ -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. -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 diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx index 3f041ada2..ef11b0f8d 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -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 diff --git a/docs/customize/model-roles.mdx b/docs/customize/model-roles.mdx index 8db06d857..7349ad539 100644 --- a/docs/customize/model-roles.mdx +++ b/docs/customize/model-roles.mdx @@ -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" --- diff --git a/docs/customize/model-roles/00-intro.mdx b/docs/customize/model-roles/00-intro.mdx index b82c9bd71..941ea0f4d 100644 --- a/docs/customize/model-roles/00-intro.mdx +++ b/docs/customize/model-roles/00-intro.mdx @@ -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) diff --git a/docs/customize/model-roles/intro.mdx b/docs/customize/model-roles/intro.mdx index fdba06544..ccdd3a3b0 100644 --- a/docs/customize/model-roles/intro.mdx +++ b/docs/customize/model-roles/intro.mdx @@ -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. diff --git a/docs/docs.json b/docs/docs.json index 8e06477f3..979ebe4e2 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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,12 +228,13 @@ "group": "Guides", "pages": [ "guides/overview", - "guides/understanding-assistants", + "guides/understanding-agents", "guides/codebase-documentation-awareness", "guides/cli", "guides/continuous-ai", "guides/plan-mode-guide", "guides/ollama-guide", + "guides/instinct", "guides/running-continue-without-internet", "guides/custom-code-rag", "guides/how-to-self-host-a-model" @@ -347,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", @@ -1105,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", @@ -1174,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" } ] } diff --git a/docs/faqs.mdx b/docs/faqs.mdx index 7836ef9d3..36b93ff77 100644 --- a/docs/faqs.mdx +++ b/docs/faqs.mdx @@ -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: diff --git a/docs/features/agent/how-to-customize.mdx b/docs/features/agent/how-to-customize.mdx index b26994906..1cf18bf31 100644 --- a/docs/features/agent/how-to-customize.mdx +++ b/docs/features/agent/how-to-customize.mdx @@ -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 diff --git a/docs/features/autocomplete/how-to-customize.mdx b/docs/features/autocomplete/how-to-customize.mdx index 854be157e..4fab64383 100644 --- a/docs/features/autocomplete/how-to-customize.mdx +++ b/docs/features/autocomplete/how-to-customize.mdx @@ -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). diff --git a/docs/features/autocomplete/next-edit.mdx b/docs/features/autocomplete/next-edit.mdx index edeb77463..9deb0c3af 100644 --- a/docs/features/autocomplete/next-edit.mdx +++ b/docs/features/autocomplete/next-edit.mdx @@ -4,7 +4,8 @@ description: "Learn how Continue's Next Edit feature predicts and suggests your --- - Next Edit is currently an experimental feature. It requires [Mercury Coder + Next Edit is currently an experimental feature. It requires + [Instinct](https://hub.continue.dev/continuedev/instinct) or [Mercury Coder model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in your Continue autocomplete settings and is not yet available for JetBrains use. @@ -71,18 +72,18 @@ Next Edit activates automatically when: Next Edit requires: -- Compatible AI models (Mercury Coder) +- Compatible AI models (Mercury Coder or Instinct) - Continue development team access - VS Code (JetBrains support coming soon) - **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview) - To use Next Edit, you must have the Mercury Coder model configured in your - Continue autocomplete model settings. This model is specifically designed for - next edit predictions. Once it's been loaded, you must reload VS Code to - activate it. + To use Next Edit, you must have the Instinct or Mercury Coder model configured + in your Continue autocomplete model settings. This model is specifically + designed for next edit predictions. Once it's been loaded, you must reload VS + Code to activate it. Next Edit Model Setup @@ -117,6 +118,7 @@ Next Edit requires: Next Edit requires AI models specifically trained for code prediction: - **Mercury Coder**: Primary model optimized for next edit prediction +- **Instinct**: The leading open Next Edit model, trained by Continue ### Automatic Detection diff --git a/docs/features/edit/how-to-customize.mdx b/docs/features/edit/how-to-customize.mdx index b200e2e67..f6925e764 100644 --- a/docs/features/edit/how-to-customize.mdx +++ b/docs/features/edit/how-to-customize.mdx @@ -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 diff --git a/docs/getting-started/extensions.mdx b/docs/getting-started/extensions.mdx index 1904b97bc..24db1064e 100644 --- a/docs/getting-started/extensions.mdx +++ b/docs/getting-started/extensions.mdx @@ -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) diff --git a/docs/getting-started/install.mdx b/docs/getting-started/install.mdx index c76a6515b..739f88394 100644 --- a/docs/getting-started/install.mdx +++ b/docs/getting-started/install.mdx @@ -24,7 +24,7 @@ The Continue logo will appear on the left sidebar. For a better experience, move -[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 @@ -54,7 +54,7 @@ Click `Install`, which will cause the Continue logo to show up on the right tool -[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 @@ -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) diff --git a/docs/getting-started/overview.mdx b/docs/getting-started/overview.mdx index 18d8b67f3..a7c610a4b 100644 --- a/docs/getting-started/overview.mdx +++ b/docs/getting-started/overview.mdx @@ -57,6 +57,6 @@ description: "To quickly understand what you can do with Continue, check out eac -## 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). diff --git a/docs/getting-started/quick-start.mdx b/docs/getting-started/quick-start.mdx index f27899dd7..c27627465 100644 --- a/docs/getting-started/quick-start.mdx +++ b/docs/getting-started/quick-start.mdx @@ -247,12 +247,12 @@ Ready to master specific features? Check out these detailed guides: 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). - 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). diff --git a/docs/guides/codebase-documentation-awareness.mdx b/docs/guides/codebase-documentation-awareness.mdx index 055055360..a79805a34 100644 --- a/docs/guides/codebase-documentation-awareness.mdx +++ b/docs/guides/codebase-documentation-awareness.mdx @@ -84,7 +84,6 @@ You can use the `gh` CLI to: #### DeepWiki MCP [DeepWiki MCP](https://hub.continue.dev/deepwiki/deepwiki-mcp) lets your agent explore any public GitHub repository. -``` Once configured, your agent can explore repositories like: - "Explore the React repository structure" @@ -180,4 +179,4 @@ The new approach provides better integration with Continue's Agent features and - Learn more about [MCP servers](/reference/continue-mcp) - Explore [rules configuration](/customize/deep-dives/rules) -- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains \ No newline at end of file +- Set up [custom assistants](/guides/understanding-assistants) with specific knowledge domains diff --git a/docs/guides/continuous-ai.mdx b/docs/guides/continuous-ai.mdx index c7280ef75..bd88c2228 100644 --- a/docs/guides/continuous-ai.mdx +++ b/docs/guides/continuous-ai.mdx @@ -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. - - 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. + + 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. @@ -203,5 +203,5 @@ Ready to amplify your development workflow with Continuous AI? Start with one si Check out our guides on [Continue CLI](/guides/cli) and [Understanding - Assistants](/guides/understanding-assistants). + Agents](/guides/understanding-agents). diff --git a/docs/guides/instinct.mdx b/docs/guides/instinct.mdx new file mode 100644 index 000000000..19f9bf7a1 --- /dev/null +++ b/docs/guides/instinct.mdx @@ -0,0 +1,39 @@ +--- +title: "Using Instinct with Ollama in Continue" +description: "Learn how to run Instinct, Continue's leading open Next Edit model, on your own hardware with Ollama" +--- + + + Instinct is a 7 billion parameter model. You should expect slow responses if + running on a laptop. To learn how to inference Instinct on a GPU, see our + [HuggingFace model card](https://huggingface.co/continuedev/instinct). + + +We recently released Instinct, a state-of-the-art open Next Edit model. Robustly fine-tuned from Qwen2.5-Coder-7B, Instinct intelligently predicts your next move to keep you in flow. To learn more about the model, check out [our blog post](https://blog.continue.dev). + + + + + +### 1. Install Ollama + +If you haven't already installed Ollama, see our guide [here](./ollama-guide.mdx). + +### 2. Download Instinct + +```bash +ollama run nate/instinct +``` + +### 3. Update your `config.yaml` + +Open your `config.yaml` and add Instinct to the models section: + +```yaml +# ... rest of config.yaml ... + +models: + - uses: continuedev/instinct +``` + +Alternatively, you can just click to add the block at https://hub.continue.dev/continuedev/instinct. diff --git a/docs/guides/ollama-guide.mdx b/docs/guides/ollama-guide.mdx index e800c34c2..e3fa3516a 100644 --- a/docs/guides/ollama-guide.mdx +++ b/docs/guides/ollama-guide.mdx @@ -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: diff --git a/docs/guides/understanding-assistants.mdx b/docs/guides/understanding-agents.mdx similarity index 62% rename from docs/guides/understanding-assistants.mdx rename to docs/guides/understanding-agents.mdx index 4bc35693b..d03ce8758 100644 --- a/docs/guides/understanding-assistants.mdx +++ b/docs/guides/understanding-agents.mdx @@ -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 cmd/ctrl + L (VS Code) or cmd/ctrl + J (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) diff --git a/docs/hub/agents/create-an-agent.mdx b/docs/hub/agents/create-an-agent.mdx new file mode 100644 index 000000000..f518c48f5 --- /dev/null +++ b/docs/hub/agents/create-an-agent.mdx @@ -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. diff --git a/docs/hub/agents/edit-an-agent.mdx b/docs/hub/agents/edit-an-agent.mdx new file mode 100644 index 000000000..d4f74fd5b --- /dev/null +++ b/docs/hub/agents/edit-an-agent.mdx @@ -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. diff --git a/docs/hub/agents/intro.mdx b/docs/hub/agents/intro.mdx new file mode 100644 index 000000000..7747c8145 --- /dev/null +++ b/docs/hub/agents/intro.mdx @@ -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. diff --git a/docs/hub/agents/use-an-agent.mdx b/docs/hub/agents/use-an-agent.mdx new file mode 100644 index 000000000..afefad9a3 --- /dev/null +++ b/docs/hub/agents/use-an-agent.mdx @@ -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) diff --git a/docs/hub/assistants/create-an-assistant.mdx b/docs/hub/assistants/create-an-assistant.mdx deleted file mode 100644 index dd7ee9678..000000000 --- a/docs/hub/assistants/create-an-assistant.mdx +++ /dev/null @@ -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. diff --git a/docs/hub/assistants/edit-an-assistant.mdx b/docs/hub/assistants/edit-an-assistant.mdx deleted file mode 100644 index 235b01358..000000000 --- a/docs/hub/assistants/edit-an-assistant.mdx +++ /dev/null @@ -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. diff --git a/docs/hub/assistants/intro.mdx b/docs/hub/assistants/intro.mdx deleted file mode 100644 index fd556b16a..000000000 --- a/docs/hub/assistants/intro.mdx +++ /dev/null @@ -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. diff --git a/docs/hub/assistants/use-an-assistant.mdx b/docs/hub/assistants/use-an-assistant.mdx deleted file mode 100644 index f6d19b836..000000000 --- a/docs/hub/assistants/use-an-assistant.mdx +++ /dev/null @@ -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) diff --git a/docs/hub/blocks/block-types.mdx b/docs/hub/blocks/block-types.mdx index f544885f9..461072d46 100644 --- a/docs/hub/blocks/block-types.mdx +++ b/docs/hub/blocks/block-types.mdx @@ -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. diff --git a/docs/hub/blocks/create-a-block.mdx b/docs/hub/blocks/create-a-block.mdx index 2c5dc58fb..3b59267a8 100644 --- a/docs/hub/blocks/create-a-block.mdx +++ b/docs/hub/blocks/create-a-block.mdx @@ -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. diff --git a/docs/hub/blocks/intro.mdx b/docs/hub/blocks/intro.mdx index d4cc1c25c..7180b3f63 100644 --- a/docs/hub/blocks/intro.mdx +++ b/docs/hub/blocks/intro.mdx @@ -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. diff --git a/docs/hub/blocks/use-a-block.mdx b/docs/hub/blocks/use-a-block.mdx index 3971dbc63..ed5ff7cb3 100644 --- a/docs/hub/blocks/use-a-block.mdx +++ b/docs/hub/blocks/use-a-block.mdx @@ -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: diff --git a/docs/hub/governance/creating-an-org.mdx b/docs/hub/governance/creating-an-org.mdx index dfcb0665e..c0a021000 100644 --- a/docs/hub/governance/creating-an-org.mdx +++ b/docs/hub/governance/creating-an-org.mdx @@ -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 diff --git a/docs/hub/secrets/secret-types.mdx b/docs/hub/secrets/secret-types.mdx index b5f75de6a..ebf3d39ca 100644 --- a/docs/hub/secrets/secret-types.mdx +++ b/docs/hub/secrets/secret-types.mdx @@ -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. diff --git a/docs/hub/sharing.mdx b/docs/hub/sharing.mdx index d8de121a0..b429dbd9d 100644 --- a/docs/hub/sharing.mdx +++ b/docs/hub/sharing.mdx @@ -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) --- diff --git a/docs/hub/source-control.mdx b/docs/hub/source-control.mdx index 5e863336b..ee0c410ec 100644 --- a/docs/hub/source-control.mdx +++ b/docs/hub/source-control.mdx @@ -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). diff --git a/docs/images/features/autocomplete/images/instinct-autocomplete.png b/docs/images/features/autocomplete/images/instinct-autocomplete.png new file mode 100644 index 000000000..3da34143d Binary files /dev/null and b/docs/images/features/autocomplete/images/instinct-autocomplete.png differ diff --git a/docs/images/instinct.gif b/docs/images/instinct.gif new file mode 100644 index 000000000..840a8f304 Binary files /dev/null and b/docs/images/instinct.gif differ diff --git a/docs/reference.mdx b/docs/reference.mdx index e67d5dad9..0024f5bff 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -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 Config YAML replaces `config.json`, which is deprecated. View the **[Migration Guide](/reference/yaml-migration)**. -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 diff --git a/docs/reference/continue-mcp.mdx b/docs/reference/continue-mcp.mdx index bd7d7d3cf..882a662c8 100644 --- a/docs/reference/continue-mcp.mdx +++ b/docs/reference/continue-mcp.mdx @@ -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 diff --git a/docs/reference/deprecated-docs.mdx b/docs/reference/deprecated-docs.mdx index c972db7fa..a62e88b49 100644 --- a/docs/reference/deprecated-docs.mdx +++ b/docs/reference/deprecated-docs.mdx @@ -408,4 +408,4 @@ The following configuration example includes: -This setup could also involve enabling Chromium as a backup for local documentation through the [User Settings Page](../customize/settings). \ No newline at end of file +This setup could also involve enabling Chromium as a backup for local documentation through the User Settings Page (Gear Icon). \ No newline at end of file diff --git a/docs/snippets/ModelRecommendations.jsx b/docs/snippets/ModelRecommendations.jsx index a65e04371..a802e96b7 100644 --- a/docs/snippets/ModelRecommendations.jsx +++ b/docs/snippets/ModelRecommendations.jsx @@ -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", }, @@ -117,11 +117,11 @@ export const ModelRecommendations = ({ role = "all" }) => { notes: "Open models are beginning to emerge for this model role", }, next_edit: { - open: ["N/A"], + 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 significantly better than open models", + notes: "Closed models are better than open models", }, }; diff --git a/extensions/cli/.github/workflows/respond-to-cubic-dev-ai.yml b/extensions/cli/.github/workflows/respond-to-cubic-dev-ai.yml deleted file mode 100644 index 5d3f40c56..000000000 --- a/extensions/cli/.github/workflows/respond-to-cubic-dev-ai.yml +++ /dev/null @@ -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 }}" diff --git a/extensions/cli/build.mjs b/extensions/cli/build.mjs index f5f20778c..5f4e18656 100644 --- a/extensions/cli/build.mjs +++ b/extensions/cli/build.mjs @@ -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 diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 6510bc717..8bb910c94 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -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", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 1fefcd973..68594f379 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -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", diff --git a/extensions/cli/spec/ctrl-c-behavior.md b/extensions/cli/spec/ctrl-c-behavior.md new file mode 100644 index 000000000..9d11f26ab --- /dev/null +++ b/extensions/cli/spec/ctrl-c-behavior.md @@ -0,0 +1,32 @@ +# Ctrl+C Exit Behavior + +## Overview + +Ctrl+C operates on two levels: + +1. **Menus/Selectors**: Immediate cancellation and return to previous state +2. **Main Application**: Two-stage exit requiring double Ctrl+C within 1 second + +## Two-Stage Exit (Main Application) + +### First Ctrl+C + +- Shows temporary status message "ctrl+c to exit" in bottom-left status bar +- Message automatically disappears after 1 second +- Clears any text in the input field (if focused) +- Does **not** exit the application + +### Second Ctrl+C (within 1 second) + +- Exits the application immediately +- Performs graceful shutdown + +### Second Ctrl+C (after 1 second) + +- Treated as a new "first Ctrl+C" +- Shows exit message again +- User must press Ctrl+C twice within 1 second window to actually exit + +## Menu/Selector Cancellation + +Ctrl+C immediately cancels and returns to the previous state in all interactive menus and selectors. diff --git a/extensions/cli/spec/otlp-metrics.md b/extensions/cli/spec/otlp-metrics.md index 744709b10..f1398558f 100644 --- a/extensions/cli/spec/otlp-metrics.md +++ b/extensions/cli/spec/otlp-metrics.md @@ -51,7 +51,7 @@ All metrics and events share these standard attributes: ## Core Metrics -### βœ… `continue.cli.session.count` +### βœ… `continue_cli_session_count` **Type:** Counter **Unit:** `count` @@ -65,7 +65,7 @@ All metrics and events share these standard attributes: --- -### βœ… `continue.cli.lines_of_code.count` +### βœ… `continue_cli_lines_of_code_count` **Type:** Counter **Unit:** `count` @@ -80,7 +80,7 @@ All metrics and events share these standard attributes: --- -### βœ… `continue.cli.pull_request.count` +### βœ… `continue_cli_pull_request_count` **Type:** Counter **Unit:** `count` @@ -94,7 +94,7 @@ All metrics and events share these standard attributes: --- -### βœ… `continue.cli.commit.count` +### βœ… `continue_cli_commit_count` **Type:** Counter **Unit:** `count` @@ -108,7 +108,7 @@ All metrics and events share these standard attributes: --- -### βœ… `continue.cli.cost.usage` +### βœ… `continue_cli_cost_usage` **Type:** Counter **Unit:** `USD` @@ -123,7 +123,7 @@ All metrics and events share these standard attributes: --- -### βœ… `continue.cli.token.usage` +### βœ… `continue_cli_token_usage` **Type:** Counter **Unit:** `tokens` @@ -139,7 +139,7 @@ All metrics and events share these standard attributes: --- -### ❌ `continue.cli.code_edit_tool.decision` +### ❌ `continue_cli_code_edit_tool_decision` **Type:** Counter **Unit:** `count` @@ -156,7 +156,7 @@ All metrics and events share these standard attributes: --- -### βœ… `continue.cli.active_time.total` +### βœ… `continue_cli_active_time_total` **Type:** Counter **Unit:** `s` @@ -172,7 +172,7 @@ All metrics and events share these standard attributes: ### βœ… User Prompt Event -**Event Name:** `continue.cli.user_prompt` +**Event Name:** `continue_cli_user_prompt` **Attributes:** @@ -188,7 +188,7 @@ All metrics and events share these standard attributes: ### βœ… Tool Result Event -**Event Name:** `continue.cli.tool_result` +**Event Name:** `continue_cli_tool_result` **Attributes:** @@ -209,7 +209,7 @@ All metrics and events share these standard attributes: ### βœ… API Request Event -**Event Name:** `continue.cli.api_request` +**Event Name:** `continue_cli_api_request` **Attributes:** @@ -232,7 +232,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Authentication Metrics -#### βœ… `continue.cli.auth.attempts` +#### βœ… `continue_cli_auth_attempts` **Type:** Counter **Unit:** `{attempt}` @@ -248,7 +248,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### MCP Integration Metrics -#### ❌ `continue.cli.mcp.connections` +#### ❌ `continue_cli_mcp_connections` **Type:** Gauge **Unit:** `{connection}` @@ -264,7 +264,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Performance Metrics -#### ❌ `continue.cli.startup.time` +#### ❌ `continue_cli_startup_time` **Type:** Histogram **Unit:** `ms` @@ -278,7 +278,7 @@ These metrics are unique to Continue CLI and provide additional insights without **Implementation:** Track in `src/index.ts` and `src/commands/chat.ts` -#### βœ… `continue.cli.response_time` +#### βœ… `continue_cli_response_time` **Type:** Histogram **Unit:** `ms` @@ -297,7 +297,7 @@ These metrics are unique to Continue CLI and provide additional insights without ### Migration from Claude Code Dashboards -The core metrics (`session.count`, `lines_of_code.count`, `token.usage`, `cost.usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code.*` to `continue.cli.*`. +The core metrics (`session_count`, `lines_of_code_count`, `token_usage`, `cost_usage`, etc.) use identical naming and attribute structures to Claude Code, allowing for easy dashboard migration by simply changing the metric prefix from `claude_code_*` to `continue_cli_*`. ### Privacy Considerations @@ -337,6 +337,6 @@ All metrics should include these resource attributes: **Missing implementations:** -- `continue.cli.code_edit_tool.decision` - requires user confirmation UI -- `continue.cli.mcp.connections` - needs MCP service monitoring -- `continue.cli.startup.time` - needs startup time tracking +- `continue_cli_code_edit_tool_decision` - requires user confirmation UI +- `continue_cli_mcp_connections` - needs MCP service monitoring +- `continue_cli_startup_time` - needs startup time tracking diff --git a/extensions/cli/spec/shell-mode.md b/extensions/cli/spec/shell-mode.md new file mode 100644 index 000000000..a3bdd6cf4 --- /dev/null +++ b/extensions/cli/spec/shell-mode.md @@ -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. diff --git a/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts new file mode 100644 index 000000000..563efbbe9 --- /dev/null +++ b/extensions/cli/src/__tests__/CtrlCProcessHandling.test.ts @@ -0,0 +1,12 @@ +import { describe, expect, it } from "vitest"; + +describe("Process SIGINT handling functions", () => { + it("exports the necessary functions for exit message handling", async () => { + const indexModule = await import("../index.js"); + + // Verify the functions exist + expect(typeof indexModule.shouldShowExitMessage).toBe("function"); + expect(typeof indexModule.setExitMessageCallback).toBe("function"); + expect(typeof indexModule.setTUIUnmount).toBe("function"); + }); +}); diff --git a/extensions/cli/src/index.ts b/extensions/cli/src/index.ts index 91b5a6c78..cd7f34704 100644 --- a/extensions/cli/src/index.ts +++ b/extensions/cli/src/index.ts @@ -23,6 +23,71 @@ import { logger } from "./util/logger.js"; import { readStdinSync } from "./util/stdin.js"; import { getVersion } from "./version.js"; +// TUI lifecycle and two-stage exit state management +let tuiUnmount: (() => void) | null; +let showExitMessage: boolean; +let exitMessageCallback: (() => void) | null; +let lastCtrlCTime: number; + +// Initialize state immediately to avoid temporal dead zone issues with exported functions +(function initializeTUIState() { + tuiUnmount = null; + showExitMessage = false; + exitMessageCallback = null; + lastCtrlCTime = 0; +})(); + +// Register TUI cleanup function for graceful shutdown +export function setTUIUnmount(unmount: () => void) { + tuiUnmount = unmount; +} + +// Register callback to trigger UI updates when exit message state changes +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; +} + // Add global error handlers to prevent uncaught errors from crashing the process process.on("unhandledRejection", (reason, promise) => { logger.error("Unhandled Rejection at:", { promise, reason }); @@ -265,12 +330,6 @@ try { process.exit(1); } -// Graceful shutdown - flush Sentry data -process.on("SIGINT", async () => { - await sentryService.flush(); - process.exit(0); -}); - process.on("SIGTERM", async () => { await sentryService.flush(); process.exit(0); diff --git a/extensions/cli/src/permissions/permissionChecker.test.ts b/extensions/cli/src/permissions/permissionChecker.test.ts index c860a6454..b28034b40 100644 --- a/extensions/cli/src/permissions/permissionChecker.test.ts +++ b/extensions/cli/src/permissions/permissionChecker.test.ts @@ -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); + }); + }); + }); }); diff --git a/extensions/cli/src/permissions/permissionChecker.ts b/extensions/cli/src/permissions/permissionChecker.ts index 9b2f5d557..55a4fbfab 100644 --- a/extensions/cli/src/permissions/permissionChecker.ts +++ b/extensions/cli/src/permissions/permissionChecker.ts @@ -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, }; } diff --git a/extensions/cli/src/services/MCPService.test.ts b/extensions/cli/src/services/MCPService.test.ts index 8fd14676e..f61be6946 100644 --- a/extensions/cli/src/services/MCPService.test.ts +++ b/extensions/cli/src/services/MCPService.test.ts @@ -1,5 +1,5 @@ import { AssistantConfig } from "@continuedev/sdk"; -import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { MCPService } from "./MCPService.js"; @@ -21,6 +21,14 @@ vi.mock("@modelcontextprotocol/sdk/client/stdio.js", () => ({ StdioClientTransport: vi.fn(), })); +vi.mock("@modelcontextprotocol/sdk/client/sse.js", () => ({ + SSEClientTransport: vi.fn(), +})); + +vi.mock("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({ + StreamableHTTPClientTransport: vi.fn(), +})); + describe("MCPService", () => { let mcpService: MCPService; let mockAssistant: AssistantConfig; @@ -152,4 +160,56 @@ describe("MCPService", () => { await expect(mcpService.cleanup()).resolves.not.toThrow(); }); }); + + describe("transport types", () => { + it("should support SSE transport", async () => { + const sseAssistant: AssistantConfig = { + name: "sse-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "sse-server", + type: "sse", + url: "https://example.com/sse", + }, + ], + } as AssistantConfig; + + await expect(mcpService.initialize(sseAssistant)).resolves.not.toThrow(); + }); + + it("should support streamable-http transport", async () => { + const httpAssistant: AssistantConfig = { + name: "http-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "http-server", + type: "streamable-http", + url: "https://example.com/http", + }, + ], + } as AssistantConfig; + + await expect(mcpService.initialize(httpAssistant)).resolves.not.toThrow(); + }); + + it("should default to stdio transport when type is not specified", async () => { + const defaultAssistant: AssistantConfig = { + name: "default-assistant", + version: "1.0.0", + mcpServers: [ + { + name: "default-server", + command: "npx", + args: ["-v"], + }, + ], + } as AssistantConfig; + + await expect( + mcpService.initialize(defaultAssistant), + ).resolves.not.toThrow(); + }); + }); }); diff --git a/extensions/cli/src/services/MCPService.ts b/extensions/cli/src/services/MCPService.ts index da56e0712..8088894e0 100644 --- a/extensions/cli/src/services/MCPService.ts +++ b/extensions/cli/src/services/MCPService.ts @@ -1,6 +1,9 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { getErrorString } from "../util/error.js"; import { logger } from "../util/logger.js"; @@ -9,9 +12,9 @@ import { BaseService, ServiceWithDependencies } from "./BaseService.js"; import { serviceContainer } from "./ServiceContainer.js"; import { MCPConnectionInfo, + MCPServerConfig, MCPServiceState, SERVICE_NAMES, - MCPServerConfig, } from "./types.js"; interface ServerConnection extends MCPConnectionInfo { @@ -214,31 +217,12 @@ export class MCPService this.updateState(); try { - if (serverConfig.type && serverConfig.type !== "stdio") { - throw new Error( - `${serverConfig.type} MCP servers are not yet supported in the Continue CLI`, - ); - } - if (!serverConfig.command) { - throw new Error("MCP server command is not specified"); - } - const client = new Client( { name: "continue-cli-client", version: "1.0.0" }, { capabilities: {} }, ); - const env: Record = serverConfig.env || {}; - if (process.env.PATH !== undefined) { - env.PATH = process.env.PATH; - } - - const transport = new StdioClientTransport({ - command: serverConfig.command, - args: serverConfig.args, - env, - stderr: "ignore", - }); + const transport = await this.constructTransport(serverConfig); logger.debug("Connecting to MCP server", { name: serverName, @@ -363,4 +347,68 @@ export class MCPService logger.debug("Shutting down MCPService"); await this.shutdownConnections(); } + + /** + * Construct transport based on server configuration + */ + private async constructTransport( + serverConfig: MCPServerConfig, + ): Promise { + const transportType = serverConfig.type || "stdio"; + + switch (transportType) { + case "stdio": + if (!serverConfig.command) { + throw new Error( + "MCP server command is not specified for stdio transport", + ); + } + + const env: Record = serverConfig.env || {}; + if (process.env.PATH !== undefined) { + env.PATH = process.env.PATH; + } + + return new StdioClientTransport({ + command: serverConfig.command, + args: serverConfig.args || [], + env, + cwd: serverConfig.cwd, + stderr: "ignore", + }); + + case "sse": + if (!serverConfig.url) { + throw new Error("MCP server URL is not specified for SSE transport"); + } + return new SSEClientTransport(new URL(serverConfig.url), { + eventSourceInit: { + fetch: (input, init) => + fetch(input, { + ...init, + headers: { + ...init?.headers, + ...(serverConfig.requestOptions?.headers as + | Record + | undefined), + }, + }), + }, + requestInit: { headers: serverConfig.requestOptions?.headers }, + }); + + case "streamable-http": + if (!serverConfig.url) { + throw new Error( + "MCP server URL is not specified for streamable-http transport", + ); + } + return new StreamableHTTPClientTransport(new URL(serverConfig.url), { + requestInit: { headers: serverConfig.requestOptions?.headers }, + }); + + default: + throw new Error(`Unsupported transport type: ${transportType}`); + } + } } diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index b5dc3d9aa..509ce8f61 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -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 }; diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 69bace2ea..06e0a68c0 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -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 { +): 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?.( diff --git a/extensions/cli/src/telemetry/posthogService.ts b/extensions/cli/src/telemetry/posthogService.ts index 22c2beb0f..0dd5691b5 100644 --- a/extensions/cli/src/telemetry/posthogService.ts +++ b/extensions/cli/src/telemetry/posthogService.ts @@ -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}`); diff --git a/extensions/cli/src/telemetry/telemetryService.ts b/extensions/cli/src/telemetry/telemetryService.ts index beffc672a..70cf90860 100644 --- a/extensions/cli/src/telemetry/telemetryService.ts +++ b/extensions/cli/src/telemetry/telemetryService.ts @@ -37,6 +37,7 @@ class TelemetryService { private startTime = Date.now(); private activeStartTime: number | null = null; private totalActiveTime = 0; + private shutdownHandlersRegistered = false; // Metrics private sessionCounter: any = null; @@ -114,7 +115,7 @@ class TelemetryService { ), }), exportIntervalMillis: parseInt( - process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000", + process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000", ), }), ); @@ -124,7 +125,7 @@ class TelemetryService { new PeriodicExportingMetricReader({ exporter: new ConsoleMetricExporter(), exportIntervalMillis: parseInt( - process.env.OTEL_METRIC_EXPORT_INTERVAL || "60000", + process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000", ), }), ); @@ -143,15 +144,38 @@ class TelemetryService { this.initializeMetrics(); - logger.debug("Telemetry service initialized", { + // Set up graceful shutdown handlers + this.setupShutdownHandlers(); + + logger.info("Telemetry service initialized", { sessionId: this.config.sessionId, exporters: metricsExporters, + exportInterval: process.env.OTEL_METRIC_EXPORT_INTERVAL || "20000", }); } catch (error) { logger.error("Failed to initialize telemetry", error); } } + /** + * Set up process handlers to ensure metrics are flushed on shutdown + */ + private setupShutdownHandlers() { + if (this.shutdownHandlersRegistered) return; + + const shutdownHandler = async () => { + logger.debug("Process shutdown detected, flushing telemetry..."); + await this.shutdown(); + }; + + // Handle graceful shutdown - use once() to avoid duplicate handlers + process.once("beforeExit", shutdownHandler); + process.once("SIGINT", shutdownHandler); + process.once("SIGTERM", shutdownHandler); + + this.shutdownHandlersRegistered = true; + } + private parseHeaders(headersStr: string): Record { const headers: Record = {}; if (!headersStr) return headers; @@ -171,7 +195,7 @@ class TelemetryService { // Core metrics (Claude Code compatible) this.sessionCounter = this.meter.createCounter( - "continue.cli.session.count", + "continue_cli_session_count", { description: "Count of CLI sessions started", unit: "count", @@ -179,7 +203,7 @@ class TelemetryService { ); this.linesOfCodeCounter = this.meter.createCounter( - "continue.cli.lines_of_code.count", + "continue_cli_lines_of_code_count", { description: "Count of lines of code modified", unit: "count", @@ -187,30 +211,30 @@ class TelemetryService { ); this.pullRequestCounter = this.meter.createCounter( - "continue.cli.pull_request.count", + "continue_cli_pull_request_count", { description: "Number of pull requests created", unit: "count", }, ); - this.commitCounter = this.meter.createCounter("continue.cli.commit.count", { + this.commitCounter = this.meter.createCounter("continue_cli_commit_count", { description: "Number of git commits created", unit: "count", }); - this.costCounter = this.meter.createCounter("continue.cli.cost.usage", { + this.costCounter = this.meter.createCounter("continue_cli_cost_usage", { description: "Cost of the Continue CLI session", unit: "USD", }); - this.tokenCounter = this.meter.createCounter("continue.cli.token.usage", { + this.tokenCounter = this.meter.createCounter("continue_cli_token_usage", { description: "Number of tokens used", unit: "tokens", }); this.codeEditDecisionCounter = this.meter.createCounter( - "continue.cli.code_edit_tool.decision", + "continue_cli_code_edit_tool_decision", { description: "Count of code editing tool permission decisions", unit: "count", @@ -218,7 +242,7 @@ class TelemetryService { ); this.activeTimeCounter = this.meter.createCounter( - "continue.cli.active_time.total", + "continue_cli_active_time_total", { description: "Total active time in seconds", unit: "s", @@ -227,7 +251,7 @@ class TelemetryService { // Additional Continue CLI specific metrics this.authAttemptsCounter = this.meter.createCounter( - "continue.cli.auth.attempts", + "continue_cli_auth_attempts", { description: "Authentication attempts", unit: "{attempt}", @@ -235,7 +259,7 @@ class TelemetryService { ); this.mcpConnectionsGauge = this.meter.createObservableGauge( - "continue.cli.mcp.connections", + "continue_cli_mcp_connections", { description: "Active MCP connections", unit: "{connection}", @@ -243,7 +267,7 @@ class TelemetryService { ); this.startupTimeHistogram = this.meter.createHistogram( - "continue.cli.startup.time", + "continue_cli_startup_time", { description: "Time from CLI start to ready state", unit: "ms", @@ -251,7 +275,7 @@ class TelemetryService { ); this.responseTimeHistogram = this.meter.createHistogram( - "continue.cli.response_time", + "continue_cli_response_time", { description: "LLM response time metrics", unit: "ms", @@ -312,6 +336,7 @@ class TelemetryService { public recordSessionStart() { if (!this.isEnabled()) return; + logger.debug("Recording session start with telemetry"); this.sessionCounter.add(1, this.getStandardAttributes()); this.recordStartupTime(Date.now() - this.startTime); } @@ -542,9 +567,26 @@ class TelemetryService { return this.config.sessionId; } - public shutdown() { + /** + * Shutdown telemetry service and ensure all metrics are flushed + */ + public async shutdown(): Promise { this.stopActiveTime(); - return this.meterProvider?.shutdown(); + + if (this.meterProvider) { + try { + logger.debug("Flushing telemetry metrics before shutdown..."); + // Force flush any pending metrics before shutdown + await this.meterProvider.forceFlush(); + logger.debug("Telemetry metrics flushed successfully"); + + // Now shutdown the provider + await this.meterProvider.shutdown(); + logger.debug("Telemetry service shut down successfully"); + } catch (error) { + logger.error("Failed to shutdown telemetry service", error); + } + } } } diff --git a/extensions/cli/src/tools/edit.test.ts b/extensions/cli/src/tools/edit.test.ts index d3b0764b9..03c58c4ed 100644 --- a/extensions/cli/src/tools/edit.test.ts +++ b/extensions/cli/src/tools/edit.test.ts @@ -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, }; diff --git a/extensions/cli/src/tools/edit.ts b/extensions/cli/src/tools/edit.ts index a7b31ca10..545d14269 100644 --- a/extensions/cli/src/tools/edit.ts +++ b/extensions/cli/src/tools/edit.ts @@ -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(); - 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); -} diff --git a/extensions/cli/src/tools/multiEdit.test.ts b/extensions/cli/src/tools/multiEdit.test.ts index 408084652..597cab767 100644 --- a/extensions/cli/src/tools/multiEdit.test.ts +++ b/extensions/cli/src/tools/multiEdit.test.ts @@ -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(() => { diff --git a/extensions/cli/src/tools/multiEdit.ts b/extensions/cli/src/tools/multiEdit.ts index b0ec1cb26..2164c6742 100644 --- a/extensions/cli/src/tools/multiEdit.ts +++ b/extensions/cli/src/tools/multiEdit.ts @@ -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", diff --git a/extensions/cli/src/tools/readFile.ts b/extensions/cli/src/tools/readFile.ts index bca811696..9f270ae30 100644 --- a/extensions/cli/src/tools/readFile.ts +++ b/extensions/cli/src/tools/readFile.ts @@ -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(); +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) { diff --git a/extensions/cli/src/tools/runTerminalCommand.ts b/extensions/cli/src/tools/runTerminalCommand.ts index 9aefceb9b..726c86501 100644 --- a/extensions/cli/src/tools/runTerminalCommand.ts +++ b/extensions/cli/src/tools/runTerminalCommand.ts @@ -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, + ): ToolPolicy => { + return evaluateTerminalCommandSecurity( + basePolicy, + parsedArgs.command as string, + ); + }, preprocess: async (args) => { const command = args.command; if (!command || typeof command !== "string") { diff --git a/extensions/cli/src/tools/types.ts b/extensions/cli/src/tools/types.ts index e70c96e7b..04c164ad4 100644 --- a/extensions/cli/src/tools/types.ts +++ b/extensions/cli/src/tools/types.ts @@ -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; readonly?: boolean; // Indicates if the tool is readonly isBuiltIn: boolean; + evaluateToolCallPolicy?: ( + basePolicy: ToolPolicy, + parsedArgs: Record, + ) => ToolPolicy; } export interface ToolCall { diff --git a/extensions/cli/src/ui/ConfigSelector.tsx b/extensions/cli/src/ui/ConfigSelector.tsx index f47a97b1b..8c8d2ae55 100644 --- a/extensions/cli/src/ui/ConfigSelector.tsx +++ b/extensions/cli/src/ui/ConfigSelector.tsx @@ -12,6 +12,7 @@ import { } from "../auth/workos.js"; import { getApiClient } from "../config.js"; import { env } from "../env.js"; +import { services } from "../services/index.js"; import { Selector, SelectorOption } from "./Selector.js"; @@ -118,8 +119,10 @@ const ConfigSelector: React.FC = ({ displaySuffix: " (opens web)", }); - // Determine current config by checking auth config + // Determine current config by checking both auth config and service state const assistantSlug = getAssistantSlug(authConfig); + const currentConfigState = services.config.getState(); + if (assistantSlug) { // Find the matching config by slug and organization const matchingConfig = options.find( @@ -129,8 +132,12 @@ const ConfigSelector: React.FC = ({ opt.organizationId === currentOrganizationId, ); currentId = matchingConfig?.id || null; - } else if (fs.existsSync(CONFIG_PATH)) { - // No assistant slug means local config is current + } else if ( + currentConfigState.configPath === CONFIG_PATH && + fs.existsSync(CONFIG_PATH) + ) { + // Only mark local config as current if it's actually the active config path in the service + // This ensures we don't show a green checkmark for first-time users just because the file exists currentId = "local"; } diff --git a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx index 5a4638e2e..0943d8015 100644 --- a/extensions/cli/src/ui/FreeTrialTransitionUI.tsx +++ b/extensions/cli/src/ui/FreeTrialTransitionUI.tsx @@ -15,6 +15,7 @@ import { import { updateAnthropicModelInYaml } from "../util/yamlConfigUpdater.js"; import { useNavigation } from "./context/NavigationContext.js"; +import { defaultBoxStyles } from "./styles.js"; const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); @@ -130,6 +131,18 @@ const FreeTrialTransitionUI: React.FC = ({ const hasOrganizations = organizations && organizations.length > 0; useInput((input, key) => { + // Allow Escape to cancel immediately, but Ctrl+C uses two-stage exit + if (key.escape) { + closeCurrentScreen(); + return; + } + + // Handle Ctrl+C with two-stage exit (delegates to main process) + if (key.ctrl && input === "c") { + process.kill(process.pid, "SIGINT"); + return; + } + if (currentStep === "choice") { handleChoiceInput({ input, @@ -215,39 +228,38 @@ const FreeTrialTransitionUI: React.FC = ({ }; if (currentStep === "choice") { + const options = [ + { num: 1, text: "πŸ’³ Sign up for models add-on (recommended)" }, + { num: 2, text: "πŸ”‘ Enter your Anthropic API key" }, + { num: 3, text: "βš™οΈ Switch to a different configuration" }, + ]; + + if (hasOrganizations) { + options.push({ + num: 4, + text: "🏒 Switch to organization configuration", + }); + } + return ( - + πŸš€ Free trial limit reached! Choose how you'd like to continue: - - {selectedOption === 1 ? "β–Ά " : " "}1. πŸ’³ Sign up for models add-on - (recommended) - - - {selectedOption === 2 ? "β–Ά " : " "}2. πŸ”‘ Enter your Anthropic API - key - - - {selectedOption === 3 ? "β–Ά " : " "}3. βš™οΈ Switch to a different - configuration - - {hasOrganizations && ( - - {selectedOption === 4 ? "β–Ά " : " "}4. 🏒 Switch to organization - configuration + {options.map((option) => ( + + {selectedOption === option.num ? "➀ " : " "} + {option.num}. {option.text} - )} + ))} - Use ↑↓ arrows or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, + ↑/↓ to navigate or {hasOrganizations ? "1/2/3/4" : "1/2/3"} to select, Enter to confirm @@ -256,12 +268,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "enterApiKey") { return ( - + Enter your Anthropic API key @@ -278,12 +285,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "processing") { return ( - + Processing... @@ -294,12 +296,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "success") { return ( - + Success! @@ -316,12 +313,7 @@ const FreeTrialTransitionUI: React.FC = ({ if (currentStep === "error") { return ( - + Error diff --git a/extensions/cli/src/ui/MCPSelector.tsx b/extensions/cli/src/ui/MCPSelector.tsx index fb84a4c60..f9db017ef 100644 --- a/extensions/cli/src/ui/MCPSelector.tsx +++ b/extensions/cli/src/ui/MCPSelector.tsx @@ -3,11 +3,18 @@ import React, { useState } from "react"; import { quote } from "shell-quote"; import { useServices } from "../hooks/useService.js"; -import { MCPServiceState, SERVICE_NAMES } from "../services/types.js"; +import { + MCPConnectionInfo, + MCPServerStatus, + MCPServiceState, + SERVICE_NAMES, +} from "../services/types.js"; import { logger } from "../util/logger.js"; +import { defaultBoxStyles } from "./styles.js"; + // Utility function to get status icon and color based on server connection -const getServerStatusDisplay = (conn: any) => { +const getServerStatusDisplay = (conn: MCPConnectionInfo) => { let icon = "βšͺ️"; // note, white circle causes extra blank line bug let color: "green" | "yellow" | "red" | "white" | "dim" = "white"; let statusText = conn.status; @@ -22,7 +29,7 @@ const getServerStatusDisplay = (conn: any) => { if (conn.warnings && conn.warnings.length > 0) { icon = "🟑"; color = "yellow"; - statusText = "connected (with warnings)"; + statusText = "connected (with warnings)" as MCPServerStatus; } else { icon = "🟒"; color = "green"; @@ -170,7 +177,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {/* Add prompts if any */} {serverInfo.prompts.length > 0 && ( - πŸ“ Prompts: {serverInfo.prompts.length} + πŸ“ Prompts: {serverInfo.prompts.length} {serverInfo.prompts.map((prompt, index) => ( β€’ {prompt.name} @@ -182,7 +189,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { {/* Add tools if any */} {serverInfo.tools.length > 0 && ( - πŸ”§ Tools: {serverInfo.tools.length} + πŸ”§ Tools: {serverInfo.tools.length} {serverInfo.tools.map((tool, index) => ( β€’ {tool.name} @@ -210,13 +217,14 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const maxIndex = Math.max(0, items.length - 1); useInput(async (input, key) => { - if (isLoading) return; - - if (key.escape) { + // Always allow escape/Ctrl+C so users can cancel even when loading + if (key.escape || (key.ctrl && input === "c")) { handleBack(); return; } + if (isLoading) return; + if (key.upArrow) { setSelectedIndex(selectedIndex <= 0 ? maxIndex : selectedIndex - 1); return; @@ -302,7 +310,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { const renderHeader = () => { return ( - + {menuState === "server-detail" && selectedServer ? `Server: ${selectedServer}` : "MCP Servers"} @@ -336,13 +344,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { }; return ( - + {renderHeader()} {message && ( @@ -369,9 +371,8 @@ export const MCPSelector: React.FC = ({ onCancel }) => { key={`${item.value}-${index}`} color={isSelected ? "blue" : "white"} bold={isSelected} - inverse={isSelected} > - {isSelected ? "> " : " "} + {isSelected ? "➀ " : " "} {item.label} ); @@ -381,7 +382,7 @@ export const MCPSelector: React.FC = ({ onCancel }) => { - Use ↑/↓ to navigate, Enter to select, Esc to go back + ↑/↓ to navigate, Enter to select, Esc to go back diff --git a/extensions/cli/src/ui/Selector.tsx b/extensions/cli/src/ui/Selector.tsx index 6d00660f0..3e01a37e2 100644 --- a/extensions/cli/src/ui/Selector.tsx +++ b/extensions/cli/src/ui/Selector.tsx @@ -1,20 +1,14 @@ import { Box, Text, useInput } from "ink"; import React, { ReactNode } from "react"; +import { defaultBoxStyles } from "./styles.js"; + export interface SelectorOption { id: string; name: string; displaySuffix?: string; } -const boxStyles: React.ComponentProps = { - flexDirection: "column", - paddingX: 2, - paddingY: 1, - borderStyle: "round", - borderColor: "blue", -}; - interface SelectorProps { title: string; options: T[]; @@ -46,8 +40,20 @@ export function Selector({ onNavigate, renderOption, }: SelectorProps) { + // Handle input for loading and error states useInput((input, key) => { - if (key.escape) { + if (loading || error) { + if (key.escape || (key.ctrl && input === "c")) { + onCancel(); + return; + } + } + }); + + useInput((input, key) => { + if (loading || error) return; // Skip normal input handling during loading/error + + if (key.escape || (key.ctrl && input === "c")) { onCancel(); return; } @@ -70,7 +76,7 @@ export function Selector({ if (loading) { return ( - + {title} @@ -84,13 +90,13 @@ export function Selector({ if (error) { return ( - + Error {error} - Press Escape to cancel + Press Esc to cancel ); @@ -106,7 +112,7 @@ export function Selector({ color={isSelected ? "blue" : isCurrent ? "green" : "white"} bold={isSelected} > - {isSelected ? "β†’ " : " "} + {isSelected ? "➀ " : " "} {option.name} {option.displaySuffix || ""} @@ -119,7 +125,7 @@ export function Selector({ ); return ( - + {title} @@ -136,7 +142,7 @@ export function Selector({ - ↑/↓ to navigate, Enter to select, Escape to cancel + ↑/↓ to navigate, Enter to select, Esc to cancel diff --git a/extensions/cli/src/ui/ServiceDebugger.tsx b/extensions/cli/src/ui/ServiceDebugger.tsx index 1f121bd0a..e10786dc5 100644 --- a/extensions/cli/src/ui/ServiceDebugger.tsx +++ b/extensions/cli/src/ui/ServiceDebugger.tsx @@ -9,6 +9,8 @@ import { ModelServiceState, } from "../services/types.js"; +import { defaultBoxStyles } from "./styles.js"; + interface ServiceDebuggerProps { services: { auth?: AuthServiceState; @@ -60,13 +62,7 @@ const ServiceDebugger: React.FC = ({ }; return ( - + πŸ”§ Service Debug Info diff --git a/extensions/cli/src/ui/SessionSelector.tsx b/extensions/cli/src/ui/SessionSelector.tsx index 670ebf01d..2cf4927a4 100644 --- a/extensions/cli/src/ui/SessionSelector.tsx +++ b/extensions/cli/src/ui/SessionSelector.tsx @@ -1,10 +1,11 @@ -import { format, isToday, isYesterday, isThisWeek, isThisYear } from "date-fns"; +import { format, isThisWeek, isThisYear, isToday, isYesterday } from "date-fns"; import { Box, Text, useInput } from "ink"; import React, { useMemo, useState } from "react"; import { SessionMetadata } from "../session.js"; import { useTerminalSize } from "./hooks/useTerminalSize.js"; +import { defaultBoxStyles } from "./styles.js"; interface SessionSelectorProps { sessions: SessionMetadata[]; @@ -70,33 +71,31 @@ export function SessionSelector({ if (sessions.length === 0) { return ( - + No previous sessions found. Start a new conversation with: cn - Press ESC or Ctrl+D to exit + Press Esc to exit ); } return ( - + Recent Sessions - - Use ↑↓ arrows to navigate, Enter to select, ESC or Ctrl+D to exit - + ↑/↓ to navigate, Enter to select, Esc to exit {displaySessions.map((session, index) => { const isSelected = index === selectedIndex; - const indicator = isSelected ? "β–Ί " : " "; - const color = isSelected ? "cyan" : "white"; + const indicator = isSelected ? "➀ " : " "; + const color = isSelected ? "blue" : "white"; return ( - + {indicator} {formatMessage(session.title)} diff --git a/extensions/cli/src/ui/SlashCommandUI.tsx b/extensions/cli/src/ui/SlashCommandUI.tsx index b4852933f..15d88bf29 100644 --- a/extensions/cli/src/ui/SlashCommandUI.tsx +++ b/extensions/cli/src/ui/SlashCommandUI.tsx @@ -73,7 +73,7 @@ const SlashCommandUI: React.FC = ({ {" "} {paddedCommandName} - {" "} + {" "} {command.description} diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index b60013046..910257523 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -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 ( + + ⚠ Interrupted by user - Press enter to resume + + ); +}; + +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 ( + + ); +}; + +const FileSearchMaybe: React.FC<{ + show: boolean; + inputMode: boolean; + hideNormalUI: boolean; + isRemoteMode: boolean; + filter: string; + selectedIndex: number; + onSelect: (path: string) => void | Promise; + onFilesUpdated: (files: Array<{ path: string; displayName: string }>) => void; +}> = ({ + show, + inputMode, + hideNormalUI, + isRemoteMode, + filter, + selectedIndex, + onSelect, + onFilesUpdated, +}) => { + if (!show || !inputMode || hideNormalUI || isRemoteMode) return null; + return ( + + ); +}; + interface UserInputProps { onSubmit: (message: string, imageMap?: Map) => void; isWaitingForResponse: boolean; @@ -70,8 +141,21 @@ const UserInput: React.FC = ({ const [inputText, setInputText] = useState(""); const [cursorPosition, setCursorPosition] = useState(0); const [showSlashCommands, setShowSlashCommands] = useState(false); + + // Clear input function for Ctrl+C + const clearInput = useCallback(() => { + textBuffer.clear(); + setInputText(""); + 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); @@ -121,6 +205,18 @@ const UserInput: React.FC = ({ 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 @@ -129,6 +225,9 @@ const UserInput: React.FC = ({ return; } + // When using slash commands, disable file search + setShowFileSearch(false); + const trimmedText = text.trimStart(); const beforeCursor = trimmedText.slice( 0, @@ -141,13 +240,8 @@ const UserInput: React.FC = ({ return; } - const afterSlash = beforeCursor.slice(1); - - // Check if we have whitespace in the command - if (afterSlash.includes(" ") || afterSlash.includes("\n")) { - setShowSlashCommands(false); - return; - } + // Get the complete slash command, not just the part before cursor + const afterSlash = trimmedText.slice(1).split(/[\s\n]/)[0]; // We're in a slash command context - check if it's a complete command const allCommands = getSlashCommands(); @@ -191,6 +285,13 @@ const UserInput: React.FC = ({ 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("@"); @@ -229,6 +330,7 @@ const UserInput: React.FC = ({ setFileSearchFilter(afterAt); setSelectedFileIndex(0); setShowSlashCommands(false); + setShowBashMode(false); } } }; @@ -273,6 +375,7 @@ const UserInput: React.FC = ({ setInputText(newText); setCursorPosition(newCursorPos); setShowSlashCommands(false); + setShowBashMode(false); } }; @@ -432,6 +535,7 @@ const UserInput: React.FC = ({ setInputText(""); setCursorPosition(0); setShowSlashCommands(false); + setShowBashMode(false); } return true; } @@ -457,6 +561,15 @@ const UserInput: React.FC = ({ 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(); @@ -478,16 +591,6 @@ const UserInput: React.FC = ({ return false; }; - // Clear input function - const clearInput = () => { - textBuffer.clear(); - setInputText(""); - setCursorPosition(0); - setShowSlashCommands(false); - setShowFileSearch(false); - inputHistory.resetNavigation(); - }; - // Handle text buffer updates for async operations like image pasting const handleTextBufferUpdate = () => { const newText = textBuffer.text; @@ -496,6 +599,7 @@ const UserInput: React.FC = ({ setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); }; @@ -592,14 +696,16 @@ const UserInput: React.FC = ({ 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 ( <> @@ -682,50 +788,44 @@ const UserInput: React.FC = ({ return ( - {/* Interruption message - shown just above the input box */} - {wasInterrupted && ( - - - ⚠ Interrupted by user - Press enter to resume - - - )} + {/* Input box */} - - {isRemoteMode ? "β—‰" : "●"}{" "} + + {showBashMode ? "$ " : isRemoteMode ? "β—‰ " : "● "} {renderInputText()} - {/* Slash command UI - show in remote mode OR when assistant is available */} - {showSlashCommands && - inputMode && - !hideNormalUI && - (isRemoteMode || assistant) && ( - - )} + - {/* File search UI - only show in local mode */} - {showFileSearch && inputMode && !hideNormalUI && !isRemoteMode && ( - - )} + ); }; diff --git a/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx new file mode 100644 index 000000000..897228a96 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/BottomStatusBarCtrlC.test.tsx @@ -0,0 +1,65 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { BottomStatusBar } from "../components/BottomStatusBar.js"; + +// Mock the index module functions +vi.mock("../../index.js", () => ({ + shouldShowExitMessage: vi.fn(() => false), + setExitMessageCallback: vi.fn(), +})); + +describe("BottomStatusBar Ctrl+C message", () => { + const defaultProps = { + currentMode: "normal" as const, + repoURLText: "github.com/user/repo", + isRemoteMode: false, + services: { model: { model: null } }, + navState: { currentScreen: "chat" }, + navigateTo: vi.fn(), + closeCurrentScreen: vi.fn(), + contextPercentage: undefined, + }; + + beforeEach(async () => { + vi.clearAllMocks(); + // Reset mocks to default state + const indexModule = (await vi.importMock("../../index.js")) as any; + indexModule.shouldShowExitMessage.mockReturnValue(false); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it("shows repo URL when not in exit message mode", async () => { + const indexModule = (await vi.importMock("../../index.js")) as any; + indexModule.shouldShowExitMessage.mockReturnValue(false); + + const { lastFrame } = render(); + + expect(lastFrame()).toContain("github.com/user/repo"); + expect(lastFrame()).not.toContain("ctrl+c to exit"); + }); + + it("shows exit message when shouldShowExitMessage returns true", async () => { + const indexModule = (await vi.importMock("../../index.js")) as any; + indexModule.shouldShowExitMessage.mockReturnValue(true); + + const { lastFrame } = render(); + + expect(lastFrame()).toContain("ctrl+c to exit"); + expect(lastFrame()).not.toContain("github.com/user/repo"); + }); + + it("registers exit message callback on mount", async () => { + const indexModule = (await vi.importMock("../../index.js")) as any; + + render(); + + expect(indexModule.setExitMessageCallback).toHaveBeenCalledWith( + expect.any(Function), + ); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/CtrlC.test.tsx b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx new file mode 100644 index 000000000..f05154977 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlC.test.tsx @@ -0,0 +1,115 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { ConfigSelector } from "../ConfigSelector.js"; +import { Selector } from "../Selector.js"; + +describe("Ctrl+C behavior", () => { + let mockOnCancel: ReturnType; + let mockOnSelect: ReturnType; + let mockProcess: any; + + beforeEach(() => { + mockOnCancel = vi.fn(); + mockOnSelect = vi.fn(); + + // Mock process.exit for testing + mockProcess = { + exit: vi.fn(), + kill: vi.fn(), + }; + vi.stubGlobal("process", mockProcess); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); + }); + + describe("Selector component", () => { + it("calls onCancel when Ctrl+C is pressed", () => { + const options = [ + { id: "1", name: "Option 1" }, + { id: "2", name: "Option 2" }, + ]; + + const { stdin } = render( + , + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + expect(mockOnSelect).not.toHaveBeenCalled(); + }); + + it("calls onCancel when Ctrl+C is pressed during loading", () => { + const options: any[] = []; + + const { stdin } = render( + , + ); + + // Simulate Ctrl+C during loading + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + + it("calls onCancel when Ctrl+C is pressed during error state", () => { + const options: any[] = []; + + const { stdin } = render( + , + ); + + // Simulate Ctrl+C during error + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + }); + + describe("ConfigSelector component", () => { + it("calls onCancel when Ctrl+C is pressed", () => { + const { stdin } = render( + , + ); + + // Simulate Ctrl+C + stdin.write("\u0003"); + + expect(mockOnCancel).toHaveBeenCalledTimes(1); + }); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx new file mode 100644 index 000000000..f40dd1414 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/CtrlCInputClearing.test.tsx @@ -0,0 +1,61 @@ +import { render } from "ink-testing-library"; +import React from "react"; +import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; + +import { UserInput } from "../UserInput.js"; + +describe("Ctrl+C input clearing", () => { + let mockOnSubmit: ReturnType; + let mockProcessKill: any; + + beforeEach(() => { + mockOnSubmit = vi.fn(); + + // Mock process.kill using vi.spyOn + mockProcessKill = vi.spyOn(process, "kill").mockImplementation(() => { + return true; + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.restoreAllMocks(); + }); + + it("sends SIGINT when Ctrl+C is pressed (input clearing tested implicitly)", () => { + const { stdin } = render( + , + ); + + // Type some text first + stdin.write("hello world"); + + // Simulate Ctrl+C using raw character code (like other tests in codebase) + stdin.write("\u0003"); + + // Should send SIGINT to process (which handles the two-stage exit) + expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT"); + }); + + it("sends SIGINT to main process for two-stage exit handling", () => { + const { stdin } = render( + , + ); + + // Simulate Ctrl+C using raw character code (like other tests in codebase) + stdin.write("\u0003"); + + // Should delegate to main process SIGINT handler + expect(mockProcessKill).toHaveBeenCalledWith(process.pid, "SIGINT"); + }); +}); diff --git a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx index 1fea1b3fb..dfb3b59ce 100644 --- a/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx +++ b/extensions/cli/src/ui/__tests__/FreeTrialTransitionUI.test.tsx @@ -37,7 +37,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { expect(frame).toContain("1. πŸ’³ Sign up for models add-on"); expect(frame).toContain("2. πŸ”‘ Enter your Anthropic API key"); expect(frame).toContain("3. βš™οΈ Switch to a different configuration"); - expect(frame).toContain("Use ↑↓ arrows or 1/2/3 to select"); + expect(frame).toContain("↑/↓ to navigate or 1/2/3 to select"); }); it("highlights first option by default", () => { @@ -46,10 +46,10 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { ); const frame = lastFrame(); - expect(frame).toContain("β–Ά 1. πŸ’³ Sign up for models add-on"); - expect(frame).not.toContain("β–Ά 2. πŸ”‘ Enter your Anthropic API key"); + expect(frame).toContain("➀ 1. πŸ’³ Sign up for models add-on"); + expect(frame).not.toContain("➀ 2. πŸ”‘ Enter your Anthropic API key"); expect(frame).not.toContain( - "β–Ά 3. βš™οΈ Switch to a different configuration", + "➀ 3. βš™οΈ Switch to a different configuration", ); }); @@ -85,7 +85,7 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { const frame = lastFrame(); expect(frame).toContain("Choose how you'd like to continue:"); expect(frame).toContain( - "Use ↑↓ arrows or 1/2/3 to select, Enter to confirm", + "↑/↓ to navigate or 1/2/3 to select, Enter to confirm", ); }); @@ -155,9 +155,9 @@ describe("FreeTrialTransitionUI - Rendering and Props Tests", () => { line.includes("Switch to a different configuration"), ); - expect(modelsLine).toContain("β–Ά"); - expect(apiKeyLine).not.toContain("β–Ά"); - expect(configLine).not.toContain("β–Ά"); + expect(modelsLine).toContain("➀"); + expect(apiKeyLine).not.toContain("➀"); + expect(configLine).not.toContain("➀"); }); }); diff --git a/extensions/cli/src/ui/components/BottomStatusBar.tsx b/extensions/cli/src/ui/components/BottomStatusBar.tsx index d31095f77..c780af456 100644 --- a/extensions/cli/src/ui/components/BottomStatusBar.tsx +++ b/extensions/cli/src/ui/components/BottomStatusBar.tsx @@ -1,6 +1,7 @@ import { Box, Text } from "ink"; -import React from "react"; +import React, { useEffect, useState } from "react"; +import { setExitMessageCallback, shouldShowExitMessage } from "../../index.js"; import type { PermissionMode } from "../../permissions/types.js"; import type { NavigationScreen } from "../context/NavigationContext.js"; import { FreeTrialStatus } from "../FreeTrialStatus.js"; @@ -31,51 +32,66 @@ export const BottomStatusBar: React.FC = ({ closeCurrentScreen, contextPercentage, hasImageInClipboard, -}) => ( - - - {currentMode === "normal" && ( - - {hasImageInClipboard ? ( - - Press Ctrl+V to paste image +}) => { + const [_refreshTrigger, setRefreshTrigger] = useState(0); + + useEffect(() => { + setExitMessageCallback(() => { + setRefreshTrigger((prev) => prev + 1); + }); + }, []); + + const showingExitMessage = shouldShowExitMessage(); + + return ( + + + {currentMode === "normal" && ( + + {hasImageInClipboard ? ( + + Press Ctrl+V to paste image + + ) : ( + + {showingExitMessage ? "ctrl+c to exit" : repoURLText} + + )} + + + )} + + {contextPercentage !== undefined && contextPercentage > 75 && ( + + + {" "} + β€’{" "} - ) : ( - - {repoURLText} - - )} - - - )} - - {contextPercentage !== undefined && contextPercentage > 75 && ( - - - {" "} - β€’{" "} - - - - )} + + + )} + + + {!isRemoteMode && services.model?.model && ( + { + if (shouldShow && navState.currentScreen === "chat") { + navigateTo("free-trial"); + } else if ( + !shouldShow && + navState.currentScreen === "free-trial" + ) { + closeCurrentScreen(); + } + }} + /> + )} + + + + - - {!isRemoteMode && services.model?.model && ( - { - if (shouldShow && navState.currentScreen === "chat") { - navigateTo("free-trial"); - } else if (!shouldShow && navState.currentScreen === "free-trial") { - closeCurrentScreen(); - } - }} - /> - )} - - - - - -); + ); +}; diff --git a/extensions/cli/src/ui/components/ScreenContent.tsx b/extensions/cli/src/ui/components/ScreenContent.tsx index 1cb0c6d22..1af22c91a 100644 --- a/extensions/cli/src/ui/components/ScreenContent.tsx +++ b/extensions/cli/src/ui/components/ScreenContent.tsx @@ -140,6 +140,7 @@ export const ScreenContent: React.FC = ({ toolArgs={activePermissionRequest.toolArgs} requestId={activePermissionRequest.requestId} toolCallPreview={activePermissionRequest.toolCallPreview} + hasDynamicEvaluation={activePermissionRequest.hasDynamicEvaluation} onResponse={handleToolPermissionResponse} /> ); diff --git a/extensions/cli/src/ui/components/StaticChatContent.tsx b/extensions/cli/src/ui/components/StaticChatContent.tsx index 0261b14d8..4c1c9f133 100644 --- a/extensions/cli/src/ui/components/StaticChatContent.tsx +++ b/extensions/cli/src/ui/components/StaticChatContent.tsx @@ -74,14 +74,12 @@ export const StaticChatContent: React.FC = ({ }, [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( = ({ ); } - // 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, diff --git a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx index 46abde7d2..f47ac23ec 100644 --- a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx +++ b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx @@ -4,6 +4,7 @@ import React, { useState } from "react"; import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; import { ToolCallPreview } from "../../tools/types.js"; +import { defaultBoxStyles } from "../styles.js"; import { ToolPreview } from "./ToolPreview.js"; @@ -21,6 +22,7 @@ interface ToolPermissionSelectorProps { toolArgs: any; requestId: string; toolCallPreview?: ToolCallPreview[]; + hasDynamicEvaluation?: boolean; onResponse: ( requestId: string, approved: boolean, @@ -29,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 = ({ 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, @@ -80,8 +86,8 @@ export const ToolPermissionSelector: React.FC = ({ return; } - // Escape to reject with stop stream - if (key.escape) { + // Escape or Ctrl+C to reject with stop stream + if (key.escape || (key.ctrl && input === "c")) { onResponse(requestId, false, false, true); return; } @@ -90,7 +96,7 @@ export const ToolPermissionSelector: React.FC = ({ 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), ); } @@ -103,12 +109,7 @@ export const ToolPermissionSelector: React.FC = ({ }); return ( - + @@ -124,7 +125,15 @@ export const ToolPermissionSelector: React.FC = ({ Would you like to continue? - {PERMISSION_OPTIONS.map((option, index) => { + {hasDynamicEvaluation && ( + + + Note: Dangerous commands will be blocked regardless of your + preference. + + + )} + {permissionOptions.map((option, index) => { const isSelected = index === selectedIndex; let shortcut = ""; if (option.id === "approve") shortcut = "(tab)"; diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts index 1c0a7341e..7056a62b6 100644 --- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts @@ -15,7 +15,6 @@ vi.mock("../../session.js", () => ({ describe("useChat clear command", () => { let mockSetChatHistory: ReturnType; - let mockExit: ReturnType; let mockOnClear: ReturnType; 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, }); diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 17aa450fb..1c289e5c7 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -46,7 +46,6 @@ interface ProcessSlashCommandResultOptions { result: SlashCommandResult; chatHistory: ChatHistoryItem[]; setChatHistory: React.Dispatch>; - 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) { diff --git a/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts b/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts new file mode 100644 index 000000000..3308fdde5 --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.shellMode.test.ts @@ -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 }, + ); + }); +}); diff --git a/extensions/cli/src/ui/hooks/useChat.shellMode.ts b/extensions/cli/src/ui/hooks/useChat.shellMode.ts new file mode 100644 index 000000000..9c441310f --- /dev/null +++ b/extensions/cli/src/ui/hooks/useChat.shellMode.ts @@ -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 => { + // 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 +}; diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 213c0212f..3a31e458a 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -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, }); }, diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index c62854ed4..9b9cc5871 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -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) { diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index c0d641b01..c5945bbf3 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -32,9 +32,14 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { onTextBufferUpdate, } = options; - // Handle Ctrl+C to clear input - if (key.ctrl && input === "c" && clearInput) { - clearInput(); + // Handle Ctrl+C with two-stage exit, Ctrl+D immediately exits + if (key.ctrl && input === "c") { + // Clear input box if clearInput function is provided + if (clearInput) { + clearInput(); + } + // Let the main process SIGINT handler handle Ctrl+C logic + process.kill(process.pid, "SIGINT"); return true; } @@ -71,7 +76,7 @@ export function handleControlKeys(options: ControlKeysOptions): boolean { // Handle Ctrl+D to exit if (key.ctrl && input === "d") { exit(); - return true; + process.exit(0); } // Handle Ctrl+L to refresh screen (clear terminal artifacts) @@ -99,6 +104,7 @@ interface TextBufferStateOptions { setCursorPosition: (pos: number) => void; updateSlashCommandState: (text: string, cursor: number) => void; updateFileSearchState: (text: string, cursor: number) => void; + updateBashModeState: (text: string) => void; inputHistory: any; } @@ -110,6 +116,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition, updateSlashCommandState, updateFileSearchState, + updateBashModeState, inputHistory, } = options; @@ -121,6 +128,7 @@ export function updateTextBufferState(options: TextBufferStateOptions) { setCursorPosition(newCursor); updateSlashCommandState(newText, newCursor); updateFileSearchState(newText, newCursor); + updateBashModeState(newText); inputHistory.resetNavigation(); } } diff --git a/extensions/cli/src/ui/index.ts b/extensions/cli/src/ui/index.ts index 3b4edece4..9f5a3ec9e 100644 --- a/extensions/cli/src/ui/index.ts +++ b/extensions/cli/src/ui/index.ts @@ -1,6 +1,7 @@ -import { render } from "ink"; +import { render, RenderOptions } from "ink"; import React from "react"; +import { enableSigintHandler, setTUIUnmount } from "../index.js"; import { PermissionMode } from "../permissions/types.js"; import { initializeServices } from "../services/index.js"; import { ServiceContainerProvider } from "../services/ServiceContainerContext.js"; @@ -54,7 +55,9 @@ export async function startTUIChat( // Use static imports since we're always loading TUI when there's piped input // Start the TUI immediately - it will handle loading states - const renderOptions: any = {}; + const renderOptions: RenderOptions = { + exitOnCtrlC: false, // Disable Ink's default Ctrl+C handling so we can implement two-stage exit + }; if (customStdin) { renderOptions.stdin = customStdin; } @@ -73,11 +76,11 @@ export async function startTUIChat( renderOptions, ); - // Handle cleanup - process.on("SIGINT", () => { - unmount(); - process.exit(0); - }); + // Register unmount function with main process for two-stage Ctrl+C exit + setTUIUnmount(unmount); + + // Enable the two-stage SIGINT handler for TUI mode + enableSigintHandler(); return { unmount }; } @@ -96,11 +99,8 @@ export async function startRemoteTUIChat( }), ); - // Handle cleanup - process.on("SIGINT", () => { - unmount(); - process.exit(0); - }); + // Register unmount function with main process for two-stage Ctrl+C exit + setTUIUnmount(unmount); return { unmount }; } diff --git a/extensions/cli/src/ui/styles.ts b/extensions/cli/src/ui/styles.ts new file mode 100644 index 000000000..4e767b0b8 --- /dev/null +++ b/extensions/cli/src/ui/styles.ts @@ -0,0 +1,17 @@ +import { Box } from "ink"; + +export const baseBoxStyles: React.ComponentProps = { + flexDirection: "column", + paddingX: 2, + paddingY: 1, + borderStyle: "round", +}; + +export const defaultBoxStyles = ( + borderColor: string, + overrides?: Partial>, +): React.ComponentProps => ({ + ...baseBoxStyles, + borderColor, + ...overrides, +}); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt index 92f9bf970..21d83a536 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/autocomplete/ContinueInlineCompletionProvider.kt @@ -4,6 +4,7 @@ import com.github.continuedev.continueintellijextension.FimResult import com.github.continuedev.continueintellijextension.Position import com.github.continuedev.continueintellijextension.nextEdit.NextEditJumpManager import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.nextEdit.NextEditStatusService import com.github.continuedev.continueintellijextension.nextEdit.NextEditUtils import com.github.continuedev.continueintellijextension.nextEdit.NextEditWindowManager import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings @@ -41,8 +42,7 @@ class ContinueInlineCompletionProvider : InlineCompletionProvider { lastUuid = uuid() lastProject = project - // Check if Next Edit is supported - val isNextEditSupported = NextEditUtils.isNextEditSupported(project) + val isNextEditSupported = project.service().isNextEditEnabled() if (isNextEditSupported) { isUsingNextEdit = true diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt index 00c82fe29..5b4f862c0 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowser.kt @@ -1,28 +1,29 @@ package com.github.continuedev.continueintellijextension.browser import com.github.continuedev.continueintellijextension.constants.MessageTypes -import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson +import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter import javax.swing.JComponent -class ContinueBrowser(private val project: Project) { +class ContinueBrowser(private val project: Project): Disposable { private val log = Logger.getInstance(ContinueBrowser::class.java.simpleName) private val browser: JBCefBrowser = JBCefBrowser.createBuilder().setOffScreenRendering(true).build() + private val myJSQueryOpenInBrowser = JBCefJSQuery.create(browser as JBCefBrowserBase) init { CefApp.getInstance().registerSchemeHandlerFactory("http", "continue", CustomSchemeHandlerFactory()) browser.jbCefClient.setProperty(JBCefClient.Properties.JS_QUERY_POOL_SIZE, 200) - val myJSQueryOpenInBrowser = JBCefJSQuery.create(browser as JBCefBrowserBase) myJSQueryOpenInBrowser.addHandler { msg: String? -> val json = Gson().fromJson(msg, BrowserMessage::class.java) val messageType = json.messageType @@ -100,6 +101,11 @@ class ContinueBrowser(private val project: Project) { browser.cefBrowser.executeJavaScript(script, getGuiUrl(), 0) } + override fun dispose() { + Disposer.dispose(myJSQueryOpenInBrowser) + Disposer.dispose(browser) + } + // todo: remove and use types.Message private data class BrowserMessage( val messageType: String, diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowserService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowserService.kt index 2bc7334a5..155d9ffe8 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowserService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/browser/ContinueBrowserService.kt @@ -1,22 +1,32 @@ package com.github.continuedev.continueintellijextension.browser +import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project +import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.JBCefApp @Service(Service.Level.PROJECT) -class ContinueBrowserService(project: Project) { +class ContinueBrowserService(project: Project): Disposable { private val browser: ContinueBrowser? = if (JBCefApp.isSupported()) ContinueBrowser(project) else null + override fun dispose() { + if (browser != null) + Disposer.dispose(browser) + } + companion object { - fun Project.getBrowser() = - service().browser + fun Project.getBrowser(): ContinueBrowser? { + if (isDisposed) + return null + return service().browser + } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 0111c1173..f5a9a9000 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -142,6 +142,7 @@ class MessageTypes { "didChangeSelectedProfile", "didChangeSelectedOrg", "tools/call", + "tools/evaluatePolicy", "controlPlane/openUrl", "isItemTooBig", "process/markAsBackgrounded", diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 9affb4c2d..ba1f4a571 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -199,7 +199,9 @@ class IntelliJIDE( } override suspend fun openFile(path: String) = - fileUtils.openFile(path) + withContext(Dispatchers.EDT) { + fileUtils.openFile(path) + } override suspend fun openUrl(url: String) { withContext(Dispatchers.IO) { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt index 04e4d3d2e..9e269226b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/process/ContinueProcessHandler.kt @@ -43,10 +43,14 @@ class ContinueProcessHandler( } scope.launch(Dispatchers.IO) { for (message in pendingWrites) { - log.debug("Write: $message") - writer.write(message) - writer.write("\r\n") - writer.flush() + try { + log.debug("Write: $message") + writer.write(message) + writer.write("\r\n") + writer.flush() + } catch (e: IOException) { + log.warn(e) + } } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt index 616702466..274d8a87f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/VerticalDiffBlock.kt @@ -14,6 +14,7 @@ import com.intellij.openapi.util.TextRange import com.intellij.ui.JBColor import com.intellij.util.application import com.intellij.util.ui.JBUI +import com.intellij.util.ui.UIUtil import java.awt.* import javax.swing.JButton import javax.swing.JTextArea @@ -229,7 +230,7 @@ class VerticalDiffBlock( border = JBUI.Borders.empty() lineWrap = false wrapStyleWord = false - font = editor.colorsScheme.getFont(EditorFontType.PLAIN) + font = UIUtil.getFontWithFallback(editor.colorsScheme.getFont(EditorFontType.PLAIN)) } private fun getButtonsXYPositions(): Pair { diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt index 69ea9b911..9d806ee66 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/error/ContinueErrorSubmitter.kt @@ -21,6 +21,7 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() { consumer: Consumer ): Boolean { try { + // todo: IdeaReportingEvent is deprecated; migrate to IdeaLoggingEvent + figure out how to read attachments val event = events.filterIsInstance() .firstOrNull() ?: return false service().report( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt index 2402ff6c4..66a096f5e 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKey.kt @@ -5,22 +5,27 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType -import com.intellij.openapi.actionSystem.ActionManager -import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper class AddLicenseKey : AnAction() { override fun actionPerformed(e: AnActionEvent) { - val dialog = AddLicenseKeyDialog(e.project) + performAddLicenseKey(e.project) + } + + private fun performAddLicenseKey(project: Project?) { + if (project == null) + return + val dialog = AddLicenseKeyDialog(project) dialog.show() if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE) return - val messenger = e.project?.service()?.coreMessenger + val messenger = project.service().coreMessenger ?: return messenger.request("mdm/setLicenseKey", mapOf("licenseKey" to dialog.licenseKey), null) { response -> val isValid = response.castNestedOrNull("content") ?: false @@ -28,7 +33,7 @@ class AddLicenseKey : AnAction() { createSuccessAction() else createErrorAction() - notification.notify(e.project) + notification.notify(project) } } @@ -37,7 +42,7 @@ class AddLicenseKey : AnAction() { "License key is valid. A restart is required for it to take effect.", NotificationType.INFORMATION ).addAction( - NotificationAction.create("Restart IDE") { event, notification -> + NotificationAction.create("Restart IDE") { _, _ -> ApplicationManager.getApplication().restart() } ) @@ -49,17 +54,7 @@ class AddLicenseKey : AnAction() { ).addAction( NotificationAction.create("Try again") { event, notification -> notification.expire() - val action = this@AddLicenseKey - action.actionPerformed( - AnActionEvent( - null, - event.dataContext, - ActionPlaces.UNKNOWN, - action.templatePresentation.clone(), - ActionManager.getInstance(), - 0 - ) - ) + performAddLicenseKey(event.project) } ) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt index 4ba6f2e21..af8763a21 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/license/AddLicenseKeyDialog.kt @@ -3,9 +3,9 @@ package com.github.continuedev.continueintellijextension.license import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo +import com.intellij.ui.dsl.builder.AlignX import com.intellij.ui.dsl.builder.bindText import com.intellij.ui.dsl.builder.panel -import com.intellij.ui.dsl.gridLayout.HorizontalAlign import javax.swing.JComponent class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) { @@ -22,7 +22,7 @@ class AddLicenseKeyDialog(project: Project?) : DialogWrapper(project) { panel { row { textField().bindText(::licenseKey) - .horizontalAlign(HorizontalAlign.FILL) + .align(AlignX.FILL) .focused() .validationOnApply { if (it.text.isBlank()) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt index 92dc3c2a3..a1d9b1f5d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/listeners/ActiveHandlerManager.kt @@ -1,7 +1,9 @@ package com.github.continuedev.continueintellijextension.listeners import com.github.continuedev.continueintellijextension.nextEdit.NextEditService +import com.github.continuedev.continueintellijextension.nextEdit.NextEditStatusService import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.LogicalPosition import com.intellij.openapi.editor.event.CaretEvent @@ -100,7 +102,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca // SelectionListener implementation override fun selectionChanged(event: SelectionEvent) { - if (isHandlingEvent || event.editor.isDisposed) return + if (isHandlingEvent || event.editor.isDisposed || !isNextEditEnabled()) return coroutineScope.launch { handleCursorMovement(event.editor, event.newRange.startOffset) @@ -109,7 +111,7 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca // CaretListener implementation override fun caretPositionChanged(event: CaretEvent) { - if (isHandlingEvent || event.editor.isDisposed) return + if (isHandlingEvent || event.editor.isDisposed || !isNextEditEnabled()) return coroutineScope.launch { handleCursorMovement(event.editor, event.caret?.offset ?: return@launch) @@ -168,6 +170,9 @@ class ActiveHandlerManager(private val project: Project) : SelectionListener, Ca } } + private fun isNextEditEnabled() = + project.service().isNextEditEnabled() + fun dispose() { clearActiveHandler() coroutineScope.cancel() diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditStatusService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditStatusService.kt new file mode 100644 index 000000000..31e68e223 --- /dev/null +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditStatusService.kt @@ -0,0 +1,115 @@ +package com.github.continuedev.continueintellijextension.nextEdit + +import com.github.continuedev.continueintellijextension.auth.ContinueAuthService +import com.github.continuedev.continueintellijextension.`continue`.ProfileInfoService +import com.github.continuedev.continueintellijextension.utils.castNestedOrNull +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.service +import com.intellij.openapi.project.Project +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.text.endsWith + +/** + * This cache-like service is introduced to enable checking the Next Edit status in a non-blocking way (e.g., while + * moving the cursor/selection or triggering autocompletion). + * + * Checking this status is problematic on the EDT because it requires making a request to the binary (settings JSON) + * and decrypting the username from the PasswordSafe, which is considered a _slow operation_. + */ +@Service(Service.Level.PROJECT) +class NextEditStatusService(private val project: Project) { + + @Volatile + private var isEnabledLastValue: Boolean = false + private val updateInProgress = AtomicBoolean(false) + private val scope = CoroutineScope(Dispatchers.Default) + + fun isNextEditEnabled(): Boolean { + if (updateInProgress.compareAndSet(false, true)) + scope.launch { + try { + isEnabledLastValue = isNextEditEnabledAsync(project) + } catch (_: Exception) { + } finally { + updateInProgress.set(false) + } + } + return isEnabledLastValue + } + + // The code below is copied from NextEditUtils + // ------------------------------------------- + + private suspend fun isNextEditEnabledAsync(project: Project): Boolean { + return try { + // NOTE: Quick filter for non-continue users. + // Remove this once we have a FIM - Next Edit toggle UI. + val authService = project.service() + val sessionInfo = authService.loadControlPlaneSessionInfo() + val userEmail = sessionInfo?.account?.id + + if (userEmail == null || !userEmail.endsWith("@continue.dev")) { + return false + } + + val profileInfoService = project.service() + val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull() + + // Use the existing utility function + val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull>() + + if (autocompleteModel != null) { + val modelName = autocompleteModel["model"] as? String ?: "" + val title = autocompleteModel["title"] as? String + val capabilities = autocompleteModel["capabilities"].castNestedOrNull>() + + isNextEditModel(modelName, title, capabilities) + } else { + false + } + } catch (e: Exception) { + println("Error checking Next Edit support: ${e.message}") + false + } + } + + private fun isNextEditModel( + model: String, + title: String?, + capabilities: Map? + ): Boolean { + // Check capabilities first - this takes precedence. + val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false + + // Check model name and title against known Next Edit models. + return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title) + } + + sealed class NextEditModelMatcher { + abstract fun matches(modelName: String?, title: String?): Boolean + + data object MercuryCoder : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("mercury-coder") == true || + title?.lowercase()?.contains("mercury coder") == true + } + + data object Instinct : NextEditModelMatcher() { + override fun matches(modelName: String?, title: String?): Boolean = + modelName?.lowercase()?.contains("instinct") == true || + title?.lowercase()?.contains("instinct") == true + } + + companion object { + private val allMatchers = listOf(MercuryCoder, Instinct) + + fun isSupported(modelName: String?, title: String?): Boolean { + return allMatchers.any { it.matches(modelName, title) } + } + } + } + +} \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt index 4ad48cc6d..f61073fa3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/nextEdit/NextEditUtils.kt @@ -7,76 +7,8 @@ import com.github.continuedev.continueintellijextension.utils.castNestedOrNull import com.intellij.openapi.components.service import com.intellij.openapi.project.Project -sealed class NextEditModelMatcher { - abstract fun matches(modelName: String?, title: String?): Boolean - - data object MercuryCoder : NextEditModelMatcher() { - override fun matches(modelName: String?, title: String?): Boolean = - modelName?.lowercase()?.contains("mercury-coder") == true || - title?.lowercase()?.contains("mercury coder") == true - } - - data object Instinct : NextEditModelMatcher() { - override fun matches(modelName: String?, title: String?): Boolean = - modelName?.lowercase()?.contains("instinct") == true || - title?.lowercase()?.contains("instinct") == true - } - - companion object { - private val allMatchers = listOf(MercuryCoder, Instinct) - - fun isSupported(modelName: String?, title: String?): Boolean { - return allMatchers.any { it.matches(modelName, title) } - } - } -} - object NextEditUtils { - suspend fun isNextEditSupported(project: Project): Boolean { - return try { - // NOTE: Quick filter for non-continue users. - // Remove this once we have a FIM - Next Edit toggle UI. - val authService = project.service() - val sessionInfo = authService.loadControlPlaneSessionInfo() - val userEmail = sessionInfo?.account?.id - - if (userEmail == null || !userEmail.endsWith("@continue.dev")) { - return false - } - - val profileInfoService = project.service() - val selectedModelByRole = profileInfoService.fetchSelectedModelByRoleOrNull() - - // Use the existing utility function - val autocompleteModel = selectedModelByRole?.get("autocomplete").castNestedOrNull>() - - if (autocompleteModel != null) { - val modelName = autocompleteModel["model"] as? String ?: "" - val title = autocompleteModel["title"] as? String - val capabilities = autocompleteModel["capabilities"].castNestedOrNull>() - - isNextEditModel(modelName, title, capabilities) - } else { - false - } - } catch (e: Exception) { - println("Error checking Next Edit support: ${e.message}") - false - } - } - - private fun isNextEditModel( - model: String, - title: String?, - capabilities: Map? - ): Boolean { - // Check capabilities first - this takes precedence. - val hasNextEditCapability = capabilities?.get("nextEdit") as? Boolean ?: false - - // Check model name and title against known Next Edit models. - return hasNextEditCapability || NextEditModelMatcher.isSupported(model, title) - } /** * Check if the diff is indeed a FIM (Fill-In-Middle). diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index daaecb123..ac5b2c7a3 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -8,6 +8,7 @@ import com.github.continuedev.continueintellijextension.listeners.ActiveHandlerM import com.github.continuedev.continueintellijextension.listeners.DocumentChangeTracker import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory import com.github.continuedev.continueintellijextension.utils.uuid +import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.editor.EditorFactory @@ -20,7 +21,7 @@ import kotlinx.coroutines.cancel import kotlin.properties.Delegates @Service(Service.Level.PROJECT) -class ContinuePluginService(private val project: Project) : DumbAware { +class ContinuePluginService(private val project: Project) : Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.Main) var listener: (() -> Unit)? = null var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ -> @@ -57,7 +58,7 @@ class ContinuePluginService(private val project: Project) : DumbAware { } } - fun dispose() { + override fun dispose() { coroutineScope.cancel() coreMessenger?.coroutineScope?.let { it.cancel() diff --git a/extensions/vscode/e2e/actions/GUI.actions.ts b/extensions/vscode/e2e/actions/GUI.actions.ts index 1091c1a0a..38a6384c8 100644 --- a/extensions/vscode/e2e/actions/GUI.actions.ts +++ b/extensions/vscode/e2e/actions/GUI.actions.ts @@ -134,7 +134,7 @@ export class GUIActions { public static async toggleToolPolicy( view: WebView, toolName: string, - n: number, + desiredState: number | string, ) { const toolButton = await TestUtils.waitForSuccess(() => GUISelectors.getToolButton(view), @@ -145,9 +145,41 @@ export class GUIActions { ); await TestUtils.waitForTimeout(500); - // Enabled -> Excluded -> Ask first - for (let i = 0; i < n; i++) { - await TestUtils.waitForSuccess(() => toolPolicyButton.click()); + // Map old number format to state names for backward compatibility + // 0 = Automatic/Auto, 1 = Excluded/Off, 2 = Ask First/Ask + let targetStates: string[]; + if (typeof desiredState === "number") { + const stateMap = [ + ["Automatic", "Auto"], // 0 + ["Excluded", "Off"], // 1 + ["Ask First", "Ask"], // 2 + ]; + targetStates = stateMap[desiredState] || ["Ask First", "Ask"]; + } else { + targetStates = [desiredState]; + } + + // Keep clicking until we reach the desired state + let maxAttempts = 5; // Safety limit to prevent infinite loops + while (maxAttempts > 0) { + const currentText = await toolPolicyButton.getText(); + + // Check if we've reached any of the target states + if (targetStates.some((state) => currentText.includes(state))) { + break; + } + + // Click to move to next state + await toolPolicyButton.click(); + await TestUtils.waitForTimeout(200); // Small delay for UI update + + maxAttempts--; + } + + if (maxAttempts === 0) { + throw new Error( + `Failed to set tool policy to ${targetStates.join(" or ")} after 5 attempts`, + ); } } } diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index e6f8a3bee..d77ac69e1 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -4,7 +4,7 @@ import { InputBox, TextEditor, VSBrowser, - Workbench + Workbench, } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; @@ -86,76 +86,69 @@ export class GlobalActions { static async setNextEditEnabled(enabled: boolean) { const workbench = new Workbench(); - - await workbench.openCommandPrompt(); - process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = 'true'; - + await workbench.openCommandPrompt(); + process.env.CONTINUE_E2E_NON_NEXT_EDIT_TEST = "true"; + // Initial wait and clear await TestUtils.waitForTimeout(1000); await GlobalActions.clearAllNotifications(); - + const statusBar = await workbench.getStatusBar(); - + // Robust element finding with text validation - const continueItem = await TestUtils.waitForSuccess( - async () => { - // Clear any new notifications - try { - await GlobalActions.clearAllNotifications(); - } catch (e) { - // Ignore + const continueItem = await TestUtils.waitForSuccess(async () => { + // Clear any new notifications + try { + await GlobalActions.clearAllNotifications(); + } catch (e) { + // Ignore + } + + const element = await statusBar.findElement( + By.xpath("//*[contains(text(), 'Continue')]"), + ); + + // Validate we can get text + const text = await element.getText(); + if (!text || text.trim() === "") { + // Try alternative methods + const textContent = await element.getAttribute("textContent"); + if (!textContent || textContent.trim() === "") { + throw new Error("Text not yet available"); } - - const element = await statusBar.findElement( - By.xpath("//*[contains(text(), 'Continue')]") - ); - - // Validate we can get text - const text = await element.getText(); - if (!text || text.trim() === '') { - // Try alternative methods - const textContent = await element.getAttribute('textContent'); - if (!textContent || textContent.trim() === '') { - throw new Error('Text not yet available'); - } - } - - return element; - }, - DEFAULT_TIMEOUT.MD - ); + } + + return element; + }, DEFAULT_TIMEOUT.MD); // Get text with retry - const text = await TestUtils.waitForSuccess( - async () => { - const itemText = await continueItem.getText(); - if (!itemText || itemText.trim() === '') { - // Fallback to textContent - const textContent = await continueItem.getAttribute('textContent'); - if (textContent && textContent.trim() !== '') { - return textContent; - } - throw new Error('Text content not yet available'); + const text = await TestUtils.waitForSuccess(async () => { + const itemText = await continueItem.getText(); + if (!itemText || itemText.trim() === "") { + // Fallback to textContent + const textContent = await continueItem.getAttribute("textContent"); + if (textContent && textContent.trim() !== "") { + return textContent; } - return itemText; - }, - DEFAULT_TIMEOUT.MD - ); - + throw new Error("Text content not yet available"); + } + return itemText; + }, DEFAULT_TIMEOUT.MD); + console.log("Final text:", text); - - const hasNE = text.includes('(NE)'); + + const hasNE = text.includes("(NE)"); console.log("hasNE:", hasNE); - + if (hasNE !== enabled) { - await workbench.executeCommand('Continue: Toggle Next Edit'); + await workbench.executeCommand("Continue: Toggle Next Edit"); // Clear any resulting notifications await TestUtils.waitForTimeout(500); await GlobalActions.clearAllNotifications(); } } - + static async disableNextEdit() { await this.setNextEditEnabled(false); } diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index 0760a607e..74128cd9d 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -7,7 +7,7 @@ import { WebDriver, WebElement, WebView, - until + until, } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index c8cd7819a..a0fa56130 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.3.2", + "version": "1.3.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.3.2", + "version": "1.3.3", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "file:../../packages/config-types", @@ -63,7 +63,7 @@ "devDependencies": { "@biomejs/biome": "1.6.4", "@nestjs/common": "^11.0.16", - "@openapitools/openapi-generator-cli": "^2.20.0", + "@openapitools/openapi-generator-cli": "^2.23.1", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", @@ -108,6 +108,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", @@ -158,6 +159,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", @@ -192,6 +194,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", @@ -743,6 +746,17 @@ "node": ">=14.21.3" } }, + "node_modules/@borewit/text-codec": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.1.1.tgz", + "integrity": "sha512-5L/uBxmjaCIX5h8Z+uu+kA9BQLkc/Wl06UGR5ajNRxu+/XjonB5i8JpgFMrPj3LXTCPA0pv8yxUvbUi+QthGGA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, "node_modules/@continuedev/config-types": { "resolved": "../../packages/config-types", "link": true @@ -1301,6 +1315,29 @@ "deprecated": "Use @eslint/object-schema instead", "dev": true }, + "node_modules/@isaacs/balanced-match": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", + "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@isaacs/brace-expansion": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz", + "integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "engines": { + "node": "20 || >=22" + } + }, "node_modules/@isaacs/cliui": { "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", @@ -1525,9 +1562,9 @@ "integrity": "sha512-/cPZD907UNz55yrc/ud4wDgQKtU1TvkD9jeqZWG6J4IMmZkp6zgjkQcKA8UvpkZlcpPHvc8J17sGzLFbP/LUYg==" }, "node_modules/@nestjs/axios": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.0.tgz", - "integrity": "sha512-1cB+Jyltu/uUPNQrpUimRHEQHrnQrpLzVj6dU3dgn6iDDDdahr10TgHFGTmw5VuJ9GzKZsCLDL78VSwJAs/9JQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@nestjs/axios/-/axios-4.0.1.tgz", + "integrity": "sha512-68pFJgu+/AZbWkGu65Z3r55bTsCPlgyKaV4BSG8yUAD72q1PPuyVRgUwFv6BxdnibTUHlyxm06FmYWNC+bjN7A==", "dev": true, "license": "MIT", "peerDependencies": { @@ -1537,13 +1574,13 @@ } }, "node_modules/@nestjs/common": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.1.tgz", - "integrity": "sha512-crzp+1qeZ5EGL0nFTPy9NrVMAaUWewV5AwtQyv6SQ9yQPXwRl9W9hm1pt0nAtUu5QbYMbSuo7lYcF81EjM+nCA==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@nestjs/common/-/common-11.1.6.tgz", + "integrity": "sha512-krKwLLcFmeuKDqngG2N/RuZHCs2ycsKcxWIDgcm7i1lf3sQ0iG03ci+DsP/r3FcT/eJDFsIHnKtNta2LIi7PzQ==", "dev": true, "license": "MIT", "dependencies": { - "file-type": "20.5.0", + "file-type": "21.0.0", "iterare": "1.2.1", "load-esm": "1.0.2", "tslib": "2.8.1", @@ -1569,9 +1606,9 @@ } }, "node_modules/@nestjs/core": { - "version": "11.1.1", - "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.1.tgz", - "integrity": "sha512-UFoUAgLKFT+RwHTANJdr0dF7p0qS9QjkaUPjg8aafnjM/qxxxrUVDB49nVvyMlk+Hr1+vvcNaOHbWWQBxoZcHA==", + "version": "11.1.6", + "resolved": "https://registry.npmjs.org/@nestjs/core/-/core-11.1.6.tgz", + "integrity": "sha512-siWX7UDgErisW18VTeJA+x+/tpNZrJewjTBsRPF3JVxuWRuAB1kRoiJcxHgln8Lb5UY9NdvklITR84DUEXD0Cg==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -1802,27 +1839,26 @@ } }, "node_modules/@openapitools/openapi-generator-cli": { - "version": "2.20.2", - "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.20.2.tgz", - "integrity": "sha512-dNFwQcQu6+rmEWSJj4KUx468+p6Co7nfpVgi5QEfVhzKj7wBytz9GEhCN2qmVgtg3ZX8H6nxbXI8cjh7hAxAqg==", + "version": "2.23.1", + "resolved": "https://registry.npmjs.org/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.23.1.tgz", + "integrity": "sha512-Kd5EZqzbcIXf6KRlpUrheHMzQNRHsJWzAGrm4ncWCNhnQl+Mh6TsFcqq+hIetgiFCknWBH6cZ2f37SxPxaon4w==", "dev": true, "hasInstallScript": true, "license": "Apache-2.0", "dependencies": { - "@nestjs/axios": "4.0.0", - "@nestjs/common": "11.1.1", - "@nestjs/core": "11.1.1", + "@nestjs/axios": "4.0.1", + "@nestjs/common": "11.1.6", + "@nestjs/core": "11.1.6", "@nuxtjs/opencollective": "0.3.2", - "axios": "1.9.0", + "axios": "1.11.0", "chalk": "4.1.2", "commander": "8.3.0", "compare-versions": "4.1.4", - "concurrently": "6.5.1", + "concurrently": "9.2.1", "console.table": "0.10.0", - "fs-extra": "11.3.0", - "glob": "9.3.5", - "inquirer": "8.2.6", - "lodash": "4.17.21", + "fs-extra": "11.3.1", + "glob": "11.0.3", + "inquirer": "8.2.7", "proxy-agent": "6.5.0", "reflect-metadata": "0.2.2", "rxjs": "7.8.2", @@ -1839,19 +1875,10 @@ "url": "https://opencollective.com/openapi_generator" } }, - "node_modules/@openapitools/openapi-generator-cli/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0" - } - }, "node_modules/@openapitools/openapi-generator-cli/node_modules/fs-extra": { - "version": "11.3.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.0.tgz", - "integrity": "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew==", + "version": "11.3.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.1.tgz", + "integrity": "sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==", "dev": true, "license": "MIT", "dependencies": { @@ -1864,45 +1891,86 @@ } }, "node_modules/@openapitools/openapi-generator-cli/node_modules/glob": { - "version": "9.3.5", - "resolved": "https://registry.npmjs.org/glob/-/glob-9.3.5.tgz", - "integrity": "sha512-e1LleDykUz2Iu+MTYdkSsuWX8lvAjAcs0Xef0lNIu0S2wOAzuTxCJtcd9S3cijlwYF18EsU3rzb8jPVobxDh9Q==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.3.tgz", + "integrity": "sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==", "dev": true, + "license": "ISC", "dependencies": { - "fs.realpath": "^1.0.0", - "minimatch": "^8.0.2", - "minipass": "^4.2.4", - "path-scurry": "^1.6.1" + "foreground-child": "^3.3.1", + "jackspeak": "^4.1.1", + "minimatch": "^10.0.3", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^2.0.0" + }, + "bin": { + "glob": "dist/esm/bin.mjs" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@openapitools/openapi-generator-cli/node_modules/jackspeak": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz", + "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/@openapitools/openapi-generator-cli/node_modules/minimatch": { - "version": "8.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-8.0.4.tgz", - "integrity": "sha512-W0Wvr9HyFXZRGIDgCicunpQ299OKXs9RgZfaukz4qAW/pJhcpUfupc9c+OObPOFueNy8VSrZgEmDtk6Kh4WzDA==", + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.3.tgz", + "integrity": "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==", "dev": true, + "license": "ISC", "dependencies": { - "brace-expansion": "^2.0.1" + "@isaacs/brace-expansion": "^5.0.0" }, "engines": { - "node": ">=16 || 14 >=14.17" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, "node_modules/@openapitools/openapi-generator-cli/node_modules/minipass": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-4.2.8.tgz", - "integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", "dev": true, + "license": "ISC", "engines": { - "node": ">=8" + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/@openapitools/openapi-generator-cli/node_modules/path-scurry": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", + "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/@pkgjs/parseargs": { @@ -3494,6 +3562,7 @@ "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", "dev": true, + "license": "MIT", "dependencies": { "type-fest": "^0.21.3" }, @@ -3509,6 +3578,7 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", "dev": true, + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=10" }, @@ -3728,13 +3798,13 @@ "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==" }, "node_modules/axios": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz", - "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz", + "integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==", "license": "MIT", "dependencies": { "follow-redirects": "^1.15.6", - "form-data": "^4.0.0", + "form-data": "^4.0.4", "proxy-from-env": "^1.1.0" } }, @@ -4172,6 +4242,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/call-me-maybe": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", @@ -4278,10 +4361,11 @@ } }, "node_modules/chardet": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", - "integrity": "sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==", - "dev": true + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.0.tgz", + "integrity": "sha512-bNFETTG/pM5ryzQ9Ad0lJOTa6HWD/YsScAR3EnCPZRPlQh77JocYktSHOUHelyhm8IARL+o4c4F1bP5KVOjiRA==", + "dev": true, + "license": "MIT" }, "node_modules/check-error": { "version": "1.0.3", @@ -4453,6 +4537,7 @@ "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-3.0.0.tgz", "integrity": "sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==", "dev": true, + "license": "ISC", "engines": { "node": ">= 10" } @@ -4844,69 +4929,28 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" }, "node_modules/concurrently": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-6.5.1.tgz", - "integrity": "sha512-FlSwNpGjWQfRwPLXvJ/OgysbBxPkWpiVjy1042b0U7on7S7qwwMIILRj7WTN1mTgqa582bG6NFuScOoh6Zgdag==", + "version": "9.2.1", + "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz", + "integrity": "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng==", "dev": true, + "license": "MIT", "dependencies": { - "chalk": "^4.1.0", - "date-fns": "^2.16.1", - "lodash": "^4.17.21", - "rxjs": "^6.6.3", - "spawn-command": "^0.0.2-1", - "supports-color": "^8.1.0", - "tree-kill": "^1.2.2", - "yargs": "^16.2.0" + "chalk": "4.1.2", + "rxjs": "7.8.2", + "shell-quote": "1.8.3", + "supports-color": "8.1.1", + "tree-kill": "1.2.2", + "yargs": "17.7.2" }, "bin": { - "concurrently": "bin/concurrently.js" + "conc": "dist/bin/concurrently.js", + "concurrently": "dist/bin/concurrently.js" }, "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/concurrently/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/concurrently/node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", - "dev": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "node_modules/concurrently/node_modules/rxjs": { - "version": "6.6.7", - "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz", - "integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==", - "dev": true, - "dependencies": { - "tslib": "^1.9.0" + "node": ">=18" }, - "engines": { - "npm": ">=2.0.0" - } - }, - "node_modules/concurrently/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" + "funding": { + "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" } }, "node_modules/concurrently/node_modules/supports-color": { @@ -4914,6 +4958,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4924,47 +4969,6 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/concurrently/node_modules/tslib": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", - "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "dev": true - }, - "node_modules/concurrently/node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/concurrently/node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", - "dev": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/consola": { "version": "3.4.2", "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", @@ -5055,9 +5059,10 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.5.tgz", - "integrity": "sha512-ZVJrKKYunU38/76t0RMOulHOnUcbU9GbpWKAOZ0mhjr7CX6FVrH+4FrAapSOekrgFQ3f/8gwMEuIft0aKq6Hug==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -5166,22 +5171,6 @@ "node": ">=18" } }, - "node_modules/date-fns": { - "version": "2.30.0", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.30.0.tgz", - "integrity": "sha512-fnULvOpxnC5/Vg3NCiWelDsLiUc9bRwAPs/+LfTLNvetFCtCTN+yQz15C/fs4AwX1R9K5GLtLfn8QW+dWisaAw==", - "dev": true, - "dependencies": { - "@babel/runtime": "^7.21.0" - }, - "engines": { - "node": ">=0.11" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/date-fns" - } - }, "node_modules/dbinfoz": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.14.0.tgz", @@ -5513,6 +5502,20 @@ "react": ">=16.12.0" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/duplexer2": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", @@ -5671,12 +5674,10 @@ "integrity": "sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==" }, "node_modules/es-define-property": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.0.tgz", - "integrity": "sha512-jxayLKShrEqqzJ0eumQbVhTYQM27CfT1T35+gCgDFoL82JLsXqTJ76zv6A0YLOgEnLUMvLzsDsGIrl8NFpT2gQ==", - "dependencies": { - "get-intrinsic": "^1.2.4" - }, + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", "engines": { "node": ">= 0.4" } @@ -5695,6 +5696,33 @@ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", "license": "MIT" }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es5-ext": { "version": "0.10.64", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz", @@ -6255,44 +6283,6 @@ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, - "node_modules/external-editor": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-3.1.0.tgz", - "integrity": "sha512-hMQ4CX1p1izmuLYyZqLMO/qGNw10wSv9QDCPfzXfyFrOaCSSoRfqE1Kf1s5an66J5JZC62NewG+mK49jOCtQew==", - "dev": true, - "dependencies": { - "chardet": "^0.7.0", - "iconv-lite": "^0.4.24", - "tmp": "^0.0.33" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/external-editor/node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "dev": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/external-editor/node_modules/tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "dev": true, - "dependencies": { - "os-tmpdir": "~1.0.2" - }, - "engines": { - "node": ">=0.6.0" - } - }, "node_modules/extsprintf": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", @@ -6400,6 +6390,7 @@ "resolved": "https://registry.npmjs.org/figures/-/figures-3.2.0.tgz", "integrity": "sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==", "dev": true, + "license": "MIT", "dependencies": { "escape-string-regexp": "^1.0.5" }, @@ -6415,6 +6406,7 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.8.0" } @@ -6432,19 +6424,19 @@ } }, "node_modules/file-type": { - "version": "20.5.0", - "resolved": "https://registry.npmjs.org/file-type/-/file-type-20.5.0.tgz", - "integrity": "sha512-BfHZtG/l9iMm4Ecianu7P8HRD2tBHLtjXinm4X62XBOYzi7CYA7jyqfJzOvXHqzVrVPYqBo2/GvbARMaaJkKVg==", + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.0.0.tgz", + "integrity": "sha512-ek5xNX2YBYlXhiUXui3D/BXa3LdqPmoLJ7rqEx2bKJ7EAUEfmXgW0Das7Dc6Nr9MvqaOnIqiPV0mZk/r/UpNAg==", "dev": true, "license": "MIT", "dependencies": { - "@tokenizer/inflate": "^0.2.6", - "strtok3": "^10.2.0", + "@tokenizer/inflate": "^0.2.7", + "strtok3": "^10.2.2", "token-types": "^6.0.0", "uint8array-extras": "^1.4.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sindresorhus/file-type?sponsor=1" @@ -6633,11 +6625,12 @@ } }, "node_modules/foreground-child": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.0.tgz", - "integrity": "sha512-Ld2g8rrAyMYFXBhEqMz8ZAHBi4J4uS1i/CxGMDnjyFWddMXLVcDp051DZfu+t7+ab7Wv6SMqpWmyFIj5UbfFvg==", + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "license": "ISC", "dependencies": { - "cross-spawn": "^7.0.0", + "cross-spawn": "^7.0.6", "signal-exit": "^4.0.1" }, "engines": { @@ -6667,12 +6660,15 @@ } }, "node_modules/form-data": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", - "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", "mime-types": "^2.1.12" }, "engines": { @@ -6838,15 +6834,21 @@ } }, "node_modules/get-intrinsic": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz", - "integrity": "sha512-5uYhsJH8VJBTv7oslg4BznJYhDoRI6waYCxMmCdnTrcCrHA/fCFKoTFz2JKKE0HdDFUF7/oQuhzumXJK7paBRQ==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3", - "hasown": "^2.0.0" + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" }, "engines": { "node": ">= 0.4" @@ -6855,6 +6857,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-stdin": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-8.0.0.tgz", @@ -7001,11 +7016,12 @@ } }, "node_modules/gopd": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.0.1.tgz", - "integrity": "sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==", - "dependencies": { - "get-intrinsic": "^1.1.3" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -7106,10 +7122,11 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/has-proto": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.0.3.tgz", - "integrity": "sha512-SJ1amZAJUiZS+PhsVLf5tGydlaVB8EdFpaSO4gmiUKUOxk8qzn5AIy4ZeJUmh22znIdk/uMAUT2pl3FxzVUH+Q==", + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", "engines": { "node": ">= 0.4" }, @@ -7117,10 +7134,14 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, "engines": { "node": ">= 0.4" }, @@ -7507,16 +7528,17 @@ "integrity": "sha512-7NXolsK4CAS5+xvdj5OMMbI962hU/wvwoxk+LWR9Ek9bVtyuuYScDN6eS0rUm6TxApFpw7CX1o4uJzcd4AyD3Q==" }, "node_modules/inquirer": { - "version": "8.2.6", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.6.tgz", - "integrity": "sha512-M1WuAmb7pn9zdFRtQYk26ZBoY043Sse0wVDdk4Bppr+JOXyQYybdtvK+l9wUibhtjdjvtoiNy8tk+EgsYIUqKg==", + "version": "8.2.7", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-8.2.7.tgz", + "integrity": "sha512-UjOaSel/iddGZJ5xP/Eixh6dY1XghiBw4XK13rCCIJcJfyhhoul/7KhLLUGtebEj6GDYM6Vnx/mVsjx2L/mFIA==", "dev": true, + "license": "MIT", "dependencies": { + "@inquirer/external-editor": "^1.0.0", "ansi-escapes": "^4.2.1", "chalk": "^4.1.1", "cli-cursor": "^3.1.0", "cli-width": "^3.0.0", - "external-editor": "^3.0.3", "figures": "^3.0.0", "lodash": "^4.17.21", "mute-stream": "0.0.8", @@ -7532,11 +7554,46 @@ "node": ">=12.0.0" } }, + "node_modules/inquirer/node_modules/@inquirer/external-editor": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.1.tgz", + "integrity": "sha512-Oau4yL24d2B5IL4ma4UpbQigkVhzPDXLoqy1ggK4gnHg/stmkffJE4oOXHXF3uz0UEpywG68KcyXsyYpA1Re/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "chardet": "^2.1.0", + "iconv-lite": "^0.6.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/inquirer/node_modules/@types/node": { + "version": "24.3.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.3.1.tgz", + "integrity": "sha512-3vXmQDXy+woz+gnrTvuvNrPzekOi+Ds0ReMxw0LzBiK3a+1k0kQn9f2NWk+lgD4rJehFUmYy2gMhJ2ZI+7YP9g==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "undici-types": "~7.10.0" + } + }, "node_modules/inquirer/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -7546,6 +7603,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -7553,6 +7611,15 @@ "node": ">=8" } }, + "node_modules/inquirer/node_modules/undici-types": { + "version": "7.10.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.10.0.tgz", + "integrity": "sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, "node_modules/ip-address": { "version": "9.0.5", "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-9.0.5.tgz", @@ -8584,6 +8651,15 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/mdast-util-definitions": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/mdast-util-definitions/-/mdast-util-definitions-5.1.2.tgz", @@ -10244,15 +10320,6 @@ "node": ">=8" } }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/ovsx": { "version": "0.8.4", "resolved": "https://registry.npmjs.org/ovsx/-/ovsx-0.8.4.tgz", @@ -10594,20 +10661,6 @@ "node": "*" } }, - "node_modules/peek-readable": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/peek-readable/-/peek-readable-7.0.0.tgz", - "integrity": "sha512-nri2TO5JE3/mRryik9LlHFT53cgHfRK0Lt0BAZQXku/AW3E6XLt2GaY8siWi7dvW/m1z0ecn+J+bpDa9ZN3IsQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Borewit" - } - }, "node_modules/pend": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", @@ -11797,6 +11850,7 @@ "resolved": "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz", "integrity": "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -12080,6 +12134,19 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz", + "integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", @@ -12257,12 +12324,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/spawn-command": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/spawn-command/-/spawn-command-0.0.2.tgz", - "integrity": "sha512-zC8zGoGkmc8J9ndvml8Xksr1Amk9qBujgbF0JAIWO7kXr43w0h/0GJNM/Vustixu+YE8N/MTrQ7N31FvHUACxQ==", - "dev": true - }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", @@ -12550,14 +12611,13 @@ "license": "MIT" }, "node_modules/strtok3": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.2.2.tgz", - "integrity": "sha512-Xt18+h4s7Z8xyZ0tmBoRmzxcop97R4BAh+dXouUDCYn+Em+1P3qpkUfI5ueWLT8ynC5hZ+q4iPEmGG1urvQGBg==", + "version": "10.3.4", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.3.4.tgz", + "integrity": "sha512-KIy5nylvC5le1OdaaoCJ07L+8iQzJHGH6pWDuzS+d07Cu7n1MZ2x26P8ZKIWfbK02+XIL8Mp4RkWeqdUCrDMfg==", "dev": true, "license": "MIT", "dependencies": { - "@tokenizer/token": "^0.3.0", - "peek-readable": "^7.0.0" + "@tokenizer/token": "^0.3.0" }, "engines": { "node": ">=18" @@ -13155,7 +13215,8 @@ "version": "2.3.8", "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/timers-ext": { "version": "0.1.8", @@ -13252,10 +13313,11 @@ } }, "node_modules/tmp": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz", - "integrity": "sha512-nZD7m9iCPC5g0pYmcaxogYKggSfLsdxl8of3Q/oIbqCqLLIO9IAF0GWjX1z9NZRHPiXv8Wex4yDCaZsgEw0Y8w==", + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", + "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", "dev": true, + "license": "MIT", "engines": { "node": ">=14.14" } @@ -13286,12 +13348,13 @@ } }, "node_modules/token-types": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.0.0.tgz", - "integrity": "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.1.tgz", + "integrity": "sha512-kh9LVIWH5CnL63Ipf0jhlBIy0UsrMj/NJDfpsy1SqOXlLKEVyXXYrnFxFT1yOOYVGBSApeVnjPw/sBz5BfEjAQ==", "dev": true, "license": "MIT", "dependencies": { + "@borewit/text-codec": "^0.1.0", "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" }, @@ -13341,6 +13404,7 @@ "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", "dev": true, + "license": "MIT", "bin": { "tree-kill": "cli.js" } @@ -13543,9 +13607,9 @@ } }, "node_modules/uint8array-extras": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.4.0.tgz", - "integrity": "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.5.0.tgz", + "integrity": "sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==", "dev": true, "license": "MIT", "engines": { @@ -16507,6 +16571,7 @@ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -16557,6 +16622,7 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -16566,6 +16632,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -16690,15 +16757,6 @@ "node": ">=12" } }, - "node_modules/yargs-parser": { - "version": "20.2.9", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.9.tgz", - "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", - "dev": true, - "engines": { - "node": ">=10" - } - }, "node_modules/yargs-unparser": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 8054468a9..a9beb535a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.3.2", + "version": "1.3.4", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -183,7 +183,7 @@ { "command": "continue.focusEdit", "category": "Continue", - "title": "Edit Highlighted Code", + "title": "Add to Edit", "group": "Continue" }, { @@ -195,7 +195,7 @@ { "command": "continue.focusContinueInputWithoutClear", "category": "Continue", - "title": "Add Highlighted Code to Context", + "title": "Add to Chat", "group": "Continue" }, { @@ -547,31 +547,6 @@ "command": "continue.focusEdit", "group": "Continue", "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.writeCommentsForCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.writeDocstringForCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.fixCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.optimizeCode", - "group": "Continue", - "when": "editorHasSelection && !editorReadonly" - }, - { - "command": "continue.fixGrammar", - "group": "Continue", - "when": "editorHasSelection && editorLangId == 'markdown' && !editorReadonly" } ], "explorer/context": [ @@ -724,7 +699,7 @@ "devDependencies": { "@biomejs/biome": "1.6.4", "@nestjs/common": "^11.0.16", - "@openapitools/openapi-generator-cli": "^2.20.0", + "@openapitools/openapi-generator-cli": "^2.23.1", "@types/chai": "^5.0.1", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 19be7545e..6f4275f67 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -3,7 +3,6 @@ import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; import { VsCodeExtension } from "../extension/VsCodeExtension"; -import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion, isUnsupportedPlatform } from "../util/util"; import { GlobalContext } from "core/util/GlobalContext"; @@ -41,7 +40,6 @@ export async function activateExtension(context: vscode.ExtensionContext) { getContinueRcPath(); // Register commands and providers - registerQuickFixProvider(); setupInlineTips(context); const vscodeExtension = new VsCodeExtension(context); diff --git a/extensions/vscode/src/lang-server/codeActions.ts b/extensions/vscode/src/lang-server/codeActions.ts deleted file mode 100644 index f39d5b926..000000000 --- a/extensions/vscode/src/lang-server/codeActions.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { EXTENSION_NAME } from "core/control-plane/env"; -import * as vscode from "vscode"; - -class ContinueQuickFixProvider implements vscode.CodeActionProvider { - public static readonly providedCodeActionKinds = [ - vscode.CodeActionKind.QuickFix, - ]; - - provideCodeActions( - document: vscode.TextDocument, - range: vscode.Range | vscode.Selection, - context: vscode.CodeActionContext, - token: vscode.CancellationToken, - ): vscode.ProviderResult<(vscode.Command | vscode.CodeAction)[]> { - if (context.diagnostics.length === 0) { - return []; - } - - const diagnostic = context.diagnostics[0]; - - const quickFix = new vscode.CodeAction( - "Ask Continue", - vscode.CodeActionKind.QuickFix, - ); - - quickFix.isPreferred = false; - - const surroundingRange = new vscode.Range( - Math.max(0, range.start.line - 3), - 0, - Math.min(document.lineCount, range.end.line + 3), - 0, - ); - - quickFix.command = { - command: "continue.quickFix", - title: "Continue Quick Fix", - arguments: [surroundingRange, diagnostic.message], - }; - - return [quickFix]; - } -} - -export default function registerQuickFixProvider() { - const isDisabled = - !!vscode.workspace - .getConfiguration(EXTENSION_NAME) - .get("disableQuickFix") === true; - - if (isDisabled) { - return; - } - - // In your extension's activate function: - vscode.languages.registerCodeActionsProvider( - { language: "*" }, - new ContinueQuickFixProvider(), - { - providedCodeActionKinds: ContinueQuickFixProvider.providedCodeActionKinds, - }, - ); -} diff --git a/gui/package-lock.json b/gui/package-lock.json index 8e4bfb7d9..2b33dc8c7 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -8,6 +8,7 @@ "license": "Apache-2.0", "dependencies": { "@continuedev/config-yaml": "file:../packages/config-yaml", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@panzoom/panzoom": "^4.6.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", @@ -266,6 +270,20 @@ "typescript": "^5.5.2" } }, + "../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/@adobe/css-tools": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.0.tgz", @@ -672,6 +690,10 @@ "resolved": "../packages/config-yaml", "link": true }, + "node_modules/@continuedev/terminal-security": { + "resolved": "../packages/terminal-security", + "link": true + }, "node_modules/@emotion/is-prop-valid": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.3.1.tgz", diff --git a/gui/package.json b/gui/package.json index 6cb45030c..2b5e31648 100644 --- a/gui/package.json +++ b/gui/package.json @@ -17,6 +17,7 @@ }, "dependencies": { "@continuedev/config-yaml": "file:../packages/config-yaml", + "@continuedev/terminal-security": "file:../packages/terminal-security", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@panzoom/panzoom": "^4.6.0", diff --git a/gui/src/components/AcceptRejectDiffButtons.tsx b/gui/src/components/AcceptRejectDiffButtons.tsx index 621fbeead..6abdded6e 100644 --- a/gui/src/components/AcceptRejectDiffButtons.tsx +++ b/gui/src/components/AcceptRejectDiffButtons.tsx @@ -58,33 +58,31 @@ export default function AcceptRejectAllButtons({ className="flex flex-row items-center justify-evenly gap-3 px-3" data-testid="accept-reject-all-buttons" > - - + + + - - + + + ); } diff --git a/gui/src/components/AssistantAndOrgListbox/index.tsx b/gui/src/components/AssistantAndOrgListbox/index.tsx index e77bf5118..72a0522db 100644 --- a/gui/src/components/AssistantAndOrgListbox/index.tsx +++ b/gui/src/components/AssistantAndOrgListbox/index.tsx @@ -125,12 +125,12 @@ export function AssistantAndOrgListbox() { {session?.AUTH_TYPE !== AuthType.OnPrem && session?.account.id} - - Logout + + + ) : ( - refreshProfiles("Manual refresh from assistant list") - } + onClick={(e: React.MouseEvent) => { + e.stopPropagation(); + refreshProfiles("Manual refresh from assistant list"); + }} > ) ) : ( - <> + +
Errors
+ {JSON.stringify(errors, null, 2)} + + } + > - -
Errors
- {JSON.stringify(errors, null, 2)} -
- +
)} diff --git a/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx b/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx index 28831b15d..3868b5a3b 100644 --- a/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx +++ b/gui/src/components/GenerateRuleDialog/GenerationScreen.tsx @@ -139,7 +139,6 @@ export function GenerationScreen({ }; const showNameSpinner = isGenerating && !formData.name && !isManualMode; - const tooltipId = "rule-type-tooltip"; return (
@@ -181,14 +180,12 @@ export function GenerationScreen({ - - + + +