diff --git a/.continue/prompts/update-llm-info.prompt b/.continue/prompts/update-llm-info.prompt index 9c1cf1f8e..07c9b1b62 100644 --- a/.continue/prompts/update-llm-info.prompt +++ b/.continue/prompts/update-llm-info.prompt @@ -52,7 +52,7 @@ Retrieve the following sites per these providers, and consider these notes on ho // TODO: add info for openai, ollama, etc For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement. -Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored. +Generally, ignore models that do not support text output. These models will be used in a coding agent client that only supports text/image input and text/output, so extraneous capabilities can be ignored. Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained. 3. UPDATE THE INFORMATION diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index cc85d0d0a..9eb505de7 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -29,7 +29,7 @@ body: - **Continue version**: v0.9.4 - **IDE version**: VSCode 1.85.1 - Model: Claude Sonnet 3.5 - - Assistant configuration + - Agent configuration value: | - OS: - Continue version: @@ -39,7 +39,7 @@ body: ```yaml ``` - OR link to assistant in Continue hub: + OR link to agent in Continue hub: render: Markdown validations: required: false diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml index 3d314ff37..3f73a5d5b 100644 --- a/.github/workflows/continue-detailed-review.yaml +++ b/.github/workflows/continue-detailed-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Detailed PR Review - uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070 + uses: continuedev/continue/actions/detailed-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: continuedev diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index 3030c6fdf..3a37e3303 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -18,7 +18,7 @@ jobs: timeout-minutes: 10 steps: - name: Run Continue PR Review Action - uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070 + uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe with: continue-api-key: ${{ secrets.CONTINUE_API_KEY }} continue-org: "continuedev" diff --git a/.github/workflows/main-build.yaml b/.github/workflows/main-build.yaml index a04afb945..808373096 100644 --- a/.github/workflows/main-build.yaml +++ b/.github/workflows/main-build.yaml @@ -24,17 +24,19 @@ jobs: - name: Get merged PR number id: get-pr + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - # Get the commit message of the merge commit - COMMIT_MSG=$(git log --format=%B -n 1 HEAD) - echo "Commit message: $COMMIT_MSG" + # Get PR number for the current commit using GitHub API + COMMIT_SHA=$(git rev-parse HEAD) + echo "Getting PR for commit: $COMMIT_SHA" - # Extract PR number from merge commit message (format: "Merge pull request #123 from...") - PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "Merge pull request #[0-9]*" | grep -o "[0-9]*" || echo "6723") + PR_NUMBER=$(curl -s -H "Authorization: token $GH_TOKEN" \ + "https://api.github.com/repos/${{ github.repository }}/commits/$COMMIT_SHA/pulls" \ + | jq -r '.[0].number // empty') if [ -z "$PR_NUMBER" ]; then - echo "❌ Could not extract PR number from commit message. This might not be a PR merge." - echo "Commit message was: $COMMIT_MSG" + echo "❌ Could not find PR for commit $COMMIT_SHA" exit 1 fi diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index 7cab0df2a..6dbd55817 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -51,6 +51,9 @@ jobs: with: fetch-depth: 0 + - name: Setup packages + uses: ./.github/actions/setup-packages + - name: Use Node.js from .nvmrc uses: actions/setup-node@v4 with: diff --git a/.gitignore b/.gitignore index 8eba642ee..48f5c370e 100644 --- a/.gitignore +++ b/.gitignore @@ -171,4 +171,5 @@ extensions/.continue-debug/ .continuerules **/.continue/assistants/ +**/.continue/agents/ keys \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fe0165951..3993294b4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -288,4 +288,4 @@ We require all contributors to accept the CLA and have made it as easy as commen I have read the CLA Document and I hereby sign the CLA ``` -3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed. +3. The CLA-Assistant bot records your signature in the repo and marks the status check as passed. diff --git a/actions/README.md b/actions/README.md index 464867658..6d3bbf377 100644 --- a/actions/README.md +++ b/actions/README.md @@ -219,7 +219,7 @@ We recommend using a specific commit SHA for stability and predictability: Example: ```yaml -uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266 +uses: continuedev/continue/actions/general-review@64bda6b2b3dac1037e9895dbee4ce1d35565e1fe ``` ## Troubleshooting diff --git a/actions/detailed-review/action.yml b/actions/detailed-review/action.yml index e0280fa28..97c47018f 100644 --- a/actions/detailed-review/action.yml +++ b/actions/detailed-review/action.yml @@ -29,12 +29,17 @@ runs: SHOULD_RUN="false" if [ "${{ github.event_name }}" = "pull_request" ]; then - # 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" + # Check if PR is a draft + if [ "${{ github.event.pull_request.draft }}" = "true" ]; then + echo "::notice::Skipping review - PR is a draft" else - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" + # 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 @@ -268,7 +273,23 @@ runs: console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2)); } - const comments = validComments.map(comment => ({ + // 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 @@ -283,12 +304,19 @@ runs: // 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: `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*πŸ’‘ To request a new detailed review, comment \`@continue-detailed-review\`*`, + body: reviewBody, event: 'COMMENT', comments: comments }); @@ -310,22 +338,19 @@ runs: } } 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: `## 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') { - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: `*Inline review triggered by @${context.payload.comment.user.login}*` + body: summaryBody }); } diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml index 060494b94..bf5e221e1 100644 --- a/actions/general-review/action.yml +++ b/actions/general-review/action.yml @@ -29,12 +29,17 @@ runs: SHOULD_RUN="false" if [ "${{ github.event_name }}" = "pull_request" ]; then - # 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" + # Check if PR is a draft + if [ "${{ github.event.pull_request.draft }}" = "true" ]; then + echo "::notice::Skipping review - PR is a draft" else - echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" + # 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 diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index db8628cde..837bb2a39 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -21,7 +21,6 @@ import { PolicySingleton } from "../control-plane/PolicySingleton.js"; import { Logger } from "../util/Logger.js"; import { Telemetry } from "../util/posthog.js"; import { - ASSISTANTS, getAllDotContinueDefinitionFiles, LoadAssistantFilesOptions, } from "./loadLocalAssistants.js"; @@ -339,7 +338,7 @@ export class ConfigHandler { async getLocalProfiles(options: LoadAssistantFilesOptions) { /** - * Users can define as many local assistants as they want in a `.continue/assistants` folder + * Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder */ // Local customization disabled for on-premise deployments @@ -358,9 +357,14 @@ export class ConfigHandler { const assistantFiles = await getAllDotContinueDefinitionFiles( this.ide, options, - ASSISTANTS, + "assistants", ); - const profiles = assistantFiles.map((assistant) => { + const agentFiles = await getAllDotContinueDefinitionFiles( + this.ide, + options, + "agents", + ); + const profiles = [...assistantFiles, ...agentFiles].map((assistant) => { return new LocalProfileLoader( this.ide, this.ideSettingsPromise, diff --git a/core/config/createNewAssistantFile.ts b/core/config/createNewAssistantFile.ts new file mode 100644 index 000000000..01b9f2492 --- /dev/null +++ b/core/config/createNewAssistantFile.ts @@ -0,0 +1,62 @@ +import { IDE } from ".."; +import { joinPathsToUri } from "../util/uri"; + +const DEFAULT_ASSISTANT_FILE = `# This is an example assistant configuration file +# It is used to define custom AI assistants within Continue +# Each assistant file can be accessed by selecting it from the assistant dropdown + +# To learn more, see the full assistant reference: https://docs.continue.dev/reference + +name: Example Assistant +version: 1.0.0 +schema: v1 + +# Models define which AI models this assistant can use +models: + - name: my gpt-5 + provider: openai + model: gpt-5 + apiKey: YOUR_API_KEY_HERE + +# Context providers define what information the assistant can access +context: + - provider: code + - provider: docs + - provider: diff + - provider: terminal + - provider: problems + - provider: folder + - provider: codebase +`; + +export async function createNewAssistantFile( + ide: IDE, + assistantPath: string | undefined, +): Promise { + const workspaceDirs = await ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + throw new Error( + "No workspace directories found. Make sure you've opened a folder in your IDE.", + ); + } + + const baseDirUri = joinPathsToUri( + workspaceDirs[0], + assistantPath ?? ".continue/assistants", + ); + + // Find the first available filename + let counter = 0; + let assistantFileUri: string; + do { + const suffix = counter === 0 ? "" : `-${counter}`; + assistantFileUri = joinPathsToUri( + baseDirUri, + `new-assistant${suffix}.yaml`, + ); + counter++; + } while (await ide.fileExists(assistantFileUri)); + + await ide.writeFile(assistantFileUri, DEFAULT_ASSISTANT_FILE); + await ide.openFile(assistantFileUri); +} diff --git a/core/config/default.ts b/core/config/default.ts index 81c133455..9cf680b17 100644 --- a/core/config/default.ts +++ b/core/config/default.ts @@ -21,7 +21,7 @@ export const defaultContextProvidersJetBrains: NonNullable< ]; export const defaultConfig: ConfigYaml = { - name: "Local Assistant", + name: "Local Agent", version: "1.0.0", schema: "v1", models: [], @@ -29,7 +29,7 @@ export const defaultConfig: ConfigYaml = { }; export const defaultConfigJetBrains: ConfigYaml = { - name: "Local Assistant", + name: "Local Agent", version: "1.0.0", schema: "v1", models: [], diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index feff60183..b6a29212d 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -10,16 +10,16 @@ import { getGlobalFolderWithName } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; -export const ASSISTANTS = "assistants"; -export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; - export function isLocalDefinitionFile(uri: string): boolean { if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { return false; } const normalizedUri = URI.normalize(uri); - return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); + return ( + normalizedUri.includes(`/.continue/agents/`) || + normalizedUri.includes(`/.continue/assistants/`) + ); } async function getDefinitionFilesInDir( diff --git a/core/config/loadLocalAssistants.vitest.ts b/core/config/loadLocalAssistants.vitest.ts index a366316d4..8527eada5 100644 --- a/core/config/loadLocalAssistants.vitest.ts +++ b/core/config/loadLocalAssistants.vitest.ts @@ -6,7 +6,7 @@ import { getAllDotContinueDefinitionFiles, LoadAssistantFilesOptions, } from "./loadLocalAssistants"; -describe("getAllDotContinueDefinitionFiles with fileExtType option", () => { +describe("ASSISTANTS getAllDotContinueDefinitionFiles with fileExtType option", () => { beforeEach(() => { setUpTestDir(); walkDirCache.invalidate(); @@ -240,3 +240,232 @@ describe("getAllDotContinueDefinitionFiles with fileExtType option", () => { ); }); }); + +describe("AGENTS getAllDotContinueDefinitionFiles with fileExtType option", () => { + beforeEach(() => { + setUpTestDir(); + walkDirCache.invalidate(); + + // Add test files to the test directory + addToTestDir([ + ".continue/agents/", + [".continue/agents/agent1.yaml", "yaml content 1"], + [".continue/agents/agent2.yml", "yaml content 2"], + [".continue/agents/agent3.md", "markdown content 1"], + [".continue/agents/agent4.txt", "txt content"], + ]); + }); + + afterEach(() => { + tearDownTestDir(); + walkDirCache.invalidate(); + }); + + it("should return only YAML files when fileExtType is 'yaml'", async () => { + const options: LoadAssistantFilesOptions = { + includeGlobal: false, // Only test workspace for simplicity + includeWorkspace: true, + fileExtType: "yaml", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "agents", + ); + expect(result).toHaveLength(2); + expect(result.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["agent1.yaml", "agent2.yml"]), + ); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "agent3.md", + ); + }); + + it("should return only Markdown files when fileExtType is 'markdown'", async () => { + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "markdown", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "agents", + ); + expect(result).toHaveLength(1); + expect(result.map((f) => f.path.split("/").pop())).toEqual(["agent3.md"]); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "agent1.yaml", + ); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "agent2.yml", + ); + }); + + it("should return all supported files when fileExtType is not specified", async () => { + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + // fileExtType not specified + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "agents", + ); + expect(result).toHaveLength(3); + expect(result.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["agent1.yaml", "agent2.yml", "agent3.md"]), + ); + // Should not include .txt files + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "agent4.txt", + ); + }); + + it("should respect includeWorkspace option with fileExtType", async () => { + // Test with includeWorkspace: false + const workspaceOffOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: false, + fileExtType: "yaml", + }; + + const noWorkspaceResult = await getAllDotContinueDefinitionFiles( + testIde, + workspaceOffOptions, + "agents", + ); + expect(noWorkspaceResult).toHaveLength(0); + + // Test with includeWorkspace: true + const workspaceOnOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const workspaceResult = await getAllDotContinueDefinitionFiles( + testIde, + workspaceOnOptions, + "agents", + ); + expect(workspaceResult).toHaveLength(2); + expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["agent1.yaml", "agent2.yml"]), + ); + }); + + it("should return empty array when no files match the specified extension type", async () => { + // Create a test directory with only non-matching files + tearDownTestDir(); + walkDirCache.invalidate(); + setUpTestDir(); + addToTestDir([ + ".continue/agents/", + [".continue/agents/nonmatch1.txt", "txt content"], + [".continue/agents/nonmatch2.json", "json content"], + ]); + + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + + fileExtType: "yaml", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "agents", + ); + expect(result).toHaveLength(0); + }); + + it("should handle directories that don't exist", async () => { + // Create a clean test directory without the agents folder + tearDownTestDir(); + setUpTestDir(); + + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "agents", + ); + expect(result).toHaveLength(0); + }); + + it("should return correct file content", async () => { + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "agents", + ); + expect(result).toHaveLength(2); + const yamlFile = result.find((f) => f.path.includes("agent1.yaml")); + expect(yamlFile?.content).toBe("yaml content 1"); + }); + + it("should filter by file extension case sensitively", async () => { + // Add files with uppercase extensions + addToTestDir([ + [".continue/agents/agent5.YAML", "uppercase yaml"], + [".continue/agents/agent6.YML", "uppercase yml"], + [".continue/agents/agent7.MD", "uppercase md"], + ]); + + const yamlOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const yamlResult = await getAllDotContinueDefinitionFiles( + testIde, + yamlOptions, + "agents", + ); + // Should only get lowercase extensions (current implementation) + expect(yamlResult).toHaveLength(2); + expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["agent1.yaml", "agent2.yml"]), + ); + expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain( + "agent5.YAML", + ); + + const markdownOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "markdown", + }; + + const markdownResult = await getAllDotContinueDefinitionFiles( + testIde, + markdownOptions, + "agents", + ); + expect(markdownResult).toHaveLength(1); + expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([ + "agent3.md", + ]); + expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain( + "agent7.MD", + ); + }); +}); diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 56d416d0b..e7a9608f1 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -33,7 +33,7 @@ export default class LocalProfileLoader implements IProfileLoader { iconUrl: "", title: overrideAssistantFile?.path ? getUriPathBasename(overrideAssistantFile.path) - : "Local Assistant", + : "Local Agent", errors: undefined, uri: overrideAssistantFile?.path ?? @@ -48,7 +48,7 @@ export default class LocalProfileLoader implements IProfileLoader { ); this.description.title = parsedAssistant.name; } catch (e) { - console.error("Failed to parse assistant file: ", e); + console.error("Failed to parse agent file: ", e); } } } diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 95db22eb9..040fd3b41 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -98,6 +98,7 @@ export default async function doLoadConfig(options: { const uniqueId = await ide.getUniqueId(); const ideSettings = await ideSettingsPromise; const workOsAccessToken = await controlPlaneClient.getAccessToken(); + const isSignedIn = await controlPlaneClient.isSignedIn(); // Migrations for old config files // Removes @@ -285,6 +286,7 @@ export default async function doLoadConfig(options: { rules: newConfig.rules, enableExperimentalTools: newConfig.experimental?.enableExperimentalTools ?? false, + isSignedIn, }), ); diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index 1903e3038..22c1d8955 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -4,7 +4,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; export const defaultConfigYaml: AssistantUnrolled = { models: [], context: [], - name: "Local Assistant", + name: "Local Agent", version: "1.0.0", schema: "v1", }; @@ -12,7 +12,7 @@ export const defaultConfigYaml: AssistantUnrolled = { export const defaultConfigYamlJetBrains: AssistantUnrolled = { models: [], context: [], - name: "Local Assistant", + name: "Local Agent", version: "1.0.0", schema: "v1", }; diff --git a/core/config/yaml/loadYaml.vitest.ts b/core/config/yaml/loadYaml.vitest.ts index fd6769f70..97c291443 100644 --- a/core/config/yaml/loadYaml.vitest.ts +++ b/core/config/yaml/loadYaml.vitest.ts @@ -1,14 +1,14 @@ -import { describe, it, expect } from "vitest"; import { - validateConfigYaml, AssistantUnrolledNonNullable, + validateConfigYaml, } from "@continuedev/config-yaml"; +import { describe, expect, it } from "vitest"; describe("MCP Server cwd configuration", () => { describe("YAML schema validation", () => { it("should accept valid MCP server with cwd", () => { const config: AssistantUnrolledNonNullable = { - name: "test-assistant", + name: "test-agent", version: "1.0.0", mcpServers: [ { @@ -28,7 +28,7 @@ describe("MCP Server cwd configuration", () => { it("should accept MCP server without cwd", () => { const config: AssistantUnrolledNonNullable = { - name: "test-assistant", + name: "test-agent", version: "1.0.0", mcpServers: [ { @@ -45,7 +45,7 @@ describe("MCP Server cwd configuration", () => { it("should accept relative paths in cwd", () => { const config: AssistantUnrolledNonNullable = { - name: "test-assistant", + name: "test-agent", version: "1.0.0", mcpServers: [ { @@ -63,7 +63,7 @@ describe("MCP Server cwd configuration", () => { it("should accept empty string cwd", () => { const config: AssistantUnrolledNonNullable = { - name: "test-assistant", + name: "test-agent", version: "1.0.0", mcpServers: [ { @@ -115,7 +115,7 @@ describe("MCP Server cwd configuration", () => { configs.forEach(({ name, server }) => { const config: AssistantUnrolledNonNullable = { - name: "test-assistant", + name: "test-agent", version: "1.0.0", mcpServers: [server], }; diff --git a/core/core.ts b/core/core.ts index 1e5b2a74b..9e34da636 100644 --- a/core/core.ts +++ b/core/core.ts @@ -51,6 +51,7 @@ import { import { BLOCK_TYPES, 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 { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules"; import { @@ -354,6 +355,13 @@ export class Core { ); }); + on("config/newAssistantFile", async (msg) => { + await createNewAssistantFile(this.ide, undefined); + await this.configHandler.reloadConfig( + "Assistant file created (config/newAssistantFile message)", + ); + }); + on("config/addLocalWorkspaceBlock", async (msg) => { await createNewWorkspaceBlockFile(this.ide, msg.data.blockType); await this.configHandler.reloadConfig( diff --git a/core/index.d.ts b/core/index.d.ts index 0962c212b..5a958a04e 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1111,6 +1111,7 @@ interface ToolChoice { export interface ConfigDependentToolParams { rules: RuleWithSource[]; enableExperimentalTools: boolean; + isSignedIn: boolean; } export type GetTool = (params: ConfigDependentToolParams) => Tool; diff --git a/core/indexing/chunk/code.test.ts b/core/indexing/chunk/code.test.ts index 0261b576f..cdd5ad2f3 100644 --- a/core/indexing/chunk/code.test.ts +++ b/core/indexing/chunk/code.test.ts @@ -1,5 +1,5 @@ import { ChunkWithoutID } from "../.."; - +import { cleanupAsyncEncoders, countTokensAsync } from "../../llm/countTokens"; import { codeChunker } from "./code"; async function genToArr(generator: AsyncGenerator): Promise { @@ -71,3 +71,60 @@ describe.skip("codeChunker", () => { expect(chunks).toContain('def method20():\n return "Hello, 20!"'); }); }); + +async function collectContents( + filepath: string, + contents: string, + maxChunkSize: number, +): Promise { + const out: string[] = []; + for await (const c of codeChunker(filepath, contents, maxChunkSize)) { + out.push(c.content); + } + return out; +} + +describe("codeChunker function definition", () => { + afterAll(async () => await cleanupAsyncEncoders()); + + test("class methods never exceed maxChunkSize", async () => { + const body = Array.from( + { length: 200 }, + (_, i) => `console.log(${i});`, + ).join("\n"); + const contents = ` +class C { + a() { + ${body} + } + b() { + ${body} + } +} +`; + const max = 50; + const chunks = await collectContents("filename1.ts", contents, max); + const counts = await Promise.all(chunks.map((s) => countTokensAsync(s))); + counts.forEach((n) => expect(n).toBeLessThanOrEqual(max)); + }); + + test("top-level functions never exceed maxChunkSize", async () => { + const body = Array.from( + { length: 150 }, + (_, i) => `const x${i} = ${i};`, + ).join("\n"); + const contents = ` +function f() { + ${body} +} + +function g() { + ${body} +} +`; + const max = 60; + const chunks = await collectContents("filename2.ts", contents, max); + const counts = await Promise.all(chunks.map((s) => countTokensAsync(s))); + counts.forEach((n) => expect(n).toBeLessThanOrEqual(max)); + }); +}); diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index 45487d551..13f1e870b 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -128,25 +128,46 @@ async function constructFunctionDefinitionChunk( maxChunkSize: number, ): Promise { const bodyNode = node.children[node.children.length - 1]; - const funcText = - code.slice(node.startIndex, bodyNode.startIndex) + - collapsedReplacement(bodyNode); + const collapsedBody = collapsedReplacement(bodyNode); + const signature = code.slice(node.startIndex, bodyNode.startIndex); + const funcText = signature + collapsedBody; - if ( + const isInClass = node.parent && ["block", "declaration_list"].includes(node.parent.type) && node.parent.parent && - ["class_definition", "impl_item"].includes(node.parent.parent.type) - ) { - // If inside a class, include the class header - const classNode = node.parent.parent; - const classBlock = node.parent; - return `${code.slice( - classNode.startIndex, - classBlock.startIndex, - )}...\n\n${" ".repeat(node.startPosition.column)}${funcText}`; + ["class_definition", "impl_item"].includes(node.parent.parent.type); + + if (isInClass) { + const classNode = node.parent!.parent!; + const classBlock = node.parent!; + const classHeader = code.slice(classNode.startIndex, classBlock.startIndex); + const indent = " ".repeat(node.startPosition.column); + const combined = `${classHeader}...\n\n${indent}${funcText}`; + + if ((await countTokensAsync(combined)) <= maxChunkSize) { + return combined; + } + if ((await countTokensAsync(funcText)) <= maxChunkSize) { + return funcText; + } + const firstLine = signature.split("\n")[0] ?? ""; + const minimal = `${firstLine} ${collapsedBody}`; + if ((await countTokensAsync(minimal)) <= maxChunkSize) { + return minimal; + } + return collapsedBody; } - return funcText; + + if ((await countTokensAsync(funcText)) <= maxChunkSize) { + return funcText; + } + const firstLine = signature.split("\n")[0] ?? ""; + const minimal = `${firstLine} ${collapsedBody}`; + if ((await countTokensAsync(minimal)) <= maxChunkSize) { + return minimal; + } + return collapsedBody; } const collapsedNodeConstructors: { diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index f167d02f9..3f9e62dfc 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -177,6 +177,7 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( // NOTE: When updating this list, // update core/nextEdit/templating/NextEditPromptEngine.ts as well. const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ + NEXT_EDIT_MODELS.MERCURY_CODER, NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, NEXT_EDIT_MODELS.INSTINCT, ]; diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 704931af5..4364257ab 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -20,6 +20,7 @@ export enum LLMConfigurationStatuses { } export enum NEXT_EDIT_MODELS { + MERCURY_CODER = "mercury-coder", MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", INSTINCT = "instinct", } diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts index 385dea23c..9d2b67ea7 100644 --- a/core/llm/llms/Inception.ts +++ b/core/llm/llms/Inception.ts @@ -1,6 +1,8 @@ import { streamSse } from "@continuedev/fetch"; -import { CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatCompletionCreateParams } from "@continuedev/openai-adapters"; +import { UNIQUE_TOKEN } from "../../nextEdit/constants.js"; import OpenAI from "./OpenAI.js"; /** @@ -32,6 +34,26 @@ class Inception extends OpenAI { return true; } + // It seems like this should be inherited automatically from the parent OpenAI class, but it sometimes doesn't. + // protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [ + // "chat", + // "embed", + // "list", + // "rerank", + // "streamChat", + // "streamFim", + // ]; + + protected modifyChatBody( + body: ChatCompletionCreateParams, + ): ChatCompletionCreateParams { + const hasNextEditCapability = this.capabilities?.nextEdit ?? false; + + // Add the nextEdit parameter for Inception-specific routing. + (body as any).nextEdit = hasNextEditCapability; + return body; + } + async *_streamFim( prefix: string, suffix: string, @@ -67,6 +89,79 @@ class Inception extends OpenAI { yield chunk.choices[0].text; } } + + protected async *_streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + if (this.isNextEdit(messages)) { + messages = this.removeNextEditToken(messages); + + // Use edit/completions endpoint. + const endpoint = new URL("edit/completions", this.apiBase); + + const resp = await this.fetch(endpoint, { + method: "POST", + body: JSON.stringify({ + model: options.model, + messages: messages, + max_tokens: options.maxTokens, + temperature: options.temperature, + top_p: options.topP, + frequency_penalty: options.frequencyPenalty, + presence_penalty: options.presencePenalty, + stop: options.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp)) { + if (chunk.choices?.[0]?.delta?.content) { + yield { + role: "assistant", + content: chunk.choices[0].delta.content, + }; + } + } + } else { + // Use regular chat/completions endpoint - call parent OpenAI implementation. + yield* super._streamChat(messages, signal, options); + } + } + + private isNextEdit(messages: ChatMessage[]): boolean { + // Check if any message contains the unique next edit token. + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(UNIQUE_TOKEN), + ); + } + + private removeNextEditToken(messages: ChatMessage[]): ChatMessage[] { + const lastMessage = messages[messages.length - 1]; + + if ( + typeof lastMessage?.content === "string" && + lastMessage.content.endsWith(UNIQUE_TOKEN) + ) { + const cleanedMessages = [...messages]; + cleanedMessages[cleanedMessages.length - 1] = { + ...lastMessage, + content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + }; + return cleanedMessages; + } + + return messages; + } } export default Inception; diff --git a/core/llm/rules/nestedDirectoryRules.vitest.ts b/core/llm/rules/nestedDirectoryRules.vitest.ts index f74637c59..7f55bc7c3 100644 --- a/core/llm/rules/nestedDirectoryRules.vitest.ts +++ b/core/llm/rules/nestedDirectoryRules.vitest.ts @@ -20,7 +20,7 @@ describe("Nested directory rules application", () => { // A global rule for comparison const globalRule: RuleWithSource = { name: "Global Rule", - rule: "SOLID Design Principles - Coding Assistant Guidelines", + rule: "SOLID Design Principles - Coding Agent Guidelines", source: "rules-block", ruleFile: ".continue/rules.md", }; diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index aa8433fc4..3481aa80f 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -164,7 +164,7 @@ Please only respond with code and put it inside of a markdown code block. Do not \`\`\`{{{language}}} `; -const xWinCoderEditPrompt = `: You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request. +const xWinCoderEditPrompt = `: You are an AI coding agent that helps people with programming. Write a response that appropriately completes the user's request. : Please rewrite the following code with these instructions: "{{{userInput}}}" \`\`\`{{{language}}} {{{codeToEdit}}} diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts index c3397878c..51502bfe8 100644 --- a/core/llm/toolSupport.test.ts +++ b/core/llm/toolSupport.test.ts @@ -280,6 +280,15 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); }); + describe("openrouter", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["openrouter"]; + + it("should return false for moonshotai/kimi-k2:free model", () => { + // This fixes issue #6619 + expect(supportsFn("moonshotai/kimi-k2:free")).toBe(false); + }); + }); + describe("edge cases", () => { it("should handle empty model names", () => { expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false); diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 40648c702..7c89dbfa4 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -239,6 +239,13 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = }, openrouter: (model) => { // https://openrouter.ai/models?fmt=cards&supported_parameters=tools + + // Specific free models that don't support tools + // Fixes issue #6619 - moonshotai/kimi-k2:free causing 400 errors + if (model.toLowerCase() === "moonshotai/kimi-k2:free") { + return false; + } + if ( ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( (part) => model.toLowerCase().includes(part), diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0b525de4a..c3bc079d1 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -31,13 +31,14 @@ import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; import { myersDiff } from "../diff/myers.js"; import { modelSupportsNextEdit } from "../llm/autodetect.js"; +import { NEXT_EDIT_MODELS } from "../llm/constants.js"; import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { INSTINCT_SYSTEM_PROMPT, - MERCURY_CODE_TO_EDIT_OPEN, MERCURY_SYSTEM_PROMPT, MODEL_WINDOW_SIZES, + UNIQUE_TOKEN, } from "./constants.js"; import { createDiff, DiffFormatType } from "./context/diffFormatting.js"; import { @@ -392,9 +393,13 @@ export class NextEditProvider { this.ide.getWorkspaceDirs(), ]); - const modelName = helper.modelName.includes("mercury-coder-nextedit") - ? "mercury-coder-nextedit" - : "instinct"; + const modelName = helper.modelName.includes( + NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, + ) + ? NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT + : helper.modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) + ? NEXT_EDIT_MODELS.MERCURY_CODER + : NEXT_EDIT_MODELS.INSTINCT; const { editableRegionStartLine, editableRegionEndLine } = opts?.usingFullFileDiff @@ -551,7 +556,10 @@ export class NextEditProvider { const modelName = helper.modelName; let ctx: any; - if (modelName.includes("mercury-coder-nextedit")) { + if ( + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) + ) { ctx = { recentlyViewedCodeSnippets: snippetPayload.recentlyVisitedRangesSnippets.map((snip) => ({ @@ -564,7 +572,7 @@ export class NextEditProvider { editDiffHistory: this.diffContext, currentFilePath: helper.filepath, }; - } else if (modelName.includes("instinct")) { + } else if (modelName.includes(NEXT_EDIT_MODELS.INSTINCT)) { // Calculate the window around the cursor position (25 lines above and below). const windowStart = Math.max(0, helper.pos.line - 25); const windowEnd = Math.min( @@ -608,9 +616,11 @@ export class NextEditProvider { const systemPrompt: Prompt = { role: "system", - content: modelName.includes("mercury-coder-nextedit") - ? MERCURY_SYSTEM_PROMPT - : INSTINCT_SYSTEM_PROMPT, + content: + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) + ? MERCURY_SYSTEM_PROMPT + : INSTINCT_SYSTEM_PROMPT, }; return [systemPrompt, promptMetadata.prompt]; @@ -677,25 +687,37 @@ export class NextEditProvider { const llm = await this._prepareLlm(); if (!llm) return undefined; - const msg: ChatMessage = await llm.chat(prompts, token); - console.log("message"); - console.log(msg.content); + // Check for mercury models, and inject unique token for next edit. + // Capture the unique tokens in llm Inception.ts and apis Inception.ts + const modelName = helper.modelName; + if ( + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER) || + modelName.includes(NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT) + ) { + // Inject the unique token to the last prompt's content. + const lastPrompt = prompts[prompts.length - 1]; + if (lastPrompt && typeof lastPrompt.content === "string") { + lastPrompt.content += UNIQUE_TOKEN; + } + } + + const msg: ChatMessage = await llm.chat([prompts[1]], token, { + stream: false, + }); if (typeof msg.content !== "string") { return undefined; } - // const nextCompletion = msg.content.split( - // `${MERCURY_CODE_TO_EDIT_OPEN}\n`, - // )[1] - // ? replaceEscapedCharacters( - // msg.content.split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1], - // ).replace(/\n$/, "") - // : replaceEscapedCharacters(msg.content); - const nextCompletion = - msg.content - .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1] - .replace(/\n$/, "") ?? msg.content; + // NOTE: Keep this in case there is a change in spec. + // const nextCompletion = + // msg.content + // .split(`${MERCURY_CODE_TO_EDIT_OPEN}\n`)[1] + // .replace(/\n$/, "") ?? msg.content; + const nextCompletion = msg.content.slice( + msg.content.indexOf("\`\`\`\n") + "\'\'\'\n".length, + msg.content.lastIndexOf("\n\n\`\`\`"), + ); if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) { return await this._handlePartialFileDiff( diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts index 27a743dcc..c569cb208 100644 --- a/core/nextEdit/constants.ts +++ b/core/nextEdit/constants.ts @@ -8,6 +8,10 @@ export const MODEL_WINDOW_SIZES: Record< NEXT_EDIT_MODELS, { topMargin: number; bottomMargin: number } > = { + "mercury-coder": { + topMargin: 0, + bottomMargin: 5, + }, // mercury coder uses full file diff, so this should be unnecessary "mercury-coder-nextedit": { topMargin: 0, bottomMargin: 5, @@ -15,13 +19,15 @@ export const MODEL_WINDOW_SIZES: Record< instinct: { topMargin: 1, bottomMargin: 5 }, }; +export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; + // Model 1-specific tokens. export const INSTINCT_USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>"; export const INSTINCT_EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>"; export const INSTINCT_EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>"; export const INSTINCT_CONTEXT_FILE_TOKEN = "<|context_file|>"; export const INSTINCT_SNIPPET_TOKEN = "<|snippet|>"; -export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI assistant is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. +export const INSTINCT_SYSTEM_PROMPT = `You are Instinct, an intelligent next-edit predictor developed by Continue.dev. Your role as an AI agent is to help developers complete their code tasks by predicting the next edit that they will make within the section of code marked by <|editable_region_start|> and <|editable_region_end|> tags. You have access to the following information to help you make informed suggestions: @@ -64,4 +70,4 @@ export const MERCURY_EDIT_DIFF_HISTORY_OPEN = "<|edit_diff_history|>"; export const MERCURY_EDIT_DIFF_HISTORY_CLOSE = "<|/edit_diff_history|>"; export const MERCURY_CURSOR = "<|cursor|>"; export const MERCURY_SYSTEM_PROMPT = - "You are Mercury, created by Inception Labs. You are an AI Assistant and an expert at coding. Your role as an AI assistant is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'\''s possible these are entirely irrelevant to the developer'\''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'\''s intentions. These changes are listed from oldest to latest. It'\''s possible a lot of old edit diff history is entirely irrelevant to the developer'\''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'\''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'\''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'\''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'\''s last change unless there are obvious typos or errors.\n- Don'\''t include the line numbers of the form #| in your response."; + "You are Mercury, created by Inception Labs. You are an AI Agent and an expert at coding. Your role as an AI agent is to help developers complete their code tasks by assisting in editing specific sections of code marked by the <|code_to_edit|> and <|/code_to_edit|> tags.\n\nYou have access to the following information to help you make informed suggestions:\n\n- recently_viewed_code_snippets: These are code snippets that the developer has recently looked at, which might provide context or examples relevant to the current task. They are listed from oldest to newest, with line numbers in the form #| to help you understand the edit diff history. It'''s possible these are entirely irrelevant to the developer'''s change.\n- current_file_content: The content of the file the developer is currently working on, providing the broader context of the code. Line numbers in the form #| are included to help you understand the edit diff history.\n- edit_diff_history: A record of changes made to the code, helping you understand the evolution of the code and the developer'''s intentions. These changes are listed from oldest to latest. It'''s possible a lot of old edit diff history is entirely irrelevant to the developer'''s change.\n- cursor position marked as <|cursor|>: Indicates where the developer'''s cursor is currently located, which can be crucial for understanding what part of the code they are focusing on.\n\nYour task is to predict and complete the changes the developer would have made next in the <|code_to_edit|> section. The developer may have stopped in the middle of typing. Your goal is to keep the developer on the path that you think they'''re following. Some examples include further implementing a class, method, or variable, or improving the quality of the code. Make sure the developer doesn'''t get distracted and ensure your suggestion is relevant. Consider what changes need to be made next, if any. If you think changes should be made, ask yourself if this is truly what needs to happen. If you are confident about it, then proceed with the changes.\n\n# Steps\n\n1. **Review Context**: Analyze the context from the resources provided, such as recently viewed snippets, edit history, surrounding code, and cursor location.\n2. **Evaluate Current Code**: Determine if the current code within the tags requires any corrections or enhancements.\n3. **Suggest Edits**: If changes are required, ensure they align with the developers patterns and improve code quality.\n4. **Maintain Consistency**: Ensure indentation and formatting follow the existing code style.\n\n# Output Format\n\n- Provide only the revised code within the tags. If no changes are necessary, simply return the original code from within the <|code_to_edit|> and <|/code_to_edit|> tags.\n- There are line numbers in the form #| in the code displayed to you above, but these are just for your reference. Please do not include the numbers of the form #| in your response.\n- Ensure that you do not output duplicate code that exists outside of these tags. The output should be the revised code that was between these tags including the <|code_to_edit|> and <|/code_to_edit|> tags.\n\n# Notes\n\n- Avoid undoing or reverting the developer'''s last change unless there are obvious typos or errors.\n- Don'''t include the line numbers of the form #| in your response."; diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 98e23e45b..d8ca2226d 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -39,11 +39,14 @@ import { type TemplateRenderer = (vars: TemplateVars) => string; const NEXT_EDIT_MODEL_TEMPLATES: Record = { + "mercury-coder": { + template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, + }, "mercury-coder-nextedit": { - template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, + template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n`, }, instinct: { - template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpts:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, + template: `${INSTINCT_USER_PROMPT_PREFIX}\n\n### Context:\n{{{contextSnippets}}}\n\n### User Edits:\n\n{{{editDiffHistory}}}\n\n### User Excerpt:\n{{{currentFilePath}}}\n\n{{{currentFileContent}}}\`\`\`\n### Response:`, }, }; @@ -90,7 +93,7 @@ export async function renderPrompt( let tv: TemplateVars; switch (modelName) { - case "mercury-coder-nextedit": { + case NEXT_EDIT_MODELS.MERCURY_CODER: { userEdits = ctx.editDiffHistory; // editedCodeWithTokens = insertTokens( @@ -119,7 +122,36 @@ export async function renderPrompt( break; } - case "instinct": { + case NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT: { + userEdits = ctx.editDiffHistory; + + // editedCodeWithTokens = insertTokens( + // helper.fileContents.split("\n"), + // helper.pos, + // MERCURY_CURSOR, + // ); + + const mercuryCtx: MercuryTemplateVars = { + recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock( + ctx.recentlyViewedCodeSnippets, + ), + currentFileContent: currentFileContentBlock( + ctx.currentFileContent, + ctx.editableRegionStartLine, + ctx.editableRegionEndLine, + helper.pos, + ), + editDiffHistory: editHistoryBlock(ctx.editDiffHistory), + currentFilePath: ctx.currentFilePath, + }; + + tv = mercuryCtx; + + editedCodeWithTokens = mercuryCtx.currentFileContent; + + break; + } + case NEXT_EDIT_MODELS.INSTINCT: { userEdits = ctx.editDiffHistory; // editedCodeWithTokens = insertTokens( diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 0b90ecda3..fd9d7d9e7 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -106,7 +106,7 @@ describe("NextEditPromptEngine", () => { expect(result.prompt.content).toContain(INSTINCT_USER_PROMPT_PREFIX); expect(result.prompt.content).toContain("### Context:"); expect(result.prompt.content).toContain("### User Edits:"); - expect(result.prompt.content).toContain("### User Excerpts:"); + expect(result.prompt.content).toContain("### User Excerpt:"); expect(result.userEdits).toBe(instinctCtx.editDiffHistory); expect(result.userExcerpts).toContain(INSTINCT_USER_CURSOR_IS_HERE_TOKEN); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 895b8313a..8fb4a9a7e 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -49,8 +49,8 @@ import { ControlPlaneSessionInfo, } from "../control-plane/AuthTypes"; import { FreeTrialStatus } from "../control-plane/client"; -import { NextEditOutcome } from "../nextEdit/types"; import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue"; +import { NextEditOutcome } from "../nextEdit/types"; export enum OnboardingModes { API_KEY = "API Key", @@ -86,6 +86,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void]; "config/newPromptFile": [undefined, void]; + "config/newAssistantFile": [undefined, void]; "config/ideSettingsUpdate": [IdeSettings, void]; "config/getSerializedProfileInfo": [ undefined, diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index bab881830..fc0b3d7b5 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -18,6 +18,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "devdata/log", "config/addModel", "config/newPromptFile", + "config/newAssistantFile", "config/ideSettingsUpdate", "config/addLocalWorkspaceBlock", "config/getSerializedProfileInfo", diff --git a/core/tools/definitions/toolDefinitions.test.ts b/core/tools/definitions/toolDefinitions.test.ts index a6e3fd717..abeac08ef 100644 --- a/core/tools/definitions/toolDefinitions.test.ts +++ b/core/tools/definitions/toolDefinitions.test.ts @@ -7,6 +7,7 @@ describe("Tool Definitions", () => { const mockParams: ConfigDependentToolParams = { rules: [], enableExperimentalTools: false, + isSignedIn: false, }; // Helper function to get the actual tool object diff --git a/core/tools/index.ts b/core/tools/index.ts index 540f4d2bb..850d89349 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -11,7 +11,6 @@ const getBaseToolDefinitions = () => [ toolDefinitions.createNewFileTool, toolDefinitions.runTerminalCommandTool, toolDefinitions.globSearchTool, - toolDefinitions.searchWebTool, toolDefinitions.viewDiffTool, toolDefinitions.readCurrentlyOpenFileTool, toolDefinitions.lsTool, @@ -27,6 +26,8 @@ export const getConfigDependentToolDefinitions = ( toolDefinitions.searchAndReplaceInFileTool, // Keep edit file tool available for models that need it toolDefinitions.editFileTool, + // Web search is only available for signed-in users + ...(params.isSignedIn ? [toolDefinitions.searchWebTool] : []), ...(params.enableExperimentalTools ? [ toolDefinitions.viewRepoMapTool, diff --git a/core/tools/searchWebGating.vitest.ts b/core/tools/searchWebGating.vitest.ts new file mode 100644 index 000000000..e68acdd52 --- /dev/null +++ b/core/tools/searchWebGating.vitest.ts @@ -0,0 +1,30 @@ +import { test, expect } from "vitest"; +import { getConfigDependentToolDefinitions } from "./index"; +import { BuiltInToolNames } from "./builtIn"; + +test("searchWeb tool is only available when user is signed in", () => { + // Test with signed-in user + const signedInTools = getConfigDependentToolDefinitions({ + rules: [], + enableExperimentalTools: false, + isSignedIn: true, + }); + + const searchWebToolSignedIn = signedInTools.find( + (tool) => tool.function.name === BuiltInToolNames.SearchWeb, + ); + expect(searchWebToolSignedIn).toBeDefined(); + expect(searchWebToolSignedIn?.displayTitle).toBe("Search Web"); + + // Test with non-signed-in user + const notSignedInTools = getConfigDependentToolDefinitions({ + rules: [], + enableExperimentalTools: false, + isSignedIn: false, + }); + + const searchWebToolNotSignedIn = notSignedInTools.find( + (tool) => tool.function.name === BuiltInToolNames.SearchWeb, + ); + expect(searchWebToolNotSignedIn).toBeUndefined(); +}); diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index ab4d507fe..59daf21c9 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -39,6 +39,7 @@ export type GlobalContextType = { */ hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; + hasShownUnsupportedPlatformWarning: boolean; showConfigUpdateToast: boolean; isSupportedLanceDbCpuTargetForLinux: boolean; sharedConfig: SharedConfigSchema; diff --git a/core/util/paths.ts b/core/util/paths.ts index 315053413..402b1b3c4 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -393,10 +393,6 @@ export function getGlobalPromptsPath(): string { return getGlobalFolderWithName("prompts"); } -export function getGlobalAssistantsPath(): string { - return getGlobalFolderWithName("assistants"); -} - export function readAllGlobalPromptFiles( folderPath: string = getGlobalPromptsPath(), ): { path: string; content: string }[] { diff --git a/docs/docs.json b/docs/docs.json index 5c88b72ce..369944933 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -46,7 +46,8 @@ "features/autocomplete/how-it-works", "features/autocomplete/model-setup", "features/autocomplete/how-to-customize", - "features/autocomplete/context-selection" + "features/autocomplete/context-selection", + "features/autocomplete/next-edit" ] }, { @@ -88,7 +89,7 @@ { "group": "Help", "icon": "book-open", - "pages": ["troubleshooting"] + "pages": ["faqs", "troubleshooting"] } ] }, @@ -1011,6 +1012,90 @@ "source": "/customization/overview#documentation-context", "destination": "/customize/context/documentation" }, + { + "source": "/troubleshooting#faqs", + "destination": "/faqs" + }, + { + "source": "/troubleshooting#networking-issues", + "destination": "/faqs#networking-issues" + }, + { + "source": "/troubleshooting#configure-certificates", + "destination": "/faqs#configure-certificates" + }, + { + "source": "/troubleshooting#vs-code-proxy-settings", + "destination": "/faqs#vs-code-proxy-settings" + }, + { + "source": "/troubleshooting#code-server", + "destination": "/faqs#code-server" + }, + { + "source": "/troubleshooting#changes-to-assistants-not-showing-in-vs-code", + "destination": "/faqs#changes-to-assistants-not-showing-in-vs-code" + }, + { + "source": "/troubleshooting#i-installed-continue-but-dont-see-the-sidebar-window", + "destination": "/faqs#i-installed-continue-but-dont-see-the-sidebar-window" + }, + { + "source": "/troubleshooting#im-getting-a-404-error-from-openai", + "destination": "/faqs#im-getting-a-404-error-from-openai" + }, + { + "source": "/troubleshooting#im-getting-a-404-error-from-openrouter", + "destination": "/faqs#im-getting-a-404-error-from-openrouter" + }, + { + "source": "/troubleshooting#indexing-issues", + "destination": "/faqs#indexing-issues" + }, + { + "source": "/troubleshooting#agent-mode-is-unavailable-or-tools-arent-working", + "destination": "/faqs#agent-mode-is-unavailable-or-tools-arent-working" + }, + { + "source": "/troubleshooting#check-if-your-model-has-tool-support", + "destination": "/faqs#check-if-your-model-has-tool-support" + }, + { + "source": "/troubleshooting#tools-not-working", + "destination": "/faqs#tools-not-working" + }, + { + "source": "/troubleshooting#images-not-uploading", + "destination": "/faqs#images-not-uploading" + }, + { + "source": "/troubleshooting#add-capabilities", + "destination": "/faqs#add-capabilities" + }, + { + "source": "/troubleshooting#verify-with-provider", + "destination": "/faqs#verify-with-provider" + }, + { + "source": "/troubleshooting#verifying-current-capabilities", + "destination": "/faqs#verifying-current-capabilities" + }, + { + "source": "/troubleshooting#android-studio-nothing-to-show-in-chat", + "destination": "/faqs#android-studio-nothing-to-show-in-chat" + }, + { + "source": "/troubleshooting#i-received-a-codebase-indexing-disabled-your-linux-system-lacks-required-cpu-features-avx2-fma-notification", + "destination": "/faqs#i-received-a-codebase-indexing-disabled-your-linux-system-lacks-required-cpu-features-avx2-fma-notification" + }, + { + "source": "/troubleshooting#how-do-i-reset-the-state-of-the-extension", + "destination": "/faqs#how-do-i-reset-the-state-of-the-extension" + }, + { + "source": "/troubleshooting#still-having-trouble", + "destination": "/faqs#still-having-trouble" + }, { "source": "/customize/model-providers", "destination": "/customize/model-providers/overview" diff --git a/docs/faqs.mdx b/docs/faqs.mdx new file mode 100644 index 000000000..7836ef9d3 --- /dev/null +++ b/docs/faqs.mdx @@ -0,0 +1,385 @@ +--- +title: "FAQs" +description: "Frequently asked questions about Continue" +--- + +## Networking Issues + +### Configure Certificates + +If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in your config file. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this: + + + + ```yaml + models: + - name: My Model + ... + requestOptions: + caBundlePath: /path/to/cert.pem + ``` + + + ```json + { + "models": [ + { + "name": "My Model", + "...": "...", + "requestOptions": { + "caBundlePath": "/path/to/cert.pem" + } + } + ] + } + ``` + + + +You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates. + +**_Windows VS Code Users_**: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue. + +### VS Code Proxy Settings + +If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use `cmd/ctrl` + `,` to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. + +### code-server + +Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server). + +## Changes to assistants not showing in VS Code + +If you've made changes to assistants (adding, modifying, or removing them) but the changes aren't appearing in the Continue extension in VS Code, try reloading the VS Code window: + +1. Open the command palette (`cmd/ctrl` + `shift` + `P`) +2. Type "Reload Window" +3. Select the reload option + +This will restart VS Code and reload all extensions, which should make your assistant changes visible. + +## I installed Continue, but don't see the sidebar window + +By default the Continue window is on the left side of VS Code, but it can be dragged to right side as well, which we recommend in our tutorial. In the situation where you have previously installed Continue and moved it to the right side, it may still be there. You can reveal Continue either by using cmd/ctrl+L or by clicking the button in the top right of VS Code to open the right sidebar. + +## I'm getting a 404 error from OpenAI + +If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists. + +## I'm getting a 404 error from OpenRouter + +If you have entered a valid API key and model, but are still getting a 404 error from OpenRouter, this may be because models that do not support function calling will return an error to Continue when a request is sent. Example error: `HTTP 404 Not Found from https://openrouter.ai/api/v1/chat/completions` + +## Indexing issues + +If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time. + +This can be accomplished using the following command: `Continue: Rebuild codebase index`. + +## Agent mode is unavailable or tools aren't working + +If Agent mode is grayed out or tools aren't functioning properly, this is likely due to model capability configuration issues. + + + Continue uses system message tools as a fallback for models without native tool support, so most models should work with Agent mode automatically. + + +### Check if your model has tool support + +1. Not all models support native tool/function calling, but Continue will automatically use system message tools as a fallback +2. Try adding `capabilities: ["tool_use"]` to your model config to force tool support +3. Verify your provider supports function calling or that system message tools are working correctly + +### Tools Not Working + +If tools aren't being called: + +1. Ensure `tool_use` is in your capabilities +2. Check that your API endpoint actually supports function calling +3. Some providers may use different function calling formats + +### Images Not Uploading + +If you can't upload images: + +1. Add `image_input` to capabilities +2. Ensure your model actually supports vision (e.g., gpt-4-vision, claude-3) +3. Check that your provider passes through image data + +### Add capabilities + +If Continue's autodetection isn't working correctly, you can manually add capabilities in your `config.yaml`: + +```yaml +models: + - name: my-model + provider: openai + model: gpt-4 + capabilities: + - tool_use + - image_input +``` + +### Verify with provider + +Some proxy services (like OpenRouter) or custom deployments may not preserve tool calling capabilities. Check your provider's documentation. + +### Verifying Current Capabilities + +To see what capabilities Continue detected for your model: + +1. Check the mode selector tooltips - they indicate if tools are available +2. Try uploading an image - if disabled, the model lacks `image_input` +3. Check if Agent mode is available - requires `tool_use` + +See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for complete configuration details. + +## Android Studio - "Nothing to show" in Chat + +This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details. + +## I received a "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)" notification + +We use LanceDB as our vector database for codebase search features. On x64 Linux systems, LanceDB requires specific CPU features (FMA and AVX2) which may not be available on older processors. + +Most Continue features will work normally, including autocomplete and chat. However, commands that rely on codebase indexing, such as `@codebase`, `@files`, and `@folder`, will be disabled. + +For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). + +## Ollama Issues + +For a comprehensive guide on setting up and troubleshooting Ollama, see the [Ollama Guide](/guides/ollama-guide). + +### Unable to connect to local Ollama instance + +If you're getting "Unable to connect to local Ollama instance" errors: + +1. **Verify Ollama is running**: Check http://localhost:11434 in your browser - you should see "Ollama is running" +2. **Start Ollama properly**: Use `ollama serve` (not just `ollama run model-name`) +3. **Check your config**: Ensure your `config.yaml` has the correct setup: + +```yaml +models: + - name: llama3 + provider: ollama + model: llama3:latest +``` + +### Connection failed to remote Ollama (EHOSTUNREACH/ECONNREFUSED) + +When connecting to Ollama on another machine: + +1. **Configure Ollama to listen on all interfaces**: + - Set environment variable: `OLLAMA_HOST=0.0.0.0:11434` + - For systemd: Edit `/etc/systemd/system/ollama.service` and add under `[Service]`: + ``` + Environment="OLLAMA_HOST=0.0.0.0:11434" + Environment="OLLAMA_ORIGINS=*" + ``` + - Restart Ollama: `sudo systemctl restart ollama` + +2. **Update your Continue config**: +```yaml +models: + - name: llama3 + provider: ollama + apiBase: http://192.168.1.136:11434 # Use your server's IP + model: llama3:latest +``` + +3. **Check firewall settings**: Ensure port 11434 is open on the server + +### Ollama not working in WSL + +For WSL users having connection issues: + +#### Windows 11 22H2+ (Recommended) +Create or edit `%UserProfile%\.wslconfig`: +```ini +[wsl2] +networkingMode=mirrored +``` +Then restart WSL: `wsl --shutdown` + +#### Older Windows/WSL versions +In PowerShell (as Administrator): +```powershell +# Add firewall rules +New-NetFireWallRule -DisplayName 'WSL Ollama' -Direction Inbound -LocalPort 11434 -Action Allow -Protocol TCP +New-NetFireWallRule -DisplayName 'WSL Ollama' -Direction Outbound -LocalPort 11434 -Action Allow -Protocol TCP + +# Get WSL IP (run 'ip addr' in WSL to find eth0 IP) +# Then add port proxy (replace with your actual IP) +netsh interface portproxy add v4tov4 listenport=11434 listenaddress=0.0.0.0 connectport=11434 connectaddress= +``` + +### Docker container can't connect to host Ollama + +When running Continue or other tools in Docker that need to connect to Ollama on the host: + +**Windows/Mac**: Use `host.docker.internal`: +```yaml +models: + - name: llama3 + provider: ollama + apiBase: http://host.docker.internal:11434 + model: llama3:latest +``` + +**Linux**: Use the Docker bridge IP (usually `172.17.0.1`): +```yaml +models: + - name: llama3 + provider: ollama + apiBase: http://172.17.0.1:11434 + model: llama3:latest +``` + +**Docker run command**: Add host mapping: +```bash +docker run -d --add-host=host.docker.internal:host-gateway ... +``` + +### Parse errors with remote Ollama + +If you're getting parse errors with remote Ollama: + +1. **Verify the model is installed on the remote**: + ```bash + OLLAMA_HOST=192.168.1.136:11434 ollama list + ``` + +2. **Install missing models**: + ```bash + OLLAMA_HOST=192.168.1.136:11434 ollama pull llama3 + ``` + +3. **Check URL format**: Ensure you're using `http://` not `https://` for local network addresses + +## Local Assistant + +### Managing Local Secrets and Environment Variables + +For running Continue completely offline without internet access, see the [Running Continue Without Internet guide](/guides/running-continue-without-internet). + +Continue supports multiple methods for managing secrets locally, searched in this order: + +1. **Workspace `.env` files**: Place a `.env` file in your workspace root directory +2. **Workspace Continue folder**: Place a `.env` file in `/.continue/.env` +3. **Global `.env` file**: Place a `.env` file in `~/.continue/.env` for user-wide secrets +4. **Process environment variables**: Use standard system environment variables + +#### Creating `.env` files + +Create a `.env` file in one of these locations: +- **Per-workspace**: `/.env` or `/.continue/.env` +- **Global**: `~/.continue/.env` + +Example `.env` file: +``` +OPENAI_API_KEY=sk-... +ANTHROPIC_API_KEY=sk-ant-... +CUSTOM_API_URL=https://api.example.com +``` + +#### Using secrets in config.yaml + +Reference your local secrets using the `secrets` namespace: +```yaml +models: + - provider: openai + apiKey: ${{ secrets.OPENAI_API_KEY }} +``` + +#### Hub-managed secrets + +For centralized team secret management, use `${{ inputs.SECRET_NAME }}` syntax in your config.yaml and manage them at [https://hub.continue.dev/settings/secrets](https://hub.continue.dev/settings/secrets): +```yaml +models: + - provider: openai + apiKey: ${{ inputs.OPENAI_API_KEY }} +``` + +#### Important notes + +- **Never commit `.env` files** to version control - add them to `.gitignore` +- The `.env` file uses standard dotenv format (KEY=value, no quotes needed) +- Secrets are loaded when Continue starts, so restart your IDE after changes +- Local `.env` files take precedence over Hub secrets when both exist + +#### Troubleshooting secrets + +If your API keys aren't being recognized: +1. Check the `.env` file is in the correct location +2. Ensure there are no quotes around values in the `.env` file +3. Restart your IDE after adding/changing secrets +4. Verify the variable name matches exactly (case-sensitive) +5. Check that your `.env` file has proper line endings (LF, not CRLF on Windows) + +### Using Model Addons Locally + +You can leverage model addons from the Continue Hub in your local assistant configurations using the `uses:` syntax. This allows you to reference pre-configured model blocks without duplicating configuration. + +#### Requirements + +- You must be logged in to Continue +- Internet connection is required (model addons are fetched from the hub) + +#### Usage + +In your local `config.yaml`, reference model addons using the format `provider/model-name`: + +```yaml +name: My Local Assistant +version: 0.0.1 +schema: v1 +models: + - uses: ollama/llama3.1-8b + - uses: anthropic/claude-3.5-sonnet + - uses: openai/gpt-4 +``` + +#### With local configuration + +You can combine hub model addons with local models: + +```yaml +name: My Local Assistant +version: 0.0.1 +schema: v1 +models: + # Hub model addon + - uses: anthropic/claude-3.5-sonnet + + # Local model configuration + - name: Local Ollama + provider: ollama + model: codellama:latest + apiBase: http://localhost:11434 +``` + +#### Override addon settings + +You can override specific settings from the model addon: + +```yaml +models: + - uses: ollama/llama3.1-8b + override: + apiBase: http://192.168.1.100:11434 # Use remote Ollama server + roles: + - chat + - autocomplete +``` + +This feature allows you to maintain consistent model configurations across teams while still allowing local customization when needed. + +## How do I reset the state of the extension? + +Continue stores its data in the `~/.continue` directory (`%USERPROFILE%\.continue` on Windows). + +If you'd like to perform a clean reset of the extension, including removing all configuration files, indices, etc, you can remove this directory, uninstall, and then reinstall. + +## Still having trouble? + +You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and GitHub Discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly. \ No newline at end of file diff --git a/docs/features/autocomplete/how-it-works.mdx b/docs/features/autocomplete/how-it-works.mdx index c0c0fddee..960cf6778 100644 --- a/docs/features/autocomplete/how-it-works.mdx +++ b/docs/features/autocomplete/how-it-works.mdx @@ -25,3 +25,10 @@ Language models aren't perfect, but can be made much closer by adjusting their o - Occasionally discarding low-quality responses, such as those with excessive repetition You can learn more about how it works in the [Autocomplete deep dive](/customization/models#autocomplete). + + + **Looking for AI that predicts your next changes or additions?** Check out + [Next Edit](/features/autocomplete/next-edit), an experimental feature that + proactively suggests code changes before you even start typing, going beyond + traditional autocomplete to anticipate entire code modifications. + diff --git a/docs/features/autocomplete/model-setup.mdx b/docs/features/autocomplete/model-setup.mdx index 0325b7fd2..80dd7a85b 100644 --- a/docs/features/autocomplete/model-setup.mdx +++ b/docs/features/autocomplete/model-setup.mdx @@ -46,6 +46,16 @@ This model provides good suggestions while keeping your code completely private. 2. Add [Qwen 2.5 Coder 1.5B](https://hub.continue.dev/ollama/qwen2.5-coder-1.5b) to your assistant on Continue Hub 3. Click `Reload config` in the assistant selector in the Continue IDE extension +## Next Edit Model + +For proactive code prediction that anticipates your next edit, Continue supports specialized [Next Edit](/features/edit/next-edit) models: + +**Supported Next Edit model:** + +- `mercury-coder-nextedit`: Primary model optimized for next edit prediction + +Next Edit automatically activates when you have a compatible model configured for autocomplete and the appropriate access permissions. + ## Need Help? If you're not seeing any completions or need more detailed configuration options, check out our comprehensive [autocomplete deep dive guide](/customize/deep-dives/autocomplete). diff --git a/docs/features/autocomplete/next-edit.mdx b/docs/features/autocomplete/next-edit.mdx new file mode 100644 index 000000000..edeb77463 --- /dev/null +++ b/docs/features/autocomplete/next-edit.mdx @@ -0,0 +1,154 @@ +--- +title: "Next Edit" +description: "Learn how Continue's Next Edit feature predicts and suggests your next code changes using AI, going beyond traditional autocomplete to anticipate entire code modifications" +--- + + + Next Edit is currently an experimental feature. It requires [Mercury Coder + model](https://hub.continue.dev/inceptionlabs/mercury-coder) configured in + your Continue autocomplete settings and is not yet available for JetBrains + use. + + +## What is Next Edit? + +Next Edit is an advanced AI-powered code prediction feature that anticipates what changes you'll make next in your code. Unlike traditional autocomplete that reacts to your typing, Next Edit proactively analyzes your recent edits and coding patterns to suggest entire code modifications before you even start typing. + +Think of it as having an AI pair programmer that understands your coding flow and suggests the logical next step in your development process. + +## How Next Edit Works + +### The Prediction Process + +1. **Context Analysis**: Captures your current cursor position and recent edit history +2. **Pattern Recognition**: Analyzes your coding patterns and the surrounding code context +3. **Next Step Prediction**: Uses specialized AI models to predict what you'll likely change next +4. **Visual Presentation**: Shows predictions as diff overlays rather than simple text completions +5. **Interactive Review**: Lets you accept (Tab) or reject (Esc) the suggested changes +6. **Jump to Next Edit Location**: Lets you jump (Tab) to the next edit location or reject (Esc) + +### Intelligent Triggering + +Next Edit activates automatically when: + +- You finish making a code change +- The AI detects a logical continuation point +- Specialized next-edit models are available +- The current context suggests a predictable next step + +## Next Edit vs Traditional Autocomplete + + + + **Autocomplete**: Completes the current line or statement you're typing + + **Next Edit**: Predicts entire code modifications across multiple lines + + + + **Autocomplete**: Shows ghost text at your cursor position + + **Next Edit**: Displays diff overlays showing before/after changes, while also displaying ghost text if the change is purely additive. + + + + + **Autocomplete**: Reactive - responds to what you're currently typing + + **Next Edit**: Proactive - anticipates what you'll do next + + + + **Autocomplete**: Focuses on immediate code completion + + **Next Edit**: Analyzes recent edit patterns and broader code context + + + +## How to Use Next Edit + +### Prerequisites + +Next Edit requires: + +- Compatible AI models (Mercury Coder) +- Continue development team access +- VS Code (JetBrains support coming soon) +- **API Keys**: Organizations can add API keys to [org secrets](/hub/secrets/secret-types) for team-wide access. Individual users need to provide their own API keys in their [model configuration](/customize/model-providers/overview) + + + To use Next Edit, you must have the Mercury Coder model configured in your + Continue autocomplete model settings. This model is specifically designed for + next edit predictions. Once it's been loaded, you must reload VS Code to + activate it. + Next Edit Model Setup + + +### Using Next Edit Predictions + + + + Edit your code normally. Next Edit will analyze your change patterns. + + + + When Next Edit activates, you'll see a diff overlay showing predicted changes + in an editable region. + + + + - **Tab**: Accept the prediction and apply changes - **Esc**: Reject the + prediction and continue coding normally + + + + If accepted, your cursor moves to the last changed line. If rejected, your + workflow continues uninterrupted. + + + +## What are the Model Requirements for Next Edit? + +### Specialized Models + +Next Edit requires AI models specifically trained for code prediction: + +- **Mercury Coder**: Primary model optimized for next edit prediction + +### Automatic Detection + +Continue automatically enables Next Edit when: + +1. Your configured autocomplete model supports next edit capabilities +2. You have development team access permissions +3. The current code context suggests predictable next steps + +## Best Practices + + + + Let Next Edit observe your coding patterns for a few editing sessions before expecting highly accurate predictions. + + + + Always review suggested changes before accepting, especially for complex logic + modifications. + + + + Have feedback? We want to hear it. __[Add your thoughts to our feedback + discussions](https://github.com/continuedev/continue/discussions/categories/feedback)__ + to help us improve. + + + + Use Next Edit alongside Continue's Chat and Agent modes for comprehensive AI-assisted development. + + + +--- + +_Next Edit represents Continue's vision for proactive AI coding assistance that anticipates developer needs rather than just reacting to input. As this feature evolves, it will become a powerful tool for accelerating development workflows and reducing repetitive coding tasks._ diff --git a/docs/features/edit/how-it-works.mdx b/docs/features/edit/how-it-works.mdx index ba8969691..79921ba7b 100644 --- a/docs/features/edit/how-it-works.mdx +++ b/docs/features/edit/how-it-works.mdx @@ -13,4 +13,8 @@ When you start an edit session, Continue: If you accept the diff, we remove the previously highlighted lines, and if you reject the diff, we remove the proposed changes. + +**Looking for AI that predicts your next edit?** Check out [Next Edit](/features/edit/next-edit), an experimental feature that proactively suggests code changes before you even start typing, going beyond traditional autocomplete to anticipate entire code modifications. + + If you would like to view the exact prompt that is sent to the model during an edit, you can [find it in the prompt logs](/troubleshooting#check-the-logs). diff --git a/docs/features/plan/how-it-works.mdx b/docs/features/plan/how-it-works.mdx index cb608f182..8555e68ff 100644 --- a/docs/features/plan/how-it-works.mdx +++ b/docs/features/plan/how-it-works.mdx @@ -85,8 +85,7 @@ Plan mode uses a dedicated system message that: - Encourages thorough analysis before suggesting changes - The system message can be customized per model. See [How to - Customize](/features/plan/how-to-customize) for details or see it [directly in + The system message can be customized per model. See it [directly in the code](https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts). diff --git a/docs/features/plan/quick-start.mdx b/docs/features/plan/quick-start.mdx index 40bbc80d0..05961273c 100644 --- a/docs/features/plan/quick-start.mdx +++ b/docs/features/plan/quick-start.mdx @@ -11,7 +11,7 @@ Plan mode provides a safe environment for understanding and constructing plans w You can switch to `Plan` in the mode selector below the chat input box. -![How to select plan mode](/images/mode-select-plan.png) +![How to select plan mode](/images/plan-mode-selector.png) If Plan is disabled with a `Not Supported` message, the selected model or diff --git a/docs/guides/llama3.1.mdx b/docs/guides/llama3.1.mdx index 5462430bc..c39071a2c 100644 --- a/docs/guides/llama3.1.mdx +++ b/docs/guides/llama3.1.mdx @@ -185,9 +185,15 @@ config.json } ``` -## How to Use Llama 3.1 with Cerebras Inference +## How to Use Llama 3.1 and 3.3 with Cerebras Inference -Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B/70B. + + Check if your chosen model is still supported by referring to the [model + status](https://status.cerebras.ai/). If a model has been + deprecated, you may encounter a 404 error when attempting to use it. + + +Cerebras Inference uses specialized silicon to provides fast inference for the Llama3.1 8B and Llama3.3 70B. 1. Create an account in the portal [here](https://cloud.cerebras.ai/). 2. Create and copy the API key for use in Continue. @@ -200,9 +206,9 @@ config.yaml ``` models: - - name: Cerebras Llama 3.1 70B + - name: Cerebras Llama 3.3 70B provider: cerebras - model: llama3.1-70b + model: llama3.3-70b apiKey: ``` @@ -212,9 +218,9 @@ config.json { "models": [ { - "title": "Cerebras Llama 3.1 70B", + "title": "Cerebras Llama 3.3 70B", "provider": "cerebras", - "model": "llama3.1-70b", + "model": "llama3.3-70b", "apiKey": "" } ] diff --git a/docs/hub/assistants/use-an-assistant.mdx b/docs/hub/assistants/use-an-assistant.mdx index 85257d250..f6d19b836 100644 --- a/docs/hub/assistants/use-an-assistant.mdx +++ b/docs/hub/assistants/use-an-assistant.mdx @@ -16,4 +16,4 @@ After saving, open your IDE extension and: - Select the assistant from the **assistant dropdown** in the Continue extension. - Begin using it for chat, code generation, or other configured capabilities. -[Extension Assistant Selector](/images/assistant-extension-select-319492a06d6249e5389747687341dfdb.png) +![Extension Assistant Selector](/images/hub/assistants/images/assistant-extension-select.png) diff --git a/docs/images/features/autocomplete/images/mercury-coder-next-edit.png b/docs/images/features/autocomplete/images/mercury-coder-next-edit.png new file mode 100644 index 000000000..0793becd0 Binary files /dev/null and b/docs/images/features/autocomplete/images/mercury-coder-next-edit.png differ diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index ad44fd0f2..0aaa45506 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -7,7 +7,7 @@ description: "Comprehensive guide to resolving common issues with Continue, incl 2. [Try the latest pre-release](#download-the-latest-pre-release) 3. [Download an older version](#download-an-older-version) 4. [Resolve keyboard shortcut issues](#keyboard-shortcuts-not-resolving) -5. [Check FAQs for common issues](#faqs) +5. [Check FAQs for common issues](/faqs) ## Check the logs @@ -79,139 +79,6 @@ If your keyboard shortcuts are not resolving, you may have other commands that a - [VSCode keyboard shortcuts docs](https://code.visualstudio.com/docs/getstarted/keybindings) - [IntelliJ keyboard shortcut docs](https://www.jetbrains.com/help/idea/configuring-keyboard-and-mouse-shortcuts.html) -## FAQs - -### Networking Issues - -#### Configure Certificates - -If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in your config file. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this: - -- YAML -- JSON - -config.yaml - -``` -models: - - name: My Model - ... - requestOptions: - caBundlePath: /path/to/cert.pem -``` - -config.json - -```json -{ "models": [ { "title": "My Model", ... "requestOptions": { "caBundlePath": "/path/to/cert.pem" } } ],} -``` - -You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates. - -**_Windows VS Code Users_**: Installing the [win-ca](https://marketplace.visualstudio.com/items?itemName=ukoloff.win-ca) extension should also correct this issue. - -#### VS Code Proxy Settings - -If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use `cmd/ctrl` + `,` to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy. - -#### code-server - -Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server). - -### I installed Continue, but don't see the sidebar window - -By default the Continue window is on the left side of VS Code, but it can be dragged to right side as well, which we recommend in our tutorial. In the situation where you have previously installed Continue and moved it to the right side, it may still be there. You can reveal Continue either by using cmd/ctrl+L or by clicking the button in the top right of VS Code to open the right sidebar. - -### I'm getting a 404 error from OpenAI - -If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists. - -### I'm getting a 404 error from OpenRouter - -If you have entered a valid API key and model, but are still getting a 404 error from OpenRouter, this may be because models that do not support function calling will return an error to Continue when a request is sent. Example error: `HTTP 404 Not Found from https://openrouter.ai/api/v1/chat/completions` - -### Indexing issues - -If you are having persistent errors with indexing, our recommendation is to rebuild your index from scratch. Note that for large codebases this may take some time. - -This can be accomplished using the following command: `Continue: Rebuild codebase index`. - -### Agent mode is unavailable or tools aren't working - -If Agent mode is grayed out or tools aren't functioning properly, this is likely due to model capability configuration issues. - - - Continue uses system message tools as a fallback for models without native - tool support, so most models should work with Agent mode automatically. - - -#### Check if your model has tool support - -1. Not all models support native tool/function calling, but Continue will automatically use system message tools as a fallback -2. Try adding `capabilities: ["tool_use"]` to your model config to force tool support -3. Verify your provider supports function calling or that system message tools are working correctly - -#### Tools Not Working - -If tools aren't being called: - -1. Ensure `tool_use` is in your capabilities -2. Check that your API endpoint actually supports function calling -3. Some providers may use different function calling formats - -#### Images Not Uploading - -If you can't upload images: - -1. Add `image_input` to capabilities -2. Ensure your model actually supports vision (e.g., gpt-4-vision, claude-3) -3. Check that your provider passes through image data - -#### Add capabilities - -If Continue's autodetection isn't working correctly, you can manually add capabilities in your `config.yaml`: - -```yaml -models: - - name: my-model - provider: openai - model: gpt-4 - capabilities: - - tool_use - - image_input -``` - -#### Verify with provider - -Some proxy services (like OpenRouter) or custom deployments may not preserve tool calling capabilities. Check your provider's documentation. - -#### Verifying Current Capabilities - -To see what capabilities Continue detected for your model: - -1. Check the mode selector tooltips - they indicate if tools are available -2. Try uploading an image - if disabled, the model lacks `image_input` -3. Check if Agent mode is available - requires `tool_use` - -See the [Model Capabilities guide](/customize/deep-dives/model-capabilities) for complete configuration details. - -### Android Studio - "Nothing to show" in Chat - -This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/596#issuecomment-1789327178) for details. - -### I received a "Codebase indexing disabled - Your Linux system lacks required CPU features (AVX2, FMA)" notification - -We use LanceDB as our vector database for codebase search features. On x64 Linux systems, LanceDB requires specific CPU features (FMA and AVX2) which may not be available on older processors. - -Most Continue features will work normally, including autocomplete and chat. However, commands that rely on codebase indexing, such as `@codebase`, `@files`, and `@folder`, will be disabled. - -For more details about this requirement, see the [LanceDB issue #2195](https://github.com/lancedb/lance/issues/2195). - -### How do I reset the state of the extension? - -Continue stores it's data in the `~/.continue` directory (%USERPROFILE%.continue\` on Windows). - -If you'd like to perform a clean reset of the extension, including removing all configuration files, indices, etc, you can remove this directory, uninstall, and then reinstall. ## Still having trouble? diff --git a/extensions/intellij/rules.md b/extensions/intellij/rules.md index 1f95724c9..e929a9f7c 100644 --- a/extensions/intellij/rules.md +++ b/extensions/intellij/rules.md @@ -2,7 +2,7 @@ ## Project Purpose -JetBrains/IntelliJ extension for Continue AI code assistant. Provides chat, autocomplete, inline edit, and agent features within JetBrains IDEs. +JetBrains/IntelliJ extension for Continue AI code agent. Provides chat, autocomplete, inline edit, and agent features within JetBrains IDEs. ## Architecture diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index e8eb4332f..c2ba370ed 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -83,6 +83,7 @@ class MessageTypes { "devdata/log", "config/addModel", "config/newPromptFile", + "config/newAssistantFile", "config/ideSettingsUpdate", "config/addLocalWorkspaceBlock", "config/getSerializedProfileInfo", diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 5970b57bd..2d4b2e1af 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -113,6 +113,13 @@ + + + + { const description = await GUISelectors.getDescription(view); expect(await description.getText()).has.string( - "Log in to quickly build your first custom AI code assistant", + "Log in to quickly build your first custom AI code agent", ); }).timeout(DEFAULT_TIMEOUT.XL); @@ -281,7 +281,7 @@ describe("GUI Test", () => { // Verify the rule content const ruleItemText = await ruleItem.getText(); - expect(ruleItemText).to.include("Assistant rule"); + expect(ruleItemText).to.include("Agent rule"); expect(ruleItemText).to.include("Always applied"); expect(ruleItemText).to.include("TEST_SYS_MSG"); }).timeout(DEFAULT_TIMEOUT.MD); diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 5b7116451..5ae6a62b8 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -18,9 +18,9 @@ "homepage": "https://continue.dev", "qna": "https://github.com/continuedev/continue/issues/new/choose", "license": "Apache-2.0", - "displayName": "Continue - open-source AI code assistant", + "displayName": "Continue - open-source AI code agent", "pricing": "Free", - "description": "The leading open-source AI code assistant", + "description": "The leading open-source AI code agent", "publisher": "Continue", "engines": { "vscode": "^1.70.0", diff --git a/extensions/vscode/rules.md b/extensions/vscode/rules.md index 865f0dac5..5a1108c05 100644 --- a/extensions/vscode/rules.md +++ b/extensions/vscode/rules.md @@ -1,4 +1,4 @@ -The `extensions/vscode` folder contains code for the "Continue" VS Code Extension. Continue is a coding assistant extension which extends IDE functionality with AI. +The `extensions/vscode` folder contains code for the "Continue" VS Code Extension. Continue is a coding extension which extends IDE functionality with AI. Core IDE functionality, such as reading files, is implemented using the `VSCodeIDE` class. Code to enable editing/diff streaming into the editor, code suggestion autocompletion, and more can also be found in this directory. Shared code that has abstract logic for the extension is in `core/`. Avoid importing code from `core/` directly where possible. Core is designed to be bundalable as a binary. Use `core.invoke` to send messages to the diff --git a/extensions/vscode/src/activation/SelectionChangeManager.ts b/extensions/vscode/src/activation/SelectionChangeManager.ts index d8851ce52..100a373be 100644 --- a/extensions/vscode/src/activation/SelectionChangeManager.ts +++ b/extensions/vscode/src/activation/SelectionChangeManager.ts @@ -150,6 +150,14 @@ export class SelectionChangeManager { ); } + /** + * Updates this class's usingFullFileDiff flag. + * @param usingFullFileDiff New value to set. + */ + public updateUsingFullFileDiff(usingFullFileDiff: boolean) { + this.usingFullFileDiff = usingFullFileDiff; + } + public documentChanged(): void { this.isTypingSession = true; this.lastDocumentChangeTime = Date.now(); diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 464f9f4f0..19be7545e 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -6,15 +6,21 @@ import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion, isUnsupportedPlatform } from "../util/util"; +import { GlobalContext } from "core/util/GlobalContext"; import { VsCodeContinueApi } from "./api"; import setupInlineTips from "./InlineTipManager"; export async function activateExtension(context: vscode.ExtensionContext) { const platformCheck = isUnsupportedPlatform(); - if (platformCheck.isUnsupported) { - // const platformTarget = `${getPlatform()}-${getArchitecture()}`; + const globalContext = new GlobalContext(); + const hasShownUnsupportedPlatformWarning = globalContext.get( + "hasShownUnsupportedPlatformWarning", + ); + + if (platformCheck.isUnsupported && !hasShownUnsupportedPlatformWarning) { const platformTarget = "windows-arm64"; + globalContext.update("hasShownUnsupportedPlatformWarning", true); void vscode.window.showInformationMessage( `Continue detected that you are using ${platformTarget}. Due to native dependencies, Continue may not be able to start`, ); diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index e8384dac0..1ca79a25f 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -86,7 +86,7 @@ export class ApplyManager { } finally { await this.webviewProtocol.request("updateApplyState", { streamId, - status: "closed", + status: "done", toolCallId, }); } diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index db420924c..f081d2430 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -132,6 +132,15 @@ export class ContinueCompletionProvider return config.selectedModelByRole.rerank ?? undefined; } + /** + * Updates this class and the prefetch queue's usingFullFileDiff flag. + * @param usingFullFileDiff New value to set. + */ + public updateUsingFullFileDiff(usingFullFileDiff: boolean) { + this.usingFullFileDiff = usingFullFileDiff; + this.prefetchQueue.initialize(this.usingFullFileDiff); + } + public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index dba2f468b..943562e80 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -44,6 +44,7 @@ import { VsCodeMessenger } from "./VsCodeMessenger"; import { getAst } from "core/autocomplete/util/ast"; import { modelSupportsNextEdit } from "core/llm/autodetect"; +import { NEXT_EDIT_MODELS } from "core/llm/constants"; import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import { isNextEditTest } from "core/nextEdit/utils"; @@ -103,6 +104,32 @@ export class VsCodeExtension { this.extensionContext = context; this.windowId = uuidv4(); + // Check if model supports next edit to determine if we should use full file diff. + const getUsingFullFileDiff = async () => { + const { config } = await this.configHandler.loadConfig(); + const autocompleteModel = config?.selectedModelByRole.autocomplete; + + if (!autocompleteModel) { + return false; + } + + if ( + !modelSupportsNextEdit( + autocompleteModel.capabilities, + autocompleteModel.model, + autocompleteModel.title, + ) + ) { + return false; + } + + if (autocompleteModel.model.includes(NEXT_EDIT_MODELS.INSTINCT)) { + return false; + } + + return true; + }; + const usingFullFileDiff = true; const selectionManager = SelectionChangeManager.getInstance(); selectionManager.initialize(this.ide, usingFullFileDiff); @@ -190,7 +217,11 @@ export class VsCodeExtension { ), ); - void this.configHandler.loadConfig().then(({ config }) => { + void this.configHandler.loadConfig().then(async ({ config }) => { + const shouldUseFullFileDiff = await getUsingFullFileDiff(); + this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff); + selectionManager.updateUsingFullFileDiff(shouldUseFullFileDiff); + const { verticalDiffCodeLens } = registerAllCodeLensProviders( context, this.verticalDiffManager.fileUriToCodeLens, @@ -203,7 +234,12 @@ export class VsCodeExtension { this.configHandler.onConfigUpdate( async ({ config: newConfig, configLoadInterrupted }) => { + const shouldUseFullFileDiff = await getUsingFullFileDiff(); + this.completionProvider.updateUsingFullFileDiff(shouldUseFullFileDiff); + selectionManager.updateUsingFullFileDiff(shouldUseFullFileDiff); + const autocompleteModel = newConfig?.selectedModelByRole.autocomplete; + if ( (autocompleteModel && modelSupportsNextEdit( diff --git a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx index 89ac2a81b..18240e098 100644 --- a/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx +++ b/gui/src/components/AssistantAndOrgListbox/AssistantOptions.tsx @@ -15,14 +15,14 @@ export function AssistantOptions({ return ( <>
- +
{profiles?.length === 0 ? (
- No assistants found + No agents found
) : ( profiles?.map((profile, idx) => ( diff --git a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx index 86ba08916..13f768111 100644 --- a/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx +++ b/gui/src/components/AssistantAndOrgListbox/SelectedAssistantButton.tsx @@ -26,7 +26,7 @@ export function SelectedAssistantButton({ >
{selectedProfile === null ? ( - "Create your first assistant" + "Create your first agent" ) : configLoading ? ( (null); const currentOrg = useAppSelector(selectCurrentOrg); const ideMessenger = useContext(IdeMessengerContext); - const { isToolbarExpanded } = useLump(); const { profiles, selectedProfile, @@ -38,7 +42,6 @@ export function AssistantAndOrgListbox() { refreshProfiles, } = useAuth(); const configLoading = useAppSelector((store) => store.config.loading); - const smallFont = useFontSize(-3); const tinyFont = useFontSize(-4); const shouldRenderOrgInfo = session && organizations.length > 1 && !isOnPremSession(session); @@ -50,10 +53,14 @@ export function AssistantAndOrgListbox() { } function onNewAssistant() { - void ideMessenger.request("controlPlane/openUrl", { - path: "/new", - orgSlug: currentOrg?.slug, - }); + if (session) { + void ideMessenger.request("controlPlane/openUrl", { + path: "/new", + orgSlug: currentOrg?.slug, + }); + } else { + void ideMessenger.request("config/newAssistantFile", undefined); + } close(); } @@ -108,12 +115,29 @@ export function AssistantAndOrgListbox() {
- -
-
- {session && session?.AUTH_TYPE !== AuthType.OnPrem && ( - - {session?.account.id} + +
+
+ {session ? ( + + {session?.AUTH_TYPE !== AuthType.OnPrem && + session?.account.id} + + Logout + + ) : ( + login(false)} + > + Log In )} {shouldRenderOrgInfo && ( @@ -138,13 +162,13 @@ export function AssistantAndOrgListbox() { value="new-assistant" fontSizeModifier={-2} className="border-border border-b px-2 py-1.5" - onClick={session ? onNewAssistant : () => login(false)} + onClick={onNewAssistant} > - New Assistant + New Agent @@ -166,32 +190,16 @@ export function AssistantAndOrgListbox() { configLoading && "animate-spin-slow", )} /> - Reload assistants + Reload agents - {session && ( - -
- Log out -
-
- )} -
- {getMetaKeyLabel()} ⇧ ' to toggle assistant + {getMetaKeyLabel()} ⇧ ' to toggle agent
diff --git a/gui/src/components/ExploreHubCard/index.tsx b/gui/src/components/ExploreHubCard/index.tsx index bf6327c35..07a9e2919 100644 --- a/gui/src/components/ExploreHubCard/index.tsx +++ b/gui/src/components/ExploreHubCard/index.tsx @@ -25,13 +25,10 @@ export function ExploreHubCard() { >
-

- Create Your Own Assistant -

+

Create Your Own Agent

- Discover and remix popular assistants, or create your own from - scratch + Discover and remix popular agents, or create your own from scratch

@@ -39,12 +36,12 @@ export function ExploreHubCard() { className="w-full" onClick={() => { ideMessenger.request("controlPlane/openUrl", { - path: "/explore/assistants", + path: "/?type=assistants", orgSlug: undefined, }); }} > - Explore Assistants + Explore Agents
- Or, create your own assistant from scratch + Or, create your own agent from scratch
diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index 40abbea5f..22fcf971e 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -58,7 +58,7 @@ export function OnboardingCardLanding({ <>

You've reached the free trial limit. Visit the Continue Platform to - select a Coding Assistant. + select a Coding Agent.

diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index f632cb10a..009fcb59b 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -90,7 +90,7 @@ const RuleCard: React.FC = ({ rule }) => { } else if (rule.source === "model-options-chat") { return "Base System Chat Message"; } else { - return "Assistant rule"; + return "Agent rule"; } } }, [rule]); diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index ad07a86d6..29feb6680 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,6 +1,5 @@ import { useLump } from "../LumpContext"; import { ContextSection } from "./ContextSection"; -import DocsSection from "./docs/DocsSection"; import { ErrorSection } from "./errors/ErrorSection"; import MCPSection from "./mcp/MCPSection"; import { ModelsSection } from "./ModelsSection"; @@ -19,8 +18,6 @@ export function SelectedSection() { return ; case "rules": return ; - case "docs": - return ; case "prompts": return ; case "context": diff --git a/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx b/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx index c887e9d9e..2dd29c13e 100644 --- a/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/RulesPeek.tsx @@ -78,7 +78,7 @@ export function RulesPeekItem({ rule }: RulesPeekItemProps) {
- {rule.name || "Assistant rule"} + {rule.name || "Agent rule"}
diff --git a/gui/src/pages/config/HelpCenterSection.tsx b/gui/src/pages/config/HelpCenterSection.tsx index 7a711068c..df8fa7bbd 100644 --- a/gui/src/pages/config/HelpCenterSection.tsx +++ b/gui/src/pages/config/HelpCenterSection.tsx @@ -40,7 +40,7 @@ export function HelpCenterSection() {
ideMessenger.post("openUrl", "https://hub.continue.dev/") diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgressSubtext.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgressSubtext.tsx index e24eb5564..ce973d21a 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgressSubtext.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgressSubtext.tsx @@ -15,7 +15,7 @@ const STATUS_TO_SUBTITLE_TEXT: Record< indexing: "Click to pause", paused: "Click to resume", failed: "Click to retry", - disabled: "Click to open assistant configuration", + disabled: "Click to open agent configuration", cancelled: "Click to restart", }; diff --git a/gui/src/pages/config/IndexingSettingsSection.tsx b/gui/src/pages/config/IndexingSettingsSection.tsx index 6df4faed0..2efdfcae9 100644 --- a/gui/src/pages/config/IndexingSettingsSection.tsx +++ b/gui/src/pages/config/IndexingSettingsSection.tsx @@ -1,26 +1,37 @@ +import DocsIndexingStatuses from "../../components/mainInput/Lump/sections/docs/DocsSection"; import { useAppSelector } from "../../redux/hooks"; import IndexingProgress from "./IndexingProgress"; export function IndexingSettingsSection() { const config = useAppSelector((state) => state.config.config); return ( -
+

@codebase index

Local embeddings of your codebase + {config.disableIndexing ? ( +
+

+ Indexing is disabled +

+

+ Open settings and toggle Enable Indexing to re-enable +

+
+ ) : ( + + )}
- {config.disableIndexing ? ( -
-

Indexing is disabled

-

- Open settings and toggle Enable Indexing to re-enable -

-
- ) : ( - - )} + +
+

@docs index

+ + Local embeddings of your documentation sources + +
+
); } diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 649de4310..bbb75b141 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -59,12 +59,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { const checkKeysButton = apiKeyUrl ? ( { - ideMessenger.post("controlPlane/openUrl", { - path: apiKeyUrl, - orgSlug: undefined, - }); - }} + onClick={() => ideMessenger.ide.openUrl(apiKeyUrl)} > View key @@ -201,9 +196,9 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
{session && selectedProfile && !isLocalProfile(selectedProfile) && (
- {`If your hub secret values may have changed, refresh your assistants`} + {`If your hub secret values may have changed, refresh your agents`} - Refresh assistant secrets + Refresh agent secrets
)} diff --git a/gui/src/redux/slices/profilesSlice.ts b/gui/src/redux/slices/profilesSlice.ts index 16d0498ae..a60c7b775 100644 --- a/gui/src/redux/slices/profilesSlice.ts +++ b/gui/src/redux/slices/profilesSlice.ts @@ -28,7 +28,7 @@ const initialState: ProfilesState = { id: "personal", profiles: [ { - title: "Local Assistant", + title: "Local Agent", id: "local", errors: [], profileType: "local", diff --git a/gui/src/util/test/utils.ts b/gui/src/util/test/utils.ts index ebc4181d7..0326306cf 100644 --- a/gui/src/util/test/utils.ts +++ b/gui/src/util/test/utils.ts @@ -10,7 +10,7 @@ function logDomText() { const doc = parser.parseFromString(bodyText, "text/html"); let cleaned = doc.body.textContent ?? ""; cleaned = cleaned?.replace( - "No resultsAaModelsRulesDocsPromptsToolsMCPCreate your first assistant", + "No resultsAaModelsRulesDocsPromptsToolsMCPCreate your first agent", "", ); cleaned = cleaned?.replace( diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index 4ba87bb81..b537ede56 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -107,7 +107,7 @@ describe("E2E Scenarios", () => { uriType: "slug", fullSlug: { ownerSlug: "test-org", - packageSlug: "assistant-with-non-existing-block", + packageSlug: "agent-with-non-existing-block", versionSlug: "latest", }, }, @@ -130,7 +130,7 @@ describe("E2E Scenarios", () => { uriType: "slug", fullSlug: { ownerSlug: "test-org", - packageSlug: "assistant", + packageSlug: "agent", versionSlug: "latest", }, }, @@ -221,7 +221,7 @@ describe("E2E Scenarios", () => { uriType: "slug", fullSlug: { ownerSlug: "test-org", - packageSlug: "assistant", + packageSlug: "agent", versionSlug: "latest", }, }, @@ -276,7 +276,7 @@ describe("E2E Scenarios", () => { const unrolledConfig = await unrollAssistant( { uriType: "file", - fileUri: "./src/__tests__/local-files/duplicate-test-assistant.yaml", + fileUri: "./src/__tests__/local-files/duplicate-test-agent.yaml", }, registry, { diff --git a/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml b/packages/config-yaml/src/__tests__/local-files/duplicate-test-agent.yaml similarity index 95% rename from packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml rename to packages/config-yaml/src/__tests__/local-files/duplicate-test-agent.yaml index 7f5eca13a..05a79683d 100644 --- a/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml +++ b/packages/config-yaml/src/__tests__/local-files/duplicate-test-agent.yaml @@ -1,4 +1,4 @@ -name: Duplicate Test Assistant +name: Duplicate Test Agent version: 0.0.1 schema: v1 diff --git a/packages/config-yaml/src/__tests__/packages/test-org/assistant-with-non-existing-block.yaml b/packages/config-yaml/src/__tests__/packages/test-org/agent-with-non-existing-block.yaml similarity index 64% rename from packages/config-yaml/src/__tests__/packages/test-org/assistant-with-non-existing-block.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/agent-with-non-existing-block.yaml index 4f01b32b8..885b0dac7 100644 --- a/packages/config-yaml/src/__tests__/packages/test-org/assistant-with-non-existing-block.yaml +++ b/packages/config-yaml/src/__tests__/packages/test-org/agent-with-non-existing-block.yaml @@ -1,4 +1,4 @@ -name: Assistant with non-existing block +name: Agent with non-existing block version: 0.0.1 schema: v1 diff --git a/packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml b/packages/config-yaml/src/__tests__/packages/test-org/agent.yaml similarity index 97% rename from packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml rename to packages/config-yaml/src/__tests__/packages/test-org/agent.yaml index 6836f0c73..9a6d53e18 100644 --- a/packages/config-yaml/src/__tests__/packages/test-org/assistant.yaml +++ b/packages/config-yaml/src/__tests__/packages/test-org/agent.yaml @@ -1,4 +1,4 @@ -name: Assistant +name: Agent version: 0.0.1 schema: v1 diff --git a/packages/config-yaml/src/load/unroll.test.ts b/packages/config-yaml/src/load/unroll.test.ts index 5df66084b..9b2551f2d 100644 --- a/packages/config-yaml/src/load/unroll.test.ts +++ b/packages/config-yaml/src/load/unroll.test.ts @@ -8,7 +8,7 @@ describe("parseMarkdownRuleOrAssistantUnrolled tests", () => { fileUri: "./foo/bar.yaml", }; const yamlContent = ` -name: Test Assistant +name: Test Agent version: 1.0.0 models: @@ -17,7 +17,7 @@ models: provider: ollama `; const result = parseMarkdownRuleOrAssistantUnrolled(yamlContent, mockId); - expect(result).toHaveProperty("name", "Test Assistant"); + expect(result).toHaveProperty("name", "Test Agent"); expect(result).toHaveProperty("version", "1.0.0"); expect(result.models?.length).toBe(1); expect(result.models?.[0]).toHaveProperty("name", "model"); @@ -58,7 +58,7 @@ This is the rule fileUri: "./foo/bar.yaml", }; const invalidContent = ` -name: Test Assistant +name: Test Agent version: 1.0.0 model: # should be models diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 21af99303..c2e524c4c 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -45,12 +45,12 @@ export function parseConfigYaml(configYaml: string): ConfigYaml { "cause" in e && e.cause === "result.success was false" ) { - throw new Error(`Failed to parse assistant: ${e.message}`); + throw new Error(`Failed to parse agent: ${e.message}`); } else if (e instanceof ZodError) { - throw new Error(`Failed to parse assistant: ${formatZodError(e)}`); + throw new Error(`Failed to parse agent: ${formatZodError(e)}`); } else { throw new Error( - `Failed to parse assistant: ${e instanceof Error ? e.message : e}`, + `Failed to parse agent: ${e instanceof Error ? e.message : e}`, ); } } @@ -65,7 +65,7 @@ export function parseAssistantUnrolled(configYaml: string): AssistantUnrolled { console.error( `Failed to parse unrolled assistant: ${e.message}\n\n${configYaml}`, ); - throw new Error(`Failed to parse unrolled assistant: ${formatZodError(e)}`); + throw new Error(`Failed to parse agent: ${formatZodError(e)}`); } } diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 2239571b2..c7025a39d 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1,19 +1,19 @@ { "name": "@continuedev/openai-adapters", - "version": "1.1.1", + "version": "1.5.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.1.1", + "version": "1.5.1", "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", - "@continuedev/config-types": "file:../config-types", - "@continuedev/config-yaml": "file:../config-yaml", - "@continuedev/fetch": "file:../fetch", + "@continuedev/config-types": "^1.0.14", + "@continuedev/config-yaml": "^1.8.0", + "@continuedev/fetch": "^1.0.16", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", @@ -42,6 +42,7 @@ "../config-types": { "name": "@continuedev/config-types", "version": "1.0.14", + "extraneous": true, "license": "Apache-2.0", "dependencies": { "zod": "^3.24.2" @@ -51,33 +52,6 @@ "typescript": "^5.5.2" } }, - "../config-yaml": { - "name": "@continuedev/config-yaml", - "version": "1.0.96", - "license": "Apache-2.0", - "dependencies": { - "@continuedev/config-types": "file:../config-types", - "yaml": "^2.6.1", - "zod": "^3.24.2" - }, - "bin": { - "config-yaml": "dist/cli.js" - }, - "devDependencies": { - "@semantic-release/changelog": "^6.0.3", - "@semantic-release/git": "^10.0.1", - "@semantic-release/github": "^9.2.6", - "@semantic-release/npm": "^10.0.6", - "@types/jest": "^29.5.14", - "@types/node": "^20.0.0", - "cross-env": "^7.0.3", - "jest": "^29.7.0", - "semantic-release": "^21.1.2", - "ts-jest": "^29.2.3", - "ts-node": "^10.9.2", - "zod-to-json-schema": "^3.24.5" - } - }, "../fetch": { "name": "@continuedev/fetch", "version": "1.0.16", @@ -1392,12 +1366,25 @@ } }, "node_modules/@continuedev/config-types": { - "resolved": "../config-types", - "link": true + "version": "1.0.14", + "license": "Apache-2.0", + "dependencies": { + "zod": "^3.24.2" + } }, "node_modules/@continuedev/config-yaml": { - "resolved": "../config-yaml", - "link": true + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.8.0.tgz", + "integrity": "sha512-L/6MNpCmpZu6H6x2iDYCdJuLYJqD8Pigj16IUofboSmQtrMKJS379MdI9+5fA/FS+bnqqyzyTNImYXoTBXUn3A==", + "license": "Apache-2.0", + "dependencies": { + "@continuedev/config-types": "file:../config-types", + "yaml": "^2.6.1", + "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" + } }, "node_modules/@continuedev/fetch": { "resolved": "../fetch", @@ -12870,7 +12857,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -13387,9 +13373,6 @@ "version": "2.7.0", "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.7.0.tgz", "integrity": "sha512-+hSoy/QHluxmC9kCIJyL/uyFmLmc+e5CFR5Wa+bpIhIj85LVb9ZH2nVnqrHoSvKogwODv0ClqZkmiSSaIH5LTA==", - "dev": true, - "optional": true, - "peer": true, "bin": { "yaml": "bin.mjs" }, diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 0065bba17..f6773a647 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.1.1", + "version": "1.5.1", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -14,9 +14,9 @@ "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", - "@continuedev/config-types": "file:../config-types", - "@continuedev/config-yaml": "file:../config-yaml", - "@continuedev/fetch": "file:../fetch", + "@continuedev/config-types": "^1.0.14", + "@continuedev/config-yaml": "^1.8.0", + "@continuedev/fetch": "^1.0.16", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", diff --git a/packages/openai-adapters/src/apis/Inception.ts b/packages/openai-adapters/src/apis/Inception.ts index 99795517a..e32694277 100644 --- a/packages/openai-adapters/src/apis/Inception.ts +++ b/packages/openai-adapters/src/apis/Inception.ts @@ -1,10 +1,28 @@ import { streamSse } from "@continuedev/fetch"; -import { ChatCompletionChunk, Model } from "openai/resources/index"; +import { + ChatCompletion, + ChatCompletionChunk, + ChatCompletionCreateParamsNonStreaming, + ChatCompletionCreateParamsStreaming, + ChatCompletionMessageParam, + Model, +} from "openai/resources/index"; import { InceptionConfig } from "../types.js"; import { chatChunk, customFetch } from "../util.js"; import { OpenAIApi } from "./OpenAI.js"; import { FimCreateParamsStreaming } from "./base.js"; +// export type InceptionChatCompletionCreateParamsStreaming = +// ChatCompletionCreateParamsStreaming & { +// nextEdit?: boolean; +// }; + +// export type InceptionChatCompletionCreateParamsNonStreaming = +// ChatCompletionCreateParamsNonStreaming & { +// nextEdit?: boolean; +// }; + +export const UNIQUE_TOKEN = "<|!@#IS_NEXT_EDIT!@#|>"; export const INCEPTION_API_BASE = "https://api.inceptionlabs.ai/v1/"; export class InceptionApi extends OpenAIApi { constructor(config: InceptionConfig) { @@ -15,6 +33,101 @@ export class InceptionApi extends OpenAIApi { }); } + // Add custom edit completions method. + async *editCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const endpoint = new URL("edit/completions", this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + for await (const chunk of streamSse(resp as any)) { + if (chunk.choices?.[0]?.delta?.content) { + yield chatChunk({ + content: chunk.choices[0].delta.content, + finish_reason: chunk.choices[0].finish_reason || null, + model: body.model, + }); + } + } + } + + // Add custom edit completions method (non-streaming). + async editCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + const endpoint = new URL("edit/completions", this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + messages: body.messages, + max_tokens: body.max_tokens, + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: body.stop, + stream: false, // Set to false for non-streaming + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + + const data = await resp.json(); + return data as ChatCompletion; + } + + // Override the regular chat stream method to route to edit endpoint for next edit requests. + async *chatCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + if (this.isNextEdit(body.messages)) { + body.messages = this.removeNextEditToken(body.messages); + yield* this.editCompletionStream(body, signal); + } else { + yield* super.chatCompletionStream(body, signal); + } + } + + // Override the regular chat non stream method to route to edit endpoint for next edit requests. + async chatCompletionNonStream( + body: ChatCompletionCreateParamsNonStreaming, + signal: AbortSignal, + ): Promise { + if (this.isNextEdit(body.messages)) { + body.messages = this.removeNextEditToken(body.messages); + return this.editCompletionNonStream(body, signal); + } else { + return super.chatCompletionNonStream(body, signal); + } + } + async *fimStream( body: FimCreateParamsStreaming, signal: AbortSignal, @@ -56,4 +169,34 @@ export class InceptionApi extends OpenAIApi { list(): Promise { throw new Error("Method not implemented."); } + + // Check if any message contains the unique next edit token. + private isNextEdit(messages: ChatCompletionMessageParam[]): boolean { + return messages.some( + (message) => + typeof message.content === "string" && + message.content.endsWith(UNIQUE_TOKEN), + ); + } + + // Remove the unique token from messages. + private removeNextEditToken( + messages: ChatCompletionMessageParam[], + ): ChatCompletionMessageParam[] { + const lastMessage = messages[messages.length - 1]; + + if ( + typeof lastMessage?.content === "string" && + lastMessage.content.endsWith(UNIQUE_TOKEN) + ) { + const cleanedMessages = [...messages]; + cleanedMessages[cleanedMessages.length - 1] = { + ...lastMessage, + content: lastMessage.content.slice(0, -UNIQUE_TOKEN.length), + }; + return cleanedMessages; + } + + return messages; + } }