Merge branch 'main' of https://github.com/continuedev/continue into mq200/fix-added-folders-not-triggering-reindex
3
.continue/environment.json
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"install": "npm i"
|
||||
}
|
||||
2
.github/pull_request_template.md
vendored
|
|
@ -5,7 +5,7 @@
|
|||
## AI Code Review
|
||||
|
||||
- **Team members only**: AI review runs automatically when PR is opened or marked ready for review
|
||||
- Team members can also trigger a review by commenting `@continue-general-review` or `@continue-detailed-review`
|
||||
- Team members can also trigger a review by commenting `@continue-review`
|
||||
|
||||
## Checklist
|
||||
|
||||
|
|
|
|||
25
.github/workflows/continue-detailed-review.yaml
vendored
|
|
@ -1,25 +0,0 @@
|
|||
name: Continue Detailed Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
detailed-code-review:
|
||||
name: Continue Detailed Review
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Detailed PR Review
|
||||
uses: continuedev/continue/actions/detailed-review@main
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: continuedev
|
||||
continue-config: continuedev/review-bot
|
||||
26
.github/workflows/pr-checks.yaml
vendored
|
|
@ -343,31 +343,6 @@ jobs:
|
|||
|
||||
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
|
||||
# This action at least lets us manage the list of required tests via source control
|
||||
pr-review-action-tests:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
- name: Cache PR review action node modules
|
||||
uses: actions/cache@v4
|
||||
id: pr-review-cache
|
||||
with:
|
||||
path: actions/detailed-review/node_modules
|
||||
key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }}
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.pr-review-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd actions/detailed-review
|
||||
npm install
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd actions/detailed-review
|
||||
npm test
|
||||
|
||||
# so that creators of new jobs can add them to this list
|
||||
require-all-checks-to-pass:
|
||||
|
|
@ -385,7 +360,6 @@ jobs:
|
|||
- vscode-package-extension-linux
|
||||
- vscode-e2e-tests
|
||||
- jetbrains-tests
|
||||
- pr-review-action-tests
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
|
|
|
|||
19
.github/workflows/release-llm-info.yml
vendored
|
|
@ -1,11 +1,17 @@
|
|||
name: Release @continuedev/llm-info
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/llm-info/**"
|
||||
- ".github/workflows/release-llm-info.yml"
|
||||
- ".github/workflows/reusable-release.yml"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
|
|
@ -16,14 +22,3 @@ jobs:
|
|||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
|
||||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
|
||||
RELACE_API_KEY: ${{ secrets.RELACE_API_KEY }}
|
||||
INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }}
|
||||
|
|
|
|||
302
.github/workflows/respond-to-cubic.yaml
vendored
|
|
@ -1,302 +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: |
|
||||
# Create a temporary file to safely handle comment body with special characters
|
||||
cat > /tmp/comment.txt << 'COMMENT_EOF'
|
||||
${{ github.event.comment.body }}
|
||||
COMMENT_EOF
|
||||
|
||||
if grep -q "@continuedev" /tmp/comment.txt; then
|
||||
echo "contains_mention=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
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
|
||||
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@v8
|
||||
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@v5
|
||||
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 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.
|
||||
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 --config continuedev/address-code-review --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@v8
|
||||
env:
|
||||
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
|
||||
with:
|
||||
script: |
|
||||
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
|
||||
const originalComment = process.env.ORIGINAL_COMMENT;
|
||||
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
|
||||
|
||||
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:"
|
||||
cat /tmp/comment.txt
|
||||
|
||||
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: |
|
||||
# Create a temporary file to safely handle comment body with special characters
|
||||
cat > /tmp/review_comment.txt << 'COMMENT_EOF'
|
||||
${{ github.event.comment.body }}
|
||||
COMMENT_EOF
|
||||
|
||||
if grep -q "@continuedev" /tmp/review_comment.txt; then
|
||||
echo "contains_mention=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
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
|
||||
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@v5
|
||||
with:
|
||||
node-version: "20"
|
||||
|
||||
- name: Install Continue CLI globally
|
||||
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 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' }}
|
||||
|
||||
${{ 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
|
||||
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 --config continuedev/address-code-review --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@v8
|
||||
env:
|
||||
ORIGINAL_COMMENT: ${{ github.event.comment.body }}
|
||||
with:
|
||||
script: |
|
||||
const sessionUrl = '${{ steps.remote-session.outputs.session_url }}';
|
||||
const originalComment = process.env.ORIGINAL_COMMENT;
|
||||
const commentBody = "I've started [a remote session](" + sessionUrl + ") to help with your request:\n> " + originalComment;
|
||||
|
||||
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:"
|
||||
cat /tmp/review_comment.txt
|
||||
8
.github/workflows/runloop-blueprint-template.json
vendored
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"name": "cn",
|
||||
"system_setup_commands": [
|
||||
"npm i -g @continuedev/cli@latest",
|
||||
"sudo apt update",
|
||||
"sudo apt install -y ripgrep"
|
||||
]
|
||||
}
|
||||
37
.github/workflows/stable-release.yml
vendored
|
|
@ -220,3 +220,40 @@ jobs:
|
|||
# Mark the original beta release as superseded
|
||||
gh release edit "v${{ steps.find_beta.outputs.beta_version }}" \
|
||||
--notes "This beta version has been promoted to stable as v${{ steps.final_version.outputs.stable_version }}."
|
||||
|
||||
- name: Publish Blueprint to Runloop
|
||||
env:
|
||||
RUNLOOP_API_KEY: ${{ secrets.RUNLOOP_API_KEY }}
|
||||
run: |
|
||||
echo "Publishing blueprint 'cn' to Runloop API for version ${{ steps.final_version.outputs.stable_version }}"
|
||||
|
||||
# Use blueprint configuration from template file
|
||||
cp .github/workflows/runloop-blueprint-template.json blueprint.json
|
||||
|
||||
# Publish to Runloop API
|
||||
response=$(curl -X POST "https://api.runloop.ai/v1/blueprints" \
|
||||
-H "Authorization: Bearer $RUNLOOP_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @blueprint.json \
|
||||
-w "%{http_code}" \
|
||||
-s)
|
||||
|
||||
http_code=$(echo "$response" | tail -c 4)
|
||||
response_body=$(echo "$response" | head -c -4)
|
||||
|
||||
if [[ "$http_code" == "200" ]] || [[ "$http_code" == "201" ]]; then
|
||||
echo "✅ Successfully published blueprint to Runloop API"
|
||||
echo "Response: $response_body"
|
||||
|
||||
# Extract blueprint ID if available
|
||||
blueprint_id=$(echo "$response_body" | jq -r '.id // empty')
|
||||
if [[ -n "$blueprint_id" ]]; then
|
||||
echo "Blueprint ID: $blueprint_id"
|
||||
echo "blueprint_id=$blueprint_id" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
else
|
||||
echo "❌ Failed to publish blueprint to Runloop API"
|
||||
echo "HTTP Code: $http_code"
|
||||
echo "Response: $response_body"
|
||||
exit 1
|
||||
fi
|
||||
|
|
|
|||
5
.gitignore
vendored
|
|
@ -172,4 +172,7 @@ extensions/.continue-debug/
|
|||
.continuerules
|
||||
**/.continue/assistants/
|
||||
**/.continue/agents/
|
||||
keys
|
||||
keys
|
||||
|
||||
.channels_cache.json
|
||||
.users_cache.json
|
||||
|
|
|
|||
1
.husky/pre-commit
Normal file
|
|
@ -0,0 +1 @@
|
|||
npx lint-staged
|
||||
|
|
@ -11,9 +11,13 @@ extensions/vscode/.vscode-test
|
|||
extensions/vscode/bin
|
||||
extensions/vscode/build
|
||||
extensions/vscode/out
|
||||
extensions/vscode/textmate-syntaxes
|
||||
extensions/vscode/gui
|
||||
extensions/vscode/e2e/.test-extensions
|
||||
extensions/vscode/e2e/test-continue
|
||||
extensions/vscode/e2e/_output
|
||||
extensions/vscode/e2e/storage
|
||||
extensions/vscode/e2e/vsix
|
||||
extensions/vscode/models
|
||||
extensions/intellij/src/main/resources
|
||||
gui/dist
|
||||
|
|
@ -26,4 +30,5 @@ CHANGELOG.md
|
|||
core/vendor
|
||||
coverage
|
||||
# e2e
|
||||
packages/continue-sdk
|
||||
packages/continue-sdk
|
||||
.conductor
|
||||
32
.vscode/launch.json
vendored
|
|
@ -159,7 +159,37 @@
|
|||
"!**/node_modules/**"
|
||||
],
|
||||
"preLaunchTask": "cli:build-and-watch-logs",
|
||||
"cwd": "${workspaceFolder}/extensions/cli"
|
||||
"cwd": "${workspaceFolder}/manual-testing-sandbox"
|
||||
},
|
||||
{
|
||||
"name": "Debug CLI - AWS Bedrock",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/extensions/cli/dist/cn.js",
|
||||
"args": [],
|
||||
"runtimeArgs": ["--enable-source-maps"],
|
||||
"env": {
|
||||
"NODE_ENV": "development",
|
||||
"CONTINUE_USE_BEDROCK": "1"
|
||||
// "CONTINUE_API_BASE": "http://localhost:3001/",
|
||||
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
|
||||
// "HUB_URL": "http://localhost:3000"
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"sourceMaps": true,
|
||||
"outFiles": ["${workspaceFolder}/extensions/cli/dist/**/*.js"],
|
||||
"sourceMapPathOverrides": {
|
||||
"../src/*": "${workspaceFolder}/extensions/cli/src/*",
|
||||
"../../core/*": "${workspaceFolder}/core/*"
|
||||
},
|
||||
"resolveSourceMapLocations": [
|
||||
"${workspaceFolder}/**",
|
||||
"!**/node_modules/**"
|
||||
],
|
||||
"preLaunchTask": "cli:build-and-watch-logs",
|
||||
"cwd": "${workspaceFolder}/manual-testing-sandbox"
|
||||
},
|
||||
{
|
||||
"name": "Debug CLI Tests",
|
||||
|
|
|
|||
|
|
@ -252,7 +252,7 @@ add it with the following steps:
|
|||
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
|
||||
in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
|
||||
4. Add a documentation page for your provider in [
|
||||
`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
|
||||
`docs/customize/model-providers/more`](./docs/customize/model-providers/more). This should show an example
|
||||
of configuring your provider in `config.yaml` and explain what options are available.
|
||||
|
||||
### Adding Models
|
||||
|
|
|
|||
|
|
@ -4,64 +4,19 @@ GitHub Actions that provide automated code reviews for pull requests using Conti
|
|||
|
||||
## Available Actions
|
||||
|
||||
This repository provides two GitHub Actions for different review styles:
|
||||
This repository provides a GitHub Action for automated PR reviews:
|
||||
|
||||
### 1. General Review Action
|
||||
### General Review Action
|
||||
|
||||
Provides high-level PR assessment with overall feedback and recommendations.
|
||||
|
||||
- **Path:** `continuedev/continue/actions/general-review@<commit-sha>`
|
||||
- **Trigger:** `@continue-general-review`
|
||||
- **Path:** `continuedev/continue/actions/general-review@main`
|
||||
- **Trigger:** `@continue-review`
|
||||
- **Output:** Summary comment with strengths, issues, and recommendations
|
||||
|
||||
### 2. Detailed Review Action
|
||||
|
||||
Provides line-by-line inline comments on specific code changes.
|
||||
|
||||
- **Path:** `continuedev/continue/actions/detailed-review@<commit-sha>`
|
||||
- **Trigger:** `@continue-detailed-review`
|
||||
- **Output:** Inline review comments on specific lines of code
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Using Both Actions Together
|
||||
|
||||
```yaml
|
||||
name: PR Reviews
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
general-review:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: continuedev/continue/actions/general-review@<commit-sha>
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "your-org-name"
|
||||
continue-config: "your-org-name/review-bot"
|
||||
|
||||
detailed-review:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: continuedev/continue/actions/detailed-review@<commit-sha>
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "your-org-name"
|
||||
continue-config: "your-org-name/review-bot"
|
||||
```
|
||||
|
||||
### General Review Only
|
||||
### Setting up General Review
|
||||
|
||||
```yaml
|
||||
name: PR General Review
|
||||
|
|
@ -81,34 +36,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: continuedev/continue/actions/general-review@<commit-sha>
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "your-org-name"
|
||||
continue-config: "your-org-name/review-bot"
|
||||
```
|
||||
|
||||
### Detailed Review Only
|
||||
|
||||
```yaml
|
||||
name: PR Detailed Review
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
review:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: continuedev/continue/actions/detailed-review@<commit-sha>
|
||||
- uses: continuedev/continue/actions/general-review@main
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "your-org-name"
|
||||
|
|
@ -117,7 +45,7 @@ jobs:
|
|||
|
||||
## Inputs
|
||||
|
||||
Both actions accept the same inputs:
|
||||
The action accepts the following inputs:
|
||||
|
||||
| Input | Description | Required |
|
||||
| ------------------ | -------------------------------------- | -------- |
|
||||
|
|
@ -155,7 +83,7 @@ The workflow requires these permissions:
|
|||
|
||||
## Triggering Reviews
|
||||
|
||||
Both actions can be triggered in two ways:
|
||||
The action can be triggered in two ways:
|
||||
|
||||
### Automatic Triggers
|
||||
|
||||
|
|
@ -166,12 +94,9 @@ Both actions can be triggered in two ways:
|
|||
|
||||
Team members can trigger reviews by commenting on any pull request:
|
||||
|
||||
- `@continue-general-review` - Triggers a general review
|
||||
- `@continue-detailed-review` - Triggers a detailed inline review
|
||||
- `@continue-review` - Triggers a review
|
||||
|
||||
## Review Outputs
|
||||
|
||||
### General Review Output
|
||||
## Review Output
|
||||
|
||||
The general review provides a structured comment that includes:
|
||||
|
||||
|
|
@ -180,46 +105,24 @@ The general review provides a structured comment that includes:
|
|||
- **Suggestions**: Improvement recommendations
|
||||
- **Overall Assessment**: Final recommendation (APPROVE, REQUEST_CHANGES, or COMMENT)
|
||||
|
||||
### Detailed Review Output
|
||||
|
||||
The detailed review provides:
|
||||
|
||||
- **Inline Comments**: Specific feedback on individual lines of code
|
||||
- **Position Markers**: Comments appear directly on the changed lines
|
||||
- **Review Summary**: Overall assessment of the changes
|
||||
- **Actionable Feedback**: Specific suggestions for each issue found
|
||||
|
||||
## How It Works
|
||||
|
||||
### General Review Process
|
||||
|
||||
1. Checks out repository code
|
||||
2. Fetches PR diff using GitHub CLI
|
||||
3. Generates a comprehensive review prompt
|
||||
4. Runs Continue CLI with specified configuration
|
||||
5. Posts review as a PR comment
|
||||
|
||||
### Detailed Review Process
|
||||
|
||||
1. Checks out repository code
|
||||
2. Fetches PR diff with GitHub API positions
|
||||
3. Annotates diff with position markers
|
||||
4. Generates inline review prompt
|
||||
5. Runs Continue CLI for detailed analysis
|
||||
6. Posts inline comments using GitHub's review API
|
||||
|
||||
## Versioning
|
||||
|
||||
We recommend using a specific commit SHA for stability and predictability:
|
||||
We recommend using the main branch:
|
||||
|
||||
- `@<commit-sha>` - Pins to a specific commit for maximum stability (recommended)
|
||||
- `@main` - Uses the latest code from the main branch (for bleeding edge)
|
||||
- `@v1` - Uses a version tag when available
|
||||
- `@main` - Uses the latest code from the main branch
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe
|
||||
uses: continuedev/continue/actions/general-review@main
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
|
@ -236,12 +139,6 @@ uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1
|
|||
- Verify your Continue configuration is correct
|
||||
- Ensure your Continue API key is valid
|
||||
|
||||
### Inline comments not appearing (Detailed Review)
|
||||
|
||||
- Check that the PR has a valid diff
|
||||
- Verify GitHub API permissions are correct
|
||||
- Review action logs for position calculation errors
|
||||
|
||||
## Support
|
||||
|
||||
For issues or questions:
|
||||
|
|
|
|||
|
|
@ -1,434 +0,0 @@
|
|||
name: 'Continue Detailed PR Review'
|
||||
description: 'Automated inline code review for pull requests using Continue CLI'
|
||||
author: 'Continue Dev, Inc.'
|
||||
|
||||
inputs:
|
||||
continue-api-key:
|
||||
description: 'API key for Continue service'
|
||||
required: true
|
||||
continue-org:
|
||||
description: 'Organization for Continue config'
|
||||
required: true
|
||||
continue-config:
|
||||
description: 'Config path to use (e.g., "myorg/review-bot")'
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Check Authorization
|
||||
shell: bash
|
||||
env:
|
||||
# Only move the dangerous check to env to prevent shell injection
|
||||
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-detailed-review') }}
|
||||
run: |
|
||||
# Check if this action should run based on event type and user permissions
|
||||
SHOULD_RUN="false"
|
||||
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
# Check if PR is a draft
|
||||
if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
|
||||
echo "::notice::Skipping review - PR is a draft"
|
||||
else
|
||||
# Check PR author association
|
||||
AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
|
||||
if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
|
||||
SHOULD_RUN="true"
|
||||
else
|
||||
echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
|
||||
fi
|
||||
fi
|
||||
elif [ "${{ github.event_name }}" = "issue_comment" ]; then
|
||||
# Check if it's a PR comment with the trigger phrase
|
||||
if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
|
||||
COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
|
||||
if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
|
||||
SHOULD_RUN="true"
|
||||
else
|
||||
echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
|
||||
fi
|
||||
else
|
||||
echo "::notice::Skipping review - Comment does not contain @continue-detailed-review trigger, or is not on a PR"
|
||||
fi
|
||||
else
|
||||
echo "::notice::Skipping review - Event type ${{ github.event_name }} is not supported"
|
||||
fi
|
||||
|
||||
if [ "$SHOULD_RUN" != "true" ]; then
|
||||
echo "SKIP_REVIEW=true" >> $GITHUB_ENV
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "SKIP_REVIEW=false" >> $GITHUB_ENV
|
||||
|
||||
- name: Setup Node.js
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
- name: Install Continue CLI
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
shell: bash
|
||||
run: npm install -g @continuedev/cli@1.4.30
|
||||
|
||||
- name: Build Inline Review Prompt
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Get PR number based on event type
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
PR_NUMBER="${{ github.event.number }}"
|
||||
else
|
||||
# For issue_comment event on a PR
|
||||
PR_NUMBER="${{ github.event.issue.number }}"
|
||||
fi
|
||||
|
||||
# Get PR files with line numbers
|
||||
gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json
|
||||
|
||||
# Get PR diff with context
|
||||
gh pr diff $PR_NUMBER --color=never > pr_diff.txt
|
||||
|
||||
# Annotate diff with GitHub API positions
|
||||
node ${{ github.action_path }}/annotate-diff.js pr_diff.txt > pr_diff_annotated.txt
|
||||
|
||||
# Debug: Show sample of annotated diff
|
||||
echo "=== SAMPLE OF ANNOTATED DIFF ==="
|
||||
head -100 pr_diff_annotated.txt | grep -E "^\[POS:|^@@|^diff --git" || head -50 pr_diff_annotated.txt
|
||||
echo "=== END SAMPLE ==="
|
||||
|
||||
# Create review prompt for inline comments
|
||||
cat > inline_review_prompt.txt << 'EOF'
|
||||
You are conducting a detailed inline code review for a pull request.
|
||||
|
||||
Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code.
|
||||
|
||||
IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line.
|
||||
|
||||
Example of how to use the position markers:
|
||||
```
|
||||
diff --git a/src/app.js b/src/app.js
|
||||
index abc123..def456 100644
|
||||
--- a/src/app.js
|
||||
+++ b/src/app.js
|
||||
@@ -10,4 +10,6 @@ function example() {
|
||||
[POS:1] console.log("context");
|
||||
[POS:2] - const old = "remove this";
|
||||
[POS:3] + const new = "add this";
|
||||
[POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4
|
||||
[POS:5] return result;
|
||||
[POS:6] + console.log("done");
|
||||
@@ -20,3 +22,4 @@ function another() {
|
||||
[POS:1] let x = 1;
|
||||
[POS:2] + let y = 2; <-- To comment here, use position: 2
|
||||
```
|
||||
|
||||
To comment on a line, simply use the number from its [POS:N] marker as the position value.
|
||||
For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"}
|
||||
|
||||
Below is the annotated PR diff:
|
||||
|
||||
EOF
|
||||
|
||||
cat pr_diff_annotated.txt >> inline_review_prompt.txt
|
||||
|
||||
cat >> inline_review_prompt.txt << 'EOF'
|
||||
|
||||
Please analyze these changes and provide inline review comments in the following JSON format:
|
||||
|
||||
{
|
||||
"review_summary": "Overall assessment of the PR",
|
||||
"comments": [
|
||||
{
|
||||
"path": "path/to/file.js",
|
||||
"position": 4,
|
||||
"body": "Brief, specific comment about this line or section"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Focus on:
|
||||
1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality
|
||||
2. **High Priority**: Performance problems, incorrect logic, missing error handling
|
||||
3. **Medium Priority**: Code style violations, potential edge cases, unclear code
|
||||
4. **Low Priority**: Suggestions for improvement, refactoring opportunities
|
||||
|
||||
Guidelines for comments:
|
||||
- Be specific and actionable
|
||||
- Use the [POS:N] number shown in the diff as the position value
|
||||
- Keep comments concise but informative
|
||||
- Suggest concrete improvements when pointing out issues
|
||||
- Only comment on actual problems or important improvements
|
||||
|
||||
Important:
|
||||
- Output ONLY valid JSON, no markdown code blocks or backticks
|
||||
- Start your response with { and end with }
|
||||
- Use the exact number from [POS:N] markers as the position
|
||||
- Only comment on changed lines (lines with + or - prefix)
|
||||
- Comment on the most important issues first
|
||||
- Limit to maximum 20 most relevant comments
|
||||
EOF
|
||||
|
||||
- name: Run Continue CLI Inline Review
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
shell: bash
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
|
||||
run: |
|
||||
echo "Running Continue CLI for inline review..."
|
||||
|
||||
# Validate required inputs
|
||||
if [ -z "${{ inputs.continue-org }}" ]; then
|
||||
echo "Error: continue-org input is required"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${{ inputs.continue-config }}" ]; then
|
||||
echo "Error: continue-config input is required"
|
||||
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
|
||||
echo "... [diff content] ..."
|
||||
tail -n 20 inline_review_prompt.txt
|
||||
echo "===== END REVIEW PROMPT ====="
|
||||
|
||||
# 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
|
||||
|
||||
- name: Post Inline Review Comments
|
||||
if: env.SKIP_REVIEW != 'true'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
|
||||
try {
|
||||
// Read the review output
|
||||
let reviewData;
|
||||
try {
|
||||
const reviewContent = fs.readFileSync('inline_review.json', 'utf8');
|
||||
reviewData = JSON.parse(reviewContent);
|
||||
} catch (parseError) {
|
||||
console.log('Failed to parse review JSON:', parseError);
|
||||
reviewData = {
|
||||
review_summary: 'AI review completed but failed to parse output',
|
||||
comments: []
|
||||
};
|
||||
}
|
||||
|
||||
// Get PR number
|
||||
let prNumber;
|
||||
if (context.eventName === 'pull_request') {
|
||||
prNumber = context.payload.pull_request.number;
|
||||
} else {
|
||||
prNumber = context.payload.issue.number;
|
||||
}
|
||||
|
||||
// Get the latest commit SHA
|
||||
const { data: pr } = await github.rest.pulls.get({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: prNumber
|
||||
});
|
||||
|
||||
const commitSha = pr.head.sha;
|
||||
|
||||
// Prepare review comments - filter out comments without required fields
|
||||
const allComments = reviewData.comments || [];
|
||||
const validComments = allComments.filter(comment =>
|
||||
comment.position &&
|
||||
comment.path &&
|
||||
comment.body &&
|
||||
typeof comment.position === 'number' &&
|
||||
comment.position > 0
|
||||
);
|
||||
|
||||
if (validComments.length < allComments.length) {
|
||||
console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`);
|
||||
const invalidComments = allComments.filter(c => !validComments.includes(c));
|
||||
console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2));
|
||||
}
|
||||
|
||||
// Deduplicate comments based on path + position + body
|
||||
const uniqueComments = [];
|
||||
const seen = new Set();
|
||||
|
||||
for (const comment of validComments) {
|
||||
const key = `${comment.path}:${comment.position}:${comment.body}`;
|
||||
if (!seen.has(key)) {
|
||||
seen.add(key);
|
||||
uniqueComments.push(comment);
|
||||
}
|
||||
}
|
||||
|
||||
if (uniqueComments.length < validComments.length) {
|
||||
console.log(`Filtered out ${validComments.length - uniqueComments.length} duplicate comments (same path + position + body)`);
|
||||
}
|
||||
|
||||
const comments = uniqueComments.map(comment => ({
|
||||
path: comment.path,
|
||||
position: comment.position,
|
||||
body: comment.body
|
||||
}));
|
||||
|
||||
// Debug: Log the positions we're trying to use
|
||||
console.log('Attempting to post comments with positions:');
|
||||
comments.forEach(c => {
|
||||
console.log(` ${c.path}: position ${c.position}`);
|
||||
});
|
||||
|
||||
// Create the review
|
||||
if (comments.length > 0) {
|
||||
try {
|
||||
let reviewBody = `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
|
||||
|
||||
// Add triggered by note if from comment
|
||||
if (context.eventName === 'issue_comment') {
|
||||
reviewBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewBody}`;
|
||||
}
|
||||
|
||||
await github.rest.pulls.createReview({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
pull_number: prNumber,
|
||||
commit_id: commitSha,
|
||||
body: reviewBody,
|
||||
event: 'COMMENT',
|
||||
comments: comments
|
||||
});
|
||||
console.log(`Successfully created review with ${comments.length} inline comments`);
|
||||
} catch (reviewError) {
|
||||
console.log('Failed to create review:', reviewError.message);
|
||||
|
||||
// Fallback: post as a regular comment if review creation fails
|
||||
const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` +
|
||||
`*Failed to post ${comments.length} inline comments. Please review the changes manually.*\n\n` +
|
||||
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: fallbackBody
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// No inline comments, just post the summary
|
||||
let summaryBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` +
|
||||
`---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`;
|
||||
|
||||
// Add triggered by note if from comment
|
||||
if (context.eventName === 'issue_comment') {
|
||||
summaryBody = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${summaryBody}`;
|
||||
}
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: summaryBody
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.log('Failed to post review:', error.message);
|
||||
console.log('Error details:', error);
|
||||
}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
- name: Upload Review Artifacts
|
||||
if: env.SKIP_REVIEW != 'true' && always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: inline-review-results
|
||||
path: |
|
||||
inline_review_raw.json
|
||||
inline_review.json
|
||||
inline_review_prompt.txt
|
||||
pr_diff.txt
|
||||
pr_diff_annotated.txt
|
||||
retention-days: 7
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Annotates a git diff with GitHub API positions
|
||||
*
|
||||
* Takes a raw diff and adds [POS:N] markers with the correct
|
||||
* GitHub API positions (cumulative, with +1 between hunks)
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
function annotateDiff(diffContent) {
|
||||
const lines = diffContent.split("\n");
|
||||
const output = [];
|
||||
let githubPos = 0;
|
||||
let inHunk = false;
|
||||
|
||||
for (const line of lines) {
|
||||
// Handle new file - reset position counter
|
||||
if (line.startsWith("diff --git")) {
|
||||
githubPos = 0;
|
||||
inHunk = false;
|
||||
output.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pass through other git headers unchanged
|
||||
if (
|
||||
line.startsWith("index ") ||
|
||||
line.startsWith("---") ||
|
||||
line.startsWith("+++") ||
|
||||
line.startsWith("rename ") ||
|
||||
line.startsWith("similarity ") ||
|
||||
line.startsWith("new file") ||
|
||||
line.startsWith("deleted file") ||
|
||||
line.startsWith("old mode") ||
|
||||
line.startsWith("new mode") ||
|
||||
line.startsWith("Binary files")
|
||||
) {
|
||||
output.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle hunk headers
|
||||
if (line.startsWith("@@")) {
|
||||
if (inHunk) {
|
||||
githubPos++; // GitHub's +1 between hunks
|
||||
}
|
||||
inHunk = true;
|
||||
output.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle "no newline" marker - it counts as a position but isn't annotated
|
||||
if (line.startsWith("\\ No newline")) {
|
||||
if (inHunk) {
|
||||
githubPos++; // GitHub counts this as a position
|
||||
}
|
||||
output.push(line); // Don't annotate it
|
||||
continue;
|
||||
}
|
||||
|
||||
// Annotate actual diff lines with GitHub positions
|
||||
if (inHunk) {
|
||||
githubPos++;
|
||||
output.push(`[POS:${githubPos}] ${line}`);
|
||||
} else {
|
||||
output.push(line);
|
||||
}
|
||||
}
|
||||
|
||||
return output.join("\n");
|
||||
}
|
||||
|
||||
// Main
|
||||
function main() {
|
||||
// Read diff from stdin or file
|
||||
let input = "";
|
||||
|
||||
if (process.argv.length > 2) {
|
||||
// Read from file
|
||||
input = fs.readFileSync(process.argv[2], "utf8");
|
||||
} else {
|
||||
// Read from stdin
|
||||
input = fs.readFileSync(0, "utf8");
|
||||
}
|
||||
|
||||
const annotated = annotateDiff(input);
|
||||
console.log(annotated);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main();
|
||||
}
|
||||
|
||||
module.exports = { annotateDiff };
|
||||
|
|
@ -1,363 +0,0 @@
|
|||
const { annotateDiff } = require("./annotate-diff.js");
|
||||
|
||||
describe("annotateDiff", () => {
|
||||
test("single file, single hunk", () => {
|
||||
const diff = `diff --git a/file.js b/file.js
|
||||
index abc123..def456 100644
|
||||
--- a/file.js
|
||||
+++ b/file.js
|
||||
@@ -1,3 +1,4 @@
|
||||
line1
|
||||
line2
|
||||
+added line
|
||||
line3`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] line2");
|
||||
expect(result).toContain("[POS:3] +added line");
|
||||
expect(result).toContain("[POS:4] line3");
|
||||
});
|
||||
|
||||
test("single file, multiple hunks with +1 between", () => {
|
||||
const diff = `diff --git a/file.js b/file.js
|
||||
index abc123..def456 100644
|
||||
--- a/file.js
|
||||
+++ b/file.js
|
||||
@@ -1,3 +1,3 @@
|
||||
line1
|
||||
-old line
|
||||
+new line
|
||||
line3
|
||||
@@ -10,3 +10,3 @@
|
||||
line10
|
||||
-old line 11
|
||||
+new line 11
|
||||
line12`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
|
||||
// First hunk
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] -old line");
|
||||
expect(result).toContain("[POS:3] +new line");
|
||||
expect(result).toContain("[POS:4] line3");
|
||||
|
||||
// Second hunk (should start at 6, because 4 lines + 1 for between hunks)
|
||||
expect(result).toContain("[POS:6] line10");
|
||||
expect(result).toContain("[POS:7] -old line 11");
|
||||
expect(result).toContain("[POS:8] +new line 11");
|
||||
expect(result).toContain("[POS:9] line12");
|
||||
});
|
||||
|
||||
test("multiple files reset position counter", () => {
|
||||
const diff = `diff --git a/file1.js b/file1.js
|
||||
index abc123..def456 100644
|
||||
--- a/file1.js
|
||||
+++ b/file1.js
|
||||
@@ -1,2 +1,2 @@
|
||||
line1
|
||||
-old
|
||||
+new
|
||||
diff --git a/file2.js b/file2.js
|
||||
index abc123..def456 100644
|
||||
--- a/file2.js
|
||||
+++ b/file2.js
|
||||
@@ -1,2 +1,2 @@
|
||||
first
|
||||
-old2
|
||||
+new2`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
|
||||
// File 1
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] -old");
|
||||
expect(result).toContain("[POS:3] +new");
|
||||
|
||||
// File 2 - positions should reset
|
||||
const file2Section = result.split("diff --git a/file2.js")[1];
|
||||
expect(file2Section).toContain("[POS:1] first");
|
||||
expect(file2Section).toContain("[POS:2] -old2");
|
||||
expect(file2Section).toContain("[POS:3] +new2");
|
||||
});
|
||||
|
||||
test("handles new file", () => {
|
||||
const diff = `diff --git a/newfile.js b/newfile.js
|
||||
new file mode 100644
|
||||
index 0000000..abc123
|
||||
--- /dev/null
|
||||
+++ b/newfile.js
|
||||
@@ -0,0 +1,3 @@
|
||||
+line1
|
||||
+line2
|
||||
+line3`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("new file mode 100644");
|
||||
expect(result).toContain("[POS:1] +line1");
|
||||
expect(result).toContain("[POS:2] +line2");
|
||||
expect(result).toContain("[POS:3] +line3");
|
||||
});
|
||||
|
||||
test("handles deleted file", () => {
|
||||
const diff = `diff --git a/deleted.js b/deleted.js
|
||||
deleted file mode 100644
|
||||
index abc123..0000000
|
||||
--- a/deleted.js
|
||||
+++ /dev/null
|
||||
@@ -1,3 +0,0 @@
|
||||
-line1
|
||||
-line2
|
||||
-line3`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("deleted file mode 100644");
|
||||
expect(result).toContain("[POS:1] -line1");
|
||||
expect(result).toContain("[POS:2] -line2");
|
||||
expect(result).toContain("[POS:3] -line3");
|
||||
});
|
||||
|
||||
test("handles renamed file with changes", () => {
|
||||
const diff = `diff --git a/old-name.js b/new-name.js
|
||||
similarity index 95%
|
||||
rename from old-name.js
|
||||
rename to new-name.js
|
||||
index abc123..def456 100644
|
||||
--- a/old-name.js
|
||||
+++ b/new-name.js
|
||||
@@ -1,3 +1,3 @@
|
||||
line1
|
||||
-old line
|
||||
+new line
|
||||
line3`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("rename from old-name.js");
|
||||
expect(result).toContain("rename to new-name.js");
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] -old line");
|
||||
expect(result).toContain("[POS:3] +new line");
|
||||
});
|
||||
|
||||
test("handles no newline at end of file", () => {
|
||||
const diff = `diff --git a/file.js b/file.js
|
||||
index abc123..def456 100644
|
||||
--- a/file.js
|
||||
+++ b/file.js
|
||||
@@ -1,2 +1,2 @@
|
||||
line1
|
||||
-old line
|
||||
\\ No newline at end of file
|
||||
+new line
|
||||
\\ No newline at end of file`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] -old line");
|
||||
// Position 3 is the first "No newline" marker (not annotated but counted)
|
||||
expect(result).toContain("\\ No newline at end of file");
|
||||
expect(result).toContain("[POS:4] +new line"); // Position 4 due to "No newline" at position 3
|
||||
// Position 5 is the second "No newline" marker (not annotated but counted)
|
||||
expect(result).toContain("\\ No newline at end of file");
|
||||
// No newline markers should not get [POS:N] annotations
|
||||
expect(result).not.toContain("[POS:3] \\");
|
||||
expect(result).not.toContain("[POS:5] \\");
|
||||
});
|
||||
|
||||
test("handles file mode changes", () => {
|
||||
const diff = `diff --git a/script.sh b/script.sh
|
||||
old mode 100644
|
||||
new mode 100755
|
||||
index abc123..def456 100644
|
||||
--- a/script.sh
|
||||
+++ b/script.sh
|
||||
@@ -1,2 +1,2 @@
|
||||
#!/bin/bash
|
||||
-echo "old"
|
||||
+echo "new"`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("old mode 100644");
|
||||
expect(result).toContain("new mode 100755");
|
||||
expect(result).toContain("[POS:1] #!/bin/bash");
|
||||
expect(result).toContain('[POS:2] -echo "old"');
|
||||
expect(result).toContain('[POS:3] +echo "new"');
|
||||
});
|
||||
|
||||
test("empty diff returns empty", () => {
|
||||
const diff = "";
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
test("handles binary files - modified", () => {
|
||||
const diff = `diff --git a/image.png b/image.png
|
||||
index abc123..def456 100644
|
||||
Binary files a/image.png and b/image.png differ`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("diff --git a/image.png b/image.png");
|
||||
expect(result).toContain("Binary files a/image.png and b/image.png differ");
|
||||
// Binary files line should not be annotated
|
||||
expect(result).not.toContain("[POS:");
|
||||
});
|
||||
|
||||
test("handles binary files - added", () => {
|
||||
const diff = `diff --git a/newimage.png b/newimage.png
|
||||
new file mode 100644
|
||||
index 0000000..abc123
|
||||
Binary files /dev/null and b/newimage.png differ`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("diff --git a/newimage.png b/newimage.png");
|
||||
expect(result).toContain("new file mode 100644");
|
||||
expect(result).toContain(
|
||||
"Binary files /dev/null and b/newimage.png differ",
|
||||
);
|
||||
// Binary files line should not be annotated
|
||||
expect(result).not.toContain("[POS:");
|
||||
});
|
||||
|
||||
test("handles binary files - deleted", () => {
|
||||
const diff = `diff --git a/oldimage.png b/oldimage.png
|
||||
deleted file mode 100644
|
||||
index abc123..0000000
|
||||
Binary files a/oldimage.png and /dev/null differ`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
expect(result).toContain("diff --git a/oldimage.png b/oldimage.png");
|
||||
expect(result).toContain("deleted file mode 100644");
|
||||
expect(result).toContain(
|
||||
"Binary files a/oldimage.png and /dev/null differ",
|
||||
);
|
||||
// Binary files line should not be annotated
|
||||
expect(result).not.toContain("[POS:");
|
||||
});
|
||||
|
||||
test("handles mixed text and binary files", () => {
|
||||
const diff = `diff --git a/text.js b/text.js
|
||||
index abc123..def456 100644
|
||||
--- a/text.js
|
||||
+++ b/text.js
|
||||
@@ -1,2 +1,2 @@
|
||||
line1
|
||||
-old
|
||||
+new
|
||||
diff --git a/image.png b/image.png
|
||||
index 111111..222222 100644
|
||||
Binary files a/image.png and b/image.png differ
|
||||
diff --git a/another.js b/another.js
|
||||
index 333333..444444 100644
|
||||
--- a/another.js
|
||||
+++ b/another.js
|
||||
@@ -1,1 +1,1 @@
|
||||
-foo
|
||||
+bar`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
|
||||
// First file (text)
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] -old");
|
||||
expect(result).toContain("[POS:3] +new");
|
||||
|
||||
// Second file (binary) - no positions
|
||||
expect(result).toContain("Binary files a/image.png and b/image.png differ");
|
||||
|
||||
// Third file (text) - positions reset
|
||||
const lastFileSection = result.split("diff --git a/another.js")[1];
|
||||
expect(lastFileSection).toContain("[POS:1] -foo");
|
||||
expect(lastFileSection).toContain("[POS:2] +bar");
|
||||
});
|
||||
|
||||
test("multiple no newline markers accumulate positions", () => {
|
||||
const diff = `diff --git a/file.js b/file.js
|
||||
index abc123..def456 100644
|
||||
--- a/file.js
|
||||
+++ b/file.js
|
||||
@@ -1,3 +1,3 @@
|
||||
line1
|
||||
-old1
|
||||
\\ No newline at end of file
|
||||
+new1
|
||||
\\ No newline at end of file
|
||||
@@ -10,3 +10,3 @@
|
||||
line10
|
||||
-old2
|
||||
\\ No newline at end of file
|
||||
+new2
|
||||
\\ No newline at end of file`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
|
||||
// First hunk
|
||||
expect(result).toContain("[POS:1] line1");
|
||||
expect(result).toContain("[POS:2] -old1");
|
||||
// Position 3 is the first "No newline" marker
|
||||
expect(result).toContain("[POS:4] +new1");
|
||||
// Position 5 is the second "No newline" marker
|
||||
|
||||
// Second hunk (starts at position 7 = 5 + 1 for between hunks + 1)
|
||||
expect(result).toContain("[POS:7] line10");
|
||||
expect(result).toContain("[POS:8] -old2");
|
||||
// Position 9 is the third "No newline" marker
|
||||
expect(result).toContain("[POS:10] +new2");
|
||||
// Position 11 is the fourth "No newline" marker
|
||||
|
||||
// Verify "No newline" markers are not annotated
|
||||
expect(result).not.toContain("[POS:3] \\");
|
||||
expect(result).not.toContain("[POS:5] \\");
|
||||
expect(result).not.toContain("[POS:9] \\");
|
||||
expect(result).not.toContain("[POS:11] \\");
|
||||
});
|
||||
|
||||
test("complex multi-file, multi-hunk diff", () => {
|
||||
const diff = `diff --git a/src/app.js b/src/app.js
|
||||
index abc123..def456 100644
|
||||
--- a/src/app.js
|
||||
+++ b/src/app.js
|
||||
@@ -10,4 +10,5 @@ function example() {
|
||||
console.log("start");
|
||||
const x = 1;
|
||||
- const y = 2;
|
||||
+ const y = 3;
|
||||
+ const z = 4;
|
||||
return x + y;
|
||||
@@ -20,3 +21,4 @@ function another() {
|
||||
let a = 1;
|
||||
let b = 2;
|
||||
+ let c = 3;
|
||||
return a + b;
|
||||
diff --git a/src/util.js b/src/util.js
|
||||
index 111111..222222 100644
|
||||
--- a/src/util.js
|
||||
+++ b/src/util.js
|
||||
@@ -1,2 +1,3 @@
|
||||
+import fs from 'fs';
|
||||
export function util() {
|
||||
return true;`;
|
||||
|
||||
const result = annotateDiff(diff);
|
||||
|
||||
// src/app.js - first hunk
|
||||
expect(result).toContain('[POS:1] console.log("start");');
|
||||
expect(result).toContain("[POS:2] const x = 1;");
|
||||
expect(result).toContain("[POS:3] - const y = 2;");
|
||||
expect(result).toContain("[POS:4] + const y = 3;");
|
||||
expect(result).toContain("[POS:5] + const z = 4;");
|
||||
expect(result).toContain("[POS:6] return x + y;");
|
||||
|
||||
// src/app.js - second hunk (7 = 6 + 1 for between hunks)
|
||||
expect(result).toContain("[POS:8] let a = 1;");
|
||||
expect(result).toContain("[POS:9] let b = 2;");
|
||||
expect(result).toContain("[POS:10] + let c = 3;");
|
||||
expect(result).toContain("[POS:11] return a + b;");
|
||||
|
||||
// src/util.js - new file, positions reset
|
||||
const utilSection = result.split("diff --git a/src/util.js")[1];
|
||||
expect(utilSection).toContain("[POS:1] +import fs from 'fs';");
|
||||
expect(utilSection).toContain("[POS:2] export function util() {");
|
||||
expect(utilSection).toContain("[POS:3] return true;");
|
||||
});
|
||||
});
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
{
|
||||
"name": "@continue/pr-review-scripts",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Scripts for Continue PR Review Action",
|
||||
"scripts": {
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0"
|
||||
},
|
||||
"jest": {
|
||||
"testEnvironment": "node",
|
||||
"testMatch": [
|
||||
"**/*.test.js"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -23,7 +23,7 @@ runs:
|
|||
shell: bash
|
||||
env:
|
||||
# Only move the dangerous check to env to prevent shell injection
|
||||
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-general-review') }}
|
||||
HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-review') }}
|
||||
run: |
|
||||
# Check if this action should run based on event type and user permissions
|
||||
SHOULD_RUN="false"
|
||||
|
|
@ -51,7 +51,7 @@ runs:
|
|||
echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
|
||||
fi
|
||||
else
|
||||
echo "::notice::Skipping review - Comment does not contain @continue-general-review trigger, or is not on a PR"
|
||||
echo "::notice::Skipping review - Comment does not contain @continue-review trigger, or is not on a PR"
|
||||
fi
|
||||
else
|
||||
echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
|
||||
|
|
@ -70,11 +70,97 @@ runs:
|
|||
shell: bash
|
||||
run: npm install -g @continuedev/cli@1.4.30
|
||||
|
||||
- name: Post Initial Comment
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
id: initial-comment
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const marker = '<!-- continue-agent-review -->';
|
||||
|
||||
// Get PR number based on event type
|
||||
let prNumber;
|
||||
if (context.eventName === 'pull_request') {
|
||||
prNumber = context.payload.pull_request.number;
|
||||
} else {
|
||||
// For issue_comment event
|
||||
prNumber = context.payload.issue.number;
|
||||
}
|
||||
|
||||
// Check for existing comment
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
per_page: 100
|
||||
});
|
||||
|
||||
// Find existing Continue review comment
|
||||
const existingComment = comments
|
||||
.filter(c => c.body && c.body.includes(marker))
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
|
||||
|
||||
// Get workflow run URL
|
||||
const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
|
||||
|
||||
// Create initial "review in progress" message
|
||||
let initialMessage = `${marker}\n**🔄 Review In Progress**\n\n`;
|
||||
|
||||
if (context.eventName === 'issue_comment') {
|
||||
initialMessage = `${marker}\n**🔄 Review In Progress**\n\n*Triggered by @${context.payload.comment.user.login}'s request*\n\n`;
|
||||
}
|
||||
|
||||
initialMessage += `Continue AI is analyzing the code changes...\n\n`;
|
||||
initialMessage += `📊 **Review Scope:**\n`;
|
||||
initialMessage += `- Repository: ${context.repo.owner}/${context.repo.repo}\n`;
|
||||
initialMessage += `- PR #${prNumber}\n\n`;
|
||||
initialMessage += `⏱️ This typically takes 1-2 minutes.\n\n`;
|
||||
initialMessage += `[View live progress →](${workflowRunUrl})\n\n`;
|
||||
initialMessage += `---\n<!-- ${new Date().toISOString()} | Powered by Continue (https://continue.dev) -->`;
|
||||
|
||||
if (existingComment) {
|
||||
// Check if comment is less than 1 hour old
|
||||
const commentAge = Date.now() - new Date(existingComment.created_at).getTime();
|
||||
const oneHour = 60 * 60 * 1000;
|
||||
|
||||
if (commentAge < oneHour) {
|
||||
// Update existing comment if less than 1 hour old
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existingComment.id,
|
||||
body: initialMessage
|
||||
});
|
||||
console.log(`Updated existing comment ${existingComment.id} to show review in progress`);
|
||||
core.setOutput('comment_id', existingComment.id);
|
||||
} else {
|
||||
// Create new comment if older than 1 hour (preserve history)
|
||||
const { data: comment } = await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: initialMessage
|
||||
});
|
||||
console.log(`Created new comment ${comment.id} showing review in progress`);
|
||||
core.setOutput('comment_id', comment.id);
|
||||
}
|
||||
} else {
|
||||
// Create new comment
|
||||
const { data: comment } = await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: initialMessage
|
||||
});
|
||||
console.log(`Created new comment ${comment.id} on PR #${prNumber}`);
|
||||
core.setOutput('comment_id', comment.id);
|
||||
}
|
||||
|
||||
- name: Build PR Review Prompt
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Get PR number based on event type
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
|
|
@ -87,60 +173,58 @@ runs:
|
|||
# Get PR diff
|
||||
gh pr diff $PR_NUMBER > pr_diff.txt
|
||||
|
||||
# Get PR details
|
||||
PR_TITLE=$(gh pr view $PR_NUMBER --json title -q .title)
|
||||
PR_AUTHOR=$(gh pr view $PR_NUMBER --json author -q .author.login)
|
||||
PR_BODY=$(gh pr view $PR_NUMBER --json body -q .body)
|
||||
FILES_CHANGED=$(gh pr view $PR_NUMBER --json files -q '.files | length')
|
||||
|
||||
# Create review prompt
|
||||
cat > review_prompt.txt << 'EOF'
|
||||
You are conducting a code review for a pull request. Below is the git diff showing all the changes:
|
||||
cat > review_prompt.txt << EOF
|
||||
You are reviewing a pull request. Please provide helpful, context-aware feedback.
|
||||
|
||||
CONTEXT:
|
||||
- Repository: ${{ github.repository }}
|
||||
- PR #$PR_NUMBER: $PR_TITLE
|
||||
- Files Changed: $FILES_CHANGED
|
||||
- Author: $PR_AUTHOR
|
||||
|
||||
REVIEW APPROACH:
|
||||
1. First, understand what this PR is trying to accomplish
|
||||
2. Check if similar patterns exist elsewhere in the codebase
|
||||
3. Focus on actual issues that affect functionality
|
||||
4. Be constructive and suggest solutions when possible
|
||||
|
||||
FOCUS ON:
|
||||
- Bugs that will cause failures or incorrect behavior
|
||||
- Security vulnerabilities (exposed secrets, injection risks)
|
||||
- Breaking changes that affect other parts of the system
|
||||
- Performance issues with real impact (memory leaks, O(n²) algorithms)
|
||||
- Missing tests for new features or bug fixes
|
||||
- Missing documentation for APIs or complex logic
|
||||
|
||||
SKIP COMMENTING ON:
|
||||
- Style and formatting (handled by linters)
|
||||
- Alternative approaches unless current is broken
|
||||
- Minor naming unless genuinely confusing
|
||||
- Trivial documentation for self-explanatory code
|
||||
|
||||
Be specific with line numbers and explain why something is an issue.
|
||||
|
||||
PR Description: ${PR_BODY:-No description provided}
|
||||
|
||||
Code Changes:
|
||||
EOF
|
||||
|
||||
echo "--- PR DIFF START ---" >> review_prompt.txt
|
||||
# Add the diff
|
||||
cat pr_diff.txt >> review_prompt.txt
|
||||
echo "--- PR DIFF END ---" >> review_prompt.txt
|
||||
|
||||
|
||||
cat >> review_prompt.txt << 'EOF'
|
||||
|
||||
Please analyze these changes and provide a comprehensive code review. Consider:
|
||||
|
||||
1. **Code Quality**: Are there any bugs, performance issues, or code smells?
|
||||
2. **Best Practices**: Does the code follow established patterns and conventions?
|
||||
3. **Security**: Are there any potential security vulnerabilities?
|
||||
4. **Testing**: Are appropriate tests included or updated?
|
||||
5. **Documentation**: Is documentation adequate for the changes?
|
||||
6. **Architecture**: Do the changes fit well with the existing codebase structure?
|
||||
|
||||
You can use the available tools to explore the codebase and understand context better.
|
||||
|
||||
Format your response as a markdown code review with the following structure:
|
||||
|
||||
## Code Review Summary
|
||||
|
||||
### ✅ Strengths
|
||||
- **[Aspect]**: [Description of what was done well]
|
||||
|
||||
### ⚠️ Issues Found
|
||||
|
||||
Only include the severity subheaders below if you actually found issues at that level:
|
||||
|
||||
#### Critical
|
||||
- **[Issue Title]**: [Description of critical issues that must be fixed before merging]
|
||||
|
||||
#### High
|
||||
- **[Issue Title]**: [Description of high-priority issues that should be fixed]
|
||||
|
||||
#### Medium
|
||||
- **[Issue Title]**: [Description of issues that should be addressed]
|
||||
|
||||
#### Low
|
||||
- **[Issue Title]**: [Description of minor issues or nice-to-have improvements]
|
||||
|
||||
|
||||
### 💡 Suggestions
|
||||
- **[Suggestion Title]**: [Description of improvement recommendations]
|
||||
|
||||
### 🚀 Overall Assessment
|
||||
[Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT]
|
||||
|
||||
Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production.
|
||||
Your Review:
|
||||
Please provide constructive feedback on the code changes.
|
||||
Focus on issues that matter for functionality, security, and maintainability.
|
||||
If the code looks good overall, acknowledge that while noting any minor suggestions.
|
||||
EOF
|
||||
|
||||
- name: Run Continue CLI Review
|
||||
|
|
@ -150,10 +234,12 @@ runs:
|
|||
CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
|
||||
CONTINUE_ORG: ${{ inputs.continue-org }}
|
||||
CONTINUE_CONFIG: ${{ inputs.continue-config }}
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
echo "Running Continue CLI with prompt:"
|
||||
echo "=================================="
|
||||
cat review_prompt.txt
|
||||
head -n 100 review_prompt.txt
|
||||
echo "... [truncated] ..."
|
||||
echo "=================================="
|
||||
echo ""
|
||||
|
||||
|
|
@ -189,7 +275,7 @@ runs:
|
|||
# Test Continue CLI availability
|
||||
if [ "$SKIP_CLI" != "true" ]; then
|
||||
echo "Testing Continue CLI..."
|
||||
if ! cn --version; then
|
||||
if ! which cn > /dev/null 2>&1; then
|
||||
echo "Warning: Continue CLI not found or not working"
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
|
@ -202,7 +288,8 @@ runs:
|
|||
EOF
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "Continue CLI version: $(cn --version)"
|
||||
echo "Continue CLI found at: $(which cn)"
|
||||
echo "Continue CLI version: $(cn --version 2>/dev/null || echo 'version check failed')"
|
||||
fi
|
||||
fi
|
||||
|
||||
|
|
@ -210,30 +297,78 @@ runs:
|
|||
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"
|
||||
# Write prompt to temp file for headless mode
|
||||
PROMPT_FILE="/tmp/continue-review-$RANDOM.txt"
|
||||
cp review_prompt.txt "$PROMPT_FILE"
|
||||
echo "Prompt file: $PROMPT_FILE"
|
||||
echo "Prompt length: $(wc -c < "$PROMPT_FILE") characters"
|
||||
|
||||
# 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
|
||||
# Use timeout to prevent hanging (360 seconds = 6 minutes)
|
||||
echo "Executing command: cn --config $CONTINUE_ORG/$CONTINUE_CONFIG -p @$PROMPT_FILE --allow Bash"
|
||||
|
||||
# Create fallback review
|
||||
cat > code_review.md << 'EOF'
|
||||
if timeout 360 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review_raw.md 2>cli_error.log; then
|
||||
echo "Continue CLI completed successfully"
|
||||
echo "Raw output length: $(wc -c < code_review_raw.md) characters"
|
||||
|
||||
# Clean up ANSI codes if any
|
||||
sed 's/\x1b\[[0-9;]*m//g' code_review_raw.md > code_review.md
|
||||
|
||||
echo "Cleaned output length: $(wc -c < code_review.md) characters"
|
||||
echo "First 500 chars of output:"
|
||||
head -c 500 code_review.md
|
||||
echo ""
|
||||
|
||||
# Check if output is empty
|
||||
if [ ! -s code_review.md ]; then
|
||||
echo "Warning: Continue CLI returned empty output"
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review failed due to service initialization issues. Please check the Continue API key and configuration.
|
||||
⚠️ Continue CLI returned an empty response. Please check the configuration.
|
||||
EOF
|
||||
fi
|
||||
else
|
||||
echo "Error: Continue CLI command failed with exit code $?"
|
||||
echo "CLI error log:"
|
||||
cat cli_error.log
|
||||
|
||||
# Check for specific error patterns
|
||||
if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally.
|
||||
EOF
|
||||
elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub.
|
||||
EOF
|
||||
elif grep -q "api\|auth" cli_error.log 2>/dev/null; then
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY.
|
||||
EOF
|
||||
else
|
||||
cat > code_review.md << 'EOF'
|
||||
## Code Review Summary
|
||||
|
||||
⚠️ AI review failed. 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
|
||||
fi
|
||||
fi
|
||||
|
||||
# Clean up temp file
|
||||
rm -f "$PROMPT_FILE"
|
||||
else
|
||||
echo "Review generated successfully"
|
||||
fi
|
||||
echo "Review generation successfully completed"
|
||||
fi
|
||||
|
||||
- name: Upload Review Results
|
||||
|
|
@ -247,7 +382,7 @@ runs:
|
|||
pr_diff.txt
|
||||
retention-days: 30
|
||||
|
||||
- name: Comment PR with Review
|
||||
- name: Update Comment with Review
|
||||
if: env.SHOULD_RUN == 'true' && always()
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
|
|
@ -256,13 +391,15 @@ runs:
|
|||
|
||||
try {
|
||||
let reviewContent = '';
|
||||
|
||||
|
||||
if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) {
|
||||
reviewContent = fs.readFileSync('code_review.md', 'utf8');
|
||||
} else {
|
||||
reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.';
|
||||
// Build direct link to workflow logs
|
||||
const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
|
||||
reviewContent = `⚠️ AI review completed but no review output was generated.\n\n**Likely cause:** Expired CONTINUE_API_KEY or missing continuedev/review-bot assistant\n\n[📋 View workflow logs](${workflowRunUrl}) for details.`;
|
||||
}
|
||||
|
||||
|
||||
// Get PR number based on event type
|
||||
let prNumber;
|
||||
if (context.eventName === 'pull_request') {
|
||||
|
|
@ -277,17 +414,115 @@ runs:
|
|||
reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`;
|
||||
}
|
||||
|
||||
// Add instructions for re-review
|
||||
reviewContent += '\n\n---\n*💡 To request a new review, comment `@continue-general-review`*';
|
||||
// Add footer with timestamp and branding
|
||||
const timestamp = new Date().toISOString();
|
||||
reviewContent += `\n\n---\n<!-- ${timestamp} | Powered by Continue (https://continue.dev) -->`;
|
||||
|
||||
// Create new comment
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Successfully created new comment on PR #${prNumber}`);
|
||||
// Look for existing review comment to update (sticky comment)
|
||||
const marker = '<!-- continue-agent-review -->';
|
||||
|
||||
// Try to get comment_id from the initial comment step
|
||||
const initialCommentId = '${{ steps.initial-comment.outputs.comment_id }}';
|
||||
|
||||
if (initialCommentId && initialCommentId !== '') {
|
||||
// We have the comment ID from the initial step, use it directly
|
||||
reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`;
|
||||
|
||||
try {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: parseInt(initialCommentId),
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Updated comment ${initialCommentId} with review results`);
|
||||
} catch (updateError) {
|
||||
console.log(`Failed to update comment ${initialCommentId}, will search for it instead:`, updateError.message);
|
||||
|
||||
// Fallback: search for the comment
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
per_page: 100
|
||||
});
|
||||
|
||||
// Find existing Continue review comment
|
||||
const existingComment = comments
|
||||
.filter(c => c.body && c.body.includes(marker))
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
|
||||
|
||||
if (existingComment) {
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existingComment.id,
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Updated existing comment ${existingComment.id} via search`);
|
||||
} else {
|
||||
// Create new comment as last resort
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Created new comment on PR #${prNumber} as fallback`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// No initial comment ID, search for existing comment
|
||||
const { data: comments } = await github.rest.issues.listComments({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: prNumber,
|
||||
per_page: 100
|
||||
});
|
||||
|
||||
// Find existing Continue review comment
|
||||
const existingComment = comments
|
||||
.filter(c => c.body && c.body.includes(marker))
|
||||
.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
|
||||
|
||||
// Add marker and review status
|
||||
reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`;
|
||||
|
||||
if (existingComment) {
|
||||
// Check if comment is less than 1 hour old
|
||||
const commentAge = Date.now() - new Date(existingComment.created_at).getTime();
|
||||
const oneHour = 60 * 60 * 1000;
|
||||
|
||||
if (commentAge < oneHour) {
|
||||
// Update existing comment if less than 1 hour old
|
||||
await github.rest.issues.updateComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
comment_id: existingComment.id,
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Updated existing comment ${existingComment.id} (${Math.round(commentAge / 1000 / 60)} minutes old)`);
|
||||
} else {
|
||||
// Create new comment if older than 1 hour (preserve history)
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Created new comment (existing comment was ${Math.round(commentAge / 1000 / 60)} minutes old)`);
|
||||
}
|
||||
} else {
|
||||
// Create new comment
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: reviewContent
|
||||
});
|
||||
console.log(`Created new comment on PR #${prNumber}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Failed to post comment:', error.message);
|
||||
console.log('Error details:', error);
|
||||
|
|
|
|||
7
binary/package-lock.json
generated
|
|
@ -48,6 +48,7 @@
|
|||
"version": "1.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.62.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
|
|
@ -6674,9 +6675,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
|
||||
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
|
||||
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import path from "path";
|
|||
import {
|
||||
ConfigResult,
|
||||
ConfigValidationError,
|
||||
mergeConfigYamlRequestOptions,
|
||||
ModelRole,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as JSONC from "comment-json";
|
||||
|
|
@ -25,6 +26,7 @@ import {
|
|||
IdeType,
|
||||
ILLM,
|
||||
ILLMLogger,
|
||||
InternalMcpOptions,
|
||||
LLMOptions,
|
||||
ModelDescription,
|
||||
RerankerDescription,
|
||||
|
|
@ -57,8 +59,9 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
|
||||
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
|
||||
import { PolicySingleton } from "../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
|
||||
|
|
@ -550,17 +553,27 @@ async function intermediateToFinalConfig({
|
|||
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,
|
||||
requestOptions: config.requestOptions,
|
||||
}),
|
||||
const mcpOptions: InternalMcpOptions[] = (
|
||||
config.experimental?.modelContextProtocolServers ?? []
|
||||
).map((server, index) => ({
|
||||
id: `continue-mcp-server-${index + 1}`,
|
||||
name: `MCP Server`,
|
||||
requestOptions: mergeConfigYamlRequestOptions(
|
||||
server.transport.type !== "stdio"
|
||||
? server.transport.requestOptions
|
||||
: undefined,
|
||||
config.requestOptions,
|
||||
),
|
||||
false,
|
||||
...server.transport,
|
||||
}));
|
||||
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
|
||||
ide,
|
||||
true,
|
||||
config.requestOptions,
|
||||
);
|
||||
errors.push(...jsonMcpErrors);
|
||||
mcpOptions.push(...mcpServers);
|
||||
mcpManager.setConnections(mcpOptions, false);
|
||||
}
|
||||
|
||||
// Handle experimental modelRole config values for apply and edit
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { BLOCK_TYPES } from "@continuedev/config-yaml";
|
||||
import ignore from "ignore";
|
||||
import * as URI from "uri-js";
|
||||
import { IDE } from "..";
|
||||
|
|
@ -6,12 +7,32 @@ import {
|
|||
DEFAULT_IGNORE_FILETYPES,
|
||||
} from "../indexing/ignore";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { RULES_MARKDOWN_FILENAME } from "../llm/rules/constants";
|
||||
import { getGlobalFolderWithName } from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
import { getUriPathBasename, joinPathsToUri } from "../util/uri";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./getWorkspaceContinueRuleDotFiles";
|
||||
export function isContinueConfigRelatedUri(uri: string): boolean {
|
||||
return (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith("AGENTS.md") ||
|
||||
uri.endsWith("AGENT.md") ||
|
||||
uri.endsWith("CLAUDE.md") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") &&
|
||||
(uri.endsWith(".yaml") ||
|
||||
uri.endsWith(".yml") ||
|
||||
uri.endsWith(".json"))) ||
|
||||
[...BLOCK_TYPES, "agents", "assistants"].some((blockType) =>
|
||||
uri.includes(`.continue/${blockType}`),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export function isLocalDefinitionFile(uri: string): boolean {
|
||||
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
|
||||
export function isContinueAgentConfigFile(uri: string): boolean {
|
||||
const isYaml = uri.endsWith(".yaml") || uri.endsWith(".yml");
|
||||
if (!isYaml) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
@ -22,6 +43,10 @@ export function isLocalDefinitionFile(uri: string): boolean {
|
|||
);
|
||||
}
|
||||
|
||||
export function isColocatedRulesFile(uri: string): boolean {
|
||||
return getUriPathBasename(uri) === RULES_MARKDOWN_FILENAME;
|
||||
}
|
||||
|
||||
async function getDefinitionFilesInDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,15 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
function createRelativeRuleFilePathParts(ruleName: string): string[] {
|
||||
const safeRuleName = sanitizeRuleName(ruleName);
|
||||
return [".continue", "rules", `${safeRuleName}.${RULE_FILE_EXTENSION}`];
|
||||
}
|
||||
|
||||
export function createRelativeRuleFilePath(ruleName: string): string {
|
||||
return createRelativeRuleFilePathParts(ruleName).join("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the file path for a rule in the workspace .continue/rules directory
|
||||
*/
|
||||
|
|
@ -11,11 +20,8 @@ export function createRuleFilePath(
|
|||
workspaceDir: string,
|
||||
ruleName: string,
|
||||
): string {
|
||||
const safeRuleName = sanitizeRuleName(ruleName);
|
||||
return joinPathsToUri(
|
||||
workspaceDir,
|
||||
".continue",
|
||||
"rules",
|
||||
`${safeRuleName}.${RULE_FILE_EXTENSION}`,
|
||||
...createRelativeRuleFilePathParts(ruleName),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import {
|
|||
BlockType,
|
||||
ConfigYaml,
|
||||
createRuleMarkdown,
|
||||
createPromptMarkdown,
|
||||
RULE_FILE_EXTENSION,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
|
|
@ -83,7 +84,10 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
|
|||
}
|
||||
|
||||
function getFileExtension(blockType: BlockType): string {
|
||||
return blockType === "rules" ? RULE_FILE_EXTENSION : "yaml";
|
||||
if (blockType === "rules" || blockType === "prompts") {
|
||||
return "md";
|
||||
}
|
||||
return "yaml";
|
||||
}
|
||||
|
||||
export function getFileContent(blockType: BlockType): string {
|
||||
|
|
@ -91,6 +95,15 @@ export function getFileContent(blockType: BlockType): string {
|
|||
return createRuleMarkdown("New Rule", "Your rule content", {
|
||||
description: "A description of your rule",
|
||||
});
|
||||
} else if (blockType === "prompts") {
|
||||
return createPromptMarkdown(
|
||||
"New prompt",
|
||||
"Please write a thorough suite of unit tests for this code, making sure to cover all relevant edge cases",
|
||||
{
|
||||
description: "New prompt",
|
||||
invokable: true,
|
||||
},
|
||||
);
|
||||
} else {
|
||||
return YAML.stringify(getContentsForNewBlock(blockType));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ describe("getFileContent", () => {
|
|||
expect(result).toContain("provider: anthropic");
|
||||
});
|
||||
|
||||
test("generates correct YAML for different block types", () => {
|
||||
test("generates correct content for different block types", () => {
|
||||
const contextResult = getFileContent("context");
|
||||
expect(contextResult).toContain("name: New context");
|
||||
expect(contextResult).toContain("context:");
|
||||
|
|
@ -31,8 +31,10 @@ describe("getFileContent", () => {
|
|||
|
||||
const promptsResult = getFileContent("prompts");
|
||||
expect(promptsResult).toContain("name: New prompt");
|
||||
expect(promptsResult).toContain("prompts:");
|
||||
expect(promptsResult).toContain("description: New prompt");
|
||||
expect(promptsResult).toContain("invokable: true");
|
||||
expect(promptsResult).toContain("thorough suite of unit tests");
|
||||
expect(promptsResult).toContain("---"); // Should be markdown with frontmatter
|
||||
|
||||
const mcpResult = getFileContent("mcpServers");
|
||||
expect(mcpResult).toContain("name: New MCP server");
|
||||
|
|
@ -96,7 +98,7 @@ describe("findAvailableFilename", () => {
|
|||
{ blockType: "context", expected: "/test/new-context.yaml" },
|
||||
{ blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
|
||||
{ blockType: "docs", expected: "/test/new-doc.yaml" },
|
||||
{ blockType: "prompts", expected: "/test/new-prompt.yaml" },
|
||||
{ blockType: "prompts", expected: "/test/new-prompt.md" },
|
||||
{ blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
|
||||
];
|
||||
|
||||
|
|
@ -148,8 +150,8 @@ describe("findAvailableFilename", () => {
|
|||
const existingFiles = new Set(
|
||||
Array.from({ length: 100 }, (_, i) =>
|
||||
i === 0
|
||||
? "/workspace/.continue/prompts/new-prompt.yaml"
|
||||
: `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
|
||||
? "/workspace/.continue/prompts/new-prompt.md"
|
||||
: `/workspace/.continue/prompts/new-prompt-${i}.md`,
|
||||
),
|
||||
);
|
||||
|
||||
|
|
@ -163,6 +165,6 @@ describe("findAvailableFilename", () => {
|
|||
mockFileExists,
|
||||
);
|
||||
|
||||
expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
|
||||
expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.md");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,7 +15,14 @@ import {
|
|||
} from "@continuedev/config-yaml";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import { ContinueConfig, IDE, IdeInfo, IdeSettings, ILLMLogger } from "../..";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeInfo,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
InternalMcpOptions,
|
||||
} from "../..";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
|
|
@ -25,6 +32,7 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
|||
|
||||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { PolicySingleton } from "../../control-plane/PolicySingleton";
|
||||
import { getBaseToolDefinitions } from "../../tools";
|
||||
|
|
@ -34,7 +42,10 @@ import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
|||
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
import { llmsFromModelConfig } from "./models";
|
||||
import { convertYamlRuleToContinueRule } from "./yamlToContinueConfig";
|
||||
import {
|
||||
convertYamlMcpConfigToInternalMcpOptions,
|
||||
convertYamlRuleToContinueRule,
|
||||
} from "./yamlToContinueConfig";
|
||||
|
||||
async function loadConfigYaml(options: {
|
||||
overrideConfigYaml: AssistantUnrolled | undefined;
|
||||
|
|
@ -227,17 +238,19 @@ export async function configYamlToContinueConfig(options: {
|
|||
}));
|
||||
|
||||
config.mcpServers?.forEach((mcpServer) => {
|
||||
const mcpArgVariables =
|
||||
mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
|
||||
if ("args" in mcpServer) {
|
||||
const mcpArgVariables =
|
||||
mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
|
||||
|
||||
if (mcpArgVariables.length === 0) {
|
||||
return;
|
||||
if (mcpArgVariables.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
|
||||
});
|
||||
}
|
||||
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
|
||||
});
|
||||
});
|
||||
|
||||
// Prompt files -
|
||||
|
|
@ -381,25 +394,18 @@ export async function configYamlToContinueConfig(options: {
|
|||
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: [],
|
||||
requestOptions: mergeConfigYamlRequestOptions(
|
||||
server.requestOptions,
|
||||
config.requestOptions,
|
||||
),
|
||||
...(server as any), // TODO: fix the types on mcpServers in config-yaml
|
||||
},
|
||||
timeout: server.connectionTimeout,
|
||||
})),
|
||||
false,
|
||||
{ ide },
|
||||
const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
|
||||
(server) =>
|
||||
convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
|
||||
);
|
||||
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
|
||||
ide,
|
||||
true,
|
||||
config.requestOptions,
|
||||
);
|
||||
localErrors.push(...jsonMcpErrors);
|
||||
mcpOptions.push(...mcpServers);
|
||||
mcpManager.setConnections(mcpOptions, false, { ide });
|
||||
}
|
||||
|
||||
return { config: continueConfig, errors: localErrors };
|
||||
|
|
|
|||
|
|
@ -1,5 +1,16 @@
|
|||
import { MCPServer, Rule } from "@continuedev/config-yaml";
|
||||
import { ExperimentalMCPOptions, RuleWithSource } from "../..";
|
||||
import {
|
||||
MCPServer,
|
||||
mergeConfigYamlRequestOptions,
|
||||
RequestOptions,
|
||||
Rule,
|
||||
} from "@continuedev/config-yaml";
|
||||
import {
|
||||
InternalMcpOptions,
|
||||
InternalSseMcpOptions,
|
||||
InternalStdioMcpOptions,
|
||||
InternalStreamableHttpMcpOptions,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
|
||||
export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
||||
if (typeof rule === "string") {
|
||||
|
|
@ -21,17 +32,43 @@ export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
}
|
||||
}
|
||||
|
||||
export function convertYamlMcpToContinueMcp(
|
||||
server: MCPServer,
|
||||
): ExperimentalMCPOptions {
|
||||
return {
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: server.command,
|
||||
args: server.args ?? [],
|
||||
env: server.env,
|
||||
cwd: server.cwd,
|
||||
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
|
||||
timeout: server.connectionTimeout,
|
||||
export function convertYamlMcpConfigToInternalMcpOptions(
|
||||
config: MCPServer,
|
||||
globalRequestOptions?: RequestOptions,
|
||||
): InternalMcpOptions {
|
||||
const { connectionTimeout, faviconUrl, name, sourceFile } = config;
|
||||
const shared = {
|
||||
id: name,
|
||||
name,
|
||||
faviconUrl: faviconUrl,
|
||||
timeout: connectionTimeout,
|
||||
sourceFile,
|
||||
};
|
||||
// Stdio
|
||||
if ("command" in config) {
|
||||
const { args, command, cwd, env, type } = config;
|
||||
const stdioOptions: InternalStdioMcpOptions = {
|
||||
type,
|
||||
command,
|
||||
args,
|
||||
cwd,
|
||||
env,
|
||||
...shared,
|
||||
};
|
||||
return stdioOptions;
|
||||
}
|
||||
// HTTP/SSE
|
||||
const { type, url, requestOptions } = config;
|
||||
const httpSseConfig:
|
||||
| InternalStreamableHttpMcpOptions
|
||||
| InternalSseMcpOptions = {
|
||||
type,
|
||||
url,
|
||||
requestOptions: mergeConfigYamlRequestOptions(
|
||||
requestOptions,
|
||||
globalRequestOptions,
|
||||
),
|
||||
...shared,
|
||||
};
|
||||
return httpSseConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,8 +10,12 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|||
import { Agent as HttpsAgent } from "https";
|
||||
import {
|
||||
IDE,
|
||||
InternalMcpOptions,
|
||||
InternalSseMcpOptions,
|
||||
InternalStdioMcpOptions,
|
||||
InternalStreamableHttpMcpOptions,
|
||||
InternalWebsocketMcpOptions,
|
||||
MCPConnectionStatus,
|
||||
MCPOptions,
|
||||
MCPPrompt,
|
||||
MCPResource,
|
||||
MCPResourceTemplate,
|
||||
|
|
@ -65,7 +69,7 @@ class MCPConnection {
|
|||
};
|
||||
|
||||
constructor(
|
||||
public options: MCPOptions,
|
||||
public options: InternalMcpOptions,
|
||||
public extras?: MCPExtras,
|
||||
) {
|
||||
// Don't construct transport in constructor to avoid blocking
|
||||
|
|
@ -132,20 +136,20 @@ class MCPConnection {
|
|||
this.abortController = new AbortController();
|
||||
|
||||
// currently support oauth for sse transports only
|
||||
if (this.options.transport.type === "sse") {
|
||||
if (!this.options.transport.requestOptions) {
|
||||
this.options.transport.requestOptions = {
|
||||
if (this.options.type === "sse") {
|
||||
if (!this.options.requestOptions) {
|
||||
this.options.requestOptions = {
|
||||
headers: {},
|
||||
};
|
||||
}
|
||||
const accessToken = await getOauthToken(
|
||||
this.options.transport.url,
|
||||
this.options.url,
|
||||
this.extras?.ide!,
|
||||
);
|
||||
if (accessToken) {
|
||||
this.isProtectedResource = true;
|
||||
this.options.transport.requestOptions.headers = {
|
||||
...this.options.transport.requestOptions.headers,
|
||||
this.options.requestOptions.headers = {
|
||||
...this.options.requestOptions.headers,
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
};
|
||||
}
|
||||
|
|
@ -178,22 +182,71 @@ class MCPConnection {
|
|||
});
|
||||
}),
|
||||
(async () => {
|
||||
this.transport = await this.constructTransportAsync(this.options);
|
||||
|
||||
try {
|
||||
await this.client.connect(this.transport);
|
||||
} catch (error) {
|
||||
// Allow the case where for whatever reason is already connected
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.message.startsWith(
|
||||
"StdioClientTransport already started",
|
||||
)
|
||||
) {
|
||||
await this.client.close();
|
||||
await this.client.connect(this.transport);
|
||||
if ("command" in this.options) {
|
||||
// STDIO: no need to check type, just if command is present
|
||||
const transport = await this.constructStdioTransport(
|
||||
this.options,
|
||||
);
|
||||
try {
|
||||
await this.client.connect(transport, {});
|
||||
this.transport = transport;
|
||||
} catch (error) {
|
||||
// Allow the case where for whatever reason is already connected
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.message.startsWith(
|
||||
"StdioClientTransport already started",
|
||||
)
|
||||
) {
|
||||
await this.client.close();
|
||||
await this.client.connect(transport);
|
||||
this.transport = transport;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// SSE/HTTP: if type isn't explicit: try http and fall back to sse
|
||||
if (this.options.type === "sse") {
|
||||
const transport = this.constructSseTransport(this.options);
|
||||
await this.client.connect(transport, {});
|
||||
this.transport = transport;
|
||||
} else if (this.options.type === "streamable-http") {
|
||||
const transport = this.constructHttpTransport(this.options);
|
||||
await this.client.connect(transport, {});
|
||||
this.transport = transport;
|
||||
} else if (this.options.type === "websocket") {
|
||||
const transport = this.constructWebsocketTransport(
|
||||
this.options,
|
||||
);
|
||||
await this.client.connect(transport, {});
|
||||
this.transport = transport;
|
||||
} else if (this.options.type) {
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${this.options.type}`,
|
||||
);
|
||||
} else {
|
||||
throw error;
|
||||
try {
|
||||
const transport = this.constructHttpTransport({
|
||||
...this.options,
|
||||
type: "streamable-http",
|
||||
});
|
||||
await this.client.connect(transport, {});
|
||||
this.transport = transport;
|
||||
} catch (e) {
|
||||
try {
|
||||
const transport = this.constructSseTransport({
|
||||
...this.options,
|
||||
type: "sse",
|
||||
});
|
||||
await this.client.connect(transport, {});
|
||||
this.transport = transport;
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`MCP config with URL and no type specified failed both SSE and HTTP connection: ${e instanceof Error ? e.message : String(e)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -202,7 +255,6 @@ class MCPConnection {
|
|||
// this.client.setNotificationHandler(, notification => {
|
||||
// console.log(notification)
|
||||
// })
|
||||
|
||||
const capabilities = this.client.getServerCapabilities();
|
||||
|
||||
// Resources <—> Context Provider
|
||||
|
|
@ -305,7 +357,7 @@ class MCPConnection {
|
|||
|
||||
// Include stdio output if available for stdio transport
|
||||
if (
|
||||
this.options.transport.type === "stdio" &&
|
||||
this.options.type === "stdio" &&
|
||||
(this.stdioOutput.stdout || this.stdioOutput.stderr)
|
||||
) {
|
||||
errorMessage += "\n\nProcess output:";
|
||||
|
|
@ -356,98 +408,97 @@ class MCPConnection {
|
|||
};
|
||||
}
|
||||
|
||||
private async constructTransportAsync(
|
||||
options: MCPOptions,
|
||||
): Promise<Transport> {
|
||||
switch (options.transport.type) {
|
||||
case "stdio":
|
||||
const env: Record<string, string> = options.transport.env
|
||||
? { ...options.transport.env }
|
||||
: {};
|
||||
private constructWebsocketTransport(
|
||||
options: InternalWebsocketMcpOptions,
|
||||
): WebSocketClientTransport {
|
||||
return new WebSocketClientTransport(new URL(options.url));
|
||||
}
|
||||
|
||||
if (process.env.PATH !== undefined) {
|
||||
// Set the initial PATH from process.env
|
||||
env.PATH = process.env.PATH;
|
||||
private constructSseTransport(
|
||||
options: InternalSseMcpOptions,
|
||||
): SSEClientTransport {
|
||||
const sseAgent =
|
||||
options.requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
// For non-Windows platforms, try to get the PATH from user shell
|
||||
if (process.platform !== "win32") {
|
||||
try {
|
||||
const shellEnvPath = await getEnvPathFromUserShell();
|
||||
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
|
||||
env.PATH = shellEnvPath;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error getting PATH:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the command and args for the current platform
|
||||
const { command, args } = this.resolveCommandForPlatform(
|
||||
options.transport.command,
|
||||
options.transport.args || [],
|
||||
);
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command,
|
||||
args,
|
||||
env,
|
||||
cwd: options.transport.cwd,
|
||||
stderr: "pipe",
|
||||
});
|
||||
|
||||
// Capture stdio output for better error reporting
|
||||
|
||||
transport.stderr?.on("data", (data: Buffer) => {
|
||||
this.stdioOutput.stderr += data.toString();
|
||||
});
|
||||
|
||||
return transport;
|
||||
case "websocket":
|
||||
return new WebSocketClientTransport(new URL(options.transport.url));
|
||||
case "sse":
|
||||
const sseAgent =
|
||||
options.transport.requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
return new SSEClientTransport(new URL(options.transport.url), {
|
||||
eventSourceInit: {
|
||||
fetch: (input, init) =>
|
||||
fetch(input, {
|
||||
...init,
|
||||
headers: {
|
||||
...init?.headers,
|
||||
...(options.transport.requestOptions?.headers as
|
||||
| Record<string, string>
|
||||
| undefined),
|
||||
},
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
}),
|
||||
},
|
||||
requestInit: {
|
||||
headers: options.transport.requestOptions?.headers,
|
||||
return new SSEClientTransport(new URL(options.url), {
|
||||
eventSourceInit: {
|
||||
fetch: (input, init) =>
|
||||
fetch(input, {
|
||||
...init,
|
||||
headers: {
|
||||
...init?.headers,
|
||||
...options.requestOptions?.headers,
|
||||
},
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
},
|
||||
});
|
||||
case "streamable-http":
|
||||
const { url, requestOptions } = options.transport;
|
||||
const streamableAgent =
|
||||
requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
}),
|
||||
},
|
||||
requestInit: {
|
||||
headers: options.requestOptions?.headers,
|
||||
...(sseAgent && { agent: sseAgent }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: {
|
||||
headers: requestOptions?.headers,
|
||||
...(streamableAgent && { agent: streamableAgent }),
|
||||
},
|
||||
});
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
);
|
||||
private constructHttpTransport(
|
||||
options: InternalStreamableHttpMcpOptions,
|
||||
): StreamableHTTPClientTransport {
|
||||
const { url, requestOptions } = options;
|
||||
const streamableAgent =
|
||||
requestOptions?.verifySsl === false
|
||||
? new HttpsAgent({ rejectUnauthorized: false })
|
||||
: undefined;
|
||||
|
||||
return new StreamableHTTPClientTransport(new URL(url), {
|
||||
requestInit: {
|
||||
headers: requestOptions?.headers,
|
||||
...(streamableAgent && { agent: streamableAgent }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async constructStdioTransport(
|
||||
options: InternalStdioMcpOptions,
|
||||
): Promise<StdioClientTransport> {
|
||||
const env: Record<string, string> = options.env ? { ...options.env } : {};
|
||||
|
||||
if (process.env.PATH !== undefined) {
|
||||
// Set the initial PATH from process.env
|
||||
env.PATH = process.env.PATH;
|
||||
|
||||
// For non-Windows platforms, try to get the PATH from user shell
|
||||
if (process.platform !== "win32") {
|
||||
try {
|
||||
const shellEnvPath = await getEnvPathFromUserShell();
|
||||
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
|
||||
env.PATH = shellEnvPath;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Error getting PATH:", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { command, args } = this.resolveCommandForPlatform(
|
||||
options.command,
|
||||
options.args || [],
|
||||
);
|
||||
|
||||
const transport = new StdioClientTransport({
|
||||
command,
|
||||
args,
|
||||
env,
|
||||
cwd: options.cwd,
|
||||
stderr: "pipe",
|
||||
});
|
||||
|
||||
// Capture stdio output for better error reporting
|
||||
transport.stderr?.on("data", (data: Buffer) => {
|
||||
this.stdioOutput.stderr += data.toString();
|
||||
});
|
||||
|
||||
return transport;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
InternalSseMcpOptions,
|
||||
InternalStdioMcpOptions,
|
||||
InternalWebsocketMcpOptions,
|
||||
} from "../..";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
|
||||
// Mock the shell path utility
|
||||
|
|
@ -16,15 +21,13 @@ describe("MCPConnection", () => {
|
|||
|
||||
describe("constructor", () => {
|
||||
it("should create instance with stdio transport", () => {
|
||||
const options = {
|
||||
const options: InternalStdioMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test-cmd",
|
||||
args: ["--test"],
|
||||
env: { TEST: "true" },
|
||||
},
|
||||
type: "stdio",
|
||||
command: "test-cmd",
|
||||
args: ["--test"],
|
||||
env: { TEST: "true" },
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
|
|
@ -33,34 +36,30 @@ describe("MCPConnection", () => {
|
|||
});
|
||||
|
||||
it("should create instance with stdio transport including cwd", () => {
|
||||
const options = {
|
||||
const options: InternalStdioMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test-cmd",
|
||||
args: ["--test"],
|
||||
env: { TEST: "true" },
|
||||
cwd: "/path/to/working/directory",
|
||||
},
|
||||
type: "stdio",
|
||||
command: "test-cmd",
|
||||
args: ["--test"],
|
||||
env: { TEST: "true" },
|
||||
cwd: "/path/to/working/directory",
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
expect(conn).toBeInstanceOf(MCPConnection);
|
||||
expect(conn.status).toBe("not-connected");
|
||||
if (conn.options.transport.type === "stdio") {
|
||||
expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
|
||||
if (conn.options.type === "stdio") {
|
||||
expect(conn.options.cwd).toBe("/path/to/working/directory");
|
||||
}
|
||||
});
|
||||
|
||||
it("should create instance with websocket transport", () => {
|
||||
const options = {
|
||||
const options: InternalWebsocketMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "websocket" as const,
|
||||
url: "ws://test.com",
|
||||
},
|
||||
type: "websocket",
|
||||
url: "ws://test.com",
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
|
|
@ -69,13 +68,11 @@ describe("MCPConnection", () => {
|
|||
});
|
||||
|
||||
it("should create instance with SSE transport", () => {
|
||||
const options = {
|
||||
const options: InternalSseMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "sse" as const,
|
||||
url: "http://test.com/events",
|
||||
},
|
||||
type: "sse",
|
||||
url: "http://test.com/events",
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
|
|
@ -84,17 +81,15 @@ describe("MCPConnection", () => {
|
|||
});
|
||||
|
||||
it("should create instance with SSE transport and custom headers", () => {
|
||||
const options = {
|
||||
const options: InternalSseMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "sse" as const,
|
||||
url: "http://test.com/events",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
Authorization: "Bearer token123",
|
||||
"X-Custom-Header": "custom-value",
|
||||
},
|
||||
type: "sse",
|
||||
url: "http://test.com/events",
|
||||
requestOptions: {
|
||||
headers: {
|
||||
Authorization: "Bearer token123",
|
||||
"X-Custom-Header": "custom-value",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
@ -108,9 +103,8 @@ describe("MCPConnection", () => {
|
|||
const options = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "invalid",
|
||||
} as any,
|
||||
type: "invalid" as any,
|
||||
url: "",
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
|
|
@ -126,14 +120,12 @@ describe("MCPConnection", () => {
|
|||
|
||||
describe("getStatus", () => {
|
||||
it("should return current status", () => {
|
||||
const options = {
|
||||
const options: InternalStdioMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test",
|
||||
args: [],
|
||||
},
|
||||
type: "stdio",
|
||||
command: "test",
|
||||
args: [],
|
||||
};
|
||||
|
||||
const conn = new MCPConnection(options);
|
||||
|
|
@ -154,14 +146,12 @@ describe("MCPConnection", () => {
|
|||
});
|
||||
|
||||
describe("connectClient", () => {
|
||||
const options = {
|
||||
const options: InternalStdioMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "test-cmd",
|
||||
args: [],
|
||||
},
|
||||
type: "stdio",
|
||||
command: "test-cmd",
|
||||
args: [],
|
||||
};
|
||||
|
||||
it("should connect successfully", async () => {
|
||||
|
|
@ -282,17 +272,15 @@ describe("MCPConnection", () => {
|
|||
vi.restoreAllMocks();
|
||||
|
||||
// Use a command that will definitely fail and produce stderr output
|
||||
const failingOptions = {
|
||||
const failingOptions: InternalStdioMcpOptions = {
|
||||
name: "failing-mcp",
|
||||
id: "failing-id",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "node",
|
||||
args: [
|
||||
"-e",
|
||||
"console.error('Custom error message from stderr'); process.exit(1);",
|
||||
],
|
||||
},
|
||||
type: "stdio",
|
||||
command: "node",
|
||||
args: [
|
||||
"-e",
|
||||
"console.error('Custom error message from stderr'); process.exit(1);",
|
||||
],
|
||||
timeout: 5000, // Give enough time for the command to run and fail
|
||||
};
|
||||
|
||||
|
|
@ -315,11 +303,9 @@ describe("MCPConnection", () => {
|
|||
const conn = new MCPConnection({
|
||||
id: "filesystem",
|
||||
name: "Filesystem",
|
||||
transport: {
|
||||
type: "stdio" as const,
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
||||
},
|
||||
type: "stdio",
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
|
||||
});
|
||||
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -1,11 +1,6 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import {
|
||||
MCPOptions,
|
||||
MCPServerStatus,
|
||||
StdioOptions,
|
||||
TransportOptions,
|
||||
} from "../..";
|
||||
import { InternalMcpOptions, MCPServerStatus } from "../..";
|
||||
import MCPConnection, { MCPExtras } from "./MCPConnection";
|
||||
|
||||
export class MCPManagerSingleton {
|
||||
|
|
@ -38,7 +33,7 @@ export class MCPManagerSingleton {
|
|||
return this.disconnectedServers;
|
||||
}
|
||||
|
||||
createConnection(id: string, options: MCPOptions): MCPConnection {
|
||||
createConnection(id: string, options: InternalMcpOptions): MCPConnection {
|
||||
if (this.connections.has(id)) {
|
||||
return this.connections.get(id)!;
|
||||
} else {
|
||||
|
|
@ -77,7 +72,7 @@ export class MCPManagerSingleton {
|
|||
}
|
||||
|
||||
setConnections(
|
||||
servers: MCPOptions[],
|
||||
servers: InternalMcpOptions[],
|
||||
forceRefresh: boolean,
|
||||
extras?: MCPExtras,
|
||||
) {
|
||||
|
|
@ -89,11 +84,7 @@ export class MCPManagerSingleton {
|
|||
!servers.find(
|
||||
// Refresh the connection if TransportOptions changed
|
||||
(s) =>
|
||||
s.id === id &&
|
||||
this.compareTransportOptions(
|
||||
connection.options.transport,
|
||||
s.transport,
|
||||
),
|
||||
s.id === id && this.compareTransportOptions(connection.options, s),
|
||||
)
|
||||
) {
|
||||
refresh = true;
|
||||
|
|
@ -124,33 +115,35 @@ export class MCPManagerSingleton {
|
|||
}
|
||||
|
||||
private compareTransportOptions(
|
||||
a: TransportOptions,
|
||||
b: TransportOptions,
|
||||
a: InternalMcpOptions,
|
||||
b: InternalMcpOptions,
|
||||
): boolean {
|
||||
if (a.type !== b.type) {
|
||||
return false;
|
||||
}
|
||||
if (a.type === "stdio" && b.type === "stdio") {
|
||||
if ("command" in a && "command" in b) {
|
||||
return (
|
||||
a.command === b.command &&
|
||||
JSON.stringify(a.args) === JSON.stringify(b.args) &&
|
||||
this.compareEnv(a, b)
|
||||
this.compareEnv(a.env, b.env)
|
||||
);
|
||||
} else if (a.type !== "stdio" && b.type !== "stdio") {
|
||||
} else if ("url" in a && "url" in b) {
|
||||
return a.url === b.url;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private compareEnv(a: StdioOptions, b: StdioOptions): boolean {
|
||||
const aEnv = a.env ?? {};
|
||||
const bEnv = b.env ?? {};
|
||||
const aKeys = Object.keys(aEnv);
|
||||
const bKeys = Object.keys(bEnv);
|
||||
private compareEnv(
|
||||
aEnv: Record<string, string> | undefined,
|
||||
bEnv: Record<string, string> | undefined,
|
||||
): boolean {
|
||||
const a = aEnv ?? {};
|
||||
const b = bEnv ?? {};
|
||||
const aKeys = Object.keys(a);
|
||||
const bKeys = Object.keys(b);
|
||||
|
||||
return (
|
||||
aKeys.length === bKeys.length &&
|
||||
aKeys.every((key) => aEnv[key] === bEnv[key])
|
||||
aKeys.length === bKeys.length && aKeys.every((key) => a[key] === b[key])
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -204,8 +197,8 @@ export class MCPManagerSingleton {
|
|||
}));
|
||||
}
|
||||
|
||||
setStatus(server: MCPServerStatus, status: MCPServerStatus["status"]) {
|
||||
this.connections.get(server.id)!.status = status;
|
||||
setStatus(serverId: string, status: MCPServerStatus["status"]) {
|
||||
this.connections.get(serverId)!.status = status;
|
||||
}
|
||||
|
||||
async getPrompt(
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { MCPOptions } from "../..";
|
||||
import { InternalMcpOptions } from "../..";
|
||||
import MCPConnection from "./MCPConnection";
|
||||
import { MCPManagerSingleton } from "./MCPManagerSingleton";
|
||||
|
||||
// Create test versions with stubbed behavior
|
||||
class TestMCPConnection extends MCPConnection {
|
||||
constructor(options: MCPOptions) {
|
||||
constructor(options: InternalMcpOptions) {
|
||||
super(options);
|
||||
|
||||
// Override with test implementations
|
||||
|
|
@ -28,14 +28,12 @@ class TestMCPConnection extends MCPConnection {
|
|||
|
||||
describe("MCPManagerSingleton", () => {
|
||||
let manager: MCPManagerSingleton;
|
||||
const testOptions: MCPOptions = {
|
||||
const testOptions: InternalMcpOptions = {
|
||||
name: "test-mcp",
|
||||
id: "test-id",
|
||||
transport: {
|
||||
type: "stdio",
|
||||
command: "test-command",
|
||||
args: [],
|
||||
},
|
||||
type: "stdio",
|
||||
command: "test-command",
|
||||
args: [],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -53,7 +51,7 @@ describe("MCPManagerSingleton", () => {
|
|||
// Override createConnection to use our TestMCPConnection
|
||||
manager.createConnection = function (
|
||||
id: string,
|
||||
options: MCPOptions,
|
||||
options: InternalMcpOptions,
|
||||
): MCPConnection {
|
||||
if (this.connections.has(id)) {
|
||||
return this.connections.get(id)!;
|
||||
|
|
|
|||
|
|
@ -8,22 +8,20 @@ import {
|
|||
OAuthTokens,
|
||||
OAuthTokensSchema,
|
||||
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
||||
import { IDE, MCPServerStatus, SSEOptions } from "../..";
|
||||
import { IDE } from "../..";
|
||||
|
||||
import http from "http";
|
||||
import url from "url";
|
||||
import crypto from "crypto";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
|
||||
|
||||
// Use a Map to support concurrent authentications for different servers
|
||||
const authenticatingContexts = new Map<
|
||||
string,
|
||||
{
|
||||
authenticatingServer: MCPServerStatus;
|
||||
ide: IDE;
|
||||
state?: string;
|
||||
}
|
||||
>();
|
||||
interface MCPOauthContext {
|
||||
serverId: string;
|
||||
ide: IDE;
|
||||
state?: string;
|
||||
}
|
||||
const authenticatingContexts = new Map<string, MCPOauthContext>();
|
||||
|
||||
// Map state parameters to server URLs for OAuth callback matching
|
||||
const stateToServerUrl = new Map<string, string>();
|
||||
|
|
@ -242,32 +240,31 @@ export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
|
|||
* checks if the authentication is already done for the current server
|
||||
* if not, starts the authentication process by opening a webpage url
|
||||
*/
|
||||
export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
|
||||
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
|
||||
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
|
||||
export async function performAuth(serverId: string, url: string, ide: IDE) {
|
||||
const authProvider = new MCPConnectionOauthProvider(url, ide);
|
||||
// Ensure redirect URL is ready before starting auth
|
||||
await authProvider.ensureRedirectUrl();
|
||||
|
||||
// Generate a unique state parameter for this auth flow
|
||||
const state = crypto.randomUUID();
|
||||
const state = uuidv4();
|
||||
|
||||
// Store context for this specific server with state
|
||||
authenticatingContexts.set(mcpServerUrl, {
|
||||
authenticatingServer: mcpServer,
|
||||
authenticatingContexts.set(url, {
|
||||
serverId,
|
||||
ide,
|
||||
state,
|
||||
});
|
||||
|
||||
// Map state to server URL for callback matching
|
||||
stateToServerUrl.set(state, mcpServerUrl);
|
||||
stateToServerUrl.set(state, url);
|
||||
|
||||
try {
|
||||
return await auth(authProvider, {
|
||||
serverUrl: mcpServerUrl,
|
||||
serverUrl: url,
|
||||
});
|
||||
} catch (error) {
|
||||
// Clean up on error
|
||||
authenticatingContexts.delete(mcpServerUrl);
|
||||
authenticatingContexts.delete(url);
|
||||
stateToServerUrl.delete(state);
|
||||
throw error;
|
||||
}
|
||||
|
|
@ -278,9 +275,7 @@ export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
|
|||
*/
|
||||
async function handleMCPOauthCode(authorizationCode: string, state?: string) {
|
||||
let serverUrl: string | undefined;
|
||||
let context:
|
||||
| { authenticatingServer: MCPServerStatus; ide: IDE; state?: string }
|
||||
| undefined;
|
||||
let context: MCPOauthContext | undefined;
|
||||
|
||||
if (state) {
|
||||
// Use state parameter to find the correct server
|
||||
|
|
@ -301,7 +296,7 @@ async function handleMCPOauthCode(authorizationCode: string, state?: string) {
|
|||
return;
|
||||
}
|
||||
|
||||
const { ide, authenticatingServer } = context;
|
||||
const { ide, serverId } = context;
|
||||
|
||||
try {
|
||||
if (!serverUrl) {
|
||||
|
|
@ -331,9 +326,7 @@ async function handleMCPOauthCode(authorizationCode: string, state?: string) {
|
|||
|
||||
if (authStatus === "AUTHORIZED") {
|
||||
const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(
|
||||
authenticatingServer.id,
|
||||
);
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(serverId);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
|
|
@ -350,8 +343,7 @@ async function handleMCPOauthCode(authorizationCode: string, state?: string) {
|
|||
}
|
||||
}
|
||||
|
||||
export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
|
||||
const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
|
||||
const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
|
||||
export function removeMCPAuth(url: string, ide: IDE) {
|
||||
const authProvider = new MCPConnectionOauthProvider(url, ide);
|
||||
authProvider.clear();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,8 @@ vi.mock("./MCPManagerSingleton", () => ({
|
|||
describe("MCPOauth", () => {
|
||||
let globalContextFilePath: string;
|
||||
let mockIde: any;
|
||||
let mockMcpServer: any;
|
||||
let mockMcpServerId: string;
|
||||
let mockMcpServerUrl: string;
|
||||
|
||||
beforeEach(() => {
|
||||
// file is present in the core/test directory
|
||||
|
|
@ -36,13 +37,8 @@ describe("MCPOauth", () => {
|
|||
getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
|
||||
};
|
||||
|
||||
mockMcpServer = {
|
||||
id: "test-server",
|
||||
transport: {
|
||||
type: "sse",
|
||||
url: "https://test-server.com",
|
||||
},
|
||||
};
|
||||
mockMcpServerId = "test-server";
|
||||
mockMcpServerUrl = "https://test-server.com";
|
||||
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
|
@ -107,7 +103,11 @@ describe("MCPOauth", () => {
|
|||
const mockAuth = vi.mocked(auth);
|
||||
mockAuth.mockResolvedValue("AUTHORIZED");
|
||||
|
||||
const result = await performAuth(mockMcpServer, mockIde);
|
||||
const result = await performAuth(
|
||||
mockMcpServerId,
|
||||
mockMcpServerUrl,
|
||||
mockIde,
|
||||
);
|
||||
|
||||
expect(mockAuth).toHaveBeenCalledWith(
|
||||
expect.any(Object), // MCPConnectionOauthProvider instance
|
||||
|
|
@ -142,7 +142,7 @@ describe("MCPOauth", () => {
|
|||
},
|
||||
});
|
||||
|
||||
removeMCPAuth(mockMcpServer, mockIde);
|
||||
removeMCPAuth(mockMcpServerUrl, mockIde);
|
||||
|
||||
const updatedStorage = globalContext.get("mcpOauthStorage");
|
||||
expect(updatedStorage).toEqual({
|
||||
|
|
@ -166,7 +166,7 @@ describe("MCPOauth", () => {
|
|||
},
|
||||
});
|
||||
|
||||
removeMCPAuth(mockMcpServer, mockIde);
|
||||
removeMCPAuth(mockMcpServerUrl, mockIde);
|
||||
|
||||
const updatedStorage = globalContext.get("mcpOauthStorage");
|
||||
expect(updatedStorage).toEqual({
|
||||
|
|
@ -193,7 +193,7 @@ describe("MCPOauth", () => {
|
|||
const mockAuth = vi.mocked(auth);
|
||||
mockAuth.mockResolvedValue("AUTHORIZED");
|
||||
|
||||
await performAuth(mockMcpServer, vscodeIde);
|
||||
await performAuth(mockMcpServerId, mockMcpServerUrl, vscodeIde);
|
||||
|
||||
expect(vscodeIde.getExternalUri).toHaveBeenCalledWith(
|
||||
"http://localhost:3000",
|
||||
|
|
@ -210,7 +210,11 @@ describe("MCPOauth", () => {
|
|||
const mockAuth = vi.mocked(auth);
|
||||
mockAuth.mockResolvedValue("AUTHORIZED");
|
||||
|
||||
await performAuth(mockMcpServer, ideWithoutExternalUri as any);
|
||||
await performAuth(
|
||||
mockMcpServerId,
|
||||
mockMcpServerUrl,
|
||||
ideWithoutExternalUri as any,
|
||||
);
|
||||
|
||||
// Should still work without getExternalUri
|
||||
expect(mockAuth).toHaveBeenCalled();
|
||||
|
|
@ -227,7 +231,7 @@ describe("MCPOauth", () => {
|
|||
mockAuth.mockResolvedValue("AUTHORIZED");
|
||||
|
||||
// Should not throw, should fallback to localhost
|
||||
await performAuth(mockMcpServer, errorIde);
|
||||
await performAuth(mockMcpServerId, mockMcpServerUrl, errorIde);
|
||||
|
||||
expect(mockAuth).toHaveBeenCalled();
|
||||
});
|
||||
|
|
@ -235,41 +239,14 @@ describe("MCPOauth", () => {
|
|||
|
||||
describe("concurrent authentication", () => {
|
||||
test("should handle multiple concurrent auth flows", async () => {
|
||||
const server1 = {
|
||||
id: "server-1",
|
||||
transport: { type: "sse" as const, url: "https://server1.com" },
|
||||
status: "connected" as const,
|
||||
errors: [],
|
||||
infos: [],
|
||||
isProtectedResource: false,
|
||||
prompts: [],
|
||||
tools: [],
|
||||
resources: [],
|
||||
resourceTemplates: [],
|
||||
name: "server-1",
|
||||
};
|
||||
const server2 = {
|
||||
id: "server-2",
|
||||
transport: { type: "sse" as const, url: "https://server2.com" },
|
||||
status: "connected" as const,
|
||||
errors: [],
|
||||
infos: [],
|
||||
isProtectedResource: false,
|
||||
prompts: [],
|
||||
tools: [],
|
||||
resources: [],
|
||||
resourceTemplates: [],
|
||||
name: "server-2",
|
||||
};
|
||||
|
||||
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockAuth = vi.mocked(auth);
|
||||
mockAuth.mockResolvedValue("AUTHORIZED");
|
||||
|
||||
// Start two auth flows concurrently
|
||||
const [result1, result2] = await Promise.all([
|
||||
performAuth(server1, mockIde),
|
||||
performAuth(server2, mockIde),
|
||||
performAuth("server-1-id", "https://server1.com", mockIde),
|
||||
performAuth("server-2-id", "https://server2.com", mockIde),
|
||||
]);
|
||||
|
||||
expect(result1).toBe("AUTHORIZED");
|
||||
|
|
@ -285,15 +262,15 @@ describe("MCPOauth", () => {
|
|||
|
||||
// First successful call to set up the context
|
||||
mockAuth.mockResolvedValueOnce("AUTHORIZED");
|
||||
await performAuth(mockMcpServer, mockIde);
|
||||
await performAuth(mockMcpServerId, mockMcpServerUrl, mockIde);
|
||||
|
||||
// Reset mock for the failure test
|
||||
mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
|
||||
|
||||
// Second call that should fail and clean up
|
||||
await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow(
|
||||
"Auth failed",
|
||||
);
|
||||
await expect(
|
||||
performAuth(mockMcpServerId, mockMcpServerUrl, mockIde),
|
||||
).rejects.toThrow("Auth failed");
|
||||
|
||||
// Verify auth was called twice
|
||||
expect(mockAuth).toHaveBeenCalledTimes(2);
|
||||
|
|
@ -301,30 +278,20 @@ describe("MCPOauth", () => {
|
|||
// The context cleanup happens internally in performAuth's catch block
|
||||
// We can verify it indirectly by checking that a subsequent auth call works
|
||||
mockAuth.mockResolvedValueOnce("AUTHORIZED");
|
||||
const result = await performAuth(mockMcpServer, mockIde);
|
||||
const result = await performAuth(
|
||||
mockMcpServerId,
|
||||
mockMcpServerUrl,
|
||||
mockIde,
|
||||
);
|
||||
expect(result).toBe("AUTHORIZED");
|
||||
});
|
||||
|
||||
test("should handle missing server URL", async () => {
|
||||
const invalidServer = {
|
||||
id: "invalid",
|
||||
transport: { type: "sse" as const, url: "" },
|
||||
status: "connected" as const,
|
||||
errors: [],
|
||||
infos: [],
|
||||
isProtectedResource: false,
|
||||
prompts: [],
|
||||
tools: [],
|
||||
resources: [],
|
||||
resourceTemplates: [],
|
||||
name: "invalid",
|
||||
};
|
||||
|
||||
const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
|
||||
const mockAuth = vi.mocked(auth);
|
||||
mockAuth.mockResolvedValue("AUTHORIZED");
|
||||
|
||||
await performAuth(invalidServer, mockIde);
|
||||
await performAuth("invalid-id", "", mockIde);
|
||||
|
||||
// Should still attempt auth with empty URL
|
||||
expect(mockAuth).toHaveBeenCalled();
|
||||
|
|
|
|||
204
core/context/mcp/json/loadJsonMcpConfigs.ts
Normal file
|
|
@ -0,0 +1,204 @@
|
|||
import {
|
||||
claudeCodeLikeConfigFileSchema,
|
||||
claudeDesktopLikeConfigFileSchema,
|
||||
ConfigValidationError,
|
||||
convertJsonMcpConfigToYamlMcpConfig,
|
||||
McpJsonConfig,
|
||||
mcpServersJsonSchema,
|
||||
RequestOptions,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as JSONC from "comment-json";
|
||||
import ignore from "ignore";
|
||||
import { IDE, InternalMcpOptions } from "../../..";
|
||||
import { convertYamlMcpConfigToInternalMcpOptions } from "../../../config/yaml/yamlToContinueConfig";
|
||||
import {
|
||||
DEFAULT_IGNORE_DIRS,
|
||||
DEFAULT_IGNORE_FILETYPES,
|
||||
} from "../../../indexing/ignore";
|
||||
import { walkDir } from "../../../indexing/walkDir";
|
||||
import { deduplicateArray } from "../../../util";
|
||||
import { getGlobalFolderWithName } from "../../../util/paths";
|
||||
import { localPathToUri } from "../../../util/pathToUri";
|
||||
import { getUriPathBasename, joinPathsToUri } from "../../../util/uri";
|
||||
|
||||
/**
|
||||
* Loads MCP configs from JSON files in ~/.continue/mcpServers and workspace .continue/mcpServers
|
||||
*/
|
||||
export async function loadJsonMcpConfigs(
|
||||
ide: IDE,
|
||||
includeGlobal: boolean,
|
||||
globalRequestOptions: RequestOptions | undefined = undefined,
|
||||
): Promise<{
|
||||
mcpServers: InternalMcpOptions[];
|
||||
errors: ConfigValidationError[];
|
||||
}> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
// Get dirs
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const mcpDirs = workspaceDirs.map((dir) =>
|
||||
joinPathsToUri(dir, ".continue", "mcpServers"),
|
||||
);
|
||||
if (includeGlobal) {
|
||||
mcpDirs.push(localPathToUri(getGlobalFolderWithName("mcpServers")));
|
||||
}
|
||||
|
||||
// Get json files and their contents
|
||||
const overrideDefaultIgnores = ignore()
|
||||
.add(
|
||||
DEFAULT_IGNORE_FILETYPES.filter(
|
||||
(val) => !["config.json", "settings.json"].includes(val),
|
||||
),
|
||||
)
|
||||
.add(DEFAULT_IGNORE_DIRS);
|
||||
|
||||
const jsonFiles: { uri: string; content: string }[] = [];
|
||||
|
||||
await Promise.all(
|
||||
mcpDirs.map(async (dir) => {
|
||||
const exists = await ide.fileExists(dir);
|
||||
if (!exists) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const uris = await walkDir(dir, ide, {
|
||||
overrideDefaultIgnores,
|
||||
source: "get mcp json files",
|
||||
});
|
||||
const jsonUris = uris.filter((uri) => uri.endsWith(".json"));
|
||||
await Promise.all(
|
||||
jsonUris.map(async (uri) => {
|
||||
try {
|
||||
const content = await ide.readFile(uri);
|
||||
jsonFiles.push({ uri, content });
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Failed to read MCP server JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Failed to check for MCP JSON files in ${dir}: ${e instanceof Error ? e.message : String(e)}`,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const validJsonConfigs: {
|
||||
name: string;
|
||||
mcpJson: McpJsonConfig;
|
||||
uri: string;
|
||||
}[] = [];
|
||||
for (const { content, uri } of jsonFiles) {
|
||||
try {
|
||||
const json = JSONC.parse(content);
|
||||
// Try parsing as a file with mcpServers and multiple servers (claude code/desktop-esque format)
|
||||
const claudeCodeFileParsed =
|
||||
claudeCodeLikeConfigFileSchema.safeParse(json);
|
||||
if (claudeCodeFileParsed.success) {
|
||||
if (claudeCodeFileParsed.data.mcpServers) {
|
||||
validJsonConfigs.push(
|
||||
...Object.entries(claudeCodeFileParsed.data.mcpServers).map(
|
||||
([name, mcpJson]) => ({
|
||||
name,
|
||||
mcpJson,
|
||||
uri,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
const projectServers = Object.values(
|
||||
claudeCodeFileParsed.data.projects,
|
||||
).map((v) => v.mcpServers);
|
||||
for (const mcpServers of projectServers) {
|
||||
if (mcpServers) {
|
||||
validJsonConfigs.push(
|
||||
...Object.entries(mcpServers).map(([name, mcpJson]) => ({
|
||||
name,
|
||||
mcpJson,
|
||||
uri,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const claudeDesktopFileParsed =
|
||||
claudeDesktopLikeConfigFileSchema.safeParse(json);
|
||||
if (claudeDesktopFileParsed.success) {
|
||||
validJsonConfigs.push(
|
||||
...Object.entries(claudeDesktopFileParsed.data.mcpServers).map(
|
||||
([name, mcpJson]) => ({
|
||||
name,
|
||||
mcpJson,
|
||||
uri,
|
||||
}),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Try parsing as single JSON file
|
||||
const singleConfigParsed = mcpServersJsonSchema.safeParse(json);
|
||||
if (singleConfigParsed.success) {
|
||||
validJsonConfigs.push({
|
||||
mcpJson: singleConfigParsed.data,
|
||||
name: getUriPathBasename(uri).replace(".json", ""),
|
||||
uri,
|
||||
});
|
||||
} else {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `MCP JSON file at ${uri} doesn't match a supported MCP JSON configuration format`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Error parsing MCP JSON file at ${uri}: ${e instanceof Error ? e.message : String(e)}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// De-duplicate
|
||||
const deduplicatedJsonConfigs = deduplicateArray(
|
||||
validJsonConfigs,
|
||||
(a, b) => a.name === b.name,
|
||||
);
|
||||
|
||||
// Two levels of conversion for now.
|
||||
const yamlConfigs = deduplicatedJsonConfigs.map((c) => {
|
||||
const { warnings, yamlConfig } = convertJsonMcpConfigToYamlMcpConfig(
|
||||
c.name,
|
||||
c.mcpJson,
|
||||
);
|
||||
return {
|
||||
warnings,
|
||||
yamlConfig: {
|
||||
...yamlConfig,
|
||||
sourceFile: c.uri,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const mcpServers = yamlConfigs.map((c) => {
|
||||
errors.push(
|
||||
...c.warnings.map((warning) => ({
|
||||
fatal: false,
|
||||
message: warning,
|
||||
})),
|
||||
);
|
||||
return convertYamlMcpConfigToInternalMcpOptions(
|
||||
c.yamlConfig,
|
||||
globalRequestOptions,
|
||||
);
|
||||
});
|
||||
// Parse and convert files
|
||||
return {
|
||||
mcpServers,
|
||||
errors,
|
||||
};
|
||||
}
|
||||
151
core/core.ts
|
|
@ -8,7 +8,6 @@ import {
|
|||
prevFilepaths,
|
||||
} from "./autocomplete/util/openedFilesLruCache";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
|
||||
import { addModel, deleteModel } from "./config/util";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
|
|
@ -49,11 +48,15 @@ import {
|
|||
type IDE,
|
||||
} from ".";
|
||||
|
||||
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
|
||||
import { createNewAssistantFile } from "./config/createNewAssistantFile";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
isColocatedRulesFile,
|
||||
isContinueAgentConfigFile,
|
||||
isContinueConfigRelatedUri,
|
||||
} from "./config/loadLocalAssistants";
|
||||
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
|
||||
import {
|
||||
setupLocalConfig,
|
||||
|
|
@ -69,7 +72,6 @@ import { streamDiffLines } from "./edit/streamDiffLines";
|
|||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import { LLMLogger } from "./llm/logger";
|
||||
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
|
||||
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
|
||||
|
|
@ -80,17 +82,6 @@ import { OnboardingModes } from "./protocol/core";
|
|||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
import { shareSession } from "./util/historyUtils";
|
||||
import { Logger } from "./util/Logger.js";
|
||||
import { getUriPathBasename } from "./util/uri";
|
||||
|
||||
const hasRulesFiles = (uris: string[]): boolean => {
|
||||
for (const uri of uris) {
|
||||
const filename = getUriPathBasename(uri);
|
||||
if (filename === RULES_MARKDOWN_FILENAME) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export class Core {
|
||||
configHandler: ConfigHandler;
|
||||
|
|
@ -522,15 +513,26 @@ export class Core {
|
|||
});
|
||||
on("mcp/startAuthentication", async (msg) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 5000));
|
||||
MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating");
|
||||
const status = await performAuth(msg.data, this.ide);
|
||||
MCPManagerSingleton.getInstance().setStatus(
|
||||
msg.data.serverId,
|
||||
"authenticating",
|
||||
);
|
||||
const status = await performAuth(
|
||||
msg.data.serverId,
|
||||
msg.data.serverUrl,
|
||||
this.ide,
|
||||
);
|
||||
if (status === "AUTHORIZED") {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(
|
||||
msg.data.serverId,
|
||||
);
|
||||
}
|
||||
});
|
||||
on("mcp/removeAuthentication", async (msg) => {
|
||||
removeMCPAuth(msg.data, this.ide);
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
removeMCPAuth(msg.data.serverUrl, this.ide);
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(
|
||||
msg.data.serverId,
|
||||
);
|
||||
});
|
||||
|
||||
// Context providers
|
||||
|
|
@ -863,40 +865,65 @@ export class Core {
|
|||
};
|
||||
|
||||
on("files/created", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
if (!data?.uris?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasRulesFiles(data.uris)) {
|
||||
const rulesCache = CodebaseRulesCache.getInstance();
|
||||
await Promise.all(
|
||||
data.uris.map((uri) => rulesCache.update(this.ide, uri)),
|
||||
);
|
||||
await this.configHandler.reloadConfig("Rules file created");
|
||||
}
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
let localAssistantCreated = false;
|
||||
for (const uri of data.uris) {
|
||||
if (isLocalDefinitionFile(uri)) {
|
||||
localAssistantCreated = true;
|
||||
}
|
||||
}
|
||||
if (localAssistantCreated) {
|
||||
await this.configHandler.refreshAll("Local assistant file created");
|
||||
}
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
const colocatedRulesUris = data.uris.filter(isColocatedRulesFile);
|
||||
const nonColocatedRuleUris = data.uris.filter(
|
||||
(uri) => !isColocatedRulesFile(uri),
|
||||
);
|
||||
if (colocatedRulesUris) {
|
||||
const rulesCache = CodebaseRulesCache.getInstance();
|
||||
void Promise.all(
|
||||
colocatedRulesUris.map((uri) => rulesCache.update(this.ide, uri)),
|
||||
).then(() => {
|
||||
void this.configHandler.reloadConfig("Codebase rule file created");
|
||||
});
|
||||
}
|
||||
|
||||
// If it's a local agent being created, we want to reload all agent so it shows up in the list
|
||||
if (nonColocatedRuleUris.some(isContinueAgentConfigFile)) {
|
||||
await this.configHandler.refreshAll("Local assistant file created");
|
||||
} else if (nonColocatedRuleUris.some(isContinueConfigRelatedUri)) {
|
||||
await this.configHandler.reloadConfig(
|
||||
".continue config-related file created",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
on("files/deleted", async ({ data }) => {
|
||||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
if (!data?.uris?.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasRulesFiles(data.uris)) {
|
||||
const rulesCache = CodebaseRulesCache.getInstance();
|
||||
data.uris.forEach((uri) => rulesCache.remove(uri));
|
||||
await this.configHandler.reloadConfig("Codebase rule file deleted");
|
||||
}
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
const colocatedRulesUris = data.uris.filter(isColocatedRulesFile);
|
||||
const nonColocatedRuleUris = data.uris.filter(
|
||||
(uri) => !isColocatedRulesFile(uri),
|
||||
);
|
||||
|
||||
if (colocatedRulesUris) {
|
||||
const rulesCache = CodebaseRulesCache.getInstance();
|
||||
void Promise.all(
|
||||
colocatedRulesUris.map((uri) => rulesCache.remove(uri)),
|
||||
).then(() => {
|
||||
void this.configHandler.reloadConfig("Codebase rule file deleted");
|
||||
});
|
||||
}
|
||||
|
||||
// If it's a local agent being deleted, we want to reload all agent so it disappears from the list
|
||||
if (nonColocatedRuleUris.some(isContinueAgentConfigFile)) {
|
||||
await this.configHandler.refreshAll("Local assistant file deleted");
|
||||
} else if (nonColocatedRuleUris.some(isContinueConfigRelatedUri)) {
|
||||
await this.configHandler.reloadConfig(
|
||||
".continue config-related file deleted",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -1225,10 +1252,9 @@ export class Core {
|
|||
const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
|
||||
diffCache.invalidate();
|
||||
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
|
||||
const currentProfileUri =
|
||||
this.configHandler.currentProfile?.profileDescription.uri ?? "";
|
||||
for (const uri of data.uris) {
|
||||
const currentProfileUri =
|
||||
this.configHandler.currentProfile?.profileDescription.uri ?? "";
|
||||
|
||||
if (URI.equal(uri, currentProfileUri)) {
|
||||
// Trigger a toast notification to provide UI feedback that config has been updated
|
||||
const showToast =
|
||||
|
|
@ -1248,24 +1274,7 @@ export class Core {
|
|||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith("AGENTS.md") ||
|
||||
uri.endsWith("AGENT.md") ||
|
||||
uri.endsWith("CLAUDE.md") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") &&
|
||||
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
|
||||
BLOCK_TYPES.some((blockType) =>
|
||||
uri.includes(`.continue/${blockType}`),
|
||||
)
|
||||
) {
|
||||
await this.configHandler.reloadConfig(
|
||||
"Config-related file updated: continuerc, prompt, local block, etc",
|
||||
);
|
||||
} else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
|
||||
if (isColocatedRulesFile(uri)) {
|
||||
try {
|
||||
const codebaseRulesCache = CodebaseRulesCache.getInstance();
|
||||
void codebaseRulesCache.update(this.ide, uri).then(() => {
|
||||
|
|
@ -1274,6 +1283,10 @@ export class Core {
|
|||
} catch (e) {
|
||||
Logger.error(`Failed to update codebase rule: ${e}`);
|
||||
}
|
||||
} else if (isContinueConfigRelatedUri(uri)) {
|
||||
await this.configHandler.reloadConfig(
|
||||
"Local config-related file updated",
|
||||
);
|
||||
} else if (
|
||||
uri.endsWith(".continueignore") ||
|
||||
uri.endsWith(".gitignore")
|
||||
|
|
|
|||
53
core/index.d.ts
vendored
|
|
@ -1246,7 +1246,6 @@ export interface StdioOptions {
|
|||
args: string[];
|
||||
env?: Record<string, string>;
|
||||
cwd?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
}
|
||||
|
||||
export interface WebSocketOptions {
|
||||
|
|
@ -1273,15 +1272,6 @@ export type TransportOptions =
|
|||
| SSEOptions
|
||||
| StreamableHTTPOptions;
|
||||
|
||||
export interface MCPOptions {
|
||||
name: string;
|
||||
id: string;
|
||||
transport: TransportOptions;
|
||||
faviconUrl?: string;
|
||||
timeout?: number;
|
||||
requestOptions?: RequestOptions;
|
||||
}
|
||||
|
||||
export type MCPConnectionStatus =
|
||||
| "connecting"
|
||||
| "connected"
|
||||
|
|
@ -1329,18 +1319,55 @@ export interface MCPTool {
|
|||
};
|
||||
}
|
||||
|
||||
export interface MCPServerStatus extends MCPOptions {
|
||||
type BaseInternalMCPOptions = {
|
||||
id: string;
|
||||
name: string;
|
||||
faviconUrl?: string;
|
||||
timeout?: number;
|
||||
requestOptions?: RequestOptions;
|
||||
sourceFile?: string;
|
||||
};
|
||||
|
||||
export type InternalStdioMcpOptions = BaseInternalMCPOptions & {
|
||||
type?: "stdio";
|
||||
command: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
cwd?: string;
|
||||
};
|
||||
|
||||
export type InternalStreamableHttpMcpOptions = BaseInternalMCPOptions & {
|
||||
type?: "streamable-http";
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type InternalSseMcpOptions = BaseInternalMCPOptions & {
|
||||
type?: "sse";
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type InternalWebsocketMcpOptions = BaseInternalMCPOptions & {
|
||||
type: "websocket"; // websocket requires explicit type
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type InternalMcpOptions =
|
||||
| InternalStdioMcpOptions
|
||||
| InternalStreamableHttpMcpOptions
|
||||
| InternalSseMcpOptions
|
||||
| InternalWebsocketMcpOptions;
|
||||
|
||||
export type MCPServerStatus = InternalMcpOptions & {
|
||||
status: MCPConnectionStatus;
|
||||
errors: string[];
|
||||
infos: string[];
|
||||
isProtectedResource: boolean;
|
||||
|
||||
prompts: MCPPrompt[];
|
||||
tools: MCPTool[];
|
||||
resources: MCPResource[];
|
||||
resourceTemplates: MCPResourceTemplate[];
|
||||
sourceFile?: string;
|
||||
}
|
||||
};
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
codeBlockToolbarPosition?: "top" | "bottom";
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ const DEFAULT_MAX_TOKENS = 4096;
|
|||
const DEFAULT_CONTEXT_LENGTH = 32_768;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
const DEFAULT_PRUNING_LENGTH = 128000;
|
||||
const DEFAULT_REASONING_TOKENS = 2048;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
maxTokens: DEFAULT_MAX_TOKENS,
|
||||
|
|
@ -31,5 +32,6 @@ export {
|
|||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_PRUNING_LENGTH,
|
||||
DEFAULT_REASONING_TOKENS,
|
||||
PROXY_URL,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -65,7 +65,6 @@ import {
|
|||
toCompleteBody,
|
||||
toFimBody,
|
||||
} from "./openaiTypeConverters.js";
|
||||
|
||||
export class LLMError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
|
|
@ -214,7 +213,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.providerName === "continue-proxy"
|
||||
? this.model?.split("/").pop() || this.model
|
||||
: this.model;
|
||||
const llmInfo = findLlmInfo(modelSearchString);
|
||||
const llmInfo = findLlmInfo(modelSearchString, this.underlyingProviderName);
|
||||
|
||||
const templateType =
|
||||
options.template ?? autodetectTemplateType(options.model);
|
||||
|
|
@ -558,12 +557,14 @@ export abstract class BaseLLM implements ILLM {
|
|||
private _formatChatMessage(msg: ChatMessage): string {
|
||||
let contentToShow = renderChatMessage(msg);
|
||||
if (msg.role === "assistant" && msg.toolCalls?.length) {
|
||||
contentToShow += msg.toolCalls
|
||||
?.map(
|
||||
(toolCall) =>
|
||||
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
|
||||
)
|
||||
.join("\n");
|
||||
contentToShow +=
|
||||
"\n" +
|
||||
msg.toolCalls
|
||||
?.map(
|
||||
(toolCall) =>
|
||||
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
|
||||
)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
return `<${msg.role}>\n${contentToShow}\n\n`;
|
||||
|
|
|
|||
|
|
@ -58,6 +58,10 @@ const messagesWithInvalidToolCallArgs: ChatMessage[] = [
|
|||
describe("LLM Pre-fetch", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks();
|
||||
// Mock getAnthropicHeaders to return fake headers
|
||||
vi.mocked(openAiAdapters.getAnthropicHeaders).mockReturnValue({
|
||||
fake: "headers",
|
||||
});
|
||||
// Log to verify the mock is properly set up
|
||||
console.log("Mock setup:", openAiAdapters);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,30 +1,36 @@
|
|||
import {
|
||||
Tool as AnthropicTool,
|
||||
ContentBlockParam,
|
||||
MessageCreateParams,
|
||||
MessageParam,
|
||||
RawContentBlockDeltaEvent,
|
||||
RawContentBlockStartEvent,
|
||||
RawMessageDeltaEvent,
|
||||
RawMessageStartEvent,
|
||||
RawMessageStreamEvent,
|
||||
ToolUseBlock,
|
||||
} from "@anthropic-ai/sdk/resources/messages.mjs";
|
||||
import { streamSse } from "@continuedev/fetch";
|
||||
import {
|
||||
addCacheControlToLastTwoUserMessages,
|
||||
getAnthropicErrorMessage,
|
||||
getAnthropicHeaders,
|
||||
getAnthropicMediaTypeFromDataUrl,
|
||||
} from "@continuedev/openai-adapters";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
Tool,
|
||||
ToolCallDelta,
|
||||
Usage,
|
||||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { DEFAULT_REASONING_TOKENS } from "../constants.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
const errorMessages = {
|
||||
invalid_request_error:
|
||||
"There was an issue with the format or content of your request.",
|
||||
authentication_error: "There's an issue with your API key.",
|
||||
permission_error:
|
||||
"Your API key does not have permission to use the specified resource.",
|
||||
not_found_error: "The requested resource was not found.",
|
||||
request_too_large:
|
||||
"Request exceeds the maximum allowed number of bytes (32 MB limit).",
|
||||
rate_limit_error: "Your account has hit a rate limit.",
|
||||
api_error:
|
||||
"An unexpected error has occurred internal to Anthropic's systems.",
|
||||
overloaded_error:
|
||||
"Anthropic's API is temporarily overloaded. Please check their status page: https://status.anthropic.com/#past-incidents",
|
||||
};
|
||||
|
||||
class Anthropic extends BaseLLM {
|
||||
static providerName = "anthropic";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
|
|
@ -36,8 +42,21 @@ class Anthropic extends BaseLLM {
|
|||
apiBase: "https://api.anthropic.com/v1/",
|
||||
};
|
||||
|
||||
public convertArgs(options: CompletionOptions) {
|
||||
// should be public for use within VertexAI
|
||||
private convertToolToAnthropicTool(tool: Tool): AnthropicTool {
|
||||
return {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
input_schema: (tool.function.parameters as AnthropicTool.InputSchema) ?? {
|
||||
// TODO unsafe tool.function.parameters casting
|
||||
type: "object",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Public for use within VertexAI
|
||||
public convertArgs(
|
||||
options: CompletionOptions,
|
||||
): Omit<MessageCreateParams, "messages"> {
|
||||
const finalOptions = {
|
||||
top_k: options.topK,
|
||||
top_p: options.topP,
|
||||
|
|
@ -46,20 +65,17 @@ class Anthropic extends BaseLLM {
|
|||
model: options.model === "claude-2" ? "claude-2.1" : options.model,
|
||||
stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
|
||||
stream: options.stream ?? true,
|
||||
tools: options.tools?.map((tool) => ({
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
input_schema: tool.function.parameters,
|
||||
})),
|
||||
tools: options.tools?.map(this.convertToolToAnthropicTool),
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled",
|
||||
budget_tokens: options.reasoningBudgetTokens,
|
||||
type: "enabled" as const,
|
||||
budget_tokens:
|
||||
options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS,
|
||||
}
|
||||
: undefined,
|
||||
tool_choice: options.toolChoice
|
||||
? {
|
||||
type: "tool",
|
||||
type: "tool" as const,
|
||||
name: options.toolChoice.function.name,
|
||||
}
|
||||
: undefined,
|
||||
|
|
@ -68,138 +84,146 @@ class Anthropic extends BaseLLM {
|
|||
return finalOptions;
|
||||
}
|
||||
|
||||
private buildTextPart(text: string, addCaching: boolean) {
|
||||
const part: any = {
|
||||
type: "text",
|
||||
text,
|
||||
};
|
||||
if (addCaching) {
|
||||
part.cache_control = { type: "ephemeral" };
|
||||
private convertMessageContentToBlocks(
|
||||
content: MessageContent,
|
||||
): ContentBlockParam[] {
|
||||
if (typeof content === "string") {
|
||||
return [
|
||||
{
|
||||
type: "text",
|
||||
text: content,
|
||||
},
|
||||
];
|
||||
}
|
||||
return part;
|
||||
return content.map((part) => {
|
||||
if (part.type === "text") {
|
||||
return {
|
||||
type: "text",
|
||||
text: part.text,
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: getAnthropicMediaTypeFromDataUrl(part.imageUrl.url),
|
||||
data: part.imageUrl.url.split(",")[1],
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private convertMessage(message: ChatMessage, addCaching: boolean): any {
|
||||
if (message.role === "tool") {
|
||||
private convertToolCallsToBlocks(
|
||||
toolCall: ToolCallDelta,
|
||||
): ToolUseBlock | undefined {
|
||||
const toolCallId = toolCall.id;
|
||||
const toolName = toolCall.function?.name;
|
||||
if (toolCallId && toolName) {
|
||||
return {
|
||||
role: "user",
|
||||
content: [
|
||||
type: "tool_use",
|
||||
id: toolCallId,
|
||||
name: toolName,
|
||||
input: safeParseToolCallArgs(toolCall),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private getContentBlocksFromChatMessage(
|
||||
message: ChatMessage,
|
||||
): ContentBlockParam[] {
|
||||
switch (message.role) {
|
||||
// One tool message = one tool_result block
|
||||
case "tool":
|
||||
return [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: message.toolCallId,
|
||||
content: renderChatMessage(message) || undefined,
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (message.role === "assistant" && message.toolCalls) {
|
||||
const parts: any[] = [];
|
||||
if (message.content) {
|
||||
];
|
||||
case "user":
|
||||
return this.convertMessageContentToBlocks(message.content);
|
||||
case "thinking":
|
||||
if (message.redactedThinking) {
|
||||
return [
|
||||
{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (typeof message.content === "string") {
|
||||
parts.push(this.buildTextPart(message.content, addCaching));
|
||||
} else if (message.content.length > 0) {
|
||||
const textContent = message.content.filter((p) => p.type === "text");
|
||||
const textParts = textContent.map((part, idx) => {
|
||||
const cache = idx === textContent.length - 1 && addCaching;
|
||||
return this.buildTextPart(part.text, cache);
|
||||
});
|
||||
parts.push(...textParts);
|
||||
return [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature ?? "", // TODO - unsafe signature
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
parts.push(
|
||||
...message.toolCalls.map((toolCall) => ({
|
||||
type: "tool_use",
|
||||
id: toolCall.id,
|
||||
name: toolCall.function?.name,
|
||||
input: safeParseToolCallArgs(toolCall),
|
||||
})),
|
||||
);
|
||||
return {
|
||||
role: "assistant",
|
||||
content: parts,
|
||||
};
|
||||
} else if (message.role === "thinking" && !message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature,
|
||||
},
|
||||
],
|
||||
};
|
||||
} else if (message.role === "thinking" && message.redactedThinking) {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "redacted_thinking",
|
||||
data: message.redactedThinking,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof message.content === "string") {
|
||||
var chatMessage = {
|
||||
role: message.role,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: message.content,
|
||||
...(addCaching ? { cache_control: { type: "ephemeral" } } : {}),
|
||||
},
|
||||
],
|
||||
};
|
||||
return chatMessage;
|
||||
}
|
||||
|
||||
return {
|
||||
role: message.role,
|
||||
content: message.content.map((part, contentIdx) => {
|
||||
if (part.type === "text") {
|
||||
const newpart = {
|
||||
...part,
|
||||
// If multiple text parts, only add cache_control to the last one
|
||||
...(addCaching && contentIdx === message.content.length - 1
|
||||
? { cache_control: { type: "ephemeral" } }
|
||||
: {}),
|
||||
};
|
||||
return newpart;
|
||||
const textParts = message.content.filter((p) => p.type === "text");
|
||||
return textParts.map((part) => ({
|
||||
type: "thinking",
|
||||
thinking: part.text,
|
||||
signature: message.signature ?? "", // TODO - unsafe signature
|
||||
}));
|
||||
case "assistant":
|
||||
const blocks: ContentBlockParam[] = this.convertMessageContentToBlocks(
|
||||
message.content,
|
||||
);
|
||||
// If any tool calls are present, always put them last
|
||||
// Loses order vs what was originally sent, but they typically come last
|
||||
for (const toolCall of message.toolCalls ?? []) {
|
||||
const block = this.convertToolCallsToBlocks(toolCall);
|
||||
if (block) {
|
||||
blocks.push(block);
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: "image/jpeg",
|
||||
data: part.imageUrl?.url.split(",")[1],
|
||||
},
|
||||
};
|
||||
}),
|
||||
};
|
||||
return blocks;
|
||||
// system, etc.
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public convertMessages(msgs: ChatMessage[]): any[] {
|
||||
// should be public for use within VertexAI
|
||||
const filteredmessages = msgs.filter((m) => m.role !== "system");
|
||||
const lastTwoUserMsgIndices = filteredmessages
|
||||
.map((msg, index) => (msg.role === "user" ? index : -1))
|
||||
.filter((index) => index !== -1)
|
||||
.slice(-2);
|
||||
public convertMessages(
|
||||
msgs: ChatMessage[],
|
||||
cachePrompt: boolean,
|
||||
): MessageParam[] {
|
||||
const nonSystemMessages = msgs.filter((m) => m.role !== "system");
|
||||
|
||||
const messages = filteredmessages.map((message, filteredMsgIdx) => {
|
||||
// Add cache_control parameter to the last two user messages
|
||||
// The second-to-last because it retrieves potentially already cached contents,
|
||||
// The last one because we want it cached for later retrieval.
|
||||
// See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
|
||||
const addCaching =
|
||||
this.cacheBehavior?.cacheConversation &&
|
||||
lastTwoUserMsgIndices.includes(filteredMsgIdx);
|
||||
const convertedMessages: MessageParam[] = [];
|
||||
let currentRole: "user" | "assistant" | undefined = undefined;
|
||||
let currentParts: ContentBlockParam[] = [];
|
||||
|
||||
const chatMessage = this.convertMessage(message, !!addCaching);
|
||||
return chatMessage;
|
||||
});
|
||||
return messages;
|
||||
const flushCurrentMessage = () => {
|
||||
if (currentRole && currentParts.length > 0) {
|
||||
convertedMessages.push({
|
||||
role: currentRole,
|
||||
content: currentParts,
|
||||
});
|
||||
currentParts = [];
|
||||
}
|
||||
};
|
||||
|
||||
for (const message of nonSystemMessages) {
|
||||
const newRole =
|
||||
message.role === "user" || message.role === "tool"
|
||||
? "user"
|
||||
: "assistant";
|
||||
if (currentRole !== newRole) {
|
||||
flushCurrentMessage();
|
||||
currentRole = newRole;
|
||||
}
|
||||
currentParts.push(...this.getContentBlocksFromChatMessage(message));
|
||||
}
|
||||
flushCurrentMessage();
|
||||
|
||||
if (cachePrompt) {
|
||||
addCacheControlToLastTwoUserMessages(convertedMessages);
|
||||
}
|
||||
|
||||
return convertedMessages;
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
|
|
@ -224,12 +248,7 @@ class Anthropic extends BaseLLM {
|
|||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
if (json.type === "error") {
|
||||
if (json.error?.type in errorMessages) {
|
||||
throw new Error(
|
||||
errorMessages[json.error.type as keyof typeof errorMessages],
|
||||
);
|
||||
}
|
||||
throw new Error(json.message);
|
||||
throw new Error(getAnthropicErrorMessage(json));
|
||||
}
|
||||
throw new Error(
|
||||
`Anthropic API sent back ${response.status}: ${JSON.stringify(json)}`,
|
||||
|
|
@ -237,17 +256,17 @@ class Anthropic extends BaseLLM {
|
|||
}
|
||||
|
||||
if (stream === false) {
|
||||
const data = await response.json();
|
||||
const cost = data.usage
|
||||
const json = await response.json();
|
||||
const cost = json.usage
|
||||
? {
|
||||
inputTokens: data.usage.input_tokens,
|
||||
outputTokens: data.usage.output_tokens,
|
||||
totalTokens: data.usage.input_tokens + data.usage.output_tokens,
|
||||
inputTokens: json.usage.input_tokens,
|
||||
outputTokens: json.usage.output_tokens,
|
||||
totalTokens: json.usage.input_tokens + json.usage.output_tokens,
|
||||
}
|
||||
: {};
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: data.content[0].text,
|
||||
content: json.content[0].text,
|
||||
...(Object.keys(cost).length > 0 ? { cost } : {}),
|
||||
};
|
||||
return;
|
||||
|
|
@ -264,51 +283,59 @@ class Anthropic extends BaseLLM {
|
|||
},
|
||||
};
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
for await (const event of streamSse(response)) {
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#event-types
|
||||
switch (value.type) {
|
||||
const rawEvent = event as RawMessageStreamEvent;
|
||||
switch (event.type) {
|
||||
case "message_start":
|
||||
// Capture initial usage information
|
||||
usage.promptTokens = value.message.usage.input_tokens;
|
||||
const startEvent = rawEvent as RawMessageStartEvent;
|
||||
usage.promptTokens = startEvent.message.usage.input_tokens;
|
||||
usage.promptTokensDetails!.cachedTokens =
|
||||
value.message.usage.cache_read_input_tokens;
|
||||
startEvent.message.usage.cache_read_input_tokens ?? undefined;
|
||||
usage.promptTokensDetails!.cacheWriteTokens =
|
||||
value.message.usage.cache_creation_input_tokens;
|
||||
startEvent.message.usage.cache_creation_input_tokens ?? undefined;
|
||||
break;
|
||||
case "message_delta":
|
||||
// Update usage information during streaming
|
||||
if (value.usage) {
|
||||
usage.completionTokens = value.usage.output_tokens;
|
||||
const deltaEvent = rawEvent as RawMessageDeltaEvent;
|
||||
if (deltaEvent.usage) {
|
||||
usage.completionTokens = deltaEvent.usage.output_tokens;
|
||||
}
|
||||
break;
|
||||
case "content_block_start":
|
||||
if (value.content_block.type === "tool_use") {
|
||||
lastToolUseId = value.content_block.id;
|
||||
lastToolUseName = value.content_block.name;
|
||||
const blockStartEvent = rawEvent as RawContentBlockStartEvent;
|
||||
if (blockStartEvent.content_block.type === "tool_use") {
|
||||
lastToolUseId = blockStartEvent.content_block.id;
|
||||
lastToolUseName = blockStartEvent.content_block.name;
|
||||
}
|
||||
// handle redacted thinking
|
||||
if (value.content_block.type === "redacted_thinking") {
|
||||
if (blockStartEvent.content_block.type === "redacted_thinking") {
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
redactedThinking: value.content_block.data,
|
||||
redactedThinking: blockStartEvent.content_block.data,
|
||||
};
|
||||
}
|
||||
break;
|
||||
case "content_block_delta":
|
||||
// https://docs.anthropic.com/en/api/messages-streaming#delta-types
|
||||
switch (value.delta.type) {
|
||||
const blockDeltaEvent = rawEvent as RawContentBlockDeltaEvent;
|
||||
switch (blockDeltaEvent.delta.type) {
|
||||
case "text_delta":
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
yield { role: "assistant", content: blockDeltaEvent.delta.text };
|
||||
break;
|
||||
case "thinking_delta":
|
||||
yield { role: "thinking", content: value.delta.thinking };
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: blockDeltaEvent.delta.thinking,
|
||||
};
|
||||
break;
|
||||
case "signature_delta":
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
signature: value.delta.signature,
|
||||
signature: blockDeltaEvent.delta.signature,
|
||||
};
|
||||
break;
|
||||
case "input_json_delta":
|
||||
|
|
@ -324,7 +351,7 @@ class Anthropic extends BaseLLM {
|
|||
type: "function",
|
||||
function: {
|
||||
name: lastToolUseName,
|
||||
arguments: value.delta.partial_json,
|
||||
arguments: blockDeltaEvent.delta.partial_json,
|
||||
},
|
||||
},
|
||||
],
|
||||
|
|
@ -365,32 +392,35 @@ class Anthropic extends BaseLLM {
|
|||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
const shouldCachePrompt = !!(
|
||||
this.cacheBehavior?.cacheConversation ||
|
||||
this.completionOptions.promptCaching
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages, shouldCachePrompt);
|
||||
const headers = getAnthropicHeaders(
|
||||
this.apiKey,
|
||||
shouldCacheSystemMessage || shouldCachePrompt,
|
||||
);
|
||||
|
||||
const body: MessageCreateParams = {
|
||||
...this.convertArgs(options),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
};
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": this.apiKey as string,
|
||||
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
|
||||
? { "anthropic-beta": "prompt-caching-2024-07-31" }
|
||||
: {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this.convertArgs(options),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
|
||||
|
|
|
|||
358
core/llm/llms/CometAPI.ts
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
import { LLMOptions } from "../../index.js";
|
||||
import { allModelProviders } from "@continuedev/llm-info";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
* CometAPI-specific error types for better error handling
|
||||
*/
|
||||
export class CometAPIError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public code?: string,
|
||||
public statusCode?: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "CometAPIError";
|
||||
}
|
||||
}
|
||||
|
||||
export class CometAPIAuthenticationError extends CometAPIError {
|
||||
constructor(message: string = "Invalid CometAPI API key") {
|
||||
super(message, "AUTHENTICATION_ERROR", 401);
|
||||
this.name = "CometAPIAuthenticationError";
|
||||
}
|
||||
}
|
||||
|
||||
export class CometAPIQuotaExceededError extends CometAPIError {
|
||||
constructor(message: string = "CometAPI quota exceeded") {
|
||||
super(message, "QUOTA_EXCEEDED", 429);
|
||||
this.name = "CometAPIQuotaExceededError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CometAPI LLM provider - aggregates multiple mainstream models
|
||||
* from various providers (GPT, Claude, Gemini, Grok, DeepSeek, Qwen, etc.)
|
||||
*
|
||||
* Uses OpenAI-compatible API format with bearer token authentication
|
||||
*/
|
||||
class CometAPI extends OpenAI {
|
||||
static providerName = "cometapi";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.cometapi.com/v1/",
|
||||
model: "gpt-4o-mini", // Default to a commonly available model
|
||||
};
|
||||
|
||||
constructor(options: LLMOptions) {
|
||||
// Validate required configuration before calling super
|
||||
CometAPI.validateConfig(options);
|
||||
super(options);
|
||||
|
||||
// Align contextLength with llm-info for cometapi specifically (non-breaking for others)
|
||||
try {
|
||||
const cometProvider = allModelProviders.find((p) => p.id === "cometapi");
|
||||
const info = cometProvider?.models.find((m) =>
|
||||
m.regex ? m.regex.test(this.model) : m.model === this.model,
|
||||
);
|
||||
if (info?.contextLength) {
|
||||
// Always prefer cometapi-specific llm-info over generic provider matches
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore - accessing protected for targeted fix
|
||||
this._contextLength = info.contextLength;
|
||||
}
|
||||
} catch {
|
||||
// no-op: do not fail construction on metadata issues
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate CometAPI configuration
|
||||
*/
|
||||
private static validateConfig(options: LLMOptions): void {
|
||||
// Allow constructing without API key (tests that only instantiate should pass).
|
||||
// Enforce credentials at request time instead.
|
||||
if (!options.apiKey) {
|
||||
if (typeof process !== "undefined" && process.env?.NODE_ENV !== "test") {
|
||||
console.warn(
|
||||
"CometAPI: No API key provided. Requests will fail until an API key is configured. Get one at https://api.cometapi.com/console/token",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (options.apiBase && !CometAPI.isValidApiBase(options.apiBase)) {
|
||||
throw new CometAPIError(
|
||||
`Invalid CometAPI base URL: ${options.apiBase}. Expected https://api.cometapi.com/v1/ or compatible endpoint`,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
options.model &&
|
||||
!CometAPI.isValidModelFormat(options.model) &&
|
||||
typeof process !== "undefined" &&
|
||||
process.env?.NODE_ENV !== "test"
|
||||
) {
|
||||
console.warn(
|
||||
`CometAPI: Model "${options.model}" may not be supported. Check CometAPI documentation for available models.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate API base URL format
|
||||
*/
|
||||
private static isValidApiBase(apiBase: string): boolean {
|
||||
try {
|
||||
const url = new URL(apiBase);
|
||||
return (
|
||||
url.protocol === "https:" &&
|
||||
(url.hostname === "api.cometapi.com" ||
|
||||
url.hostname.endsWith(".cometapi.com") ||
|
||||
apiBase.includes("v1")) // Allow custom compatible endpoints
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic model format validation
|
||||
*/
|
||||
private static isValidModelFormat(model: string): boolean {
|
||||
// Allow common model patterns
|
||||
const validPatterns = [
|
||||
/^gpt-/i,
|
||||
/^claude-/i,
|
||||
/^gemini-/i,
|
||||
/^grok/i,
|
||||
/^deepseek/i,
|
||||
/^qwen/i,
|
||||
/^text-/i,
|
||||
/^chat/i,
|
||||
];
|
||||
|
||||
return validPatterns.some((pattern) => pattern.test(model));
|
||||
}
|
||||
|
||||
/**
|
||||
* Patterns to filter out non-chat models from the model list
|
||||
* Based on CometAPI documentation requirements
|
||||
*/
|
||||
private static IGNORE_PATTERNS = [
|
||||
// Image generation models
|
||||
"dall-e",
|
||||
"dalle",
|
||||
"midjourney",
|
||||
"mj_",
|
||||
"stable-diffusion",
|
||||
"sd-",
|
||||
"flux-",
|
||||
"playground-v",
|
||||
"ideogram",
|
||||
"recraft-",
|
||||
"black-forest-labs",
|
||||
"/recraft-v3",
|
||||
"recraftv3",
|
||||
"stability-ai/",
|
||||
"sdxl",
|
||||
|
||||
// Audio generation models
|
||||
"suno_",
|
||||
"tts",
|
||||
"whisper",
|
||||
|
||||
// Video generation models
|
||||
"runway",
|
||||
"luma_",
|
||||
"luma-",
|
||||
"veo",
|
||||
"kling_",
|
||||
"minimax_video",
|
||||
"hunyuan-t1",
|
||||
|
||||
// Utility models
|
||||
"embedding",
|
||||
"search-gpts",
|
||||
"files_retrieve",
|
||||
"moderation",
|
||||
];
|
||||
|
||||
/**
|
||||
* Recommended chat models from CometAPI documentation
|
||||
*/
|
||||
private static RECOMMENDED_MODELS = [
|
||||
// GPT series
|
||||
"gpt-5-chat-latest",
|
||||
"chatgpt-4o-latest",
|
||||
"gpt-5-mini",
|
||||
"gpt-5-nano",
|
||||
"gpt-5",
|
||||
"gpt-4.1-mini",
|
||||
"gpt-4.1-nano",
|
||||
"gpt-4.1",
|
||||
"gpt-4o-mini",
|
||||
"o4-mini-2025-04-16",
|
||||
"o3-pro-2025-06-10",
|
||||
|
||||
// Claude series
|
||||
"claude-opus-4-1-20250805",
|
||||
"claude-opus-4-1-20250805-thinking",
|
||||
"claude-sonnet-4-20250514",
|
||||
"claude-sonnet-4-20250514-thinking",
|
||||
"claude-3-7-sonnet-latest",
|
||||
"claude-3-5-haiku-latest",
|
||||
|
||||
// Gemini series
|
||||
"gemini-2.5-pro",
|
||||
"gemini-2.5-flash",
|
||||
"gemini-2.5-flash-lite",
|
||||
"gemini-2.0-flash",
|
||||
|
||||
// Grok series
|
||||
"grok-4-0709",
|
||||
"grok-3",
|
||||
"grok-3-mini",
|
||||
"grok-2-image-1212",
|
||||
|
||||
// DeepSeek series
|
||||
"deepseek-v3.1",
|
||||
"deepseek-v3",
|
||||
"deepseek-r1-0528",
|
||||
"deepseek-chat",
|
||||
"deepseek-reasoner",
|
||||
|
||||
// Qwen series
|
||||
"qwen3-30b-a3b",
|
||||
"qwen3-coder-plus-2025-07-22",
|
||||
];
|
||||
|
||||
/**
|
||||
* Filter model list to exclude non-chat models
|
||||
* Uses pattern matching against model names
|
||||
*/
|
||||
protected filterChatModels(models: any[]): any[] {
|
||||
if (!models || !Array.isArray(models)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return models.filter((model) => {
|
||||
const modelId = model.id || model.model || "";
|
||||
const modelName = modelId.toLowerCase();
|
||||
|
||||
// Check if model matches any ignore pattern
|
||||
const shouldIgnore = CometAPI.IGNORE_PATTERNS.some((pattern) =>
|
||||
modelName.includes(pattern.toLowerCase()),
|
||||
);
|
||||
|
||||
return !shouldIgnore;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get recommended models for CometAPI
|
||||
* Returns predefined list since CometAPI model info is limited
|
||||
*/
|
||||
protected getRecommendedModels(): string[] {
|
||||
return [...CometAPI.RECOMMENDED_MODELS];
|
||||
}
|
||||
|
||||
/**
|
||||
* Override listModels method to apply model filtering with enhanced error handling
|
||||
*/
|
||||
async listModels(): Promise<string[]> {
|
||||
try {
|
||||
const allModels = await super.listModels();
|
||||
const filteredModels = this.filterChatModels(
|
||||
allModels.map((id) => ({ id })),
|
||||
);
|
||||
|
||||
// If filtered list is empty or very limited, return recommended models
|
||||
if (filteredModels.length < 5) {
|
||||
console.info(
|
||||
"CometAPI: Limited models available, using recommended set",
|
||||
);
|
||||
return this.getRecommendedModels();
|
||||
}
|
||||
|
||||
return filteredModels.map((model) => model.id);
|
||||
} catch (error: any) {
|
||||
// Enhanced error handling with specific error types
|
||||
const errorMessage = error?.message || "Unknown error";
|
||||
const statusCode = error?.status || error?.statusCode;
|
||||
|
||||
if (statusCode === 401) {
|
||||
throw new CometAPIAuthenticationError(
|
||||
"CometAPI authentication failed. Please check your API key.",
|
||||
);
|
||||
} else if (statusCode === 429) {
|
||||
throw new CometAPIQuotaExceededError(
|
||||
"CometAPI rate limit exceeded. Please try again later.",
|
||||
);
|
||||
} else if (statusCode >= 400 && statusCode < 500) {
|
||||
throw new CometAPIError(
|
||||
`CometAPI client error: ${errorMessage}`,
|
||||
"CLIENT_ERROR",
|
||||
statusCode,
|
||||
);
|
||||
} else if (statusCode >= 500) {
|
||||
console.warn(
|
||||
"CometAPI server error, falling back to recommended models:",
|
||||
errorMessage,
|
||||
);
|
||||
return this.getRecommendedModels();
|
||||
} else {
|
||||
// Network or other errors - fallback gracefully
|
||||
console.warn(
|
||||
"CometAPI: Failed to fetch model list, using recommended models",
|
||||
errorMessage,
|
||||
);
|
||||
return this.getRecommendedModels();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Override chat completion with enhanced error handling
|
||||
*/
|
||||
protected async *_streamChat(
|
||||
messages: any[],
|
||||
signal: AbortSignal,
|
||||
options: any = {},
|
||||
): AsyncGenerator<any> {
|
||||
try {
|
||||
yield* super._streamChat(messages, signal, options);
|
||||
} catch (error: any) {
|
||||
const statusCode = error?.status || error?.statusCode;
|
||||
const errorMessage = error?.message || "Unknown error";
|
||||
|
||||
if (statusCode === 401) {
|
||||
throw new CometAPIAuthenticationError(
|
||||
"CometAPI authentication failed during chat completion",
|
||||
);
|
||||
} else if (statusCode === 429) {
|
||||
throw new CometAPIQuotaExceededError(
|
||||
"CometAPI rate limit exceeded during chat completion",
|
||||
);
|
||||
} else if (
|
||||
errorMessage.includes("model") &&
|
||||
errorMessage.includes("not found")
|
||||
) {
|
||||
throw new CometAPIError(
|
||||
`Model "${this.model}" is not available on CometAPI. Please check available models.`,
|
||||
"MODEL_NOT_FOUND",
|
||||
404,
|
||||
);
|
||||
} else {
|
||||
// Re-throw with more context
|
||||
throw new CometAPIError(
|
||||
`CometAPI chat completion failed: ${errorMessage}`,
|
||||
"COMPLETION_ERROR",
|
||||
statusCode,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default CometAPI;
|
||||
|
|
@ -13,6 +13,7 @@ import LMStudio from "./LMStudio.js";
|
|||
import Cerebras from "./Cerebras.js";
|
||||
import DeepInfra from "./DeepInfra.js";
|
||||
import Nvidia from "./Nvidia.js";
|
||||
import CometAPI from "./CometAPI.js";
|
||||
|
||||
// Base OpenAI tests
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
|
|
@ -292,3 +293,13 @@ createOpenAISubclassTests(Nvidia, {
|
|||
truncate: "END",
|
||||
},
|
||||
});
|
||||
|
||||
createOpenAISubclassTests(CometAPI, {
|
||||
providerName: "cometapi",
|
||||
defaultApiBase: "https://api.cometapi.com/v1/",
|
||||
modelConversions: {
|
||||
"gpt-5-mini": "gpt-5-mini",
|
||||
"claude-4-sonnet": "claude-sonnet-4-20250514",
|
||||
},
|
||||
modelConversionContent: "hello",
|
||||
});
|
||||
|
|
|
|||
|
|
@ -223,6 +223,10 @@ class VertexAI extends BaseLLM {
|
|||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
const shouldCachePrompt = !!(
|
||||
this.cacheBehavior?.cacheConversation ??
|
||||
this.completionOptions.promptCaching
|
||||
);
|
||||
|
||||
// <code>/v1/publishers/anthropic/models/claude-3-5-sonnet-20240620:streamRawPredict
|
||||
|
||||
|
|
@ -234,13 +238,16 @@ class VertexAI extends BaseLLM {
|
|||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
|
||||
...(shouldCacheSystemMessage || shouldCachePrompt
|
||||
? { "anthropic-beta": "prompt-caching-2024-07-31" }
|
||||
: {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this._anthropicConvertArgs(options),
|
||||
messages: this.anthropicInstance.convertMessages(messages),
|
||||
messages: this.anthropicInstance.convertMessages(
|
||||
messages,
|
||||
shouldCachePrompt,
|
||||
),
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import BedrockImport from "./BedrockImport";
|
|||
import Cerebras from "./Cerebras";
|
||||
import Cloudflare from "./Cloudflare";
|
||||
import Cohere from "./Cohere";
|
||||
import CometAPI from "./CometAPI";
|
||||
import DeepInfra from "./DeepInfra";
|
||||
import Deepseek from "./Deepseek";
|
||||
import Docker from "./Docker";
|
||||
|
|
@ -67,6 +68,7 @@ import xAI from "./xAI";
|
|||
export const LLMClasses = [
|
||||
Anthropic,
|
||||
Cohere,
|
||||
CometAPI,
|
||||
FunctionNetwork,
|
||||
Gemini,
|
||||
Llamafile,
|
||||
|
|
|
|||
|
|
@ -7,14 +7,6 @@ class xAI extends OpenAI {
|
|||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.x.ai/v1/",
|
||||
};
|
||||
|
||||
private static MODEL_IDS: { [name: string]: string } = {
|
||||
"grok-beta": "grok-beta", // Future names might not line up
|
||||
};
|
||||
|
||||
protected _convertModelName(model: string) {
|
||||
return xAI.MODEL_IDS[model] || this.model;
|
||||
}
|
||||
}
|
||||
|
||||
export default xAI;
|
||||
|
|
|
|||
|
|
@ -280,6 +280,23 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("xAI", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["xAI"];
|
||||
|
||||
it("should return true for Grok-3 models", () => {
|
||||
expect(supportsFn("grok-3")).toBe(true);
|
||||
expect(supportsFn("grok-3-mini")).toBe(true);
|
||||
expect(supportsFn("grok-3-fast")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for Grok-4 models", () => {
|
||||
expect(supportsFn("grok-4")).toBe(true);
|
||||
expect(supportsFn("grok-4-fast-non-reasoning")).toBe(true);
|
||||
expect(supportsFn("grok-4-fast-reasoning")).toBe(true);
|
||||
expect(supportsFn("Grok-4-Fast")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("novita", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["novita"];
|
||||
|
||||
|
|
|
|||
|
|
@ -110,6 +110,10 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
}
|
||||
return ["claude", "gemini"].some((val) => lowerCaseModel.includes(val));
|
||||
},
|
||||
xAI: (model) => {
|
||||
const lowerCaseModel = model.toLowerCase();
|
||||
return ["grok-3", "grok-4"].some((val) => lowerCaseModel.includes(val));
|
||||
},
|
||||
bedrock: (model) => {
|
||||
if (
|
||||
[
|
||||
|
|
|
|||
|
|
@ -1,49 +1,47 @@
|
|||
import { getSecureID } from "./getSecureID";
|
||||
|
||||
// Mock the crypto.randomUUID function
|
||||
const mockRandomUUID = jest.fn();
|
||||
global.crypto = {
|
||||
...global.crypto,
|
||||
randomUUID: mockRandomUUID,
|
||||
};
|
||||
|
||||
describe("getSecureID", () => {
|
||||
beforeEach(() => {
|
||||
// Reset the static property before each test
|
||||
(getSecureID as any).uuid = undefined;
|
||||
|
||||
// Reset the mock implementation
|
||||
mockRandomUUID.mockReset();
|
||||
// Setup a mock implementation that returns a fixed value for testing
|
||||
mockRandomUUID.mockReturnValue("test-uuid-1234");
|
||||
});
|
||||
|
||||
test("should generate a UUID on first call", () => {
|
||||
const result = getSecureID();
|
||||
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
|
||||
expect(result).toBe("<!-- SID: test-uuid-1234 -->");
|
||||
|
||||
// Should return a properly formatted string with SID comment
|
||||
expect(result).toMatch(
|
||||
/^<!-- SID: [0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12} -->$/,
|
||||
);
|
||||
|
||||
// Should have set the static uuid property
|
||||
expect((getSecureID as any).uuid).toBeDefined();
|
||||
expect(typeof (getSecureID as any).uuid).toBe("string");
|
||||
});
|
||||
|
||||
test("should reuse the same UUID on subsequent calls", () => {
|
||||
const firstResult = getSecureID();
|
||||
const secondResult = getSecureID();
|
||||
|
||||
// The UUID generation should only happen once
|
||||
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Both results should be identical
|
||||
expect(firstResult).toBe(secondResult);
|
||||
expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
|
||||
|
||||
// Should match UUID format
|
||||
expect(firstResult).toMatch(
|
||||
/^<!-- SID: [0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12} -->$/,
|
||||
);
|
||||
});
|
||||
|
||||
test("should maintain the same UUID across different test cases if not reset", () => {
|
||||
// Don't reset the UUID here to test persistence
|
||||
// Set a specific UUID to test persistence
|
||||
(getSecureID as any).uuid = "persistent-uuid";
|
||||
|
||||
const result = getSecureID();
|
||||
|
||||
// No new UUID should be generated
|
||||
expect(mockRandomUUID).not.toHaveBeenCalled();
|
||||
// Should use the pre-existing UUID
|
||||
expect(result).toBe("<!-- SID: persistent-uuid -->");
|
||||
|
||||
// The static property should remain unchanged
|
||||
expect((getSecureID as any).uuid).toBe("persistent-uuid");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
// Utility function to get or generate UUID for LLM prompts
|
||||
export function getSecureID(): string {
|
||||
// Adding a type declaration for the static property
|
||||
if (!(getSecureID as any).uuid) {
|
||||
(getSecureID as any).uuid = crypto.randomUUID();
|
||||
(getSecureID as any).uuid = uuidv4();
|
||||
}
|
||||
return `<!-- SID: ${(getSecureID as any).uuid} -->`;
|
||||
}
|
||||
|
|
|
|||
27
core/package-lock.json
generated
|
|
@ -9,6 +9,7 @@
|
|||
"version": "1.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.62.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
|
|
@ -152,7 +153,7 @@
|
|||
},
|
||||
"../packages/config-yaml": {
|
||||
"name": "@continuedev/config-yaml",
|
||||
"version": "1.17.0",
|
||||
"version": "1.23.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -201,7 +202,7 @@
|
|||
},
|
||||
"../packages/llm-info": {
|
||||
"name": "@continuedev/llm-info",
|
||||
"version": "1.0.9",
|
||||
"version": "1.0.10",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@semantic-release/changelog": "^6.0.3",
|
||||
|
|
@ -218,6 +219,7 @@
|
|||
"version": "1.15.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.62.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
|
||||
"@aws-sdk/credential-providers": "^3.840.0",
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -297,6 +299,15 @@
|
|||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@anthropic-ai/sdk": {
|
||||
"version": "0.62.0",
|
||||
"resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.62.0.tgz",
|
||||
"integrity": "sha512-gT2VFKX0gSp7KJNlav/vzRFjJOPYDZxCJRx7MYUc+fqURc5aS6OI/UJeD2KytJkjsIWv0OOwH1ePc1S5QE2GZw==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"anthropic-ai-sdk": "bin/cli"
|
||||
}
|
||||
},
|
||||
"node_modules/@apache-arrow/ts": {
|
||||
"version": "14.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@apache-arrow/ts/-/ts-14.0.2.tgz",
|
||||
|
|
@ -16353,9 +16364,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/prebuild-install/node_modules/tar-fs": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz",
|
||||
"integrity": "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg==",
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
|
||||
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
|
|
@ -18312,9 +18323,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "3.0.9",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.9.tgz",
|
||||
"integrity": "sha512-XF4w9Xp+ZQgifKakjZYmFdkLoSWd34VGKcsTCwlNWM7QG3ZbaxnTsaBwnjFZqHRf/rROxaR8rXnbtwdvaDI+lA==",
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.1.tgz",
|
||||
"integrity": "sha512-LZA0oaPOc2fVo82Txf3gw+AkEd38szODlptMYejQUhndHMLQ9M059uXR+AfS7DNo0NpINvSqDsvyaCrBVkptWg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pump": "^3.0.0",
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@
|
|||
"vitest": "^3.1.4"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.62.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import { SharedConfigSchema } from "../config/sharedConfig";
|
|||
import { GlobalContextModelSelections } from "../util/GlobalContext";
|
||||
|
||||
import {
|
||||
BaseSessionMetadata,
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
CompiledMessagesResult,
|
||||
|
|
@ -27,7 +28,6 @@ import {
|
|||
FileSymbolMap,
|
||||
IdeSettings,
|
||||
LLMFullCompletionOptions,
|
||||
MCPServerStatus,
|
||||
MessageOption,
|
||||
ModelDescription,
|
||||
PromptLog,
|
||||
|
|
@ -35,7 +35,6 @@ import {
|
|||
RangeInFileWithNextEditInfo,
|
||||
SerializedContinueConfig,
|
||||
Session,
|
||||
BaseSessionMetadata,
|
||||
SiteIndexingConfig,
|
||||
SlashCommandDescWithSource,
|
||||
StreamDiffLinesPayload,
|
||||
|
|
@ -161,9 +160,20 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
description: string | undefined;
|
||||
},
|
||||
];
|
||||
"mcp/startAuthentication": [MCPServerStatus, void];
|
||||
"mcp/removeAuthentication": [MCPServerStatus, void];
|
||||
|
||||
"mcp/startAuthentication": [
|
||||
{
|
||||
serverId: string;
|
||||
serverUrl: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
"mcp/removeAuthentication": [
|
||||
{
|
||||
serverId: string;
|
||||
serverUrl: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
|
||||
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
|
||||
"autocomplete/complete": [AutocompleteInput, string[]];
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { NO_PARALLEL_TOOL_CALLING_INSTRUCTION } from "./editFile";
|
||||
import { singleFindAndReplaceTool } from "./singleFindAndReplace";
|
||||
|
||||
export interface EditOperation {
|
||||
old_string: string;
|
||||
|
|
@ -25,8 +24,7 @@ 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 ${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.
|
||||
description: `Use this tool to make multiple edits to a single file in one operation. It allows you to perform multiple find-and-replace operations efficiently.
|
||||
|
||||
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)
|
||||
|
|
@ -36,6 +34,7 @@ To make multiple edits to a file, provide the following:
|
|||
- replace_all: Replace all occurrences of old_string. This parameter is optional and defaults to false.
|
||||
|
||||
IMPORTANT:
|
||||
- Files may be modified between tool calls by users, linters, etc, so always make all edits in one tool call where possible. For example, do not only edit imports if there are other changes in the file, as unused imports may be removed by a linter between tool calls.
|
||||
- All edits are applied in sequence, in the order they are provided
|
||||
- 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
|
||||
|
|
|
|||
|
|
@ -12,10 +12,8 @@ const createMcpServer = (name: string): MCPServerStatus => ({
|
|||
resourceTemplates: [],
|
||||
status: "connected",
|
||||
id: "",
|
||||
transport: {
|
||||
type: "sse",
|
||||
url: "",
|
||||
},
|
||||
type: "sse",
|
||||
url: "",
|
||||
isProtectedResource: false,
|
||||
});
|
||||
|
||||
|
|
|
|||
134
docs/cli/install.mdx
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
---
|
||||
title: "Install Continue CLI"
|
||||
description: "Get Continue CLI installed and configured for command-line AI coding assistance and automation"
|
||||
sidebarTitle: "Install"
|
||||
---
|
||||
|
||||
<Info>
|
||||
Make sure you have [Node.js 18 or higher
|
||||
installed](https://nodejs.org/en/download/).
|
||||
</Info>
|
||||
|
||||
## Installation
|
||||
|
||||
Install Continue CLI globally using npm:
|
||||
|
||||
```bash
|
||||
npm i -g @continuedev/cli
|
||||
```
|
||||
|
||||
## Two Ways to Use Continue CLI
|
||||
|
||||
<Info>
|
||||
**Quick Overview**: Continue CLI works in two modes - TUI for interactive
|
||||
conversations or headless for automated commands.
|
||||
</Info>
|
||||
|
||||
<Tabs>
|
||||
<Tab title="TUI Mode">
|
||||
**Interactive development sessions**
|
||||
|
||||
Start a conversation with AI in your terminal:
|
||||
|
||||
```bash
|
||||
cn
|
||||
> @src/app.js Generate unit tests for this component
|
||||
```
|
||||
|
||||
Perfect for exploration, debugging, and iterative development.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Headless Mode">
|
||||
**Automation and scripting**
|
||||
|
||||
Single commands that return results:
|
||||
|
||||
```bash
|
||||
cn -p "Generate a commit message for current changes"
|
||||
cn -p "Review the last 5 commits for issues"
|
||||
```
|
||||
|
||||
Perfect for CI/CD, git hooks, and automated workflows.
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Setup
|
||||
|
||||
<Tabs>
|
||||
<Tab title="cn TUI Mode">
|
||||
|
||||
For interactive development and exploration:
|
||||
|
||||
<Steps>
|
||||
<Step title="Login to Continue CLI">
|
||||
```bash
|
||||
cn login
|
||||
```
|
||||
This will open your browser to authenticate with Continue Hub.
|
||||
</Step>
|
||||
|
||||
<Step title="Test TUI Mode">
|
||||
Start an interactive session:
|
||||
```bash
|
||||
cn
|
||||
```
|
||||
|
||||
Try asking a question:
|
||||
|
||||
```
|
||||
> Tell me about the CLI
|
||||
```
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
<Tab title="cn Headless Mode">
|
||||
|
||||
For automation workflows and scripting:
|
||||
|
||||
<Steps>
|
||||
<Step title="Get API Key for Automation">
|
||||
For automation workflows, get an API key:
|
||||
1. Visit [Continue Hub API Keys](https://hub.continue.dev/settings/api-keys)
|
||||
2. Click **"+ New API Key"**
|
||||
3. Copy the API key immediately (you won't see it again!)
|
||||
4. Login using your Continue account
|
||||
</Step>
|
||||
|
||||
<Step title="Add Secrets for Workflows">
|
||||
Store secure credentials for CLI workflows:
|
||||
1. Visit [Continue Hub Secrets](https://hub.continue.dev/settings/secrets)
|
||||
2. Add your API keys and sensitive data
|
||||
3. Reference in configurations with `${{ secrets.SECRET_NAME }}`
|
||||
</Step>
|
||||
|
||||
<Step title="Test Headless Mode">
|
||||
Try headless mode for automation:
|
||||
```bash
|
||||
cn -p "Generate a conventional commit message for the current git changes"
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## What's Next?
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Quick Start Guide" icon="rocket" href="/cli/quick-start">
|
||||
Learn basic usage with practical examples
|
||||
</Card>
|
||||
|
||||
<Card title="Create your first workflow" icon="gear" href="/guides/posthog-github-continuous-ai">
|
||||
Build automated workflows with Continue CLI
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you encounter issues:
|
||||
|
||||
- Ask for help in [our discussions](https://github.com/continuedev/continue/discussions)
|
||||
- Report bugs on [GitHub](https://github.com/continuedev/continue)
|
||||
228
docs/cli/overview.mdx
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
---
|
||||
title: "Continue CLI (cn) Overview"
|
||||
description: "Command-line interface for automated coding tasks, scripting, and headless development workflows with Continue's AI coding capabilities"
|
||||
sidebarTitle: "Overview"
|
||||
---
|
||||
|
||||
<Frame>
|
||||
<img src="/images/cn-demo.gif" />
|
||||
</Frame>
|
||||
|
||||
**Continue enables developers to ship faster with Continuous AI.**
|
||||
|
||||
<Tip>
|
||||
Build features from descriptions. Debug and fix issues. Navigate any codebase.
|
||||
Automate tedious tasks.
|
||||
</Tip>
|
||||
|
||||
## Get started in 30 seconds
|
||||
|
||||
Prerequisites:
|
||||
|
||||
- [Node.js 18 or newer](https://nodejs.org/en/download/)
|
||||
- A [Continue Hub](https://hub.continue.dev) account (recommended) or local configuration
|
||||
|
||||
```bash npm
|
||||
# Install Continue CLI
|
||||
npm install -g @continuedev/cli
|
||||
|
||||
# Navigate to your project
|
||||
|
||||
cd your-awesome-project
|
||||
|
||||
# Start coding with Continue
|
||||
|
||||
cn
|
||||
|
||||
# You'll be prompted to set up on first use
|
||||
|
||||
```
|
||||
|
||||
That's it! You're ready to start automating with Continue CLI.
|
||||
|
||||
[Continue with CLI Quickstart →](/cli/quick-start)
|
||||
|
||||
## Two Ways to Use Continue CLI
|
||||
|
||||
Continue CLI offers two distinct modes designed for different workflows:
|
||||
|
||||
### TUI Mode: Interactive Development
|
||||
|
||||
**Perfect for exploration, debugging, and iterating on AI workflows**
|
||||
|
||||
```bash
|
||||
cn
|
||||
> @src/components/UserProfile.js Review this component for security issues
|
||||
> Generate comprehensive unit tests
|
||||
> Suggest performance improvements
|
||||
```
|
||||
|
||||
- **Interactive conversations** with your codebase
|
||||
- **Iterate and refine** prompts and approaches
|
||||
- **Explore and understand** complex codebases
|
||||
- **Perfect for experimentation** and learning
|
||||
|
||||
### Headless Mode: Production Automation
|
||||
|
||||
**Perfect for CI/CD, automation, and reliable workflows**
|
||||
|
||||
```bash
|
||||
cn -p "Generate a conventional commit message for staged changes"
|
||||
cn -p "Review pull request changes for security vulnerabilities"
|
||||
cn -p "Update documentation based on recent code changes"
|
||||
```
|
||||
|
||||
- **Single-command execution** for automation
|
||||
- **Reliable, repeatable results** for production use
|
||||
- **CI/CD and pipeline integration**
|
||||
- **Git hooks and automated workflows**
|
||||
|
||||
### Development Workflow: TUI → Headless
|
||||
|
||||
<Tip>
|
||||
**Pro Tip**: Start in TUI mode to iterate on your AI agent and prompts. Once
|
||||
you have a workflow that works reliably, deploy it as a Continuous AI
|
||||
automation.
|
||||
</Tip>
|
||||
|
||||
1. **Experiment in TUI mode** to perfect your prompts and agent configuration
|
||||
2. **Test different approaches** interactively until you get consistent results
|
||||
3. **Convert successful workflows** to automated Continuous AI commands
|
||||
4. **Deploy in production** with confidence in your proven approach
|
||||
|
||||
## Why developers love Continue CLI
|
||||
|
||||
- **Works in your terminal**: Not another chat window. Not another IDE. Continue CLI meets you where you already work, with the tools you already love.
|
||||
- **Takes action**: Continue CLI can directly edit files, run commands, and create commits. Need more? Check out our [MCPs](/customize/deep-dives/mcp).
|
||||
- **Automate tasks**: Create issues from PostHog data, automatically assign labels to issues, and more. Do all this in a single command from your developer machines, or automatically in CI.
|
||||
- **Flexible development flow**: Start interactive, then automate proven workflows.
|
||||
|
||||
## Key Capabilities
|
||||
|
||||
### Context Engineering
|
||||
|
||||
- Use `@` to reference files and provide context
|
||||
- Use `/` to run slash commands for specific tasks
|
||||
- Access the same context providers as IDE extensions
|
||||
|
||||
### Tool Integration
|
||||
|
||||
- File editing and creation
|
||||
- Terminal command execution
|
||||
- Codebase understanding and analysis
|
||||
- Git integration
|
||||
- Web search and documentation access
|
||||
|
||||
### Model Flexibility
|
||||
|
||||
- Switch between models with `/model` command
|
||||
- Use any model configured in your `config.yaml`
|
||||
- Access Continue Hub models and configurations
|
||||
|
||||
## Continue Hub Integration
|
||||
|
||||
Continue CLI integrates seamlessly with [Continue Hub](https://hub.continue.dev) for:
|
||||
|
||||
### API Access
|
||||
|
||||
Get an API key for automation workflows:
|
||||
|
||||
1. Visit [Continue Hub API Keys](https://hub.continue.dev/settings/api-keys)
|
||||
2. Create a new API key
|
||||
3. Use with `cn login` or in your automation scripts
|
||||
|
||||
### Secrets Management
|
||||
|
||||
Store secure credentials for CLI workflows:
|
||||
|
||||
1. Visit [Continue Hub Secrets](https://hub.continue.dev/settings/secrets)
|
||||
2. Add your API keys and sensitive data
|
||||
3. Reference in configurations with `${{ secrets.SECRET_NAME }}`
|
||||
|
||||
### Configuration Sync
|
||||
|
||||
- Cloud-managed configurations automatically sync
|
||||
- Share configurations across team members
|
||||
- Version control for your AI workflows
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### TUI Mode Examples
|
||||
|
||||
**Interactive development and exploration:**
|
||||
|
||||
<CodeGroup>
|
||||
```bash Codebase Exploration
|
||||
# Start interactive session
|
||||
cn
|
||||
> @src/components Find all unused React components
|
||||
> /explain How does authentication work in this codebase?
|
||||
> @auth/ What security patterns are used here?
|
||||
```
|
||||
|
||||
```bash Iterative Debugging
|
||||
# Debug issues interactively
|
||||
cn
|
||||
> @tests/auth.test.js This test is failing, help me understand why
|
||||
> @src/auth/middleware.js Let's examine this middleware
|
||||
> /debug What could be causing the timeout error?
|
||||
```
|
||||
|
||||
```bash Workflow Development
|
||||
# Develop and test automation workflows
|
||||
cn
|
||||
> @package.json @CHANGELOG.md Generate a release notes template
|
||||
> # Test and refine the approach
|
||||
> # Once working, convert to: cn -p "Generate release notes"
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
### Headless Mode Examples
|
||||
|
||||
**Production automation and scripting:**
|
||||
|
||||
<CodeGroup>
|
||||
```bash Git Automation
|
||||
# Generate commit messages
|
||||
cn -p "Generate a conventional commit message for the current changes"
|
||||
|
||||
# Code review automation
|
||||
|
||||
cn -p "Review the current git changes for bugs and suggest improvements"
|
||||
|
||||
````
|
||||
|
||||
```bash CI/CD Integration
|
||||
# In your pipeline scripts
|
||||
cn -p "Analyze test failures and suggest fixes"
|
||||
|
||||
# Automated documentation updates
|
||||
cn -p "@README.md Update this documentation based on recent changes"
|
||||
````
|
||||
|
||||
```bash Issue Management
|
||||
# Create GitHub issues from PostHog data
|
||||
cn -p "@posthog-data.json Create GitHub issues for UX problems found in this session data"
|
||||
|
||||
# Automated security audits
|
||||
cn -p "Scan the codebase for potential security vulnerabilities"
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
## Next steps
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="CLI Quickstart" href="/cli/quick-start">
|
||||
Learn basic commands and common workflows
|
||||
</Card>
|
||||
|
||||
<Card title="Installation Guide" href="/cli/install">
|
||||
Install Continue CLI and set up your environment
|
||||
</Card>
|
||||
|
||||
<Card title="CLI Workflows" href="/guides/overview#continuous-ai">
|
||||
Task-specific tutorials and examples
|
||||
</Card>
|
||||
</CardGroup>
|
||||
176
docs/cli/quick-start.mdx
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
---
|
||||
title: "Continue CLI Quick Start"
|
||||
description: "Get hands-on experience with Continue CLI through practical examples and common use cases"
|
||||
sidebarTitle: "Quick Start"
|
||||
---
|
||||
|
||||
Get hands-on experience with Continue CLI through practical development workflows.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="TUI Mode">
|
||||
TUI Mode (`cn` command) is for **large development tasks** that require
|
||||
agentic workflows with human oversight. Perfect for complex refactors,
|
||||
feature implementation, or one-off automation tasks that need monitoring and
|
||||
iteration.
|
||||
</Tab>
|
||||
<Tab title="Headless Mode">
|
||||
Headless Mode (`-p` flag) is for **reliable, repeatable tasks** that no
|
||||
longer need constant supervision. Perfect for CI/CD pipelines, git hooks,
|
||||
and automated workflows you've already tested and refined.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## TUI Mode: Large Development Tasks
|
||||
|
||||
Make sure you have [Continue CLI installed](/cli/install) and are in a project directory.
|
||||
|
||||
### Example: Implementing a New Feature
|
||||
|
||||
```bash
|
||||
# Navigate to your project directory
|
||||
cd your-awesome-project
|
||||
|
||||
# Start TUI Mode for complex development work
|
||||
cn
|
||||
```
|
||||
|
||||
**Example workflow for adding authentication:**
|
||||
|
||||
```
|
||||
> I need to add JWT authentication to this Express app. Let me start by showing you the current structure.
|
||||
|
||||
> @src/app.js @package.json Here's my current setup. Can you implement JWT auth with middleware, login/register routes, and user model?
|
||||
|
||||
> [Agent analyzes codebase and implements auth system]
|
||||
> [You review changes, test, and provide feedback]
|
||||
> [Agent iterates based on your input until the feature is complete]
|
||||
```
|
||||
|
||||
### Example: Complex Refactoring
|
||||
|
||||
```bash
|
||||
cn
|
||||
```
|
||||
|
||||
**Refactoring a monolithic component:**
|
||||
|
||||
```
|
||||
> @src/components/Dashboard.jsx This component is 800 lines and does too much. Help me break it into smaller, reusable components.
|
||||
|
||||
> [Agent analyzes component structure]
|
||||
> [Proposes component breakdown strategy]
|
||||
> [You approve approach]
|
||||
> [Agent implements the refactor with proper props and state management]
|
||||
> [You test and request adjustments]
|
||||
```
|
||||
|
||||
### When to Use TUI Mode
|
||||
|
||||
✅ **Large development tasks** that need oversight
|
||||
✅ **Complex refactors** requiring multiple steps
|
||||
✅ **New feature implementation** with unknowns
|
||||
✅ **One-off automation tasks** you haven't done before
|
||||
✅ **Debugging complex issues** that need exploration
|
||||
|
||||
## Headless Mode: Automated Workflows
|
||||
|
||||
Once you've refined a workflow in TUI Mode, convert it to Continuous AI for automation.
|
||||
|
||||
### Example: From REPL → Continuous AI
|
||||
|
||||
**Step 1: Develop in TUI Mode**
|
||||
|
||||
```bash
|
||||
cn
|
||||
> @package.json @CHANGELOG.md Generate release notes for version 2.1.0
|
||||
> [Test and refine the prompt until it works perfectly]
|
||||
```
|
||||
|
||||
**Step 2: Convert to Continuous AI**
|
||||
|
||||
```bash
|
||||
# Now use the refined workflow in automation
|
||||
cn -p "Generate release notes for the current version based on package.json and recent commits"
|
||||
```
|
||||
|
||||
### Common Continuous AI Workflows
|
||||
|
||||
```bash
|
||||
# Git automation
|
||||
cn -p "Generate a conventional commit message for staged changes"
|
||||
cn -p "Review the last 3 commits for potential issues"
|
||||
|
||||
# Code quality
|
||||
cn -p "Fix all TypeScript errors in the src/ directory"
|
||||
cn -p "Update outdated dependencies and fix breaking changes"
|
||||
|
||||
# Documentation
|
||||
cn -p "@README.md Update documentation based on recent changes"
|
||||
cn -p "Generate API documentation from JSDoc comments"
|
||||
|
||||
# CI/CD integration
|
||||
cn -p "Analyze test failures and create GitHub issue with findings"
|
||||
cn -p "Update version numbers and create release branch"
|
||||
```
|
||||
|
||||
### When to Use Headless Mode
|
||||
|
||||
✅ **Proven workflows** you've tested in TUI Mode
|
||||
✅ **Repetitive tasks** that no longer need oversight
|
||||
✅ **CI/CD automation** in pipelines
|
||||
✅ **Git hooks** for automated checks
|
||||
✅ **Scheduled tasks** that run unattended
|
||||
|
||||
### Available Slash Commands
|
||||
|
||||
Common slash commands available in CLI:
|
||||
|
||||
- `/clear` - Clear the chat history
|
||||
- `/compact` - Summarize chat history into a compact form
|
||||
- `/config` - Switch configuration or organization
|
||||
- `/exit` - Exit the chat
|
||||
- `/fork` - Start a forked chat session from the current history
|
||||
- `/help` - Show help message
|
||||
- `/info` - Show session information
|
||||
- `/init` - Create an AGENTS.md file
|
||||
- `/login` - Authenticate with your account
|
||||
- `/logout` - Sign out of your current session
|
||||
- `/mcp` - Manage MCP server connections
|
||||
- `/model` - Switch between available chat models
|
||||
- `/resume` - Resume a previous chat session
|
||||
- `/whoami` - Check who you're currently logged in as
|
||||
|
||||
<Info>Use `/help` to see all available commands.</Info>
|
||||
|
||||
## The Development Workflow
|
||||
|
||||
<Info>
|
||||
**Recommended Approach**: Start complex tasks in TUI Mode to iterate and
|
||||
refine your approach. Once you have a reliable workflow, convert it to
|
||||
Headless Mode for automation.
|
||||
</Info>
|
||||
|
||||
### Workflow Pattern
|
||||
|
||||
1. **🔬 Experiment in TUI Mode**
|
||||
|
||||
- Try complex development tasks with human oversight
|
||||
- Iterate on prompts and approaches until they work reliably
|
||||
- Test edge cases and refine the agent's behavior
|
||||
|
||||
2. **⚡ Automate with Continuous AI**
|
||||
- Convert proven REPL workflows to single commands
|
||||
- Deploy in CI/CD, git hooks, or scheduled tasks
|
||||
- Run with confidence knowing the approach is tested
|
||||
|
||||
## Next Steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Create Your First Workflow" href="/guides/posthog-github-continuous-ai">
|
||||
Build an automated PostHog to GitHub issues workflow
|
||||
</Card>
|
||||
|
||||
<Card title="Continuous AI Guide" href="/guides/continuous-ai">
|
||||
Learn to build and deploy AI-powered development workflows
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
|
@ -65,10 +65,10 @@ Read more about [model roles](/customize/model-roles), [model capabilities](/cus
|
|||
3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
[Grok 4](https://hub.continue.dev/xai/grok-4) from xAI
|
||||
[Grok Code Fast 1](https://hub.continue.dev/xai/grok-code-fast-1) from xAI
|
||||
|
||||
1. Get your API key from [xAI](https://console.x.ai/)
|
||||
2. Add [Grok 4](https://hub.continue.dev/xai/grok-4) to an agent on Continue Hub
|
||||
2. Add [Grok Code Fast 1](https://hub.continue.dev/xai/grok-code-fast-1) to an agent on Continue Hub
|
||||
3. Add `XAI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the agent selector in the Continue IDE extension
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ Different Continue features can use different models. We call these _model roles
|
|||
|
||||
## Create a Slash Command
|
||||
|
||||
Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/slash-commands).
|
||||
Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/deep-dives/prompts).
|
||||
|
||||
## Call External Tools and Functions
|
||||
|
||||
|
|
|
|||
|
|
@ -13,4 +13,6 @@ description: "These are the specialized instructions that shape how models respo
|
|||
|
||||
## Learn More
|
||||
|
||||
Prompts have the same syntax as [prompt files](/customization/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
|
||||
- [Explore prompts](https://hub.continue.dev/?type=prompts) on the Hub
|
||||
- Learn more in the [prompts deep dive](/customize/deep-dives/prompts)
|
||||
- View [`prompts`](/reference#prompts) in the YAML Reference for more details
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ See the full reference for `config.yaml` [here](/reference).
|
|||
## Legacy Configuration Methods (Deprecated)
|
||||
|
||||
<Info>
|
||||
View the `config.json` migration guide [here](../yaml-migration)
|
||||
View the `config.json` migration guide [here](/reference/yaml-migration)
|
||||
</Info>
|
||||
|
||||
- [`config.json`](/reference) - The original configuration format which is stored in a file at the same location as `config.yaml`
|
||||
|
|
@ -63,7 +63,7 @@ Example
|
|||
|
||||
<Warning>
|
||||
The `slashCommands` array shown below is deprecated. For creating custom slash
|
||||
commands, use [prompt files](./slash-commands) instead.
|
||||
commands, use [prompt files](./prompts) instead.
|
||||
</Warning>
|
||||
|
||||
```ts title="config.ts"
|
||||
|
|
|
|||
|
|
@ -210,9 +210,14 @@ This matrix shows which models support tool use and image input capabilities. Co
|
|||
|
||||
### xAI
|
||||
|
||||
| Model | Tool Use | Image Input | Context Window |
|
||||
| :----- | -------- | ----------- | -------------- |
|
||||
| Grok 4 | Yes | Yes | 128k |
|
||||
| Model | Tool Use | Image Input | Context Window |
|
||||
| :------------------------ | -------- | ----------- | -------------- |
|
||||
| Grok Code Fast 1 | Yes | Yes | 256k |
|
||||
| Grok 4 Fast Reasoning | Yes | Yes | 2M |
|
||||
| Grok 4 Fast Non-Reasoning | Yes | Yes | 2M |
|
||||
| Grok 4 | Yes | Yes | 256k |
|
||||
| Grok 3 | Yes | Yes | 131k |
|
||||
| Grok 3 Mini | Yes | Yes | 131k |
|
||||
|
||||
### Moonshot AI
|
||||
|
||||
|
|
|
|||
|
|
@ -1,62 +1,106 @@
|
|||
---
|
||||
title: "Creating Custom Prompts in Continue"
|
||||
description: "Learn how to create reusable prompt files in Continue to streamline repetitive tasks, including examples for code reviews, security checks, and entity generation"
|
||||
title: "How to Create and Manage Prompts in Continue"
|
||||
description: "Prompts are used to kick off tasks for Agent, Plan, and Chat requests"
|
||||
keywords: [prompts, context, slash command]
|
||||
sidebarTitle: "Prompts"
|
||||
---
|
||||
|
||||
Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
|
||||
Prompts are included as user messages and are especially useful as instructions for repetitive and/or complex tasks.
|
||||
|
||||
<Info>
|
||||
Prompts were previously defined in a `.prompt` file format, but for
|
||||
consistency we now recommend using the same Markdown format as
|
||||
[rules](./rules) and adding `alwaysApply: false` to the frontmatter so
|
||||
that they are manually triggered.
|
||||
</Info>
|
||||
## Slash commands
|
||||
|
||||
## Quick Start: How to Create Your First Prompt File
|
||||
By setting `invokable` to `true`, you make the markdown file a prompt, which will be available when you type <kbd>/</kbd> in Chat, Plan, and Agent mode.
|
||||
|
||||
Below is a quick example of setting up a prompt file:
|
||||
|
||||
1. Create a folder called `.continue/rules` at the top level of your workspace
|
||||
2. Add a file called `review-prompt.md` to this folder.
|
||||
3. Write the following contents to `review-prompt.md` and save.
|
||||
|
||||
```md title="review-prompt.md"
|
||||
```md title="explain-invokable.md"
|
||||
---
|
||||
name: Redux best practices review
|
||||
alwaysApply: false
|
||||
name: Explain invokable
|
||||
description: Explains what happens when you set invokable to true
|
||||
invokable: true
|
||||
---
|
||||
|
||||
Review the currently open file for adherence to Redux best practices, as explained in their style guide at https://redux.js.org/style-guide/.
|
||||
Explain that when `invokable` is set to `true`, a slash command becomes available in the IDE extensions and CLI
|
||||
```
|
||||
|
||||
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and type out any additional instructions you'd like to add.
|
||||
These slash commands can be combined with other instructions, including highlighted code, to provide additional context.
|
||||
|
||||
## Example Prompt Templates for Common Use Cases
|
||||
## Example: `Create Supabase functions` prompt
|
||||
|
||||
Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts).
|
||||
Here is a prompt that generates high-quality PostgreSQL functions that adhere to best practices:
|
||||
|
||||
### How to Create a Security Review Prompt
|
||||
|
||||
```md title="security-review.md"
|
||||
```md title="supabase-create-functions.md"
|
||||
---
|
||||
name: Security best practices review
|
||||
alwaysApply: false
|
||||
name: Create Supabase functions
|
||||
description: Guidelines for writing Supabase database functions
|
||||
invokable: true
|
||||
---
|
||||
|
||||
Review the changes in the current git diff for these security best practices:
|
||||
# Database: Create functions
|
||||
|
||||
- Does the architecture follow security-by-design principles?
|
||||
- Are there potential security vulnerabilities in the system design?
|
||||
- Is sensitive data handled appropriately throughout the lifecycle?
|
||||
You're a Supabase Postgres expert in writing database functions. Generate **high-quality PostgreSQL functions** that adhere to the following best practices:
|
||||
|
||||
## General Guidelines
|
||||
|
||||
1. **Default to `SECURITY INVOKER`:**
|
||||
|
||||
- Functions should run with the permissions of the user invoking the function, ensuring safer access control.
|
||||
- Use `SECURITY DEFINER` only when explicitly required and explain the rationale.
|
||||
|
||||
2. **Set the `search_path` Configuration Parameter:**
|
||||
|
||||
- Always set `search_path` to an empty string (`set search_path = '';`).
|
||||
- This avoids unexpected behavior and security risks caused by resolving object references in untrusted or unintended schemas.
|
||||
- Use fully qualified names (e.g., `schema_name.table_name`) for all database objects referenced within the function.
|
||||
|
||||
3. **Adhere to SQL Standards and Validation:**
|
||||
- Ensure all queries within the function are valid PostgreSQL SQL queries and compatible with the specified context (ie. Supabase).
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
### How to Create a Prompt That References Existing Files
|
||||
<Info>You can read the rest of the `Create Supabase functions` prompt [here](http://hub.continue.dev/supabase/create-functions)</Info>
|
||||
|
||||
```md title="typeorm-entity-generator.md"
|
||||
---
|
||||
name: Generate a new TypeORM entity
|
||||
alwaysApply: false
|
||||
---
|
||||
If you are using a local `config.yaml`, you can add it to your agent like this:
|
||||
|
||||
Referencing `src/db/dataSource.ts` and `src/db/entity/SampleEntity.ts`, generate a new TypeORM entity based on the following requirements:
|
||||
```md title="config.yaml"
|
||||
...
|
||||
|
||||
prompts:
|
||||
- uses: supabase/create-functions
|
||||
|
||||
...
|
||||
```
|
||||
|
||||
If you are using Continue Hub, you can add it to your agent by selecting "Use Rule" [here](https://hub.continue.dev/supabase/create-functions)
|
||||
|
||||
To use this prompt, you can open Chat / Agent / Edit, type <kbd>/</kbd>, select the prompt, and type out any additional instructions you'd like to add.
|
||||
|
||||
## Using a prompt with `cn (TUI mode)`
|
||||
|
||||
You can run this command to start [cn](../../guides/cli) with the [Create Supabase functions](http://hub.continue.dev/supabase/create-functions) prompt.
|
||||
|
||||
```
|
||||
cn --prompt supabase/create-functions "I need a function that checks for the health status"
|
||||
```
|
||||
Alternatively, you can start [cn](../../guides/cli) and then type <kbd>/</kbd> to manually invoke the prompt yourself.
|
||||
|
||||
## Using a prompt to kick off a Continuous AI workflow with `cn (Headless mode)
|
||||
|
||||
You can kick off Continuous AI workflows using a prompt with [cn](../../guides/cli) by adding the `-p` flag.
|
||||
|
||||
For example, say you are building a SaaS application and must repeatedly create custom Supabase validation functions for each new feature that accepts user input.
|
||||
|
||||
These functions require you to interpret business requirements, implement complex cross-table logic (like checking user permissions, tier limits, and time-based restrictions), and make judgment calls about edge cases.
|
||||
|
||||
Each function is unique enough that it can't be templated or scripted. This is where kicking off a Continuous AI workflow to get you started can be quite helpful.
|
||||
|
||||
Here is a command that you could run whenever you have a new feature:
|
||||
|
||||
```
|
||||
cn -p --prompt supabase/create-functions "I need a function for the new feature on my current branch similar to my existing database functions"
|
||||
```
|
||||
|
||||
<Info>You can see the entire `Create Supabase functions` prompt [here](http://hub.continue.dev/supabase/create-functions)</Info>
|
||||
|
||||
When you run this workflow, [cn](../../guides/cli) will checkout your current branch, explore the new and existing code, and then draft a function for you.
|
||||
|
||||
You will then be able to review the implementation and improve it before you merge the new feature.
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
---
|
||||
title: "How to Create and Manage Rules in Continue"
|
||||
description: "Rules are used to provide instructions to the model for Agent, Chat, and Edit requests."
|
||||
keywords: [rules, .continuerules, system, prompt, message]
|
||||
description: "Rules are used to provide system message instructions to the model for Agent, Chat, and Edit requests"
|
||||
keywords: [rules, system, prompt, message]
|
||||
sidebarTitle: "Rules"
|
||||
---
|
||||
|
||||
|
|
@ -156,13 +156,4 @@ Continue includes a simple default system message for [Agent](../../features/age
|
|||
|
||||
This can be viewed in the rules section of the toolbar (see above), or in the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4).
|
||||
|
||||
Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](/reference#models).
|
||||
|
||||
### Legacy: .continuerules File (Deprecated)
|
||||
|
||||
<Warning>
|
||||
`.continuerules` will be deprecated in a future release. Please use the
|
||||
`.continue/rules` folder instead.
|
||||
</Warning>
|
||||
|
||||
You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules.
|
||||
Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](/reference#models).
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
---
|
||||
title: "Using Slash Commands in Continue"
|
||||
description: "Learn how to use and create Slash Commands in Continue to run custom prompts, access context providers, and speed up coding tasks."
|
||||
keywords: [slash command, custom commands, step]
|
||||
sidebarTitle: "Slash Commands"
|
||||
---
|
||||
|
||||

|
||||
|
||||
Slash commands are shortcuts that can be activated by typing '/' in a chat session (press <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> (VS Code) or <kbd>cmd/ctrl</kbd> + <kbd>J</kbd> (JetBrains)), and selecting from the dropdown.
|
||||

|
||||
|
||||
Slash commands can be combined with additional instructions, including highlighted code.
|
||||
|
||||
<Note>
|
||||
**Recommended approach**: Use prompt files to create slash commands instead of
|
||||
the deprecated `config.json` approach. The methods described below provide
|
||||
better flexibility and are the actively maintained ways to add custom
|
||||
commands.
|
||||
</Note>
|
||||
|
||||
## Ways to Create Slash Commands in Continue
|
||||
|
||||
### Agent Prompt Blocks
|
||||
|
||||
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
|
||||
|
||||
It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more.
|
||||
|
||||
Learn more about prompt files [here](./prompts).
|
||||
|
||||
### MCP Server Prompts
|
||||
|
||||
Any prompts provided by [Model Context Protocol](https://modelcontextprotocol.io/introduction) servers are also accessible in chat as Slash Commands. See the [MCP Server Deep Dive](./mcp) for more details.
|
||||
|
|
@ -3,13 +3,9 @@ title: xAI
|
|||
slug: ../xai
|
||||
---
|
||||
|
||||
<Tip>
|
||||
**Discover xAI models [here](https://hub.continue.dev/xai)**
|
||||
</Tip>
|
||||
<Tip>**Discover xAI models [here](https://hub.continue.dev/xai)**</Tip>
|
||||
|
||||
<Info>
|
||||
Get an API key from the [xAI Console](https://console.x.ai/)
|
||||
</Info>
|
||||
<Info>Get an API key from the [xAI Console](https://console.x.ai/)</Info>
|
||||
|
||||
## Configuration
|
||||
|
||||
|
|
@ -29,7 +25,7 @@ slug: ../xai
|
|||
"models": [
|
||||
{
|
||||
"title": "<MODEL_NAME>",
|
||||
"provider": "anthropic",
|
||||
"provider": "xai",
|
||||
"model": "<MODEL_ID>",
|
||||
"apiKey": "<YOUR_XAI_API_KEY>"
|
||||
}
|
||||
|
|
@ -40,5 +36,6 @@ slug: ../xai
|
|||
</Tabs>
|
||||
|
||||
<Info>
|
||||
**Check out a more advanced configuration [here](https://hub.continue.dev/xai/grok-4?view=config)**
|
||||
</Info>
|
||||
**Check out a more advanced configuration
|
||||
[here](https://hub.continue.dev/xai/grok-code-fast-1?view=config)**
|
||||
</Info>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ sidebar_position: 3
|
|||
---
|
||||
import { ModelRecommendations } from '/snippets/ModelRecommendations.jsx'
|
||||
|
||||
It's often useful to select a different model to respond to Edit prompts than for chat prompts, as Edits are often more code-specific and may require less conversational readability.
|
||||
It's often useful to select a different model to respond to Edit instructions than for Chat instructions, as Edits are often more code-specific and may require less conversational readability.
|
||||
|
||||
In Continue, you can add `edit` to a model's roles to specify that it can be used for Edit requests. If no edit models are specified, the selected `chat` model is used.
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ sidebar_position: 5
|
|||
|
||||
An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
|
||||
|
||||
In Continue, embeddings are generated during indexing and then used by [@Codebase](../context/codebase) to perform similarity search over your codebase.
|
||||
In Continue, embeddings are generated during indexing and then used by [codebase awareness](/guides/codebase-documentation-awareness) to perform similarity search over your codebase.
|
||||
|
||||
You can add `embed` to a model's `roles` to specify that it can be used to embed.
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ icon: "book-open"
|
|||
|
||||
- [`chat`](/customize/model-roles/chat): Used for chat conversations in the extension sidebar
|
||||
- [`autocomplete`](/customize/model-roles/autocomplete): Used for autocomplete code suggestions in the editor
|
||||
- [`edit`](/customize/model-roles/edit): Used to generate code based on edit prompts
|
||||
- [`edit`](/customize/model-roles/edit): Used to generate code based on edit instructions
|
||||
- [`apply`](/customize/model-roles/apply): Used to decide how to apply edits to a file
|
||||
- [`embed`](/customize/model-roles/embeddings): Used to generate embeddings used for vector search (@Codebase and @Docs context providers)
|
||||
- [`rerank`](/customize/model-roles/reranking): Used to rerank results from vector search
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ sidebar_position: 6
|
|||
|
||||
A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
|
||||
|
||||
In Continue, rerankers are designated using the `rerank` role and used by [@Codebase](../context/codebase) in order to select the most relevant code snippets after vector search.
|
||||
In Continue, rerankers are designated using the `rerank` role and used by [codebase awareness](/guides/codebase-documentation-awareness) in order to select the most relevant code snippets after vector search.
|
||||
|
||||
## Recommended reranking models
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ description: "Explore Continue's advanced capabilities for power users and compl
|
|||
|
||||
Specialized context features for codebase understanding and documentation integration.
|
||||
|
||||
[Browse Context Features →](/guides/understanding-assistants)
|
||||
[Browse Context Features →](/guides/understanding-agents)
|
||||
|
||||
## Deep Dives
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,11 @@
|
|||
"getting-started/quick-start"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "CLI",
|
||||
"icon": "terminal",
|
||||
"pages": ["cli/overview", "cli/install", "cli/quick-start"]
|
||||
},
|
||||
{
|
||||
"group": "Features",
|
||||
"icon": "star",
|
||||
|
|
@ -230,10 +235,10 @@
|
|||
"pages": [
|
||||
"guides/overview",
|
||||
"guides/understanding-agents",
|
||||
"guides/configuring-models-rules-tools",
|
||||
"guides/codebase-documentation-awareness",
|
||||
"guides/cli",
|
||||
"guides/continuous-ai",
|
||||
"guides/snyk-mcp-continue-cookbook",
|
||||
"guides/continuous-ai-readiness-assessment",
|
||||
"guides/plan-mode-guide",
|
||||
"guides/ollama-guide",
|
||||
|
|
@ -248,6 +253,7 @@
|
|||
"icon": "book-open-cover",
|
||||
"pages": [
|
||||
"guides/posthog-github-continuous-ai",
|
||||
"guides/snyk-mcp-continue-cookbook",
|
||||
"guides/netlify-mcp-continuous-deployment"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -48,7 +48,7 @@ View the exact prompt sent to the AI model in the [prompt logs](/troubleshooting
|
|||
|
||||
Learn more about how you can bring in context:
|
||||
|
||||
- [Codebase Context](/customize/context/codebase)
|
||||
- [Codebase Context](/guides/codebase-documentation-awareness)
|
||||
- [Documentation Context](/guides/codebase-documentation-awareness)
|
||||
- [Built-in Context Providers](/customize/deep-dives/custom-providers)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,4 +3,4 @@ title: "Understanding Agents"
|
|||
description: "Continue offers two ways to configure your AI assistants"
|
||||
---
|
||||
|
||||
This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-assistants)
|
||||
This content has moved to our comprehensive guide: [Understanding Agents: Hub vs Local Configuration](/guides/understanding-agents)
|
||||
|
|
|
|||
|
|
@ -59,4 +59,4 @@ description: "To quickly understand what you can do with Continue, check out eac
|
|||
|
||||
## AI Coding Agents
|
||||
|
||||
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).
|
||||
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 agents](/guides/understanding-agents).
|
||||
|
|
|
|||
|
|
@ -248,7 +248,7 @@ Ready to master specific features? Check out these detailed guides:
|
|||
<Accordion title="Chat & Agent Best Practices">
|
||||
Discover [effective prompting techniques](/customize/deep-dives/prompts), [hub
|
||||
v. local agents](/guides/understanding-agents), and [custom slash
|
||||
commands](/customize/deep-dives/slash-commands).
|
||||
commands](/customize/deep-dives/prompts).
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Enterprise & Teams">
|
||||
|
|
|
|||
|
|
@ -187,4 +187,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
|
||||
- Set up [custom agents](/guides/understanding-agents) with specific knowledge domains
|
||||
|
|
|
|||
168
docs/guides/configuring-models-rules-tools.mdx
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
---
|
||||
title: "Configuring Models, Rules, and Tools"
|
||||
description: "Learn how to work with Continue's configuration system. Understand how to use hub models, rules, and tools, create local configurations, and organize your setup for maximum reusability."
|
||||
---
|
||||
|
||||
## What Are Models, Rules, and Tools?
|
||||
|
||||
Continue agents are built from three main types of configuration:
|
||||
|
||||
<Columns cols={3}>
|
||||
<Card title="Models" icon="cube">
|
||||
Language models that power different capabilities like chat, autocomplete, and agent mode
|
||||
</Card>
|
||||
|
||||
<Card title="Rules" icon="pencil">
|
||||
Guidelines and instructions that shape how the AI behaves and responds
|
||||
</Card>
|
||||
|
||||
<Card title="Tools" icon="server">
|
||||
MCP tools that provide additional capabilities like database access, web search, or custom functions
|
||||
</Card>
|
||||
</Columns>
|
||||
|
||||
There are two places where you can define these configurations:
|
||||
|
||||
<Columns cols={2}>
|
||||
<Card title="Local" icon="computer">
|
||||
Custom configurations you create and manage in your workspace or globally
|
||||
</Card>
|
||||
|
||||
<Card title="Hub" icon="cloud">
|
||||
Pre-built models, rules, and tools from the Continue community that you can import and use immediately
|
||||
</Card>
|
||||
</Columns>
|
||||
|
||||
## Local
|
||||
|
||||
Local configurations let you create custom models, rules, and tools that automatically apply to multiple agents, reducing duplication and ensuring consistency across your setup.
|
||||
|
||||
<Columns cols={2}>
|
||||
<Card title="Global" icon="globe">
|
||||
Applied to all agents across all workspaces. Ideal for personal preferences, universal coding standards, or tools you use everywhere.
|
||||
</Card>
|
||||
<Card title="Workspace" icon="folder-open">
|
||||
Applied automatically to all agents when working in a specific project.
|
||||
|
||||
Perfect for project-specific setups like TypeScript rules for web apps or the Playwright MCP tool.
|
||||
|
||||
</Card>
|
||||
|
||||
</Columns>
|
||||
|
||||
## Hub
|
||||
|
||||
Continue hub uses a slug in the format of `owner/item-name` to resolve blocks.
|
||||
|
||||
For example, to use the [Claude 4 Sonnet model](https://hub.continue.dev/anthropic/claude-4-sonnet), you'd reference it as `anthropic/claude-4-sonnet`.
|
||||
|
||||
Import from the hub using the `uses` syntax alongside your custom configurations:
|
||||
|
||||
```yaml config.yaml highlight={6}
|
||||
name: Team Agent
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- uses: anthropic/claude-4-sonnet
|
||||
with:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} # Use a hub secret
|
||||
```
|
||||
|
||||
### Organization
|
||||
|
||||
Organize your local configurations using these directories:
|
||||
|
||||
<Columns cols={3}>
|
||||
<Card title="Models" icon="cube">
|
||||
`.continue/models`
|
||||
</Card>
|
||||
|
||||
<Card title="Rules" icon="pencil">
|
||||
`.continue/rules`
|
||||
</Card>
|
||||
|
||||
<Card title="Tools" icon="server">
|
||||
`.continue/mcpServers`
|
||||
</Card>
|
||||
</Columns>
|
||||
|
||||
## Working with Secrets
|
||||
|
||||
Models, and many MCP servers, require a secret for things like API keys.
|
||||
|
||||
On the hub, you can configure secrets when adding a model or MCP server.
|
||||
|
||||
This will use mustache notation to pass the secret, eg `${{ secrets.SECRET_NAME }}`
|
||||
|
||||
When configuring a local model or MCP server, you can use the same mustache notation for secrets which read from:
|
||||
|
||||
<Columns cols={2}>
|
||||
<Card title="Global" icon="globe">
|
||||
`.env` file in `~/.continue/.env`
|
||||
</Card>
|
||||
|
||||
<Card title="Workspace" icon="folder-open">
|
||||
`.env` file at your project root
|
||||
</Card>
|
||||
</Columns>
|
||||
|
||||
## Overriding Properties
|
||||
|
||||
You can directly override properties using the `override` syntax:
|
||||
|
||||
```yaml title="config.yaml" highlight={10-13}
|
||||
name: myprofile/custom-agent
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- uses: myprofile/custom-model
|
||||
with:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }}
|
||||
TEMP: 0.9
|
||||
override:
|
||||
roles:
|
||||
- chat
|
||||
```
|
||||
|
||||
## Advanced
|
||||
|
||||
### Inputs
|
||||
|
||||
Models and MCP server authors can configure inputs that require the user to provide a secret value by defining a `${{ inputs.SECRET_NAME }}` value.
|
||||
|
||||
For example, here is how you could require that the user provide a value for the `apiKey` property on a model:
|
||||
|
||||
```yaml title="config.yaml" highlight={8}
|
||||
name: myprofile/custom-model
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- name: My Favorite Model
|
||||
# ... other model properties ...
|
||||
apiKey: ${{ inputs.SECRET_NAME }}
|
||||
```
|
||||
|
||||
Users then map their secret to this input using a `${{ secrets.SECRET_NAME }}` value that maps to a property name which matches the required input, e.g. `SECRET_NAME`.
|
||||
|
||||
```yaml title="config.yaml" highlight={8}
|
||||
name: myprofile/custom-agent
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- uses: myprofile/custom-model
|
||||
with:
|
||||
SECRET_NAME: ${{ secrets.SECRET_NAME }}
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you understand how models, rules, and tools work, explore:
|
||||
|
||||
- **[Config Reference](/reference)**: Detailed documentation of all available properties
|
||||
- **[Continue Hub](https://hub.continue.dev)**: Browse community models, rules, and tools
|
||||
- **[Custom Context Providers](/customize/deep-dives/custom-providers)**: Create advanced context integrations
|
||||
- **[Model Roles](/customize/model-roles/intro)**: Understanding how different models work together
|
||||
|
|
@ -44,18 +44,82 @@ This cookbook teaches you to:
|
|||
|
||||
## Quick Setup
|
||||
|
||||
<Info>
|
||||
The Netlify Development Rules bundle includes guardrails for:
|
||||
- Proper `.gitignore` configuration
|
||||
- Function structure and placement
|
||||
- Edge function constraints
|
||||
- Local development best practices
|
||||
|
||||
</Info>
|
||||
For all options, first:
|
||||
<Steps>
|
||||
<Step title="Install Continue CLI">
|
||||
<Step title="Install Continue CLI">
|
||||
```bash
|
||||
npm i -g @continuedev/cli
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Install Netlify CLI">
|
||||
|
||||
1. Install Netlify CLI: `npm i -g netlify-cli`
|
||||
2. Authenticate with Netlify:
|
||||
`netlify login`
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Netlify Continuous AI Workflow Options
|
||||
|
||||
<Card title="🚀 Fastest Path to Success" icon="zap">
|
||||
Skip the manual setup and use our pre-built Netlify Continuous AI agent that includes
|
||||
optimized prompts, rules, and the Netlify MCP for more consistent results.
|
||||
</Card>
|
||||
|
||||
After completing **Quick Setup** above, you have two paths to get started:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="⚡ Quick Start (Recommended)">
|
||||
|
||||
<Steps>
|
||||
<Step title="Add the Pre-Built Agent">
|
||||
Visit the [Netlify Continuous AI Agent](https://hub.continue.dev/continuedev/netlify-continuous-ai) on Continue Hub and click **"Install Agent"**
|
||||
|
||||
This agent includes:
|
||||
- **Optimized prompts** for Netlify deployment and performance analysis
|
||||
- **Built-in rules** for consistent formatting and error handling
|
||||
- **Netlify MCP** for more reliable API interactions
|
||||
</Step>
|
||||
|
||||
<Step title="Verify Your Setup">
|
||||
The agent uses the Netlify MCP automatically and includes best practice rules for deployment and performance optimization.
|
||||
</Step>
|
||||
|
||||
<Step title="Run Performance Analysis">
|
||||
Navigate to your project directory and run:
|
||||
```bash
|
||||
cn "Analyze my Netlify site's performance and optimize it for better Core Web Vitals."
|
||||
```
|
||||
|
||||
That's it! The agent handles everything automatically.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Info>
|
||||
**Why Use the Agent?** Results are more consistent and debugging is easier thanks to the Netlify MCP integration and pre-tested prompts. You can remix the agent later to customize it to your needs.
|
||||
</Info>
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="🛠️ Manual Setup">
|
||||
<Steps>
|
||||
|
||||
<Step title="Configure Netlify MCP">
|
||||
1. Install Netlify CLI: `npm i -g netlify-cli` 2. Authenticate with Netlify:
|
||||
`netlify login` 3. Visit [Netlify MCP on Continue
|
||||
Hub](https://hub.continue.dev/netlify/netlify-mcp) 4. Follow the configuration
|
||||
instructions for your editor
|
||||
1. Authenticate with Netlify:
|
||||
`netlify login`
|
||||
2. Visit [Netlify MCP on Continue
|
||||
Hub](https://hub.continue.dev/netlify/netlify-mcp)
|
||||
3. Follow the configuration instructions for your editor
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Add Development Rules">
|
||||
|
|
@ -77,13 +141,26 @@ This cookbook teaches you to:
|
|||
```
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Info>
|
||||
The Netlify Development Rules bundle includes guardrails for: - Proper
|
||||
`.gitignore` configuration - Function structure and placement - Edge function
|
||||
constraints - Local development best practices
|
||||
</Info>
|
||||
|
||||
</Steps>
|
||||
<Info>
|
||||
You're all set! Now you can use cn CLI to interact with Netlify using natural language prompts. Check out the examples below to get started.
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Accordion title="Agent Requirements">
|
||||
To use the pre-built agent, you need either:
|
||||
- **Continue CLI Pro Plan** with
|
||||
the models add-on, OR
|
||||
- **Your own API keys** added to Continue Hub secrets
|
||||
The agent will automatically detect and use your
|
||||
configuration along with the Netlify MCP for deployment operations.
|
||||
|
||||
</Accordion>
|
||||
|
||||
---
|
||||
|
||||
## Performance Optimization Steps
|
||||
|
||||
|
|
@ -375,6 +452,14 @@ Unlike Google Analytics, Netlify Analytics:
|
|||
|
||||
## Automated Performance Checks
|
||||
|
||||
### Add GitHub Secrets
|
||||
|
||||
Navigate to **Repository Settings → Secrets and variables → Actions** and add:
|
||||
|
||||
- `CONTINUE_API_KEY`: Your Continue API key from [hub.continue.dev/settings/api-keys](https://hub.continue.dev/settings/api-keys)
|
||||
- `NETLIFY_AUTH_TOKEN`: Your Netlify personal access token
|
||||
- `NETLIFY_SITE_ID`: Your Netlify site ID
|
||||
|
||||
### GitHub Actions Performance Guard
|
||||
|
||||
Block PRs that degrade performance:
|
||||
|
|
@ -394,17 +479,28 @@ jobs:
|
|||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Install Continue CLI
|
||||
run: |
|
||||
npm install -g @continuedev/cli
|
||||
echo "✅ Continue CLI installed"
|
||||
|
||||
- name: Authenticate Continue CLI
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
run: |
|
||||
cn auth login --api-key "$CONTINUE_API_KEY"
|
||||
echo "✅ Continue CLI authenticated"
|
||||
|
||||
- name: Deploy and Test Performance
|
||||
id: perf
|
||||
env:
|
||||
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
|
||||
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
|
||||
run: |
|
||||
npx @continuedev/cli@latest << 'EOF'
|
||||
Deploy PR preview and run Lighthouse.
|
||||
Compare scores with main branch.
|
||||
Output JSON with score deltas.
|
||||
EOF > performance.json
|
||||
echo "🚀 Deploying PR preview and analyzing performance..."
|
||||
cn -p "Deploy PR preview and run Lighthouse.
|
||||
Compare scores with main branch.
|
||||
Output JSON with score deltas." > performance.json
|
||||
|
||||
- name: Comment Performance Results
|
||||
uses: actions/github-script@v7
|
||||
|
|
@ -442,9 +538,11 @@ jobs:
|
|||
```
|
||||
|
||||
<Warning>
|
||||
This workflow will: - **Block merge** if performance score drops >10 points -
|
||||
**Warn** on any performance regression - **Celebrate** improvements with green
|
||||
indicators
|
||||
This workflow will:
|
||||
- **Block merge** if performance score drops >10 points
|
||||
- **Warn** on any performance regression
|
||||
- **Celebrate** improvements with green indicators
|
||||
|
||||
</Warning>
|
||||
|
||||
## Performance Testing Locally
|
||||
|
|
@ -528,9 +626,12 @@ Features many developers don't know Netlify offers:
|
|||
|
||||
<Card title="On-Demand Builders" icon="hammer">
|
||||
**[On-Demand
|
||||
Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)** -
|
||||
Generate pages only when requested - Cache dynamically generated content -
|
||||
Perfect for large sites (10k+ pages) - Reduce build times dramatically
|
||||
Builders](https://docs.netlify.com/configure-builds/on-demand-builders/)**
|
||||
- Generate pages only when requested
|
||||
- Cache dynamically generated content
|
||||
- Perfect for large sites (10k+ pages)
|
||||
- Reduce build times dramatically
|
||||
|
||||
</Card>
|
||||
|
||||
<Card title="Netlify Functions" icon="function">
|
||||
|
|
|
|||
|
|
@ -1,23 +1,32 @@
|
|||
---
|
||||
title: "Building a Continuous AI Workflow with PostHog and GitHub"
|
||||
description: "Build an automated system that continuously monitors PostHog session recordings, analyzes UX issues using Continue CLI, and creates GitHub issues automatically."
|
||||
sidebarTitle: "PostHog Session Analysis with Continue CLI"
|
||||
description: "Build an automated system that continuously monitors PostHog analytics, analyzes user behavior with AI, and creates GitHub issues automatically using PostHog MCP."
|
||||
sidebarTitle: "PostHog Analytics with Continue CLI"
|
||||
---
|
||||
|
||||
<Card title="What You'll Build" icon="robot">
|
||||
A fully automated workflow that uses Continue CLI to fetch PostHog session
|
||||
data, analyze user experience issues with AI, and automatically create GitHub
|
||||
issues with specific technical recommendations
|
||||
A fully automated workflow that uses Continue CLI with the PostHog MCP to fetch analytics data, analyze user experience issues with AI, and automatically create GitHub
|
||||
issues with the GitHub CLI.
|
||||
</Card>
|
||||
|
||||
## What You'll Learn
|
||||
|
||||
This cookbook teaches you to:
|
||||
|
||||
- Use [PostHog MCP](https://posthog.com/docs/model-context-protocol) to query [analytics](https://posthog.com/docs/web-analytics), [errors](https://posthog.com/docs/error-tracking), and [feature flags](https://posthog.com/docs/feature-flags)
|
||||
- Analyze user behavior patterns with AI
|
||||
- Automatically create GitHub issues using GitHub CLI
|
||||
- Set up continuous monitoring with GitHub Actions
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before starting, ensure you have:
|
||||
|
||||
- GitHub repository where you want to create issues
|
||||
- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)**
|
||||
- [PostHog account](https://posthog.com) with [session recordings enabled](https://posthog.com/docs/session-replay/installation) and data collecting
|
||||
- Node.js 18+ installed locally
|
||||
- Continue CLI account with **active credits** (required for API usage)
|
||||
- [Continue CLI](https://docs.continue.dev/guides/cli) with **active credits** (required for API usage)
|
||||
- [GitHub CLI](https://cli.github.com/) installed (`gh` command)
|
||||
|
||||
<Steps>
|
||||
<Step title="Install Continue CLI">
|
||||
|
|
@ -66,39 +75,38 @@ First, you'll need to gather your PostHog and GitHub API credentials and add the
|
|||
7. Note your PostHog host URL (e.g., `https://us.posthog.com` or your custom domain)
|
||||
8. You'll also need your POSTHOG_AUTH_HEADER value, which is simply `Bearer YOUR_API_KEY`
|
||||
|
||||
<Tip>
|
||||
**Find Your Project Details**: Your Project ID is in your PostHog URL:
|
||||
`https://app.posthog.com/project/YOUR_PROJECT_ID`
|
||||
</Tip>
|
||||
<Info>
|
||||
**Continue Secrets**: The `POSTHOG_AUTH_HEADER` secret should be stored in
|
||||
Continue's secure secrets storage. This keeps your API key safe and the MCP
|
||||
automatically connects to your default PostHog project.
|
||||
</Info>
|
||||
|
||||
</Tab>
|
||||
<Tab title="GitHub Personal Access Token">
|
||||
You'll need a **Personal Access Token** to create issues in your GitHub repository:
|
||||
<Tab title="Set Up GitHub CLI Authentication">
|
||||
GitHub CLI handles authentication automatically - no manual PAT needed:
|
||||
|
||||
1. Go to [GitHub Personal Access Tokens](https://github.com/settings/personal-access-tokens/new)
|
||||
2. Click **"Generate new token (classic)"**
|
||||
3. Name it "Continue CLI PostHog Analysis"
|
||||
4. Select these scopes:
|
||||
- `repo` (or just `public_repo` if your repository is public)
|
||||
- `issues:write` - **Required** for creating issues
|
||||
5. Copy the token immediately
|
||||
1. Install GitHub CLI if not already installed
|
||||
2. Run `gh auth login` and follow the prompts
|
||||
3. Choose authentication method (browser or token)
|
||||
4. Grant necessary permissions when prompted (`issues:write` is **required** for creating issues)
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
<Tab title= "Configure API Access in Continue CLI">
|
||||
|
||||
<Tip>
|
||||
See https://docs.continue.dev/hub/secrets/secret-types#secret-types for adding secrets
|
||||
</Tip>
|
||||
|
||||
### Add Secrets to Continue CLI
|
||||
|
||||
To add environment variables to your Continue Hub account:
|
||||
You only need to configure the PostHog MCP credential - it automatically handles project selection. To add environment variables to your Continue Hub account:
|
||||
|
||||
1. Go to the [Continue Hub](https://hub.continue.dev)
|
||||
2. Sign in to your account
|
||||
3. Navigate to your user settings
|
||||
4. Look for the "Secrets" section
|
||||
5. Add your variables there (like POSTHOG_API_KEY, POSTHOG_PROJECT_ID,
|
||||
POSTHOG_HOST,GITHUB_PAT, etc.)
|
||||
5. Add your Personal API Key from PostHog (phx_...) as POSTHOG_AUTH_HEADER secret with format: Bearer YOUR_API_KEY
|
||||
|
||||
These environment variables will then be securely stored and available for use in
|
||||
your Continue workflows.
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## PostHog GitHub Continuous AI Workflow Options
|
||||
|
||||
|
|
@ -107,7 +115,17 @@ your Continue workflows.
|
|||
optimized prompts, rules, and the PostHog MCP for more consistent results.
|
||||
</Card>
|
||||
|
||||
After completing **Step 1** below, you have two paths to get started:
|
||||
<Info>
|
||||
**How PostHog MCP Works**:
|
||||
- Your API key is tied to your PostHog account and
|
||||
organization
|
||||
- It automatically uses your default project (no project ID
|
||||
needed)
|
||||
- If you have multiple projects, use `mcp__posthog__switch-project` to
|
||||
change
|
||||
- The MCP connects via `https://mcp.posthog.com/sse` using your account context.
|
||||
|
||||
</Info>
|
||||
|
||||
<Tabs>
|
||||
<Tab title="⚡ Quick Start (Recommended)">
|
||||
|
|
@ -115,20 +133,16 @@ After completing **Step 1** below, you have two paths to get started:
|
|||
|
||||
<Steps>
|
||||
<Step title="Add the Pre-Built Agent">
|
||||
Visit the [PostHog GitHub Continuous AI Agent](https://hub.continue.dev/continuedev/awesome-models-posthog-gh) on Continue Hub and click **"Install Agent"**
|
||||
Visit the [PostHog GitHub Continuous AI Agent](https://hub.continue.dev/continuedev/awesome-models-posthog-gh) on Continue Hub and click **"Install Agent"** or run:
|
||||
|
||||
```bash
|
||||
cn --config continuedev/awesome-models-posthog-gh
|
||||
```
|
||||
|
||||
This agent includes:
|
||||
- **Optimized prompts** for PostHog analysis and GitHub issue creation
|
||||
- **Built-in rules** for consistent formatting and error handling
|
||||
- **PostHog MCP** for more reliable API interactions
|
||||
</Step>
|
||||
|
||||
<Step title="Verify Your Secrets">
|
||||
The agent uses these Hub resources automatically:
|
||||
- **Environment Variables**: [bekahhw/env-vars](https://hub.continue.dev/bekahhw/env-vars)
|
||||
- **Analysis Rules**: [bekah-hawrot-weigel/posthog-github-continuous-ai-rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules)
|
||||
- **Analysis Prompt**: [continuedev/posthog-analysis](https://hub.continue.dev/continuedev/posthog-analysis)
|
||||
- **Issue Creation Prompt**: [continuedev/github-issues](https://hub.continue.dev/continuedev/github-issues)
|
||||
- **Optimized prompts** for [PostHog analysis](https://hub.continue.dev/continuedev/posthog-analysis) and [GitHub issue creation](https://hub.continue.dev/continuedev/posthog-github-issues)
|
||||
- **[Built-in rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules)** for consistent formatting and error handling
|
||||
- **[PostHog MCP](https://hub.continue.dev/posthog/posthog-mcp)** for more reliable API interactions
|
||||
</Step>
|
||||
|
||||
<Step title="Run the Analysis">
|
||||
|
|
@ -148,72 +162,41 @@ After completing **Step 1** below, you have two paths to get started:
|
|||
</Tab>
|
||||
|
||||
<Tab title="🛠️ Manual Setup">
|
||||
**Perfect for:** Learning the process and customizing prompts.
|
||||
<Steps>
|
||||
<Step title="Add PostHog MCP to Continue CLI">
|
||||
First, install the [PostHog MCP](https://hub.continue.dev/posthog/posthog-mcp) or run:
|
||||
```bash
|
||||
npx -y mcp-remote@latest https://mcp.posthog.com/sse --header Authorization:${{ secrets.continuedev/awesome-models-posthog-gh/posthog/posthog-mcp/POSTHOG_AUTH_HEADER }}
|
||||
```
|
||||
</Step>
|
||||
<Step title="Add PostHog + GitHub Analysis Rules">
|
||||
In the Continue Hub, add the [PostHog GitHub Continuous AI Rules](https://hub.continue.dev/bekah-hawrot-weigel/posthog-github-continuous-ai-rules) to your account for better formatting and error handling.
|
||||
</Step>
|
||||
<Step title="Create Your Custom Prompts">
|
||||
Use this prompt with Continue CLI to analyze PostHog data and create GitHub issues:
|
||||
|
||||
Now you'll use Continue CLI to fetch PostHog session data and analyze it for UX issues. Continue CLI handles all the API calls and analysis automatically.
|
||||
```bash
|
||||
|
||||
### Run the PostHog Analysis
|
||||
|
||||
Use this prompt with Continue CLI to fetch and analyze your PostHog sessions:
|
||||
|
||||
```bash
|
||||
cn -p "I need you to help me analyze PostHog session recordings to identify UX issues. Please:
|
||||
|
||||
1. First, fetch session recordings from PostHog using these details:
|
||||
- Use the POSTHOG_API_KEY, POSTHOG_PROJECT_ID, and POSTHOG_HOST from my secrets
|
||||
- API endpoint: {POSTHOG_HOST}/api/projects/{POSTHOG_PROJECT_ID}/session_recordings/?limit=20
|
||||
- Include Authorization header: 'Bearer {POSTHOG_API_KEY}'
|
||||
|
||||
2. Filter the sessions to find problematic ones with either:
|
||||
- console_error_count > 0 (JavaScript errors)
|
||||
- recording_duration > 300 (sessions longer than 5 minutes)
|
||||
|
||||
3. Analyze the filtered sessions and create exactly 3 GitHub issues for the most critical UX problems.
|
||||
|
||||
4. Format each issue like this:
|
||||
### 1. **Issue Title Here**
|
||||
**Problem**: One sentence describing the user problem
|
||||
**Technical Causes**: Brief technical explanation
|
||||
**Affected Pages**: List the URLs
|
||||
**Recommended Fix**:
|
||||
- Specific action item 1
|
||||
- Specific action item 2
|
||||
**Priority**: **HIGH** or **MEDIUM** or **LOW**
|
||||
**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions')
|
||||
|
||||
Please make the API call, analyze the data, and provide the 3 formatted issues. Base all recommendations on actual patterns in the session data."
|
||||
```
|
||||
|
||||
### Create GitHub Issues from PostHog Analysis
|
||||
|
||||
Now use Continue CLI to create GitHub issues from your analysis results:
|
||||
|
||||
```bash
|
||||
cn -p "I have analyzed PostHog session data and identified UX issues. Now I need you to create GitHub issues using the GitHub API.
|
||||
|
||||
Use these details from my secrets:
|
||||
- GITHUB_PAT: My GitHub Personal Access Token
|
||||
- Repository: Extract from git remote or ask me to specify
|
||||
|
||||
For each issue in my analysis:
|
||||
1. Parse the issue title, body content, and priority level
|
||||
2. Create a GitHub issue via API POST to: https://api.github.com/repos/{owner}/{repo}/issues
|
||||
3. Use these headers:
|
||||
- Authorization: token {GITHUB_PAT}
|
||||
- Accept: application/vnd.github.v3+json
|
||||
- Content-Type: application/json
|
||||
4. Set labels based on priority:
|
||||
- HIGH: [\"bug\", \"high-priority\", \"user-experience\", \"automated\"]
|
||||
- MEDIUM: [\"enhancement\", \"medium-priority\", \"user-experience\", \"automated\"]
|
||||
- LOW: [\"low-priority\", \"user-experience\", \"automated\"]
|
||||
5. Format the issue title as: \"🔍 UX Issue: {original title}\"
|
||||
|
||||
Please create the GitHub issues and confirm they were successfully created with issue numbers and URLs.
|
||||
"
|
||||
```
|
||||
# In cn TUI mode:
|
||||
"Create GitHub issues from the PostHog analysis using gh CLI:
|
||||
- For each issue, run: gh issue create --title '🔍 UX Issue: [title]' --body '[details]'
|
||||
- Add labels: --label 'bug,user-experience,automated'
|
||||
- Set priority labels (high/medium/low)
|
||||
- Include session data and technical details in the body
|
||||
Execute the commands and confirm each issue was created with URL."
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
<Info>
|
||||
|
||||
**Why GitHub CLI over GitHub MCP**: While GitHub MCP is available, it can be
|
||||
token-expensive to run. The `gh` CLI is more efficient, requires no API tokens
|
||||
(authenticated via `gh auth login`), and provides a cleaner command-line
|
||||
experience. GitHub MCP remains an option if you prefer full MCP integration.
|
||||
</Info>
|
||||
|
||||
<Accordion title="Agent Requirements">
|
||||
To use the pre-built agent, you need either:
|
||||
|
|
@ -492,16 +475,17 @@ Consider enhancing your workflow with these advanced Continue CLI prompts:
|
|||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Performance Analysis" icon="chart-line">
|
||||
"Analyze PostHog performance metrics alongside session recordings to
|
||||
identify slow page loads affecting user experience"
|
||||
"Analyze [PostHog performance
|
||||
metrics](https://posthog.com/docs/web-analytics) alongside session
|
||||
recordings to identify slow page loads affecting user experience"
|
||||
</Card>
|
||||
<Card title="Error Correlation" icon="bug">
|
||||
"Cross-reference JavaScript console errors with user actions to identify the
|
||||
root cause of UX issues"
|
||||
</Card>
|
||||
<Card title="Feature Flag Analysis" icon="flag">
|
||||
"Analyze how PostHog feature flags impact user behavior in session
|
||||
recordings"
|
||||
"Analyze how [PostHog feature flags](https://posthog.com/docs/feature-flags)
|
||||
impact user behavior in session recordings"
|
||||
</Card>
|
||||
<Card title="Custom Slack Alerts" icon="slack">
|
||||
"Create Slack alerts when critical UX issues are detected in PostHog
|
||||
|
|
@ -511,7 +495,19 @@ Consider enhancing your workflow with these advanced Continue CLI prompts:
|
|||
|
||||
## Next Steps
|
||||
|
||||
1. **Monitor your first issues** - Review the GitHub issues created and implement fixes
|
||||
2. **Measure impact** - Track how resolved issues improve PostHog metrics
|
||||
3. **Refine prompts** - Adjust the Continue CLI prompts based on issue quality
|
||||
4. **Scale the system** - Add more data sources or create specialized analysis workflows
|
||||
- Consider [GitHub MCP](https://hub.continue.dev/github/github-mcp) as an alternative (note: can be token-expensive)
|
||||
- Configure [Slack MCP](https://hub.continue.dev/slack/slack-mcp) for alerts
|
||||
- Set up [PostHog performance monitoring](https://posthog.com/docs/web-analytics)
|
||||
- Join the [Continue Discord](https://discord.gg/continue) for support
|
||||
|
||||
## Resources
|
||||
|
||||
- [PostHog API Documentation](https://posthog.com/docs/api)
|
||||
- [PostHog MCP Documentation](https://posthog.com/docs/model-context-protocol)
|
||||
- [PostHog Session Replay](https://posthog.com/docs/session-replay)
|
||||
- [PostHog Feature Flags](https://posthog.com/docs/feature-flags)
|
||||
- [PostHog Error Tracking](https://posthog.com/docs/error-tracking)
|
||||
- [GitHub CLI Documentation](https://cli.github.com/)
|
||||
- [GitHub MCP on Continue Hub](https://hub.continue.dev/github/github-mcp) (alternative option)
|
||||
- [Continue CLI Guide](https://docs.continue.dev/guides/cli)
|
||||
- [Continuous AI Best Practices](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)
|
||||
|
|
|
|||
|
|
@ -20,9 +20,74 @@ Before starting, ensure you have:
|
|||
- [Snyk account](https://snyk.io/) (free tier works)
|
||||
- A local project to scan for vulnerabilities
|
||||
|
||||
For all options, first:
|
||||
<Steps>
|
||||
<Step title="Install Continue CLI">
|
||||
```bash
|
||||
npm i -g @continuedev/cli
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="Add Your Project to Snyk">
|
||||
|
||||
1. Sign up for a Snyk account at [snyk.io](https://snyk.io/)
|
||||
2. Create a new project in Snyk by importing your code repository (Git
|
||||
provider or manual upload)
|
||||
</Step>
|
||||
</Steps>
|
||||
<Warning>
|
||||
To use agents in headless mode, you need a [Continue API key](https://hub.continue.dev/settings/api-keys).
|
||||
</Warning>
|
||||
|
||||
## Snyk Continuous AI Workflow Options
|
||||
|
||||
<Card title="🚀 Fastest Path to Success" icon="zap">
|
||||
Skip the manual setup and use our pre-built Snyk Continuous AI agent that includes
|
||||
the Snyk MCP and optimized security scanning workflows for more consistent results.
|
||||
</Card>
|
||||
|
||||
|
||||
After ensuring you meet the **Prerequisites** above, you have two paths to get started:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="⚡ Quick Start (Recommended)">
|
||||
<Steps>
|
||||
<Step title="Load the Pre-Built Agent">
|
||||
Navigate to your project directory and run:
|
||||
```bash
|
||||
cn --config continuedev/snyk-continuous-ai
|
||||
```
|
||||
|
||||
This agent includes:
|
||||
- **Snyk MCP** pre-configured and ready to use
|
||||
- **Security-focused rules** for best practices
|
||||
</Step>
|
||||
|
||||
<Step title="Run Your First Security Scan">
|
||||
Start with a comprehensive security scan:
|
||||
```bash
|
||||
# TUI mode
|
||||
cn -p "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity."
|
||||
```
|
||||
|
||||
That's it! The agent handles everything automatically.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Info>
|
||||
**Why Use the Agent?** The pre-built agent provides consistent security scanning workflows and handles MCP configuration automatically, making it easier to get started with AI-powered security scanning.
|
||||
</Info>
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="🛠️ Manual Setup">
|
||||
<Steps>
|
||||
<Step title="Create a New Agent via the Continue Hub">
|
||||
Go to the [Continue Hub](https://hub.continue.dev) and [create a new agent](https://hub.continue.dev/new?type=agent).
|
||||
</Step>
|
||||
|
||||
<Step title="Connect Snyk MCP via Continue Hub">
|
||||
Visit the [Snyk MCP on Continue Hub](https://hub.continue.dev/snyk/snyk-mcp) and click **Install** to add it to your Continue account.
|
||||
Visit the [Snyk MCP on Continue Hub](https://hub.continue.dev/snyk/snyk-mcp) and click **Install** to add it to the agent you created in the step above.
|
||||
|
||||
This will add Snyk MCP to your agent's available tools. The Hub listing automatically configures the MCP command:
|
||||
```bash
|
||||
|
|
@ -31,7 +96,7 @@ Before starting, ensure you have:
|
|||
|
||||
<Tip>
|
||||
**Alternative installation methods:**
|
||||
1. **Quick CLI install**: `cn -p --mcp snyk/snyk-mcp`
|
||||
1. **Quick CLI install**: `cn --mcp snyk/snyk-mcp`
|
||||
2. **Manual configuration**: Add the MCP to your `~/.continue/config.json` under the `mcpServers` section
|
||||
|
||||
Once installed, Snyk MCP tools become available to your Continue agent for all prompts.
|
||||
|
|
@ -59,35 +124,42 @@ Before starting, ensure you have:
|
|||
|
||||
</Step>
|
||||
|
||||
<Step title="Authenticate with Snyk">
|
||||
Use this prompt with your Continue agent to set up authentication:
|
||||
|
||||
```
|
||||
Check Snyk auth status. If not authenticated, authenticate me and confirm my org context.
|
||||
```
|
||||
|
||||
Or use the Continue CLI:
|
||||
<Step title="Run Your First Security Scan">
|
||||
Start with a comprehensive security scan:
|
||||
```bash
|
||||
cn -p "Check Snyk auth status. If not authenticated, authenticate me and confirm my org context."
|
||||
# TUI mode
|
||||
cn "Run a complete security scan on this project including code vulnerabilities, dependencies, and any IaC files. Summarize findings by severity."
|
||||
```
|
||||
|
||||
<Tip>
|
||||
A browser window will open for Snyk login. After authenticating, approve
|
||||
the request to trust your project folder when prompted.
|
||||
</Tip>
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Accordion title="Agent Requirements">
|
||||
To use the pre-built agent, you need either:
|
||||
- **Continue CLI Pro Plan** with the models add-on, OR
|
||||
- **Your own API keys** added to Continue Hub secrets (same as manual setup)
|
||||
|
||||
The agent will automatically detect and use your configuration along with the pre-configured Snyk MCP for security scanning operations.
|
||||
|
||||
</Accordion>
|
||||
|
||||
---
|
||||
|
||||
## Security Scanning Recipes
|
||||
|
||||
Now you can use natural language prompts to run comprehensive security scans. The Continue agent automatically calls the appropriate Snyk MCP tools.
|
||||
|
||||
<Info>
|
||||
You can add prompts to your agent's configuration for easy access in future sessions. Go to your agent in the [Continue Hub](https://hub.continue.dev), click **Edit**, and add prompts under the **Prompts** section.
|
||||
</Info>
|
||||
|
||||
<Info>
|
||||
**Where to run these workflows:**
|
||||
- **IDE Extensions**: Use Continue in VS Code, JetBrains, or other supported IDEs
|
||||
- **Terminal (TUI mode)**: Run `cn` to enter interactive mode, then type your prompts
|
||||
- **CLI (headless mode)**: Use `cn -p "your prompt"` for one-off commands
|
||||
- **CLI (headless mode)**: Use `cn -p "your prompt"` for headless commands
|
||||
|
||||
**Test in Plan Mode First**: Before running security scans that might make
|
||||
changes, test your prompts in plan mode (see the [Plan Mode
|
||||
|
|
@ -101,14 +173,14 @@ Now you can use natural language prompts to run comprehensive security scans. Th
|
|||
<Card title="Static Application Security Testing" icon="code">
|
||||
Scan your source code for security vulnerabilities and code quality issues.
|
||||
|
||||
**Example prompt:**
|
||||
**TUI Mode Prompt:**
|
||||
```
|
||||
Run a Snyk Code scan on this repo with severity threshold medium.
|
||||
Summarize issues with file:line. Propose minimal diffs for the top 3
|
||||
and rerun to verify.
|
||||
```
|
||||
|
||||
**Using Continue CLI:**
|
||||
**Headless Mode Prompt:**
|
||||
```bash
|
||||
cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summarize issues with file:line. Propose minimal diffs for the top 3 and rerun to verify."
|
||||
```
|
||||
|
|
@ -120,14 +192,14 @@ cn -p "Run a Snyk Code scan on this repo with severity threshold medium. Summari
|
|||
<Card title="Software Composition Analysis" icon="cube">
|
||||
Check open source dependencies for known vulnerabilities.
|
||||
|
||||
**Example prompt:**
|
||||
**TUI Mode Prompt:**
|
||||
```
|
||||
Run Snyk Open Source on this repo (include dev deps).
|
||||
Summarize vulnerable paths and propose a minimal-risk upgrade plan.
|
||||
Re-test after the plan (dry run).
|
||||
```
|
||||
|
||||
**Using Continue CLI:**
|
||||
**Headless Mode Prompt:**
|
||||
```bash
|
||||
cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerable paths and propose a minimal-risk upgrade plan. Re-test after the plan (dry run)."
|
||||
```
|
||||
|
|
@ -139,13 +211,13 @@ cn -p "Run Snyk Open Source on this repo (include dev deps). Summarize vulnerabl
|
|||
<Card title="IaC Security" icon="cloud">
|
||||
Scan Terraform, CloudFormation, and Kubernetes configs for misconfigurations.
|
||||
|
||||
**Example prompt:**
|
||||
**TUI Mode Prompt:**
|
||||
```
|
||||
Scan ./infra with Snyk IaC. Report high/critical misconfigs
|
||||
with exact files/lines. Provide code changes and re-scan to confirm.
|
||||
```
|
||||
|
||||
**Using Continue CLI:**
|
||||
**Headless Mode Prompt:**
|
||||
```bash
|
||||
cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact files/lines. Provide code changes and re-scan to confirm."
|
||||
```
|
||||
|
|
@ -157,14 +229,14 @@ cn -p "Scan ./infra with Snyk IaC. Report high/critical misconfigs with exact fi
|
|||
<Card title="Container Security" icon="docker">
|
||||
Analyze Docker images for vulnerabilities in base images and packages.
|
||||
|
||||
**Example prompt:**
|
||||
**TUI Mode Prompt:**
|
||||
```
|
||||
Scan image my-api:latest. Exclude base image vulns.
|
||||
Print dependency tree. Recommend a safer base image or upgrades.
|
||||
Re-test after the change (dry run).
|
||||
```
|
||||
|
||||
**Using Continue CLI:**
|
||||
**Headless Mode Prompt:**
|
||||
```bash
|
||||
cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree. Recommend a safer base image or upgrades. Re-test after the change (dry run)."
|
||||
```
|
||||
|
|
@ -176,13 +248,13 @@ cn -p "Scan image my-api:latest. Exclude base image vulns. Print dependency tree
|
|||
<Card title="Changed Files Only" icon="code-branch">
|
||||
Focus scanning on modified files to catch issues before merging.
|
||||
|
||||
**Example prompt:**
|
||||
**TUI Mode Prompt:**
|
||||
```
|
||||
Scan only files changed since origin/main with Snyk Code.
|
||||
Block if new high issues would be introduced. Show deltas.
|
||||
```
|
||||
|
||||
**Using Continue CLI:**
|
||||
**Headless Mode Prompt:**
|
||||
```bash
|
||||
cn -p "Scan only files changed since origin/main with Snyk Code. Block if new high issues would be introduced. Show deltas."
|
||||
```
|
||||
|
|
@ -194,12 +266,12 @@ cn -p "Scan only files changed since origin/main with Snyk Code. Block if new hi
|
|||
<Card title="Snyk Learn Integration" icon="graduation-cap">
|
||||
Access security education resources based on identified vulnerabilities ([CWE](https://cwe.mitre.org/)).
|
||||
|
||||
**Example prompt:**
|
||||
**TUI Mode Prompt:**
|
||||
```
|
||||
Open Snyk Learn lessons related to the top CWE(s) from this scan.
|
||||
```
|
||||
|
||||
**Using Continue CLI:**
|
||||
**Headless Mode Prompt:**
|
||||
```bash
|
||||
cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan."
|
||||
```
|
||||
|
|
@ -208,7 +280,7 @@ cn -p "Open Snyk Learn lessons related to the top CWE(s) from this scan."
|
|||
|
||||
## Continuous Security with GitHub Actions
|
||||
|
||||
This example demonstrates a **Continuous AI workflow** where security scanning runs automatically in your CI/CD pipeline using Continue CLI in headless mode (`cn -p`) with Snyk MCP.
|
||||
This example demonstrates a **Continuous AI workflow** where security scanning runs automatically in your CI/CD pipeline Headless Mode Prompt in headless mode (`cn -p`) with Snyk MCP.
|
||||
|
||||
### Add GitHub Secrets
|
||||
|
||||
|
|
@ -249,8 +321,10 @@ jobs:
|
|||
echo "✅ Continue CLI installed"
|
||||
|
||||
- name: Authenticate Continue CLI
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
run: |
|
||||
cn auth login --api-key "${{ secrets.CONTINUE_API_KEY }}"
|
||||
cn auth login --api-key "$CONTINUE_API_KEY"
|
||||
echo "✅ Continue CLI authenticated"
|
||||
|
||||
- name: Run Security Scans
|
||||
|
|
|
|||
|
|
@ -8,7 +8,8 @@ sidebarTitle: "Create an AI Agent"
|
|||
|
||||
To create an agent from scratch, select “New agent” in the top bar.
|
||||
|
||||

|
||||

|
||||
|
||||
|
||||
Choose a name, slug, description, and icon for your agent.
|
||||
|
||||
|
|
@ -24,7 +25,7 @@ You can also create an agent by remixing an existing one. This is useful if you
|
|||
|
||||
By clicking the “remix” button, you’ll be taken to the “Create a remix” page.
|
||||
|
||||

|
||||

|
||||
|
||||
Once here, you’ll be able to
|
||||
|
||||
|
|
|
|||
|
|
@ -1,34 +1,31 @@
|
|||
---
|
||||
title: "Blocks: Models, Rules, Prompts, and MCP servers"
|
||||
title: "Models, Rules, Prompts, and MCP servers"
|
||||
sideBarTitle: "Block Types"
|
||||
description: "Explore the different types of reusable blocks in Continue Hub including models, MCP servers, rules, and prompts"
|
||||
---
|
||||
|
||||
## Models
|
||||
|
||||
Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/explore/models).
|
||||
|
||||
Continue supports [many model providers](/customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. Read more about roles [here](/customize/model-roles). View [`models`](/reference#models) in the YAML Reference for more details.
|
||||
Models are blocks that let you specify Large Language Models (LLMs) and other deep learning models to be used for various roles in the open-source IDE extension like Chat, Autocomplete, Edit, Embed, Rerank, etc. You can explore available models on [the hub](https://hub.continue.dev/?type=models).
|
||||
|
||||
Continue supports [many model providers](/customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have one or more of the following roles depending on its capabilities, including `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`.
|
||||
|
||||
Read more about roles [here](/customize/model-roles) and view [`models`](/reference#models) in the YAML Reference for more details.
|
||||
|
||||
## MCP Servers
|
||||
|
||||
Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks. [Explore MCP Servers](https://hub.continue.dev/explore/mcp) on the hub.
|
||||
Model Context Protocol (MCP) is a standard way of building and sharing tools for language models. MCP Servers can be defined in `mcpServers` blocks.
|
||||
|
||||
Learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
|
||||
[Explore MCP Servers](https://hub.continue.dev/?type=mcpServers) on the Hub, learn more in the [MCP deep dive](/customize/deep-dives/mcp), and view [`mcpServers`](/reference#mcpservers) in the YAML Reference for more details.
|
||||
|
||||
## Rules
|
||||
|
||||
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.
|
||||
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, Plan, and Agent requests.
|
||||
|
||||
Learn more in the [rules deep dive](/customize/deep-dives/rules), and view [`rules`](/reference#rules) in the YAML Reference for more details.
|
||||
[Explore rules](https://hub.continue.dev/?type=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.
|
||||
|
||||
## Prompts
|
||||
|
||||
Prompts blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
|
||||
|
||||
Prompt blocks are pre-written, reusable prompts that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks. [Explore prompts](https://hub.continue.dev/explore/prompts) on the hub.
|
||||
Prompt blocks have the same syntax as [prompt files](/customize/deep-dives/prompts). The `config.yaml` spec for `prompts` can be found [here](/reference#prompts).
|
||||
|
||||
Prompts blocks are pre-written, reusable instructions that are used to kick off a task. They are especially useful as context for repetitive and/or complex tasks.
|
||||
|
||||
[Explore prompts](https://hub.continue.dev/?type=prompts) on the Hub, learn more in the [prompts deep dive](/customize/deep-dives/prompts), and view [`prompts`](/reference#prompts) in the YAML Reference for more details.
|
||||
|
|
@ -10,6 +10,6 @@ Continue Hub provides a centralized platform for managing the essential building
|
|||
- **[Models](/hub/blocks/block-types#models)**: Discover and configure models from various providers
|
||||
- **[MCP Tools](/hub/blocks/block-types#mcp-servers)**: Access and integrate Model Context Protocol tools to retrieve real-time data and take action
|
||||
- **[Rules](/hub/blocks/block-types#rules)**: Define custom guidelines for your custom AI coding agent to follow
|
||||
- **[Prompts](/hub/blocks/block-types#prompts)**: Create and share reusable prompts that kickoff your custom AI coding agent
|
||||
- **[Prompts](/hub/blocks/block-types#prompts)**: Create and share reusable instructions that kickoff your agent
|
||||
|
||||
Continue Hub also makes it easy for engineering leaders to centrally [configure](/hub/secrets/secret-types) and [govern](/hub/governance/org-permissions) these resources for their organization.
|
||||
|
|
@ -25,7 +25,7 @@ Explore assistants created by the community for specific use cases and workflows
|
|||
|
||||
Learn how to discover, install, and use community-created assistants in your projects.
|
||||
|
||||
[Learn About Agents →](/hub/assistants/intro)
|
||||
[Learn About Agents →](/hub/agents/intro)
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
Before Width: | Height: | Size: 4.6 MiB After Width: | Height: | Size: 6.8 MiB |
BIN
docs/images/hub/agent-remix-button.png
Normal file
|
After Width: | Height: | Size: 166 KiB |
|
Before Width: | Height: | Size: 318 KiB |
|
Before Width: | Height: | Size: 318 KiB |
|
Before Width: | Height: | Size: 318 KiB |
|
Before Width: | Height: | Size: 120 KiB |
BIN
docs/images/hub/new-agent-button.png
Normal file
|
After Width: | Height: | Size: 81 KiB |
143
docs/index.mdx
|
|
@ -1,55 +1,148 @@
|
|||
---
|
||||
title: "Introduction"
|
||||
title: "Welcome to Continue"
|
||||
icon: book-open
|
||||
description: "Continue is an open source platform for building AI-powered coding assistants with customizable components for chat, autocomplete, edit, and agent workflows in VS Code and JetBrains IDEs"
|
||||
description: "Practice Continuous AI with an open-source CLI, open-source IDE extensions, and a Hub for custom AI coding agents"
|
||||
---
|
||||
|
||||
<Frame>
|
||||
<img src="/images/intro-0c302b9c15b890c251b1ad04586c880f.png" />
|
||||
</Frame>
|
||||
|
||||
**Continue enables developers to ship faster with Continuous AI.**
|
||||
<Note>
|
||||
**Build faster with AI across your IDE, terminal, and CI/CD pipelines with
|
||||
Continue.**
|
||||
</Note>
|
||||
|
||||
**You can use Continue to build and run custom agents across your IDE, terminal, and CI.**
|
||||
## Continue CLI
|
||||
|
||||
1. Get started with Continue in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
|
||||
<Info>Terminal-native AI coding assistance with TUI and headless modes.</Info>
|
||||
|
||||
2. Try out [Continue CLI (cn)](https://docs.continue.dev/guides/cli) and give us feedback
|
||||
<CodeGroup>
|
||||
|
||||
3. Discover models, rules, and MCP tools on [Continue Hub](https://hub.continue.dev/)
|
||||
```bash npm
|
||||
npm install -g @continuedev/cli
|
||||
```
|
||||
|
||||
```bash yarn
|
||||
yarn global add @continuedev/cli
|
||||
```
|
||||
|
||||
```bash pnpm
|
||||
pnpm add -g @continuedev/cli
|
||||
```
|
||||
|
||||
</CodeGroup>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="Agent"
|
||||
icon="robot"
|
||||
href="/features/agent/quick-start"
|
||||
horizontal
|
||||
title="TUI Mode"
|
||||
icon="terminal"
|
||||
href="/cli/overview#tui-mode%3A-interactive-development"
|
||||
>
|
||||
to work on development tasks together with AI
|
||||
Interactive terminal interface for development workflows
|
||||
<br />
|
||||
<sub>• Automate builds & refactoring</sub>
|
||||
<br />
|
||||
<sub>• Pre-commit hooks & scripted fixes</sub>
|
||||
<br />
|
||||
<sub>• Terminal-first development</sub>
|
||||
</Card>
|
||||
<Card
|
||||
title="Chat"
|
||||
icon="messages"
|
||||
href="/features/chat/quick-start"
|
||||
horizontal
|
||||
title="Headless Mode"
|
||||
icon="server"
|
||||
href="/cli/overview#headless-mode%3A-production-automation"
|
||||
>
|
||||
to ask general questions and clarify code sections
|
||||
Automated AI coding for CI/CD and server environments
|
||||
<br />
|
||||
<sub>• Run in CI/CD pipelines</sub>
|
||||
<br />
|
||||
<sub>• Batch processing & bulk operations</sub>
|
||||
<br />
|
||||
<sub>• Server & container deployments</sub>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## IDE Extensions
|
||||
|
||||
<Info>
|
||||
**Complement your CLI workflow** - Rich editor integrations for interactive
|
||||
development.
|
||||
</Info>
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card
|
||||
title="VS Code"
|
||||
icon="code"
|
||||
href="https://marketplace.visualstudio.com/items?itemName=Continue.continue"
|
||||
>
|
||||
Install from VS Code Marketplace
|
||||
<br />
|
||||
<sub>Real-time coding assistance and refactoring</sub>
|
||||
</Card>
|
||||
<Card
|
||||
title="Edit"
|
||||
icon="pen-to-square"
|
||||
href="/features/edit/quick-start"
|
||||
horizontal
|
||||
title="JetBrains"
|
||||
icon="jet-fighter"
|
||||
href="https://plugins.jetbrains.com/plugin/22707-continue-extension"
|
||||
>
|
||||
to modify a code section without leaving your current file
|
||||
Install from JetBrains Plugin Repository
|
||||
<br />
|
||||
<sub>Autocomplete and multi-file edits</sub>
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Core Features
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Agent" icon="robot" href="/features/agent/quick-start">
|
||||
Multi-step workflows and complex task automation
|
||||
</Card>
|
||||
<Card title="Chat" icon="messages" href="/features/chat/quick-start">
|
||||
Ask questions and explore your codebase
|
||||
</Card>
|
||||
<Card title="Edit" icon="pen-to-square" href="/features/edit/quick-start">
|
||||
In-place code editing without breaking flow
|
||||
</Card>
|
||||
<Card
|
||||
title="Autocomplete"
|
||||
icon="sparkles"
|
||||
href="/features/autocomplete/quick-start"
|
||||
horizontal
|
||||
>
|
||||
to receive inline code suggestions as you type
|
||||
Inline AI suggestions as you type
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Configuration
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Models" icon="brain" href="/customization/models">
|
||||
Connect your preferred AI models
|
||||
</Card>
|
||||
<Card title="Rules" icon="shield" href="/customization/rules">
|
||||
Configure AI behavior and constraints
|
||||
</Card>
|
||||
<Card title="MCPs" icon="wrench" href="/customization/mcp-tools">
|
||||
Extend functionality with MCP tools
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Resources
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Continue Hub" icon="globe" href="https://hub.continue.dev/">
|
||||
Community models, rules, and tools
|
||||
</Card>
|
||||
<Card
|
||||
title="GitHub Discussions"
|
||||
icon="comments"
|
||||
href="https://github.com/continuedev/continue/discussions"
|
||||
>
|
||||
Get help from the community
|
||||
</Card>
|
||||
<Card
|
||||
title="CLI Examples"
|
||||
icon="code-branch"
|
||||
href="/guides/overview#continuous-ai"
|
||||
>
|
||||
TUI and headless workflow examples
|
||||
</Card>
|
||||
|
||||
</CardGroup>
|
||||
|
|
|
|||
|
|
@ -1,136 +1,23 @@
|
|||
---
|
||||
title: "config.yaml Reference"
|
||||
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."
|
||||
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 YAML configuration."
|
||||
---
|
||||
|
||||
## Introduction
|
||||
|
||||
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 Agents are defined using the `config.yaml` specification.
|
||||
|
||||
- [Continue Hub](https://hub.continue.dev/explore/agents) - YAML is stored on the hub and automatically synced to the extension
|
||||
**Agents** are composed of models, rules, and tools (MCP servers).
|
||||
|
||||
- Locally
|
||||
- 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
|
||||
<Columns cols={2}>
|
||||
<Card title="Configuring Models, Rules, and Tools" icon="cube" href="/guides/configuring-models-rules-tools">
|
||||
Learn how to work with Continue's configuration system, including using hub models, rules, and tools, creating local configurations, and organizing your setup.
|
||||
</Card>
|
||||
|
||||
<Info>
|
||||
Config YAML replaces `config.json`, which is deprecated. View the **[Migration
|
||||
Guide](/reference/yaml-migration)**.
|
||||
</Info>
|
||||
|
||||
An agent is made up of:
|
||||
|
||||
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 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 agents can be found on the [Continue Hub](https://hub.continue.dev).
|
||||
|
||||
Agents can either explicitly define blocks - see [Properties](#properties) below - or import and configure existing hub blocks.
|
||||
|
||||
### Using Blocks
|
||||
|
||||
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 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 agent imports an Anthropic model and defines an Ollama DeepSeek one.
|
||||
|
||||
Agent models section
|
||||
|
||||
```yaml
|
||||
name: Team Agent
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- uses: anthropic/claude-3.5-sonnet # an imported model block
|
||||
- model: deepseek-reasoner # an explicit model block
|
||||
provider: ollama
|
||||
```
|
||||
|
||||
### 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 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:
|
||||
|
||||
Agents:
|
||||
|
||||
- `.continue/agents` - for agents
|
||||
|
||||
Blocks:
|
||||
|
||||
- `.continue/rules` - for rules
|
||||
- `.continue/models` - for models
|
||||
- `.continue/prompts` - for prompts
|
||||
- `.continue/context` - for context providers
|
||||
- `.continue/docs` - for docs
|
||||
- `.continue/data` - for data
|
||||
- `.continue/mcpServers` - for MCP Servers
|
||||
|
||||
You can find many examples of each of these block types on the [Continue Explore Page](https://hub.continue.dev/explore/models)
|
||||
|
||||
<Info>
|
||||
Local blocks utilizing mustache notation for secrets (`${{ secrets.SECRET_NAME }}`) can read secret values:
|
||||
|
||||
- globally, from a `.env` located in the global `.continue` folder (`~/.continue/.env`)
|
||||
- per-workspace, from a `.env` file located at the root of the current workspace.
|
||||
|
||||
</Info>
|
||||
|
||||
### Inputs
|
||||
|
||||
Blocks can be passed user inputs, including hub secrets and raw text values. To create a block that has an input, use mustache templating as follows:
|
||||
|
||||
```yaml title="config.yaml"
|
||||
name: myprofile/custom-model
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- name: My Favorite Model
|
||||
provider: anthropic
|
||||
apiKey: ${{ inputs.ANTHROPIC_API_KEY }}
|
||||
defaultCompletionOptions:
|
||||
temperature: ${{ inputs.TEMP }}
|
||||
```
|
||||
|
||||
Which can then be imported like this:
|
||||
|
||||
```yaml title="config.yaml"
|
||||
name: myprofile/custom-agent
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- uses: myprofile/custom-model
|
||||
with:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }}
|
||||
TEMP: 0.9
|
||||
```
|
||||
|
||||
Note that hub secrets can be passed as inputs, using a similar mustache format: `secrets.SECRET_NAME`.
|
||||
|
||||
### Overrides
|
||||
|
||||
Block properties can be also be directly overriden using `override`. For example:
|
||||
|
||||
```yaml title="config.yaml"
|
||||
name: myprofile/custom-agent
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
models:
|
||||
- uses: myprofile/custom-model
|
||||
with:
|
||||
ANTHROPIC_API_KEY: ${{ secrets.MY_ANTHROPIC_API_KEY }}
|
||||
TEMP: 0.9
|
||||
override:
|
||||
roles:
|
||||
- chat
|
||||
```
|
||||
<Card title="Understanding Agents" icon="robot" href="/guides/understanding-agents">
|
||||
Learn how to build and configure agents, understand their capabilities, and customize them for your development workflow.
|
||||
</Card>
|
||||
</Columns>
|
||||
|
||||
## Properties
|
||||
|
||||
|
|
@ -326,47 +213,55 @@ context:
|
|||
|
||||
### `rules`
|
||||
|
||||
List of rules that the LLM should follow. These are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests. See the [rules deep dive](/customize/deep-dives/rules) for details.
|
||||
Rules are concatenated into the system message for all [Agent](/features/agent/quick-start), [Chat](/features/chat/quick-start), and [Edit](/features/edit/quick-start) requests.
|
||||
|
||||
Explicit rules can either be simple text or an object with the following properties:
|
||||
Confiugration example:
|
||||
|
||||
- `name` (**required**): A display name/title for the rule
|
||||
- `rule` (**required**): The text content of the rule
|
||||
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
|
||||
|
||||
```yaml title="config.yaml"l
|
||||
```yaml title="config.yaml"
|
||||
rules:
|
||||
- Always annotate Python functions with their parameter and return types
|
||||
- name: TypeScript best practices
|
||||
rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly.
|
||||
globs: "**/*.{ts,tsx}"
|
||||
- name: TypeScript test patterns
|
||||
rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking.
|
||||
globs:
|
||||
- "src/**/*.test.ts"
|
||||
- "tests/**/*.ts"
|
||||
- uses: myprofile/my-mood-setter
|
||||
with:
|
||||
TONE: concise
|
||||
- uses: sanity/sanity-opinionated # rules file stored on Continue Hub
|
||||
- uses: file://user/Desktop/rules.md # rules file stored on local computer
|
||||
```
|
||||
|
||||
Rules file example:
|
||||
|
||||
```md title="rules.md"
|
||||
---
|
||||
name: Pirate rule
|
||||
---
|
||||
|
||||
Talk like a pirate
|
||||
```
|
||||
|
||||
See the [rules deep dive](/customize/deep-dives/rules) for more details.
|
||||
|
||||
---
|
||||
|
||||
### `prompts`
|
||||
|
||||
A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text.
|
||||
Prompts can be invoked with a <kbd>/</kbd> command.
|
||||
|
||||
Configuration example:
|
||||
|
||||
```yaml title="config.yaml"
|
||||
prompts:
|
||||
- name: check
|
||||
description: Check for mistakes in my code
|
||||
prompt: |
|
||||
Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:
|
||||
- Syntax errors
|
||||
- Logic errors
|
||||
- Security vulnerabilities
|
||||
- uses: supabase/create-functions # prompts file stored on Continue Hub
|
||||
- uses: file://user/Desktop/prompts.md # prompts file stored on local computer
|
||||
```
|
||||
|
||||
Prompts file example:
|
||||
|
||||
```md title="prompts.md"
|
||||
---
|
||||
name: Make pirate comments
|
||||
invokable: true
|
||||
---
|
||||
|
||||
Rewrite all comments in the active file to talk like a pirate
|
||||
```
|
||||
|
||||
See the [prompts deep dive](/customize/deep-dives/prompts) for more details.
|
||||
|
||||
---
|
||||
|
||||
### `docs`
|
||||
|
|
@ -402,8 +297,8 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
|
|||
- `args`: An optional array of arguments for the command.
|
||||
- `env`: An optional map of environment variables for the server process.
|
||||
- `cwd`: An optional working directory to run the command in. Can be absolute or relative path.
|
||||
- `connectionTimeout`: An optional connection timeout number to the server in milliseconds.
|
||||
- `requestOptions`: Optional request options for `sse` and `streamable-http` servers. Same format as [model requestOptions](#models).
|
||||
- `connectionTimeout`: Optional timeout for _initial_ connection to MCP server
|
||||
|
||||
**Example:**
|
||||
|
||||
|
|
@ -566,3 +461,9 @@ models:
|
|||
maxPromptTokens: 1024
|
||||
onlyMyCode: true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## `config.json` Deprecation
|
||||
|
||||
`config.yaml `replaces `config.json`, which is deprecated. View the **[Migration Guide](/reference/yaml-migration)** for help transitioning from the old format.
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ noindex: true
|
|||
|
||||
<Warning>
|
||||
**This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use:
|
||||
- [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands
|
||||
- [Prompt blocks and prompt files](/customize/deep-dives/prompts) for slash commands
|
||||
- [config.yaml](/reference) for configuration
|
||||
|
||||
See the `config.yaml` reference and migration guide
|
||||
|
|
|
|||
4
extensions/cli/package-lock.json
generated
|
|
@ -117,6 +117,7 @@
|
|||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.62.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.779.0",
|
||||
"@aws-sdk/client-sagemaker-runtime": "^3.777.0",
|
||||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
|
|
@ -236,7 +237,7 @@
|
|||
},
|
||||
"../../packages/config-yaml": {
|
||||
"name": "@continuedev/config-yaml",
|
||||
"version": "1.17.0",
|
||||
"version": "1.23.0",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
|
|
@ -268,6 +269,7 @@
|
|||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.62.0",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
|
||||
"@aws-sdk/credential-providers": "^3.840.0",
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
|
|||
**The onboarding flow runs when the user hasn't completed onboarding before, regardless of whether they have a valid config.yaml file.**
|
||||
|
||||
1. If the --config flag is provided, load this config
|
||||
2. Otherwise, we will present the user with two options:
|
||||
2. If the CONTINUE_USE_BEDROCK environment variable is set to "1", automatically use AWS Bedrock configuration and skip interactive prompts
|
||||
3. Present the user with available options:
|
||||
|
||||
- Log in with Continue: log them in, which will automatically create their assistant and then we can load the first assistant from the first org
|
||||
- Enter your Anthropic API key: let them enter the key, and then either create a ~/.continue/config.yaml with the following contents OR update the existing config.yaml to add the model
|
||||
|
|
@ -23,7 +24,26 @@ When a user first runs `cn` in interactive mode, they will be taken through "onb
|
|||
ANTHROPIC_API_KEY: <THEIR_ANTHROPIC_API_KEY>
|
||||
```
|
||||
|
||||
When something in the onboarding flow is done automatically, we should tell the user what happened.
|
||||
When CONTINUE_USE_BEDROCK=1 is detected, it will use AWS Bedrock configuration. The user must have AWS credentials configured through the standard AWS credential chain (AWS CLI, environment variables, IAM roles, etc.).
|
||||
|
||||
When something in the onboarding flow is done automatically, we should tell the user what happened. For example, when CONTINUE_USE_BEDROCK=1 is detected, the CLI displays: "✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"
|
||||
|
||||
### AWS Bedrock Environment Variable
|
||||
|
||||
Users can bypass the interactive onboarding menu by setting the `CONTINUE_USE_BEDROCK` environment variable to "1":
|
||||
|
||||
```bash
|
||||
export CONTINUE_USE_BEDROCK=1
|
||||
cn <command>
|
||||
```
|
||||
|
||||
This will:
|
||||
|
||||
- Skip the interactive onboarding prompts
|
||||
- Automatically configure the CLI to use AWS Bedrock
|
||||
- Require that AWS credentials are already configured through the standard AWS credential chain
|
||||
- Display a confirmation message to the user
|
||||
- Mark onboarding as completed
|
||||
|
||||
## Normal flow
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { createRelativeRuleFilePath } from "core/config/markdown/utils.js";
|
||||
|
||||
import { SlashCommandResult } from "../ui/hooks/useChat.types.js";
|
||||
|
||||
function createInitPrompt(): string {
|
||||
return `Please analyze this repository and create a comprehensive AGENTS.md file. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup.
|
||||
const relativeRuleFilepath = createRelativeRuleFilePath("review");
|
||||
return `Please analyze this repository and create a comprehensive AGENTS.md file, along with a custom slash command. Use your available tools to understand the project structure, read important files like README.md, package.json, requirements.txt, and other configuration files to understand the technology stack and setup.
|
||||
|
||||
Create an AGENTS.md file with the following structure:
|
||||
|
||||
|
|
@ -30,7 +32,23 @@ Create an AGENTS.md file with the following structure:
|
|||
- Development environment setup
|
||||
- Lint and format commands
|
||||
|
||||
Please create the AGENTS.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the file concise but informational.`;
|
||||
Additionally, create a slash command file at ${relativeRuleFilepath} with the following structure:
|
||||
|
||||
\`\`\`md
|
||||
---
|
||||
invokable: true
|
||||
---
|
||||
|
||||
Review this code for potential issues, including:
|
||||
|
||||
<insert custom things to look for based on the repository details you find>
|
||||
|
||||
Provide specific, actionable feedback for improvements.
|
||||
\`\`\`
|
||||
|
||||
This slash command will be invokable using /review and will provide instructions for code review tasks common to this repository.
|
||||
|
||||
Please create both the AGENTS.md file and the .continue/rules/review.md file using the Write tool after analyzing the repository. Focus on providing actionable information that would help both AI agents and human developers understand and work effectively with this codebase. Keep the files concise but informational.`;
|
||||
}
|
||||
|
||||
export async function handleInit(
|
||||
|
|
|
|||
|
|
@ -145,6 +145,77 @@ describe("remote command", () => {
|
|||
expect(mockConsoleLog).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should fetch tunnel and connect when id option is provided", async () => {
|
||||
const agentId = "agent-789";
|
||||
|
||||
mockFetch
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }),
|
||||
})
|
||||
.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
id: "test-agent-id",
|
||||
url: "ws://test-url.com",
|
||||
port: 8080,
|
||||
}),
|
||||
});
|
||||
|
||||
await remote("test prompt", { id: agentId });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith(
|
||||
"ws://tunnel-url.com",
|
||||
"test prompt",
|
||||
);
|
||||
});
|
||||
|
||||
it("should output JSON without starting TUI when using --id with --start", async () => {
|
||||
const agentId = "agent-456";
|
||||
const tunnelResponse = { url: "ws://existing-tunnel.com", port: 7070 };
|
||||
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => tunnelResponse,
|
||||
});
|
||||
|
||||
await remote("test prompt", { id: agentId, start: true });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase),
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "Bearer test-token",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled();
|
||||
expect(mockConsoleLog).toHaveBeenCalledWith(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Remote agent tunnel connection details",
|
||||
url: tunnelResponse.url,
|
||||
containerPort: tunnelResponse.port,
|
||||
agentId,
|
||||
mode: "existing_agent",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle proper request body structure with all fields", async () => {
|
||||
const testIdempotencyKey = "structured-test-key";
|
||||
|
||||
|
|
@ -298,10 +369,10 @@ describe("remote command", () => {
|
|||
repoUrl: "https://github.com/user/test-repo.git",
|
||||
name: expect.stringMatching(/^devbox-\d+$/),
|
||||
prompt: "test prompt",
|
||||
idempotencyKey: undefined,
|
||||
agent: undefined,
|
||||
config: undefined,
|
||||
});
|
||||
expect(requestBody).not.toHaveProperty("idempotencyKey");
|
||||
});
|
||||
|
||||
describe("start mode (-s / --start flag)", () => {
|
||||
|
|
|
|||
|
|
@ -9,155 +9,258 @@ import { getRepoUrl } from "../util/git.js";
|
|||
import { logger } from "../util/logger.js";
|
||||
import { readStdinSync } from "../util/stdin.js";
|
||||
|
||||
type RemoteCommandOptions = {
|
||||
url?: string;
|
||||
id?: string;
|
||||
idempotencyKey?: string;
|
||||
start?: boolean;
|
||||
branch?: string;
|
||||
repo?: string;
|
||||
config?: string;
|
||||
};
|
||||
|
||||
type TunnelResponse = {
|
||||
url: string;
|
||||
port?: number;
|
||||
};
|
||||
|
||||
type AgentCreationResponse = TunnelResponse & {
|
||||
id: string;
|
||||
};
|
||||
|
||||
class AuthenticationRequiredError extends Error {
|
||||
constructor() {
|
||||
super("Not authenticated. Please run 'cn login' first.");
|
||||
}
|
||||
}
|
||||
|
||||
export async function remote(
|
||||
prompt: string | undefined,
|
||||
options: {
|
||||
url?: string;
|
||||
idempotencyKey?: string;
|
||||
start?: boolean;
|
||||
branch?: string;
|
||||
repo?: string;
|
||||
config?: string;
|
||||
} = {},
|
||||
options: RemoteCommandOptions = {},
|
||||
) {
|
||||
// Check if prompt should come from stdin instead of parameter
|
||||
let actualPrompt = prompt;
|
||||
if (prompt) {
|
||||
// If prompt is provided, still check for stdin and combine them
|
||||
const stdinInput = readStdinSync();
|
||||
if (stdinInput) {
|
||||
// Combine stdin and prompt argument - stdin comes first in XML block
|
||||
actualPrompt = `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`;
|
||||
const actualPrompt = resolvePrompt(prompt);
|
||||
|
||||
try {
|
||||
if (options.url) {
|
||||
await connectToRemoteUrl(options.url, actualPrompt, options.start);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Try to read from stdin (for piped input like: echo "hello" | cn remote -s)
|
||||
const stdinInput = readStdinSync();
|
||||
if (stdinInput) {
|
||||
actualPrompt = stdinInput;
|
||||
}
|
||||
}
|
||||
// If --url is provided, connect directly to that URL
|
||||
if (options.url) {
|
||||
if (options.start) {
|
||||
// In start mode, output connection details as JSON and exit
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Remote environment connection details",
|
||||
url: options.url,
|
||||
mode: "direct_url",
|
||||
}),
|
||||
|
||||
const accessToken = requireAccessToken();
|
||||
|
||||
if (options.id) {
|
||||
await connectExistingAgent(
|
||||
options.id,
|
||||
accessToken,
|
||||
actualPrompt,
|
||||
options.start,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote environment at: ${options.url}`),
|
||||
);
|
||||
await createAndConnectRemoteEnvironment(accessToken, actualPrompt, options);
|
||||
} catch (error) {
|
||||
await handleRemoteError(error);
|
||||
}
|
||||
}
|
||||
|
||||
// Record session start
|
||||
telemetryService.recordSessionStart();
|
||||
telemetryService.startActiveTime();
|
||||
function resolvePrompt(prompt: string | undefined): string | undefined {
|
||||
const stdinInput = readStdinSync();
|
||||
|
||||
try {
|
||||
// Start the TUI in remote mode
|
||||
await startRemoteTUIChat(options.url, actualPrompt);
|
||||
} finally {
|
||||
telemetryService.stopActiveTime();
|
||||
}
|
||||
if (!stdinInput) {
|
||||
return prompt;
|
||||
}
|
||||
|
||||
if (!prompt) {
|
||||
return stdinInput;
|
||||
}
|
||||
|
||||
return `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`;
|
||||
}
|
||||
|
||||
async function connectToRemoteUrl(
|
||||
remoteUrl: string,
|
||||
prompt: string | undefined,
|
||||
startOnly?: boolean,
|
||||
) {
|
||||
if (startOnly) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
message: "Remote environment connection details",
|
||||
url: remoteUrl,
|
||||
mode: "direct_url",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const authConfig = loadAuthConfig();
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote environment at: ${remoteUrl}`),
|
||||
);
|
||||
await launchRemoteTUI(remoteUrl, prompt);
|
||||
}
|
||||
|
||||
// Check if we have any valid authentication (file-based or environment variable)
|
||||
if (!authConfig || !getAccessToken(authConfig)) {
|
||||
console.error(
|
||||
chalk.red("Not authenticated. Please run 'cn login' first."),
|
||||
);
|
||||
await gracefulExit(1);
|
||||
}
|
||||
function requireAccessToken(): string {
|
||||
const authConfig = loadAuthConfig();
|
||||
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
if (!authConfig) {
|
||||
throw new AuthenticationRequiredError();
|
||||
}
|
||||
|
||||
const requestBody: any = {
|
||||
repoUrl: options.repo || getRepoUrl(),
|
||||
name: `devbox-${Date.now()}`,
|
||||
prompt: actualPrompt,
|
||||
idempotencyKey: options.idempotencyKey,
|
||||
agent: options.config,
|
||||
config: options.config,
|
||||
};
|
||||
const accessToken = getAccessToken(authConfig);
|
||||
|
||||
// Add branchName to request body if branch option is provided
|
||||
if (options.branch) {
|
||||
requestBody.branchName = options.branch;
|
||||
}
|
||||
if (!accessToken) {
|
||||
throw new AuthenticationRequiredError();
|
||||
}
|
||||
|
||||
const response = await fetch(new URL("agents", env.apiBase), {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
async function connectExistingAgent(
|
||||
agentId: string,
|
||||
accessToken: string,
|
||||
prompt: string | undefined,
|
||||
startOnly?: boolean,
|
||||
) {
|
||||
const tunnel = await fetchAgentTunnel(agentId, accessToken);
|
||||
|
||||
if (startOnly) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
message: "Remote agent tunnel connection details",
|
||||
url: tunnel.url,
|
||||
containerPort: tunnel.port,
|
||||
agentId,
|
||||
mode: "existing_agent",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote agent tunnel at: ${tunnel.url}`),
|
||||
);
|
||||
await launchRemoteTUI(tunnel.url, prompt);
|
||||
}
|
||||
|
||||
async function createAndConnectRemoteEnvironment(
|
||||
accessToken: string,
|
||||
prompt: string | undefined,
|
||||
options: RemoteCommandOptions,
|
||||
) {
|
||||
const requestBody = buildAgentRequestBody(options, prompt);
|
||||
|
||||
const response = await fetch(new URL("agents", env.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to create remote environment: ${response.status} ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = (await response.json()) as AgentCreationResponse;
|
||||
|
||||
if (options.start) {
|
||||
printStartJson({
|
||||
status: "success",
|
||||
message: "Remote development environment created successfully",
|
||||
url: `${env.appUrl}/agents/${result.id}`,
|
||||
containerUrl: result.url,
|
||||
containerPort: result.port,
|
||||
name: requestBody.name,
|
||||
mode: "new_environment",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.green("✅ Remote development environment created successfully!"),
|
||||
);
|
||||
|
||||
if (!result.url) {
|
||||
throw new Error("No URL returned from remote environment creation");
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote environment at: ${result.url}`),
|
||||
);
|
||||
await launchRemoteTUI(result.url, prompt);
|
||||
}
|
||||
|
||||
function buildAgentRequestBody(
|
||||
options: RemoteCommandOptions,
|
||||
prompt: string | undefined,
|
||||
) {
|
||||
const body: Record<string, unknown> = {
|
||||
repoUrl: options.repo ?? getRepoUrl(),
|
||||
name: `devbox-${Date.now()}`,
|
||||
prompt,
|
||||
agent: options.config,
|
||||
config: options.config,
|
||||
};
|
||||
|
||||
if (options.idempotencyKey) {
|
||||
body.idempotencyKey = options.idempotencyKey;
|
||||
}
|
||||
|
||||
if (options.branch) {
|
||||
body.branchName = options.branch;
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
async function fetchAgentTunnel(agentId: string, accessToken: string) {
|
||||
const response = await fetch(
|
||||
new URL(`agents/${agentId}/tunnel`, env.apiBase),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to create remote environment: ${response.status} ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (options.start) {
|
||||
// In start mode, output connection details as JSON and exit
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
message: "Remote development environment created successfully",
|
||||
url: `${env.appUrl}/agents/${result.id}`,
|
||||
containerUrl: result.url,
|
||||
containerPort: result.port,
|
||||
name: requestBody.name,
|
||||
mode: "new_environment",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
console.info(
|
||||
chalk.green("✅ Remote development environment created successfully!"),
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`Failed to create tunnel for agent ${agentId}: ${response.status} ${errorText}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (result.url && result.port) {
|
||||
const remoteUrl = result.url;
|
||||
console.info(
|
||||
chalk.white(`Connecting to remote environment at: ${remoteUrl}`),
|
||||
);
|
||||
return (await response.json()) as TunnelResponse;
|
||||
}
|
||||
|
||||
// Record session start
|
||||
telemetryService.recordSessionStart();
|
||||
telemetryService.startActiveTime();
|
||||
async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) {
|
||||
telemetryService.recordSessionStart();
|
||||
telemetryService.startActiveTime();
|
||||
|
||||
try {
|
||||
// Start the TUI in remote mode (prompt is optional)
|
||||
await startRemoteTUIChat(remoteUrl, actualPrompt);
|
||||
} finally {
|
||||
telemetryService.stopActiveTime();
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
"No URL or port returned from remote environment creation",
|
||||
);
|
||||
}
|
||||
} catch (error: any) {
|
||||
logger.error(
|
||||
chalk.red(`Failed to create remote environment: ${error.message}`),
|
||||
);
|
||||
await gracefulExit(1);
|
||||
try {
|
||||
await startRemoteTUIChat(remoteUrl, prompt);
|
||||
} finally {
|
||||
telemetryService.stopActiveTime();
|
||||
}
|
||||
}
|
||||
|
||||
function printStartJson(payload: Record<string, unknown>) {
|
||||
console.log(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
async function handleRemoteError(error: unknown) {
|
||||
if (error instanceof AuthenticationRequiredError) {
|
||||
logger.error(chalk.red(error.message));
|
||||
} else if (error instanceof Error) {
|
||||
logger.error(chalk.red(error.message));
|
||||
} else {
|
||||
logger.error(chalk.red("An unknown error occurred while starting remote"));
|
||||
}
|
||||
|
||||
await gracefulExit(1);
|
||||
}
|
||||
|
|
|
|||