diff --git a/.continue/prompts/update-llm-info.prompt b/.continue/prompts/update-llm-info.prompt index 7264ebf38..9c1cf1f8e 100644 --- a/.continue/prompts/update-llm-info.prompt +++ b/.continue/prompts/update-llm-info.prompt @@ -44,8 +44,8 @@ export const AllMediaTypes = [ 2. EXTRACT NEW INFORMATION -New information will be pulled from the internet. -If you do not see a web search tool, let me know. +Fetch information from the internet using the search web and read url tools. +If you do not see either of these tools, stop and let me know. Retrieve the following sites per these providers, and consider these notes on how to extract the information: - "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit" diff --git a/.continue/rules/documentation-standards.md b/.continue/rules/documentation-standards.md index a510b7ca7..4fa6984de 100644 --- a/.continue/rules/documentation-standards.md +++ b/.continue/rules/documentation-standards.md @@ -1,16 +1,111 @@ --- -globs: docs/**/*.{md,mdx} -description: Standards for writing and maintaining Continue Docs +globs: docs/\*_/_.{md,mdx} +description: This style guide should be used as a reference for maintaining consistency across all Continue documentation +alwaysApply: false --- -# Continue Docs Standards +# Continue Documentation Style Guide + +## Overview + +## Writing Tone & Voice + +### Conversational and Direct - Follow Docusaurus documentation standards -- Include YAML frontmatter with title, description, and keywords -- Use consistent heading hierarchy starting with h2 (##) -- Include relevant Admonition components for tips, warnings, and info -- Use descriptive alt text for images -- Include cross-references to related documentation -- Reference other docs with relative paths +- Use simple, conversational language that gets straight to the point +- Avoid overly technical jargon when simpler terms work +- Write as if speaking directly to the developer using the tool - Keep paragraphs concise and scannable -- Use code blocks with appropriate language tags + +**Example:** +✅ "You send it a question, and it replies with an answer" +❌ "The system processes user queries and generates corresponding responses" + +### Helpful and Instructional + +- Focus on helping users accomplish their goals +- Use active voice and imperative mood for instructions +- Assume users want to get things done quickly +- Include relevant Admonition components for tips, warnings, and info + +**Example:** +✅ "Press cmd/ctrl + L to begin a new session" +❌ "A new session can be initiated by pressing cmd/ctrl + L" + +### Practical and Task-Oriented + +- Emphasize what users can accomplish with each feature +- Lead with benefits and use cases before diving into mechanics +- Keep explanations grounded in real-world scenarios + +## Content Structure + +### Page Organization + +1. **Visual Introduction**: Lead with GIFs or images showing the feature in action +2. **Purpose Statement**: Brief explanation of what the feature does and when to use it +3. **Step-by-Step Instructions**: Clear, actionable steps with keyboard shortcuts +4. **Platform-Specific Notes**: Separate sections for VS Code and JetBrains when needed +5. **Additional Tips**: Advanced usage or troubleshooting notes + +### Section Headers + +- Use consistent heading hierarchy starting with h2 (##) +- Include YAML frontmatter with title, description, and keywords +- Use action-oriented headers that describe what users will do +- Format: "Verb + object" (e.g., "Type a request and press enter") +- Keep headers concise but descriptive +- Use title case + +**Examples:** +✅ "Highlight code and activate" +✅ "Accept or reject changes" +✅ "Switch between different models" + +### Lists and Steps + +- Use numbered lists for sequential steps +- Use bullet points for feature lists or options +- Keep list items parallel in structure +- Start action items with verbs + +## Technical Writing Standards + +### Code and Keyboard Shortcuts + +- Use `backticks` for inline code elements +- Format keyboard shortcuts consistently: `cmd/ctrl + L` +- Always provide shortcuts for Mac/Windows/Linux +- Use code blocks for configuration examples with proper syntax highlighting + +### Cross-References + +- Link to related sections using descriptive anchor text +- Use relative links to other documentation pages +- Format: `[descriptive text](/path/to/page)` + +### Platform Differences + +- Always address both VS Code and JetBrains when applicable +- Use clear subheadings to separate platform-specific instructions +- Lead with the more common platform (typically VS Code) when both are covered + +## Language Conventions + +### Terminology + +- **Consistent Terms**: Use the same terms throughout (e.g., "LLM" not "AI model" in some places) +- **Product Names**: Capitalize product names correctly (VS Code, JetBrains, Continue) +- **Feature Names**: Use consistent capitalization for Continue features (Chat, Edit, Agent, Autocomplete) + +### Abbreviations + +- Spell out acronyms on first use, then use abbreviation consistently +- Common abbreviations: LLM, IDE, API, URL + +### Pronouns + +- Use "you" to address the user directly +- Use "it" to refer to the tool/model +- Avoid "we" unless referring to the Continue team diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json index c36494c2f..69d4e1087 100644 --- a/.eslintrc.shared.json +++ b/.eslintrc.shared.json @@ -10,6 +10,7 @@ "@typescript-eslint/naming-convention": "off", "@typescript-eslint/no-floating-promises": "warn", "@typescript-eslint/semi": "warn", + "@typescript-eslint/no-misused-promises": "error", "curly": "warn", "eqeqeq": "warn", "no-throw-literal": "warn", diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 919ae0fe7..326934314 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -396,6 +396,11 @@ jobs: npx tsc --noEmit npm run lint + - name: Run vitest tests + run: | + cd extensions/vscode + npm run vitest + core-tests: needs: [install-core, install-config-yaml] runs-on: ubuntu-latest @@ -434,7 +439,7 @@ jobs: GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} - AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1b981a612..6d89e4655 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -123,6 +123,12 @@ version of Node.js for this project by running the following command in the root nvm use ``` +Then, install Vite globally + +```bash +npm i -g vite +``` + #### Fork the Continue Repository 1. Go to the [Continue GitHub repository](https://github.com/continuedev/continue) and fork it to your GitHub account. diff --git a/binary/package-lock.json b/binary/package-lock.json index abb11ce8e..ead2d8b83 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -20,6 +20,7 @@ "posthog-node": "^3.6.3", "system-ca": "^1.0.2", "tar": "^7.4.3", + "undici": "^7.10.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "win-ca": "^3.5.1" @@ -52,9 +53,9 @@ "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", "@continuedev/config-yaml": "file:../packages/config-yaml", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.13", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.25", + "@continuedev/openai-adapters": "^1.0.32", "@modelcontextprotocol/sdk": "^1.12.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -105,6 +106,7 @@ "sqlite3": "^5.1.7", "system-ca": "^1.0.3", "tar": "^7.4.3", + "tree-sitter-structured-text": "^0.0.1", "tree-sitter-wasms": "^0.1.11", "uuid": "^9.0.1", "vectordb": "^0.4.20", @@ -143,8 +145,10 @@ "myers-diff": "^2.1.0", "onnxruntime-common": "1.14.0", "onnxruntime-web": "1.14.0", + "tree-sitter-cli": "^0.22.5", "ts-jest": "^29.1.1", - "typescript": "^5.6.3" + "typescript": "^5.6.3", + "vitest": "^3.1.4" }, "engines": { "node": ">=20.19.0" @@ -6773,6 +6777,15 @@ "node": ">=8" } }, + "node_modules/undici": { + "version": "7.10.0", + "resolved": "https://registry.npmmirror.com/undici/-/undici-7.10.0.tgz", + "integrity": "sha512-u5otvFBOBZvmdjWLVW+5DAc9Nkq8f24g0O9oY7qw2JVIF1VocIFoyz9JFkuVOS2j41AufeO0xnlweJ2RLT8nGw==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/universal-user-agent": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", diff --git a/binary/package.json b/binary/package.json index 0e8949aa6..11161d67e 100644 --- a/binary/package.json +++ b/binary/package.json @@ -53,6 +53,7 @@ "posthog-node": "^3.6.3", "system-ca": "^1.0.2", "tar": "^7.4.3", + "undici": "^7.10.0", "uuid": "^9.0.1", "vectordb": "^0.4.20", "win-ca": "^3.5.1" diff --git a/binary/utils/ripgrep.js b/binary/utils/ripgrep.js index 9a26ebe26..725c4d8fe 100644 --- a/binary/utils/ripgrep.js +++ b/binary/utils/ripgrep.js @@ -4,6 +4,7 @@ const { rimrafSync } = require("rimraf"); const tar = require("tar"); const { RIPGREP_VERSION, TARGET_TO_RIPGREP_RELEASE } = require("./targets"); const AdmZip = require("adm-zip"); +const { ProxyAgent } = require("undici"); const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/download/${RIPGREP_VERSION}`; @@ -16,8 +17,13 @@ const RIPGREP_BASE_URL = `https://github.com/BurntSushi/ripgrep/releases/downloa */ async function downloadFile(url, destPath) { // Use the built-in fetch API instead of node-fetch + // Use proxy if set in environment variables + const proxy = process.env.https_proxy || process.env.HTTPS_PROXY; + const agent = proxy ? new ProxyAgent(proxy) : undefined; + const response = await fetch(url, { redirect: "follow", // Automatically follow redirects + dispatcher: agent, }); if (!response.ok) { diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 8a579c231..749b44e25 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -127,6 +127,7 @@ export class CompletionProvider { public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, + force?: boolean, ): Promise { try { // Create abort signal if not given @@ -146,8 +147,12 @@ export class CompletionProvider { const options = await this._getAutocompleteOptions(llm); // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; + if (!force) { + if ( + await this.debouncer.delayAndShouldDebounce(options.debounceDelay) + ) { + return undefined; + } } if (llm.promptTemplates?.autocomplete) { diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.vitest.ts similarity index 100% rename from core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts rename to core/autocomplete/context/root-path-context/test/RootPathContextService.vitest.ts diff --git a/core/autocomplete/context/root-path-context/test/testUtils.ts b/core/autocomplete/context/root-path-context/test/testUtils.ts index 83afc47ef..036097523 100644 --- a/core/autocomplete/context/root-path-context/test/testUtils.ts +++ b/core/autocomplete/context/root-path-context/test/testUtils.ts @@ -40,7 +40,7 @@ export async function testRootPathContext( // @ts-ignore .spyOn(service, "getSnippets") // @ts-ignore - .mockImplementation(async (_filepath, _endPosition) => { + .mockImplementation((_filePath, _endPosition) => { return []; }); diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.vitest.ts similarity index 100% rename from core/autocomplete/filtering/streamTransforms/charStream.test.ts rename to core/autocomplete/filtering/streamTransforms/charStream.vitest.ts diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts similarity index 100% rename from core/autocomplete/filtering/streamTransforms/lineStream.test.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.vitest.ts similarity index 100% rename from core/autocomplete/filtering/test/filter.test.ts rename to core/autocomplete/filtering/test/filter.vitest.ts diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.vitest.ts similarity index 100% rename from core/autocomplete/generation/GeneratorReuseManager.test.ts rename to core/autocomplete/generation/GeneratorReuseManager.vitest.ts diff --git a/core/autocomplete/generation/ListenableGenerator.test.ts b/core/autocomplete/generation/ListenableGenerator.vitest.ts similarity index 100% rename from core/autocomplete/generation/ListenableGenerator.test.ts rename to core/autocomplete/generation/ListenableGenerator.vitest.ts diff --git a/core/autocomplete/generation/utils.test.ts b/core/autocomplete/generation/utils.vitest.ts similarity index 100% rename from core/autocomplete/generation/utils.test.ts rename to core/autocomplete/generation/utils.vitest.ts diff --git a/core/autocomplete/snippets/gitDiffCache.test.ts b/core/autocomplete/snippets/gitDiffCache.vitest.ts similarity index 100% rename from core/autocomplete/snippets/gitDiffCache.test.ts rename to core/autocomplete/snippets/gitDiffCache.vitest.ts diff --git a/core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts b/core/autocomplete/templating/__tests__/formatOpenedFilesContext.vitest.ts similarity index 100% rename from core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts rename to core/autocomplete/templating/__tests__/formatOpenedFilesContext.vitest.ts diff --git a/core/autocomplete/util/completionTestUtils.test.ts b/core/autocomplete/util/completionTestUtils.vitest.ts similarity index 100% rename from core/autocomplete/util/completionTestUtils.test.ts rename to core/autocomplete/util/completionTestUtils.vitest.ts diff --git a/core/autocomplete/util/processSingleLineCompletion.test.ts b/core/autocomplete/util/processSingleLineCompletion.vitest.ts similarity index 100% rename from core/autocomplete/util/processSingleLineCompletion.test.ts rename to core/autocomplete/util/processSingleLineCompletion.vitest.ts diff --git a/core/commands/index.ts b/core/commands/index.ts index 3037d7ef7..d87a3536f 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -25,6 +25,7 @@ export function slashFromCustomCommand( config, selectedCode, fetch, + abortController, }) { // Render prompt template let renderedPrompt: string; @@ -63,7 +64,7 @@ export function slashFromCustomCommand( for await (const chunk of llm.streamChat( messages, - new AbortController().signal, + abortController.signal, completionOptions, )) { yield renderChatMessage(chunk); diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 8fc1ae27b..55499b583 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -4,7 +4,7 @@ import { renderChatMessage } from "../../util/messageContent.js"; const CommitMessageCommand: SlashCommand = { name: "commit", description: "Generate a commit message for current changes", - run: async function* ({ ide, llm, params }) { + run: async function* ({ ide, llm, params, abortController }) { const includeUnstaged = params?.includeUnstaged ?? false; const diff = await ide.getDiff(includeUnstaged); @@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = { const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; for await (const chunk of llm.streamChat( [{ role: "user", content: prompt }], - new AbortController().signal, + abortController.signal, )) { yield renderChatMessage(chunk); } diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 637013476..fba5d4cd3 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -24,7 +24,7 @@ Body:\n\n`; const DraftIssueCommand: SlashCommand = { name: "issue", description: "Draft a GitHub issue", - run: async function* ({ input, llm, history, params }) { + run: async function* ({ input, llm, history, params, abortController }) { if (params?.repositoryUrl === undefined) { yield "This command requires a repository URL to be set in the config file."; return; @@ -46,7 +46,7 @@ const DraftIssueCommand: SlashCommand = { for await (const chunk of llm.streamChat( messages, - new AbortController().signal, + abortController.signal, )) { body += chunk.content; yield renderChatMessage(chunk); diff --git a/core/commands/slash/mcp.ts b/core/commands/slash/mcp.ts index 84df38989..89af5c5c2 100644 --- a/core/commands/slash/mcp.ts +++ b/core/commands/slash/mcp.ts @@ -60,7 +60,7 @@ export function constructMcpSlashCommand( for await (const chunk of context.llm.streamChat( messages, - new AbortController().signal, + context.abortController.signal, context.completionOptions, )) { yield renderChatMessage(chunk); diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index b53c8d3a9..545b75cc2 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -41,7 +41,7 @@ const MAX_EXPLORE_DEPTH = 2; const OnboardSlashCommand: SlashCommand = { name: "onboard", description: "Familiarize yourself with the codebase", - run: async function* ({ llm, ide }) { + run: async function* ({ llm, ide, abortController }) { const [workspaceDir] = await ide.getWorkspaceDirs(); const context = await gatherProjectContext(workspaceDir, ide); @@ -49,7 +49,7 @@ const OnboardSlashCommand: SlashCommand = { for await (const chunk of llm.streamChat( [{ role: "user", content: prompt }], - new AbortController().signal, + abortController.signal, )) { yield renderChatMessage(chunk); } diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index a3a2be6a7..6190f5499 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -38,14 +38,14 @@ function getLastUserHistory(history: ChatMessage[]): string { const ReviewMessageCommand: SlashCommand = { name: "review", description: "Review code and give feedback", - run: async function* ({ llm, history }) { + run: async function* ({ llm, history, abortController }) { const reviewText = getLastUserHistory(history).replace("\\review", ""); const content = `${prompt} \r\n ${reviewText}`; for await (const chunk of llm.streamChat( [{ role: "user", content: content }], - new AbortController().signal, + abortController.signal, )) { yield renderChatMessage(chunk); } diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index d0b830440..f61908e32 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -87,38 +87,40 @@ export class ProfileLifecycleManager { } // Set pending config promise - this.pendingConfigPromise = new Promise(async (resolve, reject) => { - let result: ConfigResult; - // This try catch is expected to catch high-level errors that aren't block-specific - // Like invalid json, invalid yaml, file read errors, etc. - // NOT block-specific loading errors - try { - result = await this.profileLoader.doLoadConfig(); - } catch (e) { - const message = - e instanceof Error - ? `${e.message}\n${e.stack ? e.stack : ""}` - : "Error loading config"; - result = { - errors: [ - { - fatal: true, - message, - }, - ], - config: undefined, - configLoadInterrupted: true, - }; - } + this.pendingConfigPromise = new Promise((resolve) => { + void (async () => { + let result: ConfigResult; + // This try catch is expected to catch high-level errors that aren't block-specific + // Like invalid json, invalid yaml, file read errors, etc. + // NOT block-specific loading errors + try { + result = await this.profileLoader.doLoadConfig(); + } catch (e) { + const message = + e instanceof Error + ? `${e.message}\n${e.stack ? e.stack : ""}` + : "Error loading config"; + result = { + errors: [ + { + fatal: true, + message, + }, + ], + config: undefined, + configLoadInterrupted: true, + }; + } - if (result.config) { - // Add registered context providers - result.config.contextProviders = ( - result.config.contextProviders ?? [] - ).concat(additionalContextProviders); - } + if (result.config) { + // Add registered context providers + result.config.contextProviders = ( + result.config.contextProviders ?? [] + ).concat(additionalContextProviders); + } - resolve(result); + resolve(result); + })(); }); // Wait for the config promise to resolve diff --git a/core/config/loadLocalAssistants.test.ts b/core/config/loadLocalAssistants.test.ts new file mode 100644 index 000000000..2865a5b34 --- /dev/null +++ b/core/config/loadLocalAssistants.test.ts @@ -0,0 +1,241 @@ +import { walkDirCache } from "../indexing/walkDir"; +import { testIde } from "../test/fixtures"; +import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir"; +import { + getAllDotContinueDefinitionFiles, + LoadAssistantFilesOptions, +} from "./loadLocalAssistants"; +describe("getAllDotContinueDefinitionFiles with fileExtType option", () => { + beforeEach(() => { + setUpTestDir(); + walkDirCache.invalidate(); + + // Add test files to the test directory + addToTestDir([ + ".continue/assistants/", + [".continue/assistants/assistant1.yaml", "yaml content 1"], + [".continue/assistants/assistant2.yml", "yaml content 2"], + [".continue/assistants/assistant3.md", "markdown content 1"], + [".continue/assistants/assistant4.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, + "assistants", + ); + expect(result).toHaveLength(2); + expect(result.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), + ); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "assistant3.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, + "assistants", + ); + expect(result).toHaveLength(1); + expect(result.map((f) => f.path.split("/").pop())).toEqual([ + "assistant3.md", + ]); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "assistant1.yaml", + ); + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "assistant2.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, + "assistants", + ); + expect(result).toHaveLength(3); + expect(result.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining([ + "assistant1.yaml", + "assistant2.yml", + "assistant3.md", + ]), + ); + // Should not include .txt files + expect(result.map((f) => f.path.split("/").pop())).not.toContain( + "assistant4.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, + "assistants", + ); + expect(noWorkspaceResult).toHaveLength(0); + + // Test with includeWorkspace: true + const workspaceOnOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const workspaceResult = await getAllDotContinueDefinitionFiles( + testIde, + workspaceOnOptions, + "assistants", + ); + expect(workspaceResult).toHaveLength(2); + expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["assistant1.yaml", "assistant2.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/assistants/", + [".continue/assistants/nonmatch1.txt", "txt content"], + [".continue/assistants/nonmatch2.json", "json content"], + ]); + + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + + fileExtType: "yaml", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "assistants", + ); + expect(result).toHaveLength(0); + }); + + it("should handle directories that don't exist", async () => { + // Create a clean test directory without the assistants folder + tearDownTestDir(); + setUpTestDir(); + + const options: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const result = await getAllDotContinueDefinitionFiles( + testIde, + options, + "assistants", + ); + 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, + "assistants", + ); + expect(result).toHaveLength(2); + const yamlFile = result.find((f) => f.path.includes("assistant1.yaml")); + expect(yamlFile?.content).toBe("yaml content 1"); + }); + + it("should filter by file extension case sensitively", async () => { + // Add files with uppercase extensions + addToTestDir([ + [".continue/assistants/assistant5.YAML", "uppercase yaml"], + [".continue/assistants/assistant6.YML", "uppercase yml"], + [".continue/assistants/assistant7.MD", "uppercase md"], + ]); + + const yamlOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "yaml", + }; + + const yamlResult = await getAllDotContinueDefinitionFiles( + testIde, + yamlOptions, + "assistants", + ); + // Should only get lowercase extensions (current implementation) + expect(yamlResult).toHaveLength(2); + expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual( + expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]), + ); + expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain( + "assistant5.YAML", + ); + + const markdownOptions: LoadAssistantFilesOptions = { + includeGlobal: false, + includeWorkspace: true, + fileExtType: "markdown", + }; + + const markdownResult = await getAllDotContinueDefinitionFiles( + testIde, + markdownOptions, + "assistants", + ); + expect(markdownResult).toHaveLength(1); + expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([ + "assistant3.md", + ]); + expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain( + "assistant7.MD", + ); + }); +}); diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 90c5922a2..feff60183 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -1,4 +1,5 @@ import ignore from "ignore"; +import * as URI from "uri-js"; import { IDE } from ".."; import { DEFAULT_IGNORE_DIRS, @@ -12,18 +13,19 @@ import { joinPathsToUri } from "../util/uri"; export const ASSISTANTS = "assistants"; export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; -export function isLocalAssistantFile(uri: string): boolean { +export function isLocalDefinitionFile(uri: string): boolean { if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) { return false; } - const normalizedUri = uri.replace(/\\/g, "/"); + const normalizedUri = URI.normalize(uri); return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); } async function getDefinitionFilesInDir( ide: IDE, dir: string, + fileExtType?: "yaml" | "markdown", ): Promise<{ path: string; content: string }[]> { try { const exists = await ide.fileExists(dir); @@ -40,9 +42,19 @@ async function getDefinitionFilesInDir( overrideDefaultIgnores, source: "get assistant files", }); - const assistantFilePaths = uris.filter( - (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), - ); + let assistantFilePaths: string[]; + if (fileExtType === "yaml") { + assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + ); + } else if (fileExtType === "markdown") { + assistantFilePaths = uris.filter((p) => p.endsWith(".md")); + } else { + assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"), + ); + } + const results = assistantFilePaths.map(async (uri) => { const content = await ide.readFile(uri); // make a try catch return { path: uri, content }; @@ -57,6 +69,7 @@ async function getDefinitionFilesInDir( export interface LoadAssistantFilesOptions { includeGlobal: boolean; includeWorkspace: boolean; + fileExtType?: "yaml" | "markdown"; } export function getDotContinueSubDirs( @@ -84,7 +97,7 @@ export function getDotContinueSubDirs( /** * This method searches in both ~/.continue and workspace .continue - * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts + * for all YAML/Markdown files in the specified subdirectory, for example .continue/assistants or .continue/prompts */ export async function getAllDotContinueDefinitionFiles( ide: IDE, @@ -101,15 +114,14 @@ export async function getAllDotContinueDefinitionFiles( subDirName, ); - // Get all assistant files from the directories - const assistantFiles = ( - await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir))) + // Get all definition files from the directories + const definitionFiles = ( + await Promise.all( + fullDirs.map((dir) => + getDefinitionFilesInDir(ide, dir, options.fileExtType), + ), + ) ).flat(); - return await Promise.all( - assistantFiles.map(async (file) => { - const content = await ide.readFile(file.path); - return { path: file.path, content }; - }), - ); + return definitionFiles; } diff --git a/core/config/markdown/index.ts b/core/config/markdown/index.ts index feb841e75..98c94e77f 100644 --- a/core/config/markdown/index.ts +++ b/core/config/markdown/index.ts @@ -1,3 +1 @@ -export * from "./createMarkdownRule"; export * from "./loadMarkdownRules"; -export * from "./parseMarkdownRule"; diff --git a/core/config/markdown/loadCodebaseRules.ts b/core/config/markdown/loadCodebaseRules.ts index d3861b7f3..b0d8cac6d 100644 --- a/core/config/markdown/loadCodebaseRules.ts +++ b/core/config/markdown/loadCodebaseRules.ts @@ -1,9 +1,11 @@ -import { ConfigValidationError } from "@continuedev/config-yaml"; +import { + ConfigValidationError, + markdownToRule, +} from "@continuedev/config-yaml"; import { IDE, RuleWithSource } from "../.."; import { walkDirs } from "../../indexing/walkDir"; import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants"; import { getUriPathBasename } from "../../util/uri"; -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; /** * Loads rules from rules.md files colocated in the codebase @@ -29,9 +31,9 @@ export async function loadCodebaseRules(ide: IDE): Promise<{ for (const filePath of rulesMdFiles) { try { const content = await ide.readFile(filePath); - const rule = convertMarkdownRuleToContinueRule(filePath, content); + const rule = markdownToRule(content, { uriType: "file", filePath }); - rules.push(rule); + rules.push({ ...rule, source: "rules-block" }); } catch (e) { errors.push({ fatal: false, diff --git a/core/config/markdown/loadCodebaseRules.vitest.ts b/core/config/markdown/loadCodebaseRules.vitest.ts index 2a60c0de2..9a77f692b 100644 --- a/core/config/markdown/loadCodebaseRules.vitest.ts +++ b/core/config/markdown/loadCodebaseRules.vitest.ts @@ -1,16 +1,16 @@ +import { markdownToRule } from "@continuedev/config-yaml"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { IDE } from "../.."; import { walkDirs } from "../../indexing/walkDir"; import { loadCodebaseRules } from "./loadCodebaseRules"; -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; // Mock dependencies vi.mock("../../indexing/walkDir", () => ({ walkDirs: vi.fn(), })); -vi.mock("./parseMarkdownRule", () => ({ - convertMarkdownRuleToContinueRule: vi.fn(), +vi.mock("@continuedev/config-yaml", () => ({ + markdownToRule: vi.fn(), })); describe("loadCodebaseRules", () => { @@ -82,10 +82,10 @@ describe("loadCodebaseRules", () => { return Promise.resolve(mockRuleContent[path] || ""); }); - // Mock convertMarkdownRuleToContinueRule to return converted rules - (convertMarkdownRuleToContinueRule as any).mockImplementation( - (path: string, content: string) => { - return mockConvertedRules[path]; + // Mock markdownToRule to return converted rules + (markdownToRule as any).mockImplementation( + (content: string, options: any) => { + return mockConvertedRules[options.filePath]; }, ); }); @@ -107,7 +107,7 @@ describe("loadCodebaseRules", () => { expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md"); // Should convert all rules - expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4); + expect(markdownToRule).toHaveBeenCalledTimes(4); // Should return all rules expect(rules).toHaveLength(4); diff --git a/core/config/markdown/loadMarkdownRules.ts b/core/config/markdown/loadMarkdownRules.ts index b0bbb8005..dd506f75c 100644 --- a/core/config/markdown/loadMarkdownRules.ts +++ b/core/config/markdown/loadMarkdownRules.ts @@ -1,7 +1,9 @@ -import { ConfigValidationError } from "@continuedev/config-yaml"; +import { + ConfigValidationError, + markdownToRule, +} from "@continuedev/config-yaml"; import { IDE, RuleWithSource } from "../.."; import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants"; -import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule"; /** * Loads rules from markdown files in the .continue/rules directory @@ -17,7 +19,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ // Get all .md files from .continue/rules const markdownFiles = await getAllDotContinueDefinitionFiles( ide, - { includeGlobal: true, includeWorkspace: true }, + { includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" }, "rules", ); @@ -27,8 +29,11 @@ export async function loadMarkdownRules(ide: IDE): Promise<{ // Process each markdown file for (const file of mdFiles) { try { - const rule = convertMarkdownRuleToContinueRule(file.path, file.content); - rules.push(rule); + const rule = markdownToRule(file.content, { + uriType: "file", + filePath: file.path, + }); + rules.push({ ...rule, source: "rules-block" }); } catch (e) { errors.push({ fatal: false, diff --git a/core/config/markdown/parseMarkdownRule.test.ts b/core/config/markdown/parseMarkdownRule.test.ts deleted file mode 100644 index c23aae7f0..000000000 --- a/core/config/markdown/parseMarkdownRule.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { - convertMarkdownRuleToContinueRule, - parseMarkdownRule, -} from "./parseMarkdownRule"; - -describe("parseMarkdownRule", () => { - it("should correctly parse markdown with YAML frontmatter", () => { - const content = `--- -globs: "**/test/**/*.kt" ---- - -# Test Rule - -This is a test rule.`; - - const result = parseMarkdownRule(content); - expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); - expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); - }); - - it("should handle missing frontmatter", () => { - const content = `# Test Rule - -This is a test rule without frontmatter.`; - - const result = parseMarkdownRule(content); - expect(result.frontmatter).toEqual({}); - expect(result.markdown).toBe(content); - }); - - it("should handle empty frontmatter", () => { - const content = `--- ---- - -# Test Rule - -This is a test rule with empty frontmatter.`; - - const result = parseMarkdownRule(content); - - // Log exact strings for debugging - console.log("Actual:", JSON.stringify(result.markdown)); - console.log( - "Expected:", - JSON.stringify( - "# Test Rule\n\nThis is a test rule with empty frontmatter.", - ), - ); - - expect(result.frontmatter).toEqual({}); - expect(result.markdown).toBe( - "# Test Rule\n\nThis is a test rule with empty frontmatter.", - ); - }); - - it("should handle frontmatter with whitespace", () => { - const content = `--- -globs: "**/test/**/*.kt" ---- - -# Test Rule - -This is a test rule.`; - - const result = parseMarkdownRule(content); - expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); - expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); - }); - - it("should handle Windows line endings (CRLF)", () => { - // Using \r\n for CRLF line endings - const content = `---\r -globs: "**/test/**/*.kt"\r ----\r -\r -# Test Rule\r -\r -This is a test rule.`; - - const result = parseMarkdownRule(content); - expect(result.frontmatter).toEqual({ globs: "**/test/**/*.kt" }); - // The result should be normalized to \n - expect(result.markdown).toBe("# Test Rule\n\nThis is a test rule."); - }); - - it("should handle malformed frontmatter", () => { - const content = `--- -globs: - "**/test/**/*.kt" -invalid: yaml: content ---- - -# Test Rule - -This is a test rule.`; - - // Should treat as only markdown when frontmatter is malformed - const result = parseMarkdownRule(content); - expect(result.frontmatter).toEqual({}); - expect(result.markdown).toBe(content); - }); -}); - -describe("convertMarkdownRuleToContinueRule", () => { - it("should convert markdown with frontmatter to a rule", () => { - const content = `--- -globs: "**/test/**/*.kt" -name: Custom Name ---- - -# Test Rule - -This is a test rule.`; - - const result = convertMarkdownRuleToContinueRule( - "/path/to/rule.md", - content, - ); - expect(result.rule).toBe("# Test Rule\n\nThis is a test rule."); - expect(result.globs).toBe("**/test/**/*.kt"); - expect(result.name).toBe("Custom Name"); - expect(result.source).toBe("rules-block"); - expect(result.ruleFile).toBe("/path/to/rule.md"); - }); - - it("should use the first heading as name if not in frontmatter", () => { - const content = `--- -globs: "**/test/**/*.kt" ---- - -# Test Rule Title - -This is a test rule.`; - - const result = convertMarkdownRuleToContinueRule( - "/path/to/rule.md", - content, - ); - expect(result.name).toBe("Test Rule Title"); - }); - - it("should use filename as name if no heading or frontmatter name", () => { - const content = `--- -globs: "**/test/**/*.kt" ---- - -This is a test rule without a heading.`; - - const result = convertMarkdownRuleToContinueRule( - "/path/to/custom-rule.md", - content, - ); - expect(result.name).toBe("custom-rule"); - }); - - it("should include description from frontmatter", () => { - const content = `--- -globs: "**/test/**/*.kt" -name: Test Rule -description: This is a rule description from frontmatter ---- - -# Test Rule - -This is the content of the rule.`; - - const result = convertMarkdownRuleToContinueRule( - "/path/to/rule.md", - content, - ); - expect(result.description).toBe( - "This is a rule description from frontmatter", - ); - }); - - it("should include `alwaysApply` from frontmatter", () => { - const content = `--- -globs: "**/test/**/*.kt" -name: Test Rule -alwaysApply: false ---- - -# Test Rule - -This is a rule with alwaysApply explicitly set to false.`; - - const result = convertMarkdownRuleToContinueRule( - "/path/to/rule.md", - content, - ); - expect(result.alwaysApply).toBe(false); - }); -}); diff --git a/core/config/markdown/utils.ts b/core/config/markdown/utils.ts new file mode 100644 index 000000000..5fbade09b --- /dev/null +++ b/core/config/markdown/utils.ts @@ -0,0 +1,21 @@ +import { + RULE_FILE_EXTENSION, + sanitizeRuleName, +} from "@continuedev/config-yaml"; +import { joinPathsToUri } from "../../util/uri"; + +/** + * Creates the file path for a rule in the workspace .continue/rules directory + */ +export function createRuleFilePath( + workspaceDir: string, + ruleName: string, +): string { + const safeRuleName = sanitizeRuleName(ruleName); + return joinPathsToUri( + workspaceDir, + ".continue", + "rules", + `${safeRuleName}.${RULE_FILE_EXTENSION}`, + ); +} diff --git a/core/config/markdown/utils.vitest.ts b/core/config/markdown/utils.vitest.ts new file mode 100644 index 000000000..57f20abe7 --- /dev/null +++ b/core/config/markdown/utils.vitest.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vitest"; +import { createRuleFilePath } from "./utils"; + +describe("createRuleFilePath", () => { + it("should create correct rule file path", () => { + const result = createRuleFilePath("/workspace", "My Test Rule"); + expect(result).toBe("/workspace/.continue/rules/my-test-rule.md"); + }); + + it("should handle special characters in rule name", () => { + const result = createRuleFilePath("/home/user", "Rule with @#$% chars"); + expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md"); + }); + + it("should handle edge case rule names", () => { + const result = createRuleFilePath("/test", " Multiple Spaces "); + expect(result).toBe("/test/.continue/rules/multiple-spaces.md"); + }); +}); diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts index 67dfeeffd..e27a631dc 100644 --- a/core/config/migrateSharedConfig.ts +++ b/core/config/migrateSharedConfig.ts @@ -211,6 +211,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { new GlobalContext().updateSharedConfig(shareConfigUpdates); } } catch (e) { - throw new Error(`Migration: Failed to parse config.json: ${e}`); + console.error(`Migration: Failed to parse config.json: ${e}`); } } diff --git a/core/config/types.ts b/core/config/types.ts index 8b7b07e3d..df29d6071 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -719,7 +719,7 @@ declare global { getPinnedFiles(): Promise; - getSearchResults(query: string): Promise; + getSearchResults(query: string, maxResults?: number): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; diff --git a/core/config/usesFreeTrialApiKey.test.ts b/core/config/usesFreeTrialApiKey.test.ts new file mode 100644 index 000000000..8e8727084 --- /dev/null +++ b/core/config/usesFreeTrialApiKey.test.ts @@ -0,0 +1,344 @@ +import { jest } from "@jest/globals"; +import { BrowserSerializedContinueConfig } from ".."; + +// Create the mock before importing anything else +const mockDecodeSecretLocation = jest.fn(); + +// Mock the module +jest.unstable_mockModule("@continuedev/config-yaml", () => ({ + SecretType: { + User: "user", + Organization: "organization", + FreeTrial: "free_trial", + }, + decodeSecretLocation: mockDecodeSecretLocation, +})); + +// Import after mocking +const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey"); +const { SecretType } = await import("@continuedev/config-yaml"); + +beforeEach(() => { + mockDecodeSecretLocation.mockReset(); +}); + +test("usesFreeTrialApiKey should return false when config is null", () => { + const result = usesFreeTrialApiKey(null); + expect(result).toBe(false); +}); + +test("usesFreeTrialApiKey should return false when config is undefined", () => { + const result = usesFreeTrialApiKey(undefined as any); + expect(result).toBe(false); +}); + +test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + underlyingProviderName: "test", + }, + { + title: "Model 2", + provider: "test", + model: "test-model-2", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); +}); + +test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + ], + edit: [ + { + title: "Model 2", + provider: "test", + model: "test-model-2", + apiKeyLocation: "organization:testorg/api-key", + underlyingProviderName: "test", + }, + ], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.Organization, + orgSlug: "testorg", + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); +}); + +test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + { + title: "Free Trial Model", + provider: "test", + model: "free-trial-model", + apiKeyLocation: "free_trial:owner/package/api-key", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.FreeTrial, + blockSlug: { ownerSlug: "owner", packageSlug: "package" }, + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(true); + expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2); +}); + +test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "user:testuser/api-key", + underlyingProviderName: "test", + }, + ], + edit: [ + { + title: "Free Trial Edit Model", + provider: "test", + model: "free-trial-edit-model", + apiKeyLocation: "free_trial:owner/package/api-key", + underlyingProviderName: "test", + }, + ], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation + .mockReturnValueOnce({ + secretType: SecretType.User, + userSlug: "testuser", + secretName: "api-key", + }) + .mockReturnValueOnce({ + secretType: SecretType.FreeTrial, + blockSlug: { ownerSlug: "owner", packageSlug: "package" }, + secretName: "api-key", + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(true); +}); + +test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => { + const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {}); + + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [ + { + title: "Model 1", + provider: "test", + model: "test-model", + apiKeyLocation: "invalid-secret-location", + underlyingProviderName: "test", + }, + ], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + mockDecodeSecretLocation.mockImplementation(() => { + throw new Error("Invalid secret location format"); + }); + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(consoleSpy).toHaveBeenCalledWith( + "Error checking for free trial API key:", + expect.any(Error), + ); + + consoleSpy.mockRestore(); +}); + +test("usesFreeTrialApiKey should handle empty modelsByRole object", () => { + const config: BrowserSerializedContinueConfig = { + modelsByRole: { + chat: [], + edit: [], + apply: [], + summarize: [], + autocomplete: [], + rerank: [], + embed: [], + }, + selectedModelByRole: { + chat: null, + edit: null, + apply: null, + summarize: null, + autocomplete: null, + rerank: null, + embed: null, + }, + contextProviders: [], + slashCommands: [], + tools: [], + mcpServerStatuses: [], + usePlatform: false, + rules: [], + }; + + const result = usesFreeTrialApiKey(config); + expect(result).toBe(false); + expect(mockDecodeSecretLocation).not.toHaveBeenCalled(); +}); diff --git a/gui/src/util/freeTrialHelpers.ts b/core/config/usesFreeTrialApiKey.ts similarity index 94% rename from gui/src/util/freeTrialHelpers.ts rename to core/config/usesFreeTrialApiKey.ts index 4f316b005..6657b1edf 100644 --- a/gui/src/util/freeTrialHelpers.ts +++ b/core/config/usesFreeTrialApiKey.ts @@ -1,5 +1,6 @@ import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml"; -import { BrowserSerializedContinueConfig } from "core"; +import { BrowserSerializedContinueConfig } from ".."; + /** * Helper function to determine if the config uses a free trial API key * @param config The serialized config object diff --git a/core/config/workspace/workspaceBlocks.test.ts b/core/config/workspace/workspaceBlocks.test.ts index e7b2fd77f..532444196 100644 --- a/core/config/workspace/workspaceBlocks.test.ts +++ b/core/config/workspace/workspaceBlocks.test.ts @@ -1,12 +1,10 @@ -import { BlockType } from "@continuedev/config-yaml"; -import { describe, expect, test } from "vitest"; -import { RULE_FILE_EXTENSION } from "../markdown"; +import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml"; +import { describe, expect, test } from "@jest/globals"; import { findAvailableFilename, getFileContent } from "./workspaceBlocks"; describe("getFileContent", () => { test("returns markdown content for rules block type", () => { const result = getFileContent("rules"); - expect(result).toContain("# New Rule"); expect(result).toContain("Your rule content"); expect(result).toContain("A description of your rule"); }); diff --git a/core/config/workspace/workspaceBlocks.ts b/core/config/workspace/workspaceBlocks.ts index 322d8a99e..25a606bf9 100644 --- a/core/config/workspace/workspaceBlocks.ts +++ b/core/config/workspace/workspaceBlocks.ts @@ -1,8 +1,12 @@ -import { BlockType, ConfigYaml } from "@continuedev/config-yaml"; +import { + BlockType, + ConfigYaml, + createRuleMarkdown, + RULE_FILE_EXTENSION, +} from "@continuedev/config-yaml"; import * as YAML from "yaml"; import { IDE } from "../.."; import { joinPathsToUri } from "../../util/uri"; -import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown"; const BLOCK_TYPE_CONFIG: Record< BlockType, diff --git a/core/config/yaml/LocalPlatformClient.test.ts b/core/config/yaml/LocalPlatformClient.vitest.ts similarity index 100% rename from core/config/yaml/LocalPlatformClient.test.ts rename to core/config/yaml/LocalPlatformClient.vitest.ts diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 2217d222c..0c6436c38 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -97,7 +97,7 @@ async function loadConfigYaml(options: { for (const blockType of BLOCK_TYPES) { const localBlocks = await getAllDotContinueDefinitionFiles( ide, - { includeGlobal: true, includeWorkspace: true }, + { includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" }, blockType, ); allLocalBlocks.push( @@ -134,6 +134,7 @@ async function loadConfigYaml(options: { rootPath, }), { + renderSecrets: true, currentUserSlug: "", onPremProxyUrl: null, orgScopeId, @@ -142,9 +143,7 @@ async function loadConfigYaml(options: { controlPlaneClient, ide, ), - renderSecrets: true, injectBlocks: allLocalBlocks, - asConfigResult: true, }, ); config = unrollResult.config; @@ -153,13 +152,8 @@ async function loadConfigYaml(options: { } } - if (config) { - isAssistantUnrolledNonNullable(config) - ? errors.push(...validateConfigYaml(config)) - : errors.push({ - fatal: true, - message: "Assistant includes blocks that don't exist", - }); + if (config && isAssistantUnrolledNonNullable(config)) { + errors.push(...validateConfigYaml(config)); } if (errors?.some((error) => error.fatal)) { @@ -223,7 +217,8 @@ async function configYamlToContinueConfig(options: { config: continueConfig, errors: [ { - message: "Found missing blocks in config.yaml", + message: + "Failed to load config due to missing blocks, see which blocks are missing below", fatal: true, }, ], diff --git a/core/context/providers/SearchContextProvider.ts b/core/context/providers/SearchContextProvider.ts index ec75994c3..b6ec40133 100644 --- a/core/context/providers/SearchContextProvider.ts +++ b/core/context/providers/SearchContextProvider.ts @@ -6,6 +6,7 @@ import { import { formatGrepSearchResults } from "../../util/grepSearch.js"; import { BaseContextProvider } from "../index.js"; +const DEFAULT_MAX_SEARCH_CONTEXT_RESULTS = 200; class SearchContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { title: "search", @@ -19,8 +20,12 @@ class SearchContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const results = await extras.ide.getSearchResults(query); - const formatted = formatGrepSearchResults(results); + const results = await extras.ide.getSearchResults( + query, + this.options?.maxResults ?? DEFAULT_MAX_SEARCH_CONTEXT_RESULTS, + ); + // Note, search context provider will not truncate result chars, but will limit number of results + const { formatted } = formatGrepSearchResults(results); return [ { description: "Search results", diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index f35809fed..ca88c479e 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -1,4 +1,5 @@ import { Chunk } from "../../../"; +import { Telemetry } from "../../../util/posthog"; import { findUriInDirs } from "../../../util/uri"; import { requestFilesFromRepoMap } from "../repoMapRequest"; import { deduplicateChunks } from "../util"; @@ -23,7 +24,8 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { try { ftsChunks = await this.retrieveFts(args, ftsNFinal); } catch (error) { - console.error("Error retrieving FTS chunks:", error); + await Telemetry.captureError("no_reranker_fts_retrieval", error); + // console.error("Error retrieving FTS chunks:", error); } let embeddingsChunks: Chunk[] = []; @@ -32,6 +34,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { ? await this.retrieveEmbeddings(input, embeddingsNFinal) : []; } catch (error) { + await Telemetry.captureError("no_reranker_embeddings_retrieval", error); console.error("Error retrieving embeddings:", error); } @@ -40,6 +43,10 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); } catch (error) { + await Telemetry.captureError( + "no_reranker_recently_edited_retrieval", + error, + ); console.error("Error retrieving recently edited files:", error); } @@ -53,6 +60,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { filterDirectory, ); } catch (error) { + await Telemetry.captureError("no_reranker_repo_map_retrieval", error); console.error("Error retrieving repo map chunks:", error); } diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index e73edf118..28de3d096 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -1,5 +1,6 @@ import { Chunk } from "../../.."; import { RETRIEVAL_PARAMS } from "../../../util/parameters"; +import { Telemetry } from "../../../util/posthog"; import { findUriInDirs } from "../../../util/uri"; import { requestFilesFromRepoMap } from "../repoMapRequest"; import { deduplicateChunks } from "../util"; @@ -20,7 +21,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { try { ftsChunks = await this.retrieveFts(args, nRetrieve); } catch (error) { - console.error("Error retrieving FTS chunks:", error); + await Telemetry.captureError("reranker_fts_retrieval", error); + // console.error("Error retrieving FTS chunks:", error); } let embeddingsChunks: Chunk[] = []; @@ -29,6 +31,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { ? await this.retrieveEmbeddings(input, nRetrieve) : []; } catch (error) { + await Telemetry.captureError("reranker_embeddings_retrieval", error); console.error("Error retrieving embeddings chunks:", error); } @@ -37,6 +40,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { recentlyEditedFilesChunks = await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); } catch (error) { + await Telemetry.captureError("reranker_recently_edited_retrieval", error); console.error("Error retrieving recently edited files chunks:", error); } @@ -50,6 +54,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { filterDirectory, ); } catch (error) { + await Telemetry.captureError("reranker_repo_map_retrieval", error); console.error("Error retrieving repo map chunks:", error); } diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 72523aa08..a1fe22099 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -182,4 +182,38 @@ export class ControlPlaneClient { return null; } } + + /** + * JetBrains does not support deep links, so we only check for `vsCodeUriScheme` + * @param vsCodeUriScheme + * @returns + */ + public async getModelsAddOnCheckoutUrl( + vsCodeUriScheme?: string, + ): Promise<{ url: string } | null> { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const params = new URLSearchParams({ + // LocalProfileLoader ID + profile_id: "local", + }); + + if (vsCodeUriScheme) { + params.set("vscode_uri_scheme", vsCodeUriScheme); + } + + const resp = await this.request( + `ide/get-models-add-on-checkout-url?${params.toString()}`, + { + method: "GET", + }, + ); + return (await resp.json()) as { url: string }; + } catch (e) { + return null; + } + } } diff --git a/core/core.ts b/core/core.ts index 2fe76ecf6..5e8d4d060 100644 --- a/core/core.ts +++ b/core/core.ts @@ -42,14 +42,15 @@ import { IdeSettings, ModelDescription, RangeInFile, + ToolCall, type ContextItem, type ContextItemId, type IDE, } from "."; -import { ConfigYaml } from "@continuedev/config-yaml"; +import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml"; import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; -import { isLocalAssistantFile } from "./config/loadLocalAssistants"; +import { isLocalDefinitionFile } from "./config/loadLocalAssistants"; import { setupLocalConfig, setupProviderConfig, @@ -58,6 +59,7 @@ import { import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; import { setMdmLicenseKey } from "./control-plane/mdm/mdm"; +import { ApplyAbortManager } from "./edit/applyAbortManager"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; @@ -67,7 +69,6 @@ import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import { OnboardingModes } from "./protocol/core"; import type { IMessenger, Message } from "./protocol/messenger"; -import { StreamAbortManager } from "./util/abortManager"; import { getUriPathBasename } from "./util/uri"; const hasRulesFiles = (uris: string[]): boolean => { @@ -145,8 +146,20 @@ export class Core { this.messenger, ); - MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => { - await this.configHandler.reloadConfig(); + MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => { + void this.configHandler.reloadConfig(); + + // Refresh @mention dropdown submenu items for MCP providers + const mcpManager = MCPManagerSingleton.getInstance(); + const mcpProviderNames = Array.from(mcpManager.connections.keys()).map( + (mcpId) => `mcp-${mcpId}`, + ); + + if (mcpProviderNames.length > 0) { + this.messenger.send("refreshSubmenuItems", { + providers: mcpProviderNames, + }); + } }; this.codeBaseIndexer = new CodebaseIndexer( @@ -156,24 +169,26 @@ export class Core { this.globalContext.get("indexingPaused"), ); - this.configHandler.onConfigUpdate(async (result) => { - const serializedResult = await this.configHandler.getSerializedConfig(); - this.messenger.send("configUpdate", { - result: serializedResult, - profileId: - this.configHandler.currentProfile?.profileDescription.id || null, - organizations: this.configHandler.getSerializedOrgs(), - selectedOrgId: this.configHandler.currentOrg.id, - }); - - // update additional submenu context providers registered via VSCode API - const additionalProviders = - this.configHandler.getAdditionalSubmenuContextProviders(); - if (additionalProviders.length > 0) { - this.messenger.send("refreshSubmenuItems", { - providers: additionalProviders, + this.configHandler.onConfigUpdate((result) => { + void (async () => { + const serializedResult = await this.configHandler.getSerializedConfig(); + this.messenger.send("configUpdate", { + result: serializedResult, + profileId: + this.configHandler.currentProfile?.profileDescription.id || null, + organizations: this.configHandler.getSerializedOrgs(), + selectedOrgId: this.configHandler.currentOrg.id, }); - } + + // update additional submenu context providers registered via VSCode API + const additionalProviders = + this.configHandler.getAdditionalSubmenuContextProviders(); + if (additionalProviders.length > 0) { + this.messenger.send("refreshSubmenuItems", { + providers: additionalProviders, + }); + } + })(); }); // Dev Data Logger @@ -357,6 +372,12 @@ export class Core { return this.configHandler.controlPlaneClient.getFreeTrialStatus(); }); + on("controlPlane/getModelsAddOnUpgradeUrl", async (msg) => { + return this.configHandler.controlPlaneClient.getModelsAddOnCheckoutUrl( + msg.data.vsCodeUriScheme, + ); + }); + on("mcp/reloadServer", async (msg) => { await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id); }); @@ -504,6 +525,11 @@ export class Core { throw new Error("No model selected"); } + const abortManager = ApplyAbortManager.getInstance(); + const abortController = abortManager.get( + data.fileUri ?? "current-file-stream", + ); // not super important since currently cancelling apply will cancel all streams it's one file at a time + return streamDiffLines({ highlighted: data.highlighted, prefix: data.prefix, @@ -517,13 +543,13 @@ export class Core { language: data.language, onlyOneInsertion: false, overridePrompt: undefined, - abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time + abortController, }); }); on("cancelApply", async (msg) => { - const abortManager = StreamAbortManager.getInstance(); - abortManager.clear(); + const abortManager = ApplyAbortManager.getInstance(); + abortManager.clear(); // for now abort all streams }); on("onboarding/complete", this.handleCompleteOnboarding.bind(this)); @@ -600,7 +626,7 @@ export class Core { // If it's a local assistant being created, we want to reload all assistants so it shows up in the list let localAssistantCreated = false; for (const uri of data.uris) { - if (isLocalAssistantFile(uri)) { + if (isLocalDefinitionFile(uri)) { localAssistantCreated = true; } } @@ -730,44 +756,9 @@ export class Core { return { url }; }); - on("tools/call", async ({ data: { toolCall } }) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } - - const tool = config.tools.find( - (t) => t.function.name === toolCall.function.name, - ); - - if (!tool) { - throw new Error(`Tool ${toolCall.function.name} not found`); - } - - if (!config.selectedModelByRole.chat) { - throw new Error("No chat model selected"); - } - - // Define a callback for streaming output updates - const onPartialOutput = (params: { - toolCallId: string; - contextItems: ContextItem[]; - }) => { - this.messenger.send("toolCallPartialOutput", params); - }; - - return await callTool(tool, toolCall, { - config, - ide: this.ide, - llm: config.selectedModelByRole.chat, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - toolCallId: toolCall.id, - onPartialOutput, - codeBaseIndexer: this.codeBaseIndexer, - }); - }); + on("tools/call", async ({ data: { toolCall } }) => + this.handleToolCall(toolCall), + ); on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); @@ -792,6 +783,45 @@ export class Core { }); } + private async handleToolCall(toolCall: ToolCall) { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } + + const tool = config.tools.find( + (t) => t.function.name === toolCall.function.name, + ); + + if (!tool) { + throw new Error(`Tool ${toolCall.function.name} not found`); + } + + if (!config.selectedModelByRole.chat) { + throw new Error("No chat model selected"); + } + + // Define a callback for streaming output updates + const onPartialOutput = (params: { + toolCallId: string; + contextItems: ContextItem[]; + }) => { + this.messenger.send("toolCallPartialOutput", params); + }; + + return await callTool(tool, toolCall, { + config, + ide: this.ide, + llm: config.selectedModelByRole.chat, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + tool, + toolCallId: toolCall.id, + onPartialOutput, + codeBaseIndexer: this.codeBaseIndexer, + }); + } + private async isItemTooBig(item: ContextItemWithId) { const { config } = await this.configHandler.loadConfig(); if (!config) { @@ -879,7 +909,12 @@ export class Core { uri.endsWith(".prompt") || uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || (uri.includes(".continue") && uri.endsWith(".yaml")) || - uri.endsWith(RULES_MARKDOWN_FILENAME) + uri.endsWith(RULES_MARKDOWN_FILENAME) || + BLOCK_TYPES.some( + (blockType) => + uri.includes(`.continue/${blockType}`) || + uri.includes(`.continue\\${blockType}`), + ) ) { await this.configHandler.reloadConfig(); } else if ( diff --git a/core/util/abortManager.ts b/core/edit/applyAbortManager.ts similarity index 70% rename from core/util/abortManager.ts rename to core/edit/applyAbortManager.ts index e7de53bca..e811b5d4b 100644 --- a/core/util/abortManager.ts +++ b/core/edit/applyAbortManager.ts @@ -1,16 +1,16 @@ -export class StreamAbortManager { - private static instance: StreamAbortManager; +export class ApplyAbortManager { + private static instance: ApplyAbortManager; private controllers: Map; private constructor() { this.controllers = new Map(); } - public static getInstance(): StreamAbortManager { - if (!StreamAbortManager.instance) { - StreamAbortManager.instance = new StreamAbortManager(); + public static getInstance(): ApplyAbortManager { + if (!ApplyAbortManager.instance) { + ApplyAbortManager.instance = new ApplyAbortManager(); } - return StreamAbortManager.instance; + return ApplyAbortManager.instance; } public get(id: string): AbortController { diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 8ca9a8154..b58b9d4ec 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -16,6 +16,7 @@ export async function applyCodeBlock( newLazyFile: string, filename: string, llm: ILLM, + abortController: AbortController, ): Promise<{ isInstantApply: boolean; diffLinesGenerator: AsyncGenerator; @@ -51,6 +52,12 @@ export async function applyCodeBlock( return { isInstantApply: false, - diffLinesGenerator: streamLazyApply(oldFile, filename, newLazyFile, llm), + diffLinesGenerator: streamLazyApply( + oldFile, + filename, + newLazyFile, + llm, + abortController, + ), }; } diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index 0b4f6cc6b..1a5ba704d 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -59,6 +59,7 @@ export async function* getReplacementWithLlm( linesBefore: string[], linesAfter: string[], llm: ILLM, + abortController: AbortController, ): AsyncGenerator { const userPrompt = dedent` ORIGINAL CODE: @@ -88,7 +89,7 @@ export async function* getReplacementWithLlm( { role: "user", content: userPrompt }, { role: "assistant", content: assistantPrompt }, ], - new AbortController().signal, + abortController.signal, ); let lines = streamLines(completion); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index ce7af0ef7..f8ec0905c 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -16,6 +16,7 @@ export async function* streamLazyApply( filename: string, newCode: string, llm: ILLM, + abortController: AbortController, ): AsyncGenerator { const promptFactory = lazyApplyPromptForModel(llm.model, llm.providerName); if (!promptFactory) { @@ -23,10 +24,7 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat( - promptMessages, - new AbortController().signal, - ); + const lazyCompletion = llm.streamChat(promptMessages, abortController.signal); // Do find and replace over the lazy edit response async function* replacementFunction( @@ -39,6 +37,7 @@ export async function* streamLazyApply( linesBefore, linesAfter, llm, + abortController, )) { yield line; } diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 096b31d7d..f64448f36 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -20,7 +20,6 @@ import { streamDiff } from "../diff/streamDiff"; import { streamLines } from "../diff/util"; import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules"; import { gptEditPrompt } from "../llm/templates/edit"; -import { StreamAbortManager } from "../util/abortManager"; import { findLast } from "../util/findLast"; import { Telemetry } from "../util/posthog"; import { recursiveStream } from "./recursiveStream"; @@ -64,7 +63,7 @@ export async function* streamDiffLines({ highlighted, suffix, llm, - abortControllerId, + abortController, input, language, onlyOneInsertion, @@ -75,15 +74,13 @@ export async function* streamDiffLines({ highlighted: string; suffix: string; llm: ILLM; - abortControllerId: string; + abortController: AbortController; input: string; language: string | undefined; onlyOneInsertion: boolean; overridePrompt: ChatMessage[] | undefined; rulesToInclude: RuleWithSource[] | undefined; }): AsyncGenerator { - const abortManager = StreamAbortManager.getInstance(); - const abortController = abortManager.get(abortControllerId); void Telemetry.capture( "inlineEdit", { diff --git a/core/index.d.ts b/core/index.d.ts index ce78a8d82..d2792a228 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -781,9 +781,9 @@ export interface IDE { getPinnedFiles(): Promise; - getSearchResults(query: string): Promise; + getSearchResults(query: string, maxResults?: number): Promise; - getFileResults(pattern: string): Promise; + getFileResults(pattern: string, maxResults?: number): Promise; subprocess(command: string, cwd?: string): Promise<[string, string]>; @@ -833,6 +833,7 @@ export interface ContinueSDK { config: ContinueConfig; fetch: FetchFunction; completionOptions?: LLMFullCompletionOptions; + abortController: AbortController; } export interface SlashCommand { @@ -1280,7 +1281,7 @@ export interface HighlightedCodePayload { } export interface AcceptOrRejectDiffPayload { - filepath: string; + filepath?: string; streamId?: string; } diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 0bf6c94ca..0a285b15d 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -97,8 +97,8 @@ export class LanceDbIndex implements CodebaseIndex { contents TEXT NOT NULL )`); - await new Promise((resolve) => - migrate( + await new Promise((resolve) => { + void migrate( "lancedb_sqlite_artifact_id_column", async () => { try { @@ -118,8 +118,8 @@ export class LanceDbIndex implements CodebaseIndex { } }, () => resolve(undefined), - ), - ); + ); + }); } private async computeRows(items: PathAndCacheKey[]): Promise { diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index d51f368a2..d46dd2e3b 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -50,24 +50,25 @@ export async function* chunkDocument({ maxChunkSize, )) { chunkPromises.push( - new Promise(async (resolve) => { - if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) { - // console.debug( - // `Chunk with more than ${maxChunkSize} tokens constructed: `, - // filepath, - // countTokens(chunkWithoutId.content), - // ); - return resolve(undefined); - } - resolve({ - ...chunkWithoutId, - digest, - index, - filepath, - }); + new Promise((resolve) => { + void (async () => { + if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) { + // console.debug( + // `Chunk with more than ${maxChunkSize} tokens constructed: `, + // filepath, + // countTokens(chunkWithoutId.content), + // ); + return resolve(undefined); + } + resolve({ + ...chunkWithoutId, + digest, + index: index++, + filepath, + }); + })(); }), ); - index++; } for await (const chunk of chunkPromises) { if (!chunk) { diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index d82c34b20..6bd285520 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -186,7 +186,9 @@ export default class DocsService { private async init(configHandler: ConfigHandler) { const result = await configHandler.loadConfig(); await this.handleConfigUpdate(result); - configHandler.onConfigUpdate(this.handleConfigUpdate.bind(this)); + configHandler.onConfigUpdate( + this.handleConfigUpdate.bind(this) as (arg: any) => void, + ); } readonly statuses: Map = new Map(); diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index b9d5fbcf8..dc8879c67 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -6,8 +6,8 @@ import { editConfigFile, migrate } from "../../util/paths.js"; import DocsService, { SqliteDocsRow } from "./DocsService.js"; export async function runLanceMigrations(table: Table) { - await new Promise((resolve) => - migrate( + await new Promise((resolve) => { + void migrate( "rename_baseurl_column_for_lance_docs", async () => { try { @@ -21,8 +21,8 @@ export async function runLanceMigrations(table: Table) { } }, () => resolve(undefined), - ), - ); + ); + }); } export async function runSqliteMigrations(db: Database) { diff --git a/core/jest.config.js b/core/jest.config.js index 01cff7760..da7a57815 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -29,12 +29,5 @@ export default { globalSetup: "/test/jest.global-setup.ts", setupFilesAfterEnv: ["/test/jest.setup-after-env.js"], maxWorkers: 1, // equivalent to CLI --runInBand - // modulePathIgnorePatterns: [ - // "/config/yaml/LocalPlatformClient.test.ts", - // ], - testPathIgnorePatterns: [ - "/config/", - "/autocomplete/", - "/context/", - ], + testMatch: ["**/*.test.ts"], }; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index e6acea28e..dd65cc2d9 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -52,6 +52,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [ "msty", "anthropic", "bedrock", + "cohere", "sagemaker", "continue-proxy", "mistral", @@ -65,6 +66,7 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [ const PROVIDER_SUPPORTS_IMAGES: string[] = [ "openai", "ollama", + "cohere", "gemini", "msty", "anthropic", @@ -89,6 +91,8 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "gpt-4o-mini", "gpt-4-vision", "claude-3", + "c4ai-aya-vision-8b", + "c4ai-aya-vision-32b", "gemini-ultra", "gemini-1.5-pro", "gemini-1.5-flash", @@ -140,6 +144,7 @@ function modelSupportsImages( const PARALLEL_PROVIDERS: string[] = [ "anthropic", "bedrock", + "cohere", "sagemaker", "deepinfra", "gemini", @@ -176,6 +181,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined { if ( lower.includes("gpt") || lower.includes("command") || + lower.includes("aya") || lower.includes("chat-bison") || lower.includes("pplx") || lower.includes("gemini") || diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 5358deee5..49115cb6f 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -11,6 +11,7 @@ import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; +import { RulePolicies } from "./rules/types"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; @@ -108,6 +109,7 @@ export function constructMessages( history: ChatHistoryItem[], baseChatOrAgentSystemMessage: string | undefined, rules: RuleWithSource[], + rulePolicies?: RulePolicies, ): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", @@ -164,6 +166,7 @@ export function constructMessages( rules, userMessage: lastUserMsg, contextItems: lastUserContextItems, + rulePolicies, }); if (systemMessage.trim()) { diff --git a/core/llm/index.ts b/core/llm/index.ts index ca33b7437..6cadb6992 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1068,9 +1068,17 @@ export abstract class BaseLLM implements ILLM { documents: chunks.map((chunk) => chunk.content), }); - // Put them in the order they were given - const sortedResults = results.data.sort((a, b) => a.index - b.index); - return sortedResults.map((result) => result.relevance_score); + // Standard OpenAI format + if (results.data && Array.isArray(results.data)) { + return results.data + .sort((a, b) => a.index - b.index) + .map((result) => result.relevance_score); + } + + throw new Error( + `Unexpected rerank response format from ${this.providerName}. ` + + `Expected 'data' array but got: ${JSON.stringify(Object.keys(results))}`, + ); } throw new Error( diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index ae21e68ee..c3acdb211 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -161,12 +161,7 @@ function testLLM( group: "Hello", }, ], - toolChoice: { - type: "function", - function: { - name: "say_hello", - }, - }, + toolChoice: { type: "function", function: { name: "say_hello" } }, }, )) { const typedChunk = chunk as AssistantChatMessage; @@ -211,10 +206,7 @@ describe("LLM", () => { model: "claude-3-5-sonnet-latest", apiKey: process.env.ANTHROPIC_API_KEY, }), - { - skip: false, - testToolCall: true, - }, + { skip: false, testToolCall: true }, ); testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), { skip: false, @@ -240,12 +232,7 @@ describe("LLM", () => { apiKey: process.env.MISTRAL_API_KEY, model: "codestral-latest", }), - { - testFim: true, - skip: false, - testToolCall: true, - timeout: 60000, - }, + { testFim: true, skip: false, testToolCall: true, timeout: 60000 }, ); testLLM( new Azure({ @@ -260,11 +247,10 @@ describe("LLM", () => { ); testLLM( new Azure({ - apiKey: process.env.AZURE_FOUNDRY_API_KEY, - model: "codestral-latest", - apiBase: - "https://codestral-2501-continue-testing.eastus.models.ai.azure.com", - apiType: "azure-foundry", + apiKey: process.env.AZURE_FOUNDRY_CODESTRAL_API_KEY, + model: "Codestral-2501", + apiBase: "https://continue-foundry-resource.services.ai.azure.com", + env: { apiType: "azure-foundry", apiVersion: "2024-05-01-preview" }, }), { testFim: false, skip: false, timeout: 20000 }, ); diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index b4d2c3b41..ca12161ad 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -1,9 +1,10 @@ -import { streamJSON } from "@continuedev/fetch"; +import { streamSse } from "@continuedev/fetch"; import { ChatMessage, Chunk, CompletionOptions, LLMOptions, + MessageContent, } from "../../index.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -11,21 +12,89 @@ import { BaseLLM } from "../index.js"; class Cohere extends BaseLLM { static providerName = "cohere"; static defaultOptions: Partial = { - apiBase: "https://api.cohere.ai/v1", + apiBase: "https://api.cohere.ai/v2", maxEmbeddingBatchSize: 96, }; static maxStopSequences = 5; private _convertMessages(msgs: ChatMessage[]): any[] { const messages = []; + let lastToolPlan: MessageContent | undefined; for (const m of msgs) { - if (m.role === "system" || !m.content) { + if (!m.content) { continue; } - messages.push({ - role: m.role === "assistant" ? "chatbot" : m.role, - message: m.content, - }); + switch (m.role) { + case "user": + if (typeof m.content === "string") { + messages.push({ + role: m.role, + content: m.content, + }); + break; + } + + messages.push({ + role: m.role, + content: m.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url", + image_url: { url: part.imageUrl.url }, + }; + } + return part; + }), + }); + break; + case "thinking": + lastToolPlan = m.content; + break; + case "assistant": + if (m.toolCalls) { + if (!lastToolPlan) { + throw new Error("No tool plan found"); + } + messages.push({ + role: m.role, + tool_calls: m.toolCalls.map((toolCall) => ({ + id: toolCall.id, + type: "function", + function: { + name: toolCall.function?.name, + arguments: toolCall.function?.arguments, + }, + })), + // Ideally the tool plan would be in this message, but it is + // split in another, usually the previous, this one's content is + // a space. + // tool_plan: m.content, + tool_plan: lastToolPlan, + }); + lastToolPlan = undefined; + break; + } + messages.push({ + role: m.role, + content: m.content, + }); + break; + case "system": + messages.push({ + role: m.role, + content: stripImages(m.content), + }); + break; + case "tool": + messages.push({ + role: m.role, + content: m.content, + tool_call_id: m.toolCallId, + }); + break; + default: + break; + } } return messages; } @@ -41,7 +110,14 @@ class Cohere extends BaseLLM { stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences), frequency_penalty: options.frequencyPenalty, presence_penalty: options.presencePenalty, - raw_prompting: options.raw, + tools: options.tools?.map((tool) => ({ + type: "function", + function: { + name: tool.function.name, + parameters: tool.function.parameters, + description: tool.function.description, + }, + })), }; } @@ -67,19 +143,12 @@ class Cohere extends BaseLLM { ...this.requestOptions?.headers, }; - let preamble: string | undefined = undefined; - const systemMessage = messages.find((m) => m.role === "system")?.content; - if (systemMessage) { - preamble = stripImages(systemMessage); - } const resp = await this.fetch(new URL("chat", this.apiBase), { method: "POST", headers, body: JSON.stringify({ ...this._convertArgs(options), - message: messages.pop()?.content, - chat_history: this._convertMessages(messages), - preamble, + messages: this._convertMessages(messages), }), signal, }); @@ -90,13 +159,97 @@ class Cohere extends BaseLLM { if (options.stream === false) { const data = await resp.json(); - yield { role: "assistant", content: data.text }; + if (data.message.tool_calls) { + yield { + // Use the "thinking" role for `tool_plan`, since there is no such + // role in the Cohere API at the moment and it is a "a + // chain-of-thought style reflection". + role: "thinking", + content: data.message.tool_plan, + }; + yield { + role: "assistant", + content: "", + toolCalls: data.message.tool_calls.map((toolCall: any) => ({ + id: toolCall.id, + type: "function", + function: { + name: toolCall.function?.name, + arguments: toolCall.function?.arguments, + }, + })), + }; + return; + } + yield { role: "assistant", content: data.message.content[0].text }; return; } - for await (const value of streamJSON(resp)) { - if (value.event_type === "text-generation") { - yield { role: "assistant", content: value.text }; + let lastToolUseId: string | undefined; + let lastToolUseName: string | undefined; + for await (const value of streamSse(resp)) { + // https://docs.cohere.com/v2/docs/streaming#stream-events + switch (value.type) { + // https://docs.cohere.com/v2/docs/streaming#content-delta + case "content-delta": + yield { + role: "assistant", + content: value.delta.message.content.text, + }; + break; + // https://docs.cohere.com/reference/chat-stream#request.body.messages.assistant.tool_plan + case "tool-plan-delta": + // Use the "thinking" role for `tool_plan`, since there is no such + // role in the Cohere API at the moment and it is a "a + // chain-of-thought style reflection". + yield { + role: "thinking", + content: value.delta.message.tool_plan, + }; + break; + case "tool-call-start": + lastToolUseId = value.delta.message.tool_calls.id; + lastToolUseName = value.delta.message.tool_calls.function.name; + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: lastToolUseId, + type: "function", + function: { + name: lastToolUseName, + arguments: value.delta.message.tool_calls.function.arguments, + }, + }, + ], + }; + break; + case "tool-call-delta": + if (!lastToolUseId || !lastToolUseName) { + throw new Error("No tool use found"); + } + yield { + role: "assistant", + content: "", + toolCalls: [ + { + id: lastToolUseId, + type: "function", + function: { + name: lastToolUseName, + arguments: value.delta.message.tool_calls.function.arguments, + }, + }, + ], + }; + break; + case "tool-call-end": + lastToolUseId = undefined; + lastToolUseName = undefined; + break; + default: + break; } } } diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index 991b09c3e..ac550f153 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -1,7 +1,25 @@ -import { LLMOptions } from "../../index.js"; +import { Chunk, LLMOptions } from "../../index.js"; import OpenAI from "./OpenAI.js"; +// vLLM-specific rerank response types +interface VllmRerankItem { + index: number; + document: { + text: string; + }; + relevance_score: number; +} + +interface VllmRerankResponse { + id: string; + model: string; + usage: { + total_tokens: number; + }; + results: VllmRerankItem[]; +} + class Vllm extends OpenAI { static providerName = "vllm"; constructor(options: LLMOptions) { @@ -16,6 +34,28 @@ class Vllm extends OpenAI { return false; } + async rerank(query: string, chunks: Chunk[]): Promise { + if (this.useOpenAIAdapterFor.includes("rerank") && this.openaiAdapter) { + const results = (await this.openaiAdapter.rerank({ + model: this.model, + query, + documents: chunks.map((chunk) => chunk.content), + })) as unknown as VllmRerankResponse; + + // vLLM uses 'results' array instead of 'data' + if (results.results && Array.isArray(results.results)) { + const sortedResults = results.results.sort((a, b) => a.index - b.index); + return sortedResults.map((result) => result.index); + } + + throw new Error( + `vLLM rerank response missing 'results' array. Got: ${JSON.stringify(Object.keys(results))}`, + ); + } + + throw new Error("vLLM rerank requires OpenAI adapter"); + } + private _setupCompletionOptions() { this.fetch(this._getEndpoint("models"), { method: "GET", diff --git a/core/llm/rules/alwaysApply.vitest.ts b/core/llm/rules/alwaysApply.vitest.ts new file mode 100644 index 000000000..f8d6e1160 --- /dev/null +++ b/core/llm/rules/alwaysApply.vitest.ts @@ -0,0 +1,186 @@ +import { describe, expect, it } from "vitest"; +import { + ContextItemId, + ContextItemWithId, + RuleWithSource, + UserChatMessage, +} from "../.."; +import { getApplicableRules } from "./getSystemMessageWithRules"; + +describe("alwaysApply Behavior", () => { + // Common test fixtures + const testFile = "src/app.ts"; + const matchingFile = "src/components/Button.tsx"; + const nonMatchingFile = "src/utils/helper.js"; // Not matching *.tsx glob + + // File context items + const matchingFileContext: ContextItemWithId = { + id: { providerTitle: "file", itemId: "match1" } as ContextItemId, + uri: { type: "file", value: matchingFile }, + content: "export const Button = () => {...}", + name: "Button.tsx", + description: "Component file", + }; + + const nonMatchingFileContext: ContextItemWithId = { + id: { providerTitle: "file", itemId: "nonmatch1" } as ContextItemId, + uri: { type: "file", value: nonMatchingFile }, + content: "export const helper = () => {...}", + name: "helper.js", + description: "Helper file", + }; + + // Message with no file references + const messageWithoutFile: UserChatMessage = { + role: "user", + content: "Can you help me understand how this works?", + }; + + it("alwaysApply: true - Always include the rule, regardless of file context", () => { + // Rule with alwaysApply: true + const alwaysApplyRule: RuleWithSource = { + name: "Always Apply Rule", + rule: "This rule should always be applied", + alwaysApply: true, + globs: "**/*.tsx", // Should be ignored since alwaysApply is true + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Test with no file context + let applicableRules = getApplicableRules( + messageWithoutFile, + [alwaysApplyRule], + [], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Always Apply Rule"); + + // Test with matching file + applicableRules = getApplicableRules( + undefined, + [alwaysApplyRule], + [matchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Always Apply Rule"); + + // Test with non-matching file + applicableRules = getApplicableRules( + undefined, + [alwaysApplyRule], + [nonMatchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Always Apply Rule"); + }); + + it("alwaysApply: false - Only include if globs exist AND match file context", () => { + // Rule with alwaysApply: false and globs + const conditionalRule: RuleWithSource = { + name: "Conditional Rule", + rule: "Apply only to matching files", + alwaysApply: false, + globs: "**/*.tsx", + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Rule with alwaysApply: false and no globs + const neverApplyRule: RuleWithSource = { + name: "Never Apply Rule", + rule: "This rule should never apply", + alwaysApply: false, + // No globs + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Test with no file context + let applicableRules = getApplicableRules( + messageWithoutFile, + [conditionalRule, neverApplyRule], + [], + ); + expect(applicableRules).toHaveLength(0); // No rules should apply + + // Test with matching file + applicableRules = getApplicableRules( + undefined, + [conditionalRule, neverApplyRule], + [matchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Conditional Rule"); + expect(applicableRules.map((r) => r.name)).not.toContain( + "Never Apply Rule", + ); + + // Test with non-matching file + applicableRules = getApplicableRules( + undefined, + [conditionalRule, neverApplyRule], + [nonMatchingFileContext], + ); + expect(applicableRules).toHaveLength(0); // No rules should apply + }); + + it("alwaysApply: undefined - Default behavior: include if no globs exist OR globs exist and match", () => { + // Rule with undefined alwaysApply and no globs (should behave like a global rule) + const defaultNoGlobsRule: RuleWithSource = { + name: "Default No Globs Rule", + rule: "Default rule with no globs", + source: "rules-block", + ruleFile: ".continue/rules.md", + // No alwaysApply, no globs + }; + + // Rule with undefined alwaysApply and globs + const defaultWithGlobsRule: RuleWithSource = { + name: "Default With Globs Rule", + rule: "Default rule with globs", + globs: "**/*.tsx", + source: "rules-block", + ruleFile: ".continue/rules.md", + // No alwaysApply, with globs + }; + + // Test with no file context + let applicableRules = getApplicableRules( + messageWithoutFile, + [defaultNoGlobsRule, defaultWithGlobsRule], + [], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Default No Globs Rule"); + expect(applicableRules.map((r) => r.name)).not.toContain( + "Default With Globs Rule", + ); + + // Test with matching file + applicableRules = getApplicableRules( + undefined, + [defaultNoGlobsRule, defaultWithGlobsRule], + [matchingFileContext], + ); + expect(applicableRules).toHaveLength(2); + expect(applicableRules.map((r) => r.name)).toContain( + "Default No Globs Rule", + ); + expect(applicableRules.map((r) => r.name)).toContain( + "Default With Globs Rule", + ); + + // Test with non-matching file + applicableRules = getApplicableRules( + undefined, + [defaultNoGlobsRule, defaultWithGlobsRule], + [nonMatchingFileContext], + ); + expect(applicableRules).toHaveLength(1); + expect(applicableRules[0].name).toBe("Default No Globs Rule"); + expect(applicableRules.map((r) => r.name)).not.toContain( + "Default With Globs Rule", + ); + }); +}); diff --git a/core/llm/rules/alwaysApplyRules.vitest.ts b/core/llm/rules/alwaysApplyRules.vitest.ts index 0508a1e38..538ab03cf 100644 --- a/core/llm/rules/alwaysApplyRules.vitest.ts +++ b/core/llm/rules/alwaysApplyRules.vitest.ts @@ -6,6 +6,7 @@ import { UserChatMessage, } from "../.."; import { getApplicableRules } from "./getSystemMessageWithRules"; +import { RulePolicies } from "./types"; describe("Rule application with alwaysApply", () => { // Create an always-apply rule @@ -136,4 +137,38 @@ describe("Rule application with alwaysApply", () => { expect(applicableRules).toHaveLength(1); expect(applicableRules.map((r) => r.name)).toContain("Always Apply Rule"); }); + + it("should respect 'off' rulePolicies over alwaysApply when there are no file paths", () => { + // Rule with alwaysApply: true + const globalRule: RuleWithSource = { + name: "Global Rule", + rule: "This rule has alwaysApply: true but is blocked by rulePolicies", + alwaysApply: true, + source: "rules-block", + ruleFile: "src/some/path.md", + }; + + // Message with no code blocks or file references + const simpleMessage: UserChatMessage = { + role: "user", + content: "Can you help me with something?", + }; + + // Create a rule policy that blocks the rule + const rulePolicies: RulePolicies = { + "Global Rule": "off", + }; + + // The rule should NOT be applied due to the "off" policy, + // even though it has alwaysApply: true and there are no file paths + const applicableRules = getApplicableRules( + simpleMessage, + [globalRule], + [], + rulePolicies, + ); + + expect(applicableRules).toHaveLength(0); + expect(applicableRules.map((r) => r.name)).not.toContain("Global Rule"); + }); }); diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index e83a2cbfc..a0f3cf64f 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -8,6 +8,7 @@ import { import { renderChatMessage } from "../../util/messageContent"; import { getCleanUriPath } from "../../util/uri"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; +import { RulePolicies } from "./types"; /** * Checks if a path matches any of the provided globs @@ -120,13 +121,21 @@ const isGlobalRule = (rule: RuleWithSource): boolean => { export const shouldApplyRule = ( rule: RuleWithSource, filePaths: string[], + rulePolicies: RulePolicies = {}, ): boolean => { + const policy = rulePolicies[rule.name || ""]; + + // Never apply if policy is "off" + if (policy === "off") { + return false; + } + // If it's a global rule, always apply it regardless of file paths if (isGlobalRule(rule)) { return true; } - // If there are no file paths to check: + // If there are no file paths to check and we've made it here: // - We've already handled global rules above // - Don't apply other rules since we have no files to match against if (filePaths.length === 0) { @@ -196,11 +205,9 @@ export const getApplicableRules = ( userMessage: UserChatMessage | ToolResultChatMessage | undefined, rules: RuleWithSource[], contextItems: ContextItemWithId[], + rulePolicies: RulePolicies = {}, ): RuleWithSource[] => { - // First, extract any global rules that should always apply - const globalRules = rules.filter((rule) => isGlobalRule(rule)); - - // Get file paths from message and context for regular rule matching + // Get file paths from message and context for rule matching const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) : []; @@ -213,41 +220,34 @@ export const getApplicableRules = ( // Combine file paths from both sources const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems]; - // If we have no file paths, just return the global rules - if (allFilePaths.length === 0) { - return globalRules; - } + // Apply shouldApplyRule to all rules - this will handle global rules, rule policies, + // and path matching in a consistent way + const applicableRules = rules.filter((rule) => + shouldApplyRule(rule, allFilePaths, rulePolicies), + ); - // Get rules that match file paths - const matchingRules = rules - .filter((rule) => !isGlobalRule(rule)) // Skip global rules as we've already handled them - .filter((rule) => shouldApplyRule(rule, allFilePaths)); - - // Combine global rules with matching rules, ensuring no duplicates - return [...globalRules, ...matchingRules]; + return applicableRules; }; -/** - * Creates a system message string with applicable rules appended - * - * @param baseSystemMessage - The base system message to start with - * @param userMessage - The user message to check for file paths - * @param rules - The list of rules to filter - * @param contextItems - Context items to check for file paths - * @returns System message with applicable rules appended - */ export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, rules, contextItems, + rulePolicies = {}, }: { baseSystemMessage?: string; userMessage: UserChatMessage | ToolResultChatMessage | undefined; rules: RuleWithSource[]; contextItems: ContextItemWithId[]; + rulePolicies?: RulePolicies; }) => { - const applicableRules = getApplicableRules(userMessage, rules, contextItems); + const applicableRules = getApplicableRules( + userMessage, + rules, + contextItems, + rulePolicies, + ); let systemMessage = baseSystemMessage ?? ""; for (const rule of applicableRules) { diff --git a/core/llm/rules/getSystemMessageWithRules.vitest.ts b/core/llm/rules/getSystemMessageWithRules.vitest.ts index 0e7bd39fe..f652d3a77 100644 --- a/core/llm/rules/getSystemMessageWithRules.vitest.ts +++ b/core/llm/rules/getSystemMessageWithRules.vitest.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { RuleWithSource } from "../.."; import { shouldApplyRule } from "./getSystemMessageWithRules"; +import { RulePolicies } from "./types"; describe("Rule colocation glob matching", () => { // This test file demonstrates the expected behavior after our fix @@ -132,3 +133,114 @@ describe("Rule colocation glob matching", () => { ); }); }); + +describe("Rule policies", () => { + const componentRule: RuleWithSource = { + name: "Components Rule", + rule: "Use functional components with hooks", + source: "rules-block", + ruleFile: "src/components/rules.md", + }; + + const testFiles = ["src/components/Button.tsx"]; + const nonMatchingFiles = ["src/utils/helpers.ts"]; + + it("should never apply rules with 'off' policy regardless of file paths", () => { + const rulePolicies: RulePolicies = { + "Components Rule": "off", + }; + + // Should not apply even to matching files + expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(false); + + // Rule with alwaysApply: true should still be overridden by 'off' policy + const alwaysApplyRule: RuleWithSource = { + name: "Always Apply Rule", + rule: "This rule would normally always apply", + alwaysApply: true, + source: "rules-block", + ruleFile: "src/components/rules.md", + }; + + const offPolicies: RulePolicies = { + "Always Apply Rule": "off", + }; + + expect(shouldApplyRule(alwaysApplyRule, testFiles, offPolicies)).toBe( + false, + ); + }); + + it("should apply 'on' policy rules based on normal matching logic", () => { + const rulePolicies: RulePolicies = { + "Components Rule": "on", + }; + + // Should apply to matching files + expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true); + + // Should not apply to non-matching files + expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe( + false, + ); + }); + + it("should use default behavior when no policy is specified", () => { + // Empty policies object should use default behavior + const rulePolicies: RulePolicies = {}; + + // Should apply to matching files + expect(shouldApplyRule(componentRule, testFiles, rulePolicies)).toBe(true); + + // Should not apply to non-matching files + expect(shouldApplyRule(componentRule, nonMatchingFiles, rulePolicies)).toBe( + false, + ); + }); + + it("should handle policy interaction with global rules", () => { + // Root level rule which would normally apply globally + const rootRule: RuleWithSource = { + name: "Root Rule", + rule: "Follow project standards", + source: "rules-block", + ruleFile: ".continue/rules.md", + }; + + // Off policy should override even global rules + const offPolicies: RulePolicies = { + "Root Rule": "off", + }; + + expect(shouldApplyRule(rootRule, testFiles, offPolicies)).toBe(false); + + // On policy should maintain global rule behavior + const onPolicies: RulePolicies = { + "Root Rule": "on", + }; + + expect(shouldApplyRule(rootRule, testFiles, onPolicies)).toBe(true); + }); + + it("should prioritize 'off' policy over alwaysApply and directory restrictions", () => { + // Create rule with multiple matching criteria + const complexRule: RuleWithSource = { + name: "Complex Rule", + rule: "This rule has complex matching logic", + alwaysApply: true, + globs: "**/*.ts", + source: "rules-block", + ruleFile: "src/utils/rules.md", + }; + + // Off policy should win over everything + const offPolicies: RulePolicies = { + "Complex Rule": "off", + }; + + // Even with matching files and alwaysApply: true, off policy wins + expect( + shouldApplyRule(complexRule, ["src/utils/test.ts"], offPolicies), + ).toBe(false); + }); +}); diff --git a/core/llm/rules/types.ts b/core/llm/rules/types.ts new file mode 100644 index 000000000..f973d8260 --- /dev/null +++ b/core/llm/rules/types.ts @@ -0,0 +1,2 @@ +export type RulePolicy = "on" | "off"; +export type RulePolicies = { [ruleName: string]: RulePolicy }; diff --git a/core/llm/streamChat.ts b/core/llm/streamChat.ts index c899e437f..3f52a0192 100644 --- a/core/llm/streamChat.ts +++ b/core/llm/streamChat.ts @@ -1,6 +1,7 @@ import { fetchwithRequestOptions } from "@continuedev/fetch"; import { ChatMessage, IDE, PromptLog } from ".."; import { ConfigHandler } from "../config/ConfigHandler"; +import { usesFreeTrialApiKey } from "../config/usesFreeTrialApiKey"; import { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import { IMessenger, Message } from "../protocol/messenger"; import { Telemetry } from "../util/posthog"; @@ -84,6 +85,7 @@ export async function* llmStreamChat( config.requestOptions, ), completionOptions, + abortController, }); let next = await gen.next(); while (!next.done) { @@ -135,6 +137,8 @@ export async function* llmStreamChat( true, ); + void checkForFreeTrialExceeded(configHandler, messenger); + if (!next.done) { throw new Error("Will never happen"); } @@ -142,3 +146,29 @@ export async function* llmStreamChat( return next.value; } } + +async function checkForFreeTrialExceeded( + configHandler: ConfigHandler, + messenger: IMessenger, +) { + const { config } = await configHandler.getSerializedConfig(); + + // Only check if the user is using the free trial + if (config && !usesFreeTrialApiKey(config)) { + return; + } + + try { + const freeTrialStatus = + await configHandler.controlPlaneClient.getFreeTrialStatus(); + if ( + freeTrialStatus && + freeTrialStatus.chatCount && + freeTrialStatus.chatCount > freeTrialStatus.chatLimit + ) { + void messenger.request("freeTrialExceeded", undefined); + } + } catch (error) { + console.error("Error checking free trial status:", error); + } +} diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts index d3100a61b..8d1a574df 100644 --- a/core/llm/toolSupport.test.ts +++ b/core/llm/toolSupport.test.ts @@ -109,6 +109,19 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); }); + describe("cohere", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["cohere"]; + + it("should return true for Command models", () => { + expect(supportsFn("command-r")).toBe(true); + expect(supportsFn("command-a")).toBe(true); + }); + + it("should return false for other models", () => { + expect(supportsFn("c4ai-aya-expanse-32b")).toBe(false); + }); + }); + describe("gemini", () => { const supportsFn = PROVIDER_TOOL_SUPPORT["gemini"]; @@ -221,6 +234,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => { expect(supportsFn("qwen2")).toBe(true); expect(supportsFn("mixtral-8x7b")).toBe(true); expect(supportsFn("command-r")).toBe(true); + expect(supportsFn("command-a")).toBe(true); expect(supportsFn("smollm2")).toBe(true); expect(supportsFn("hermes3")).toBe(true); expect(supportsFn("athene-v2")).toBe(true); diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index e6d4387ce..5f6ffbce8 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -71,6 +71,9 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, + cohere: (model) => { + return model.toLowerCase().startsWith("command"); + }, gemini: (model) => { // All gemini models support function calling return model.toLowerCase().includes("gemini"); @@ -144,6 +147,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "qwen3", "mixtral", "command-r", + "command-a", "smollm2", "hermes3", "athene-v2", @@ -226,6 +230,7 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = "qwen/qwen3", "qwen/qwen-", "cohere/command-r", + "cohere/command-a", "ai21/jamba-1.6", "mistralai/mistral", "mistralai/ministral", diff --git a/core/package-lock.json b/core/package-lock.json index 54b04b90f..81c23f4f1 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -113,10 +113,10 @@ "node": ">=20.19.0" } }, - "../../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { + "../../../dallin/documents/code/continuedev/continue/packages/config-yaml": { "extraneous": true }, - "../../../../documents/code/continuedev/continue/packages/config-yaml": { + "../../../documents/code/continuedev/continue/packages/config-yaml": { "version": "1.0.78", "extraneous": true, "license": "Apache-2.0", diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index d9904d6d8..8e1478648 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -79,7 +79,7 @@ export function slashCommandFromPromptFileV1( for await (const chunk of context.llm.streamChat( messages, - new AbortController().signal, + context.abortController.signal, context.completionOptions, )) { yield renderChatMessage(chunk); diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e34a332bd..dfc0d87d6 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -40,6 +40,7 @@ import { FreeTrialStatus } from "../control-plane/client"; export enum OnboardingModes { API_KEY = "API Key", LOCAL = "Local", + MODELS_ADD_ON = "Models Add-On", } export interface ListHistoryOptions { @@ -199,6 +200,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null]; + "controlPlane/getModelsAddOnUpgradeUrl": [ + { vsCodeUriScheme?: string }, + { url: string } | null, + ]; isItemTooBig: [{ item: ContextItemWithId }, boolean]; didChangeControlPlaneSessionInfo: [ { sessionInfo: ControlPlaneSessionInfo | undefined }, diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index fda1b84fe..7a9b8d68e 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -29,8 +29,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { openFile: [{ path: string }, void]; openUrl: [string, void]; runCommand: [{ command: string; options?: TerminalOptions }, void]; - getSearchResults: [{ query: string }, string]; - getFileResults: [{ pattern: string }, string[]]; + getSearchResults: [{ query: string; maxResults?: number }, string]; + getFileResults: [{ pattern: string; maxResults?: number }, string[]]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; fileExists: [{ filepath: string }, boolean]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 39ae205a5..074e3837f 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -76,7 +76,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setColors: [{ [key: string]: string }, void]; "jetbrains/editorInsetRefresh": [undefined, void]; "jetbrains/isOSREnabled": [boolean, void]; - addApiKey: [undefined, void]; + setupApiKey: [undefined, void]; setupLocalConfig: [undefined, void]; incrementFtc: [undefined, void]; openOnboardingCard: [undefined, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 2bc52bca8..87e1ec642 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -185,8 +185,8 @@ export class MessageIde implements IDE { return this.request("getPinnedFiles", undefined); } - getSearchResults(query: string): Promise { - return this.request("getSearchResults", { query }); + getSearchResults(query: string, maxResults?: number): Promise { + return this.request("getSearchResults", { query, maxResults }); } getFileResults(pattern: string): Promise { diff --git a/core/protocol/messenger/reverseMessageIde.ts b/core/protocol/messenger/reverseMessageIde.ts index f40915664..ba37c610d 100644 --- a/core/protocol/messenger/reverseMessageIde.ts +++ b/core/protocol/messenger/reverseMessageIde.ts @@ -159,11 +159,11 @@ export class ReverseMessageIde { }); this.on("getSearchResults", (data) => { - return this.ide.getSearchResults(data.query); + return this.ide.getSearchResults(data.query, data.maxResults); }); this.on("getFileResults", (data) => { - return this.ide.getFileResults(data.pattern); + return this.ide.getFileResults(data.pattern, data.maxResults); }); this.on("getProblems", (data) => { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 014c1a968..105636d2f 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -61,6 +61,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "didChangeSelectedOrg", "tools/call", "controlPlane/openUrl", + "controlPlane/getModelsAddOnUpgradeUrl", "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", @@ -84,4 +85,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = "sessionUpdate", "didCloseFiles", "toolCallPartialOutput", + "freeTrialExceeded", ]; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 5ba47e3d4..1a8d40313 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -43,4 +43,5 @@ export type ToWebviewFromIdeOrCoreProtocol = { "jetbrains/setColors": [Record, void]; sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void]; toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void]; + freeTrialExceeded: [undefined, void]; }; diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 892cc3ff8..5a2408a0c 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -11,6 +11,7 @@ export enum BuiltInToolNames { LSTool = "builtin_ls", CreateRuleBlock = "builtin_create_rule_block", RequestRule = "builtin_request_rule", + FetchUrlContent = "builtin_fetch_url_content", // excluded from allTools for now ViewRepoMap = "builtin_view_repo_map", diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 6ea95610b..40dd7abe2 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -5,6 +5,7 @@ import { BuiltInToolNames } from "./builtIn"; import { createNewFileImpl } from "./implementations/createNewFile"; import { createRuleBlockImpl } from "./implementations/createRuleBlock"; +import { fetchUrlContentImpl } from "./implementations/fetchUrlContent"; import { fileGlobSearchImpl } from "./implementations/globSearch"; import { grepSearchImpl } from "./implementations/grepSearch"; import { lsToolImpl } from "./implementations/lsTool"; @@ -151,6 +152,8 @@ async function callBuiltInTool( return await runTerminalCommandImpl(args, extras); case BuiltInToolNames.SearchWeb: return await searchWebImpl(args, extras); + case BuiltInToolNames.FetchUrlContent: + return await fetchUrlContentImpl(args, extras); case BuiltInToolNames.ViewDiff: return await viewDiffImpl(args, extras); case BuiltInToolNames.LSTool: diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 1653cb279..6c6ad6fd9 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -14,6 +14,7 @@ export const editFileTool: Tool = { hasAlready: "edited {{{ filepath }}}", group: BUILT_IN_GROUP_NAME, readonly: false, + isInstant: false, function: { name: BuiltInToolNames.EditExistingFile, description: diff --git a/core/tools/definitions/fetchUrlContent.ts b/core/tools/definitions/fetchUrlContent.ts new file mode 100644 index 000000000..e0122f55b --- /dev/null +++ b/core/tools/definitions/fetchUrlContent.ts @@ -0,0 +1,28 @@ +import { Tool } from "../.."; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; + +export const fetchUrlContentTool: Tool = { + type: "function", + displayTitle: "Read URL", + wouldLikeTo: "fetch {{{ url }}}", + isCurrently: "fetching {{{ url }}}", + hasAlready: "viewed {{{ url }}}", + readonly: true, + isInstant: true, + group: BUILT_IN_GROUP_NAME, + function: { + name: BuiltInToolNames.FetchUrlContent, + description: + "Can be used to view the contents of a website using a URL. Do NOT use this for files.", + parameters: { + type: "object", + required: ["url"], + properties: { + url: { + type: "string", + description: "The URL to read", + }, + }, + }, + }, +}; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index 5c2375124..b3cbcac5b 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -12,7 +12,8 @@ export const globSearchTool: Tool = { group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.FileGlobSearch, - description: "Search for files in the project", + description: + "Search for files in the project. Output may be truncated; use targeted patterns", parameters: { type: "object", required: ["pattern"], diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index ca8a73a30..60a4e2710 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -12,7 +12,8 @@ export const grepSearchTool: Tool = { group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.GrepSearch, - description: "Perform a search over the repository using ripgrep.", + description: + "Perform a search over the repository using ripgrep. Output may be truncated, so use targeted queries", parameters: { type: "object", required: ["query"], diff --git a/core/tools/implementations/createRuleBlock.test.ts b/core/tools/implementations/createRuleBlock.test.ts index ab7e16c38..261f8eeb9 100644 --- a/core/tools/implementations/createRuleBlock.test.ts +++ b/core/tools/implementations/createRuleBlock.test.ts @@ -1,5 +1,5 @@ +import { parseMarkdownRule } from "@continuedev/config-yaml"; import { jest } from "@jest/globals"; -import { parseMarkdownRule } from "../../config/markdown"; import { createRuleBlockImpl } from "./createRuleBlock"; const mockIde = { @@ -40,7 +40,6 @@ test("createRuleBlockImpl should create a rule with glob pattern", async () => { globs: "**/*.{ts,tsx}", }); - expect(markdown).toContain("# TypeScript Rule"); expect(markdown).toContain("Use interfaces for object shapes"); }); @@ -76,7 +75,6 @@ test("createRuleBlockImpl should create a rule with description pattern", async description: "This is a detailed explanation of the rule", }); - expect(markdown).toContain("# Description Test"); expect(markdown).toContain("This is the rule content"); }); @@ -100,7 +98,6 @@ test("createRuleBlockImpl should include both globs and description in frontmatt globs: "**/*.js", }); - expect(markdown).toContain("# Complete Rule"); expect(markdown).toContain("Follow this standard"); }); diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index da0f0303b..a38e06056 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -1,6 +1,7 @@ +import { createRuleMarkdown } from "@continuedev/config-yaml"; import { ToolImpl } from "."; import { RuleWithSource } from "../.."; -import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown"; +import { createRuleFilePath } from "../../config/markdown/utils"; export type CreateRuleBlockArgs = Pick< Required, diff --git a/core/tools/implementations/fetchUrlContent.ts b/core/tools/implementations/fetchUrlContent.ts new file mode 100644 index 000000000..d2c031d4e --- /dev/null +++ b/core/tools/implementations/fetchUrlContent.ts @@ -0,0 +1,6 @@ +import { ToolImpl } from "."; +import { getUrlContextItems } from "../../context/providers/URLContextProvider"; + +export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { + return getUrlContextItems(args.url, extras.fetch); +}; diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts index c0b214357..1e551d9e2 100644 --- a/core/tools/implementations/globSearch.ts +++ b/core/tools/implementations/globSearch.ts @@ -1,12 +1,28 @@ import { ToolImpl } from "."; +import { ContextItem } from "../.."; +const MAX_AGENT_GLOB_RESULTS = 100; export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { - const results = await extras.ide.getFileResults(args.pattern); - return [ + const results = await extras.ide.getFileResults( + args.pattern, + MAX_AGENT_GLOB_RESULTS, + ); + const contextItems: ContextItem[] = [ { name: "File results", description: "Results from file glob search", content: results.join("\n"), }, ]; + + // In case of truncation, add a warning + if (results.length === MAX_AGENT_GLOB_RESULTS) { + contextItems.push({ + name: "Truncation warning", + description: "Inform the model that results were truncated", + content: `Warning: the results above were truncated to the first ${MAX_AGENT_GLOB_RESULTS} files. If the results are not satisfactory, refine your search pattern`, + }); + } + + return contextItems; }; diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index a506be9cd..149b68a75 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,13 +1,44 @@ import { ToolImpl } from "."; +import { ContextItem } from "../.."; import { formatGrepSearchResults } from "../../util/grepSearch"; +const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; +const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now + export const grepSearchImpl: ToolImpl = async (args, extras) => { - const results = await extras.ide.getSearchResults(args.query); - return [ + const results = await extras.ide.getSearchResults( + args.query, + DEFAULT_GREP_SEARCH_RESULTS_LIMIT, + ); + const { formatted, numResults, truncated } = formatGrepSearchResults( + results, + DEFAULT_GREP_SEARCH_CHAR_LIMIT, + ); + const truncationReasons: string[] = []; + if (numResults === DEFAULT_GREP_SEARCH_RESULTS_LIMIT) { + truncationReasons.push( + `the number of results exceeded ${DEFAULT_GREP_SEARCH_RESULTS_LIMIT}`, + ); + } + if (truncated) { + truncationReasons.push( + `the number of characters exceeded ${DEFAULT_GREP_SEARCH_CHAR_LIMIT}`, + ); + } + + const contextItems: ContextItem[] = [ { name: "Search results", description: "Results from grep search", - content: formatGrepSearchResults(results), + content: formatted, }, ]; + if (truncationReasons.length > 0) { + contextItems.push({ + name: "Search truncation warning", + description: "Informs the model that search results were truncated", + content: `The above search results were truncated because ${truncationReasons.join(" and ")}. If the results are not satisfactory, try refining your search query.`, + }); + } + return contextItems; }; diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts index 86aff6280..a8801f344 100644 --- a/core/tools/implementations/requestRule.ts +++ b/core/tools/implementations/requestRule.ts @@ -1,5 +1,4 @@ import { ToolImpl } from "."; -import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule"; export const requestRuleImpl: ToolImpl = async (args, extras) => { // Find the rule by name in the config @@ -11,14 +10,11 @@ export const requestRuleImpl: ToolImpl = async (args, extras) => { ); } - const fileContent = await extras.ide.readFile(rule.ruleFile); - const { markdown, frontmatter } = parseMarkdownRule(fileContent); - return [ { - name: frontmatter.name ?? "", - description: frontmatter.description ?? "", - content: markdown, + name: rule.name ?? "", + description: rule.description ?? "", + content: rule.rule, uri: { type: "file", value: rule.ruleFile, diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 785f4ee30..3d3ac85cb 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -10,6 +10,16 @@ import { const asyncExec = util.promisify(childProcess.exec); +// Add color-supporting environment variables +const getColorEnv = () => ({ + ...process.env, + FORCE_COLOR: "1", + COLORTERM: "truecolor", + TERM: "xterm-256color", + CLICOLOR: "1", + CLICOLOR_FORCE: "1", +}); + const ENABLED_FOR_REMOTES = [ "", "local", @@ -56,10 +66,11 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { } } - // Use spawn instead of exec to get streaming output + // Use spawn with color environment const childProc = childProcess.spawn(args.command, { cwd, shell: true, + env: getColorEnv(), // Add enhanced environment for colors }); childProc.stdout?.on("data", (data) => { @@ -130,26 +141,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { return; } - if (!waitForCompletion) { - // Already resolved, just update the UI with final output - if (extras.onPartialOutput) { - const status = - code === 0 || !code - ? "\nBackground command completed" - : `\nBackground command failed with exit code ${code}`; - extras.onPartialOutput({ - toolCallId, - contextItems: [ - { - name: "Terminal", - description: "Terminal command output", - content: terminalOutput, - status: status, - }, - ], - }); - } - } else { + if (waitForCompletion) { // Normal completion, resolve now if (code === 0) { const status = "Command completed"; @@ -172,6 +164,25 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ]); } + } else { + // Already resolved, just update the UI with final output + if (extras.onPartialOutput) { + const status = + code === 0 || !code + ? "\nBackground command completed" + : `\nBackground command failed with exit code ${code}`; + extras.onPartialOutput({ + toolCallId, + contextItems: [ + { + name: "Terminal", + description: "Terminal command output", + content: terminalOutput, + status: status, + }, + ], + }); + } } }); @@ -197,14 +208,43 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { const workspaceDirs = await extras.ide.getWorkspaceDirs(); const cwd = fileURLToPath(workspaceDirs[0]); - if (!waitForCompletion) { + if (waitForCompletion) { + // Standard execution, waiting for completion + try { + // Use color environment for exec as well + const output = await asyncExec(args.command, { + cwd, + env: getColorEnv(), + }); + const status = "Command completed"; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: output.stdout ?? "", + status: status, + }, + ]; + } catch (error: any) { + const status = `Command failed with: ${error.message || error.toString()}`; + return [ + { + name: "Terminal", + description: "Terminal command output", + content: error.stderr ?? error.toString(), + status: status, + }, + ]; + } + } else { // For non-streaming but also not waiting for completion, use spawn // but don't attach any listeners other than error try { - // Use spawn instead of exec but don't wait + // Use spawn with color environment const childProc = childProcess.spawn(args.command, { cwd, shell: true, + env: getColorEnv(), // Add color environment // Detach the process so it's not tied to the parent detached: true, // Redirect to /dev/null equivalent (works cross-platform) @@ -246,30 +286,6 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { }, ]; } - } else { - // Standard execution, waiting for completion - try { - const output = await asyncExec(args.command, { cwd }); - const status = "Command completed"; - return [ - { - name: "Terminal", - description: "Terminal command output", - content: output.stdout ?? "", - status: status, - }, - ]; - } catch (error: any) { - const status = `Command failed with: ${error.message || error.toString()}`; - return [ - { - name: "Terminal", - description: "Terminal command output", - content: error.stderr ?? error.toString(), - status: status, - }, - ]; - } } } } diff --git a/core/tools/index.ts b/core/tools/index.ts index f7ed3be4b..c4d1c658b 100644 --- a/core/tools/index.ts +++ b/core/tools/index.ts @@ -2,6 +2,7 @@ import { ConfigDependentToolParams, Tool } from ".."; import { createNewFileTool } from "./definitions/createNewFile"; import { createRuleBlock } from "./definitions/createRuleBlock"; import { editFileTool } from "./definitions/editFile"; +import { fetchUrlContentTool } from "./definitions/fetchUrlContent"; import { globSearchTool } from "./definitions/globSearch"; import { grepSearchTool } from "./definitions/grepSearch"; import { lsTool } from "./definitions/lsTool"; @@ -24,6 +25,7 @@ export const baseToolDefinitions = [ readCurrentlyOpenFileTool, lsTool, createRuleBlock, + fetchUrlContentTool, // replacing with ls tool for now // viewSubdirectoryTool, // viewRepoMapTool, diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 0bdaffbfd..8b50a3cae 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -234,11 +234,14 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } - async getSearchResults(query: string): Promise { + async getSearchResults(query: string, maxResults?: number): Promise { return ""; } - async getFileResults(pattern: string): Promise { + async getFileResults( + pattern: string, + maxResults?: number, + ): Promise { return []; } diff --git a/core/util/grepSearch.ts b/core/util/grepSearch.ts index a30982e77..be5b7ee08 100644 --- a/core/util/grepSearch.ts +++ b/core/util/grepSearch.ts @@ -1,4 +1,19 @@ -export function formatGrepSearchResults(results: string): string { +/* + Formats the output of a grep search to reduce unnecessary indentation, lines, etc + Assumes a command with these params + ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e . + + Also can truncate the output to a specified number of characters +*/ +export function formatGrepSearchResults( + results: string, + maxChars?: number, +): { + formatted: string; + numResults: number; + truncated: boolean; +} { + let numResults = 0; const keepLines: string[] = []; function countLeadingSpaces(line: string) { @@ -45,6 +60,7 @@ export function formatGrepSearchResults(results: string): string { if (line.startsWith("./") || line === "--") { processResult(resultLines); // process previous result resultLines = [line]; + numResults++; continue; } @@ -57,5 +73,18 @@ export function formatGrepSearchResults(results: string): string { } processResult(resultLines); - return keepLines.join("\n"); + const formatted = keepLines.join("\n"); + if (maxChars && formatted.length > maxChars) { + return { + formatted: formatted.substring(0, maxChars), + numResults, + truncated: true, + }; + } else { + return { + formatted, + numResults, + truncated: false, + }; + } } diff --git a/core/util/grepSearch.vitest.ts b/core/util/grepSearch.vitest.ts new file mode 100644 index 000000000..df1a71efd --- /dev/null +++ b/core/util/grepSearch.vitest.ts @@ -0,0 +1,217 @@ +import { expect, test } from "vitest"; +import { formatGrepSearchResults } from "./grepSearch"; + +// Sample grep output mimicking what would come from ripgrep with the params: +// ripgrep -i --ignore-file .continueignore --ignore-file .gitignore -C 2 --heading -m 100 -e . +const sampleGrepOutput = `./program.cs + Console.WriteLine("Hello World!"); + Calculator calc = new Calculator(); + calc.Add(5).Subtract(3); + Console.WriteLine("Result: " + calc.GetResult()); + } +-- + } + + public Calculator Subtract(double number) + { + result -= number; + +./test.kt + } + + fun subtract(number: Double): Test { + result -= number + return this + +./test.php + } + + public function subtract($number) { + $this->result -= $number; + return $this; +-- + +$calc = new Calculator(); +$calc->add(10)->subtract(5); +echo "Result: " . $calc->getResult() . "\n"; + + +./Calculator.java + } + + public Calculator subtract(double number) { + result -= number; + return this; +-- + public static void main(String[] args) { + Calculator calc = new Calculator(); + calc.add(10).subtract(5); + System.out.println("Result: " + calc.getResult()); + } + +./calculator_test/Calculator.java + } + + public int subtract(int a, int b) { + return a - b; + } + +./test.rb + end + + def subtract(number) + @result -= number + self +-- + +calc = Calculator.new +calc.add(5).subtract(3) +puts "Result: #{calc.get_result}" + +./test.js + return this; + } + subtract(number) { + return this; + } + +./test.py + return self + + def subtract(self, number): + self.result -= number + return self + +./test.ts + } + + subtract(number: number): Calculator { + this.result -= number; + return this;`; + +test("formats grep search results correctly", () => { + const result = formatGrepSearchResults(sampleGrepOutput); + + expect(result.numResults).toBe(13); // 4 file paths in the sample + expect(result.truncated).toBe(false); + + // Check that all file paths are preserved + expect(result.formatted).toContain("./program.cs"); + expect(result.formatted).toContain("./test.kt"); + expect(result.formatted).toContain("./test.php"); + expect(result.formatted).toContain("./Calculator.java"); + + // Check that content is preserved and properly indented + expect(result.formatted).toContain('Console.WriteLine("Hello World!");'); + expect(result.formatted).toContain("fun subtract(number: Double): Test {"); + expect(result.formatted).toContain("public function subtract($number) {"); + expect(result.formatted).toContain( + "public Calculator subtract(double number) {", + ); +}); + +test("handles empty input", () => { + const result = formatGrepSearchResults(""); + + expect(result.numResults).toBe(0); + expect(result.truncated).toBe(false); + expect(result.formatted).toBe(""); +}); + +test("handles input with only file paths (no content) - lines should be skipped", () => { + const input = + "./empty-file.ts\n./another-empty.js\n./has-content.ts\n searchMatch"; + const result = formatGrepSearchResults(input); + + expect(result.numResults).toBe(3); + expect(result.formatted).toBe("./has-content.ts\n searchMatch"); +}); + +test("truncates output when exceeding maxChars", () => { + const maxChars = 50; + const result = formatGrepSearchResults(sampleGrepOutput, maxChars); + + expect(result.truncated).toBe(true); + expect(result.formatted.length).toBe(maxChars); +}); + +test("normalizes indentation to 2 spaces", () => { + const input = `./file.ts + function test() { + const x = 1; + console.log(x); + }`; + + const result = formatGrepSearchResults(input); + + // The function should normalize the indentation to 2 spaces + expect(result.formatted).toContain("./file.ts"); + expect(result.formatted).toContain(" function test() {"); + expect(result.formatted).toContain(" const x = 1;"); + expect(result.formatted).toContain(" console.log(x);"); + expect(result.formatted).toContain(" }"); +}); + +test("skips leading single-char or empty lines after file paths", () => { + const input = `./file.ts + +function test() { + console.log("test"); +}`; + + const result = formatGrepSearchResults(input); + + expect(result.formatted).toContain("./file.ts"); + expect(result.formatted).not.toContain("\n \n"); // The single space line should be skipped + expect(result.formatted).toContain("function test() {"); +}); + +test("processes separator lines correctly", () => { + const input = `./file1.ts +function one() { + return 1; +} +-- +function two() { + return 2; +} + +./file2.ts +class Test { + method() {} +}`; + + const result = formatGrepSearchResults(input); + + expect(result.numResults).toBe(3); + expect(result.formatted).toContain("./file1.ts"); + expect(result.formatted).toContain("--"); + expect(result.formatted).toContain("function two() {"); + expect(result.formatted).toContain("./file2.ts"); +}); + +test("increases indentation when original is less than 2 spaces", () => { + const input = `./minimal-indent.ts +function test() { + singleSpaceIndent(); +}`; + + const result = formatGrepSearchResults(input); + + expect(result.formatted).toContain(" function test() {"); + expect(result.formatted).toContain(" singleSpaceIndent();"); + expect(result.formatted).toContain(" }"); +}); + +test("decreases indentation when original is more than 2 spaces", () => { + const input = `./excessive-indent.ts + function test() { + tooMuchIndent(); + }`; + + const result = formatGrepSearchResults(input); + + expect(result.formatted).toContain(" function test() {"); + expect(result.formatted).toContain(" tooMuchIndent();"); + expect(result.formatted).toContain(" }"); +}); diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 25b3ab600..dfde657fb 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -4,6 +4,7 @@ import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; import type { PostHog as PostHogType } from "posthog-node"; +import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js"; export enum PosthogFeatureFlag { AutocompleteTimeout = "autocomplete-timeout", @@ -37,6 +38,24 @@ export class Telemetry { static os: string | undefined = undefined; static ideInfo: IdeInfo | undefined = undefined; + /** + * Convenience method for capturing errors in a single event + */ + static async captureError(errorName: string, error: unknown) { + if (!(error instanceof Error)) { + return; + } + await Telemetry.capture( + "extension_error_caught", + { + errorName, + message: error.message, + stack: extractMinimalStackTraceInfo(error.stack), + }, + false, + ); + } + static async capture( event: string, properties: { [key: string]: any }, diff --git a/core/util/shellPath.ts b/core/util/shellPath.ts index a1772ba81..f2ade2443 100644 --- a/core/util/shellPath.ts +++ b/core/util/shellPath.ts @@ -1,10 +1,6 @@ import { execSync } from "child_process"; +import { homedir } from "os"; -/** - * Gets the PATH env var from the user's login shell on non-Windows platforms. - * Windows is not implemented primarily because it is not needed at the moment. - * @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined - */ export function getEnvPathFromUserShell(): string | undefined { if (process.platform === "win32") { console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`); @@ -16,7 +12,8 @@ export function getEnvPathFromUserShell(): string | undefined { } try { - const command = `${process.env.SHELL} -l -c 'echo $PATH'`; + // Source common profile files + const command = `${process.env.SHELL} -l -c 'for f in ~/.zprofile ~/.zshrc ~/.bash_profile ~/.bashrc; do [ -f "$f" ] && source "$f" 2>/dev/null; done; echo $PATH'`; const stdout = execSync(command, { encoding: "utf8", diff --git a/core/vitest.config.ts b/core/vitest.config.ts index 746b1fa3d..8657b43d6 100644 --- a/core/vitest.config.ts +++ b/core/vitest.config.ts @@ -9,11 +9,6 @@ export default defineConfig({ globalSetup: "./test/vitest.global-setup.ts", setupFiles: "./test/vitest.setup.ts", fileParallelism: false, - include: [ - "**/*.vitest.ts", - "config/**/*.test.ts", - "autocomplete/**/*.test.ts", - "context/**/*.test.ts", - ], + include: ["**/*.vitest.ts"], }, }); diff --git a/docs/docs/agent/how-it-works.md b/docs/docs/agent/how-it-works.md index 1191fa9f8..5847b99a5 100644 --- a/docs/docs/agent/how-it-works.md +++ b/docs/docs/agent/how-it-works.md @@ -32,6 +32,7 @@ Continue includes several built-in tools which provide the model access to IDE f - **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file - **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model - **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project +- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. - **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root - **Search web** (`builtin_search_web`): Perform a web search to get top results - **View diff** (`builtin_view_diff`): View the current working git diff diff --git a/docs/docs/autocomplete/how-to-use-it.md b/docs/docs/autocomplete/how-to-use-it.md index b9b3c19d2..950a41993 100644 --- a/docs/docs/autocomplete/how-to-use-it.md +++ b/docs/docs/autocomplete/how-to-use-it.md @@ -23,3 +23,7 @@ Reject a full suggestion with Esc ### Partially accepting a suggestion For more granular control, use cmd/ctrl + → to accept parts of the suggestion word-by-word. + +### Forcing a suggestion (VS Code) + +If you want to trigger a suggestion immediately without waiting, or if you've dismissed a suggestion and want a new one, you can force it by using the keyboard shortcut **cmd/ctrl + alt + space**. diff --git a/docs/docs/customize/context-providers.mdx b/docs/docs/customize/context-providers.mdx index 204f680f0..c55bbfbbd 100644 --- a/docs/docs/customize/context-providers.mdx +++ b/docs/docs/customize/context-providers.mdx @@ -288,6 +288,8 @@ Reference the results of codebase search, just like the results you would get fr ```yaml title="config.yaml" context: - provider: search + params: + maxResults: 100 # optional, defaults to 200 ``` @@ -295,7 +297,10 @@ Reference the results of codebase search, just like the results you would get fr { "contextProviders": [ { - "name": "search" + "name": "search", + "params": { + "maxResults": 100 // optional, defaults to 200 + } } ] } diff --git a/docs/docs/customize/deep-dives/mcp.mdx b/docs/docs/customize/deep-dives/mcp.mdx index 04366d210..9899518e7 100644 --- a/docs/docs/customize/deep-dives/mcp.mdx +++ b/docs/docs/customize/deep-dives/mcp.mdx @@ -7,45 +7,175 @@ keywords: [tool, use, function calling, claude, automatic] import TabItem from "@theme/TabItem"; import Tabs from "@theme/Tabs"; -## MCP +# MCP -Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. +As AI systems get better, they're still held back by their training data and +can't access real-time information or specialized tools. The [Model Context +Protocol](https://modelcontextprotocol.io/introduction) (MCP) fixes this by +letting AI models connect with outside data sources, tools, and environments. +This allows smooth sharing of information and abilities between AI systems and +the wider digital world. This standard, created by Anthropic to bring together +prompts, context, and tool use, is key for building truly useful AI experiences +that can be set up with custom tools. -MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can explore available MCP server blocks [here](https://hub.continue.dev/explore/mcp). +## How it works + +Currently custom tools can be configured using the Model Context +Protocol standard to unify prompts, context, and tool use. + +MCP Servers can be added to hub Assistants using `mcpServers` blocks. You can +explore available MCP server blocks +[here](https://hub.continue.dev/explore/mcp). :::info MCP can only be used in the **agent** mode. ::: -To set up your own MCP server, read the [MCP quickstart](https://modelcontextprotocol.io/quickstart) and then [create an `mcpServers` block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add the following to your [config file](./configuration.md): +## Quick Start - +Below is a quick example of setting up a new MCP server for use in your assistant: + +1. Create a folder called `.continue/mcpServers` at the top level of your workspace +2. Add a file called `playwright-mcp.yaml` to this folder. +3. Write the following contents to `playwright-mcp.yaml` and save. + +```yaml title=".continue/mcpServers/playwright-mcp.yaml" +name: Playwright mcpServer +version: 0.0.1 +schema: v1 +mcpServers: + - name: Browser search + command: npx + args: + - "@playwright/mcp@latest" +``` + +Now test your MCP server by prompting the following command: + +``` +Open the browser and navigate Hacker News. Save the top 10 headlines in a hn.txt file. +``` + +The result will be a generated file called `hn.txt` in the current working directory. + +![playwright mcp](/img/mcp-playwright.png) + +## Using MCP Servers + +To set up your own MCP server, read the [MCP +quickstart](https://modelcontextprotocol.io/quickstart) and then [create an +`mcpServers` +block](https://hub.continue.dev/new?type=block&blockType=mcpServers) or add a local MCP +server block to your [config file](./configuration.md): + + ```yaml title="config.yaml" mcpServers: - - name: My MCP Server - command: uvx + - name: SQLite MCP + command: npx args: - - mcp-server-sqlite - - --db-path - - /Users/NAME/test.db - ``` - - - ```json title="config.json" - { - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } + - "-y" + - "mcp-sqlite" + - "/path/to/your/database.db" + +```` + + +```json title="config.json" +{ + "experimental": { + "modelContextProtocolServers": [ + { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/path/to/your/database.db"] } - ] - } + } + ] } - ``` +} +```` + + +### Syntax + +MCP blocks follow the established syntax for blocks, with a few additional properties specific to MCP servers. + +- `name` (**required**): A display name for the MCP server. +- `command` (**required**): The command to run to start the MCP server. +- `type` (optional): The type of the MCP server: `sse`, `stdio`, `streamable-http` +- `args` (optional): Arguments to pass to the command. +- `env` (optional): Secrets to be injected into the command as environment variables. + +### Transport Types + +MCP now supports remote server connections through HTTP-based transports, expanding beyond the traditional local stdio transport method. This enables integration with cloud-hosted MCP servers and distributed architectures. + +#### Server-Sent Events (SSE) Transport + +For real-time streaming communication, use the SSE transport: + +```yaml +mcpServers: + - name: Name + type: sse + url: https://.... +``` + +#### Standard Input/Output (stdio) + +For local MCP servers that communicate via standard input and output: + +```yaml +mcpServers: + - name: Name + type: stdio + command: npx + args: + - "@modelcontextprotocol/server-sqlite" + - "/path/to/your/database.db" +``` + +#### Streamable HTTP Transport + +For standard HTTP-based communication with streaming capabilities: + +```yaml +mcpServers: + - name: Name + type: streamable-http + url: https://.... +``` + +These remote transport options allow you to connect to MCP servers hosted on remote infrastructure, enabling more flexible deployment architectures and shared server resources across multiple clients. + +For detailed information about transport mechanisms and their use cases, refer to the official MCP documentation on [transports](https://modelcontextprotocol.io/docs/concepts/transports#server-sent-events-sse). + +### Working with Secrets + +With some MCP servers you will need to use API keys or other secrets. You can leverage locally stored environments secrets +as well as access hosted secrets in the Continue Hub. To leverage Hub secrets, you can use the `inputs` property in your MCP env block instead of `secrets`. + +```yaml +mcpServers: + - name: Supabase MCP + command: npx + args: + - -y + - "@supabase/mcp-server-supabase@latest" + - --access-token + - ${{ secrets.SUPABASE_TOKEN }} + env: + SUPABASE_TOKEN: ${{ secrets.SUPABASE_TOKEN }} + - name: GitHub + command: npx + args: + - "-y" + - "@modelcontextprotocol/server-github" + env: + GITHUB_PERSONAL_ACCESS_TOKEN: ${{ secrets.GITHUB_PERSONAL_ACCESS_TOKEN }} +``` diff --git a/docs/docs/customize/deep-dives/rules.mdx b/docs/docs/customize/deep-dives/rules.mdx index 59c9c3894..147606f85 100644 --- a/docs/docs/customize/deep-dives/rules.mdx +++ b/docs/docs/customize/deep-dives/rules.mdx @@ -63,8 +63,9 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark - `name` (**required** for YAML): A display name/title for the rule - `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). +- `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context. - `alwaysApply`: true - Always include the rule, regardless of file context -- `alwaysApply`: false - Only include if globs exist AND match file context +- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description - `alwaysApply`: undefined - Default behavior: include if no globs exist OR globs exist and match diff --git a/docs/docs/customize/model-providers/more/cohere.mdx b/docs/docs/customize/model-providers/more/cohere.mdx index 352908e12..b68814ffd 100644 --- a/docs/docs/customize/model-providers/more/cohere.mdx +++ b/docs/docs/customize/model-providers/more/cohere.mdx @@ -7,15 +7,15 @@ Before using Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/a ## Chat model -We recommend configuring **Command-R Plus** as your chat model. +We recommend configuring **Command A** as your chat model. ```yaml title="config.yaml" models: - - name: Cohere + - name: Command A 03-2025 provider: cohere - model: command-r-plus + model: command-a-03-2025 apiKey: ``` @@ -24,9 +24,9 @@ We recommend configuring **Command-R Plus** as your chat model. { "models": [ { - "title": "Cohere", + "title": "Command A 03-2025", "provider": "cohere", - "model": "command-r-plus", + "model": "command-a-03-2025", "apiKey": "" } ] @@ -43,15 +43,15 @@ Cohere currently does not offer any autocomplete models. ## Embeddings model -We recommend configuring **embed-english-v3.0** as your embeddings model. +We recommend configuring **embed-v4.0** as your embeddings model. ```yaml title="config.yaml" models: - - name: Cohere Embed + - name: Cohere Embed v4.0 provider: cohere - model: embed-english-v3.0 + model: embed-v4.0 apiKey: roles: - embed @@ -62,7 +62,7 @@ We recommend configuring **embed-english-v3.0** as your embeddings model. { "embeddingsProvider": { "provider": "cohere", - "model": "embed-english-v3.0", + "model": "embed-v4.0", "apiKey": "" } } @@ -72,15 +72,15 @@ We recommend configuring **embed-english-v3.0** as your embeddings model. ## Reranking model -We recommend configuring **rerank-english-v3.0** as your reranking model. +We recommend configuring **rerank-v3.5** as your reranking model. ```yaml title="config.yaml" models: - - name: Cohere Reranker + - name: Cohere Rerank v3.5 provider: cohere - model: rerank-english-v3.0 + model: rerank-v3.5 apiKey: roles: - rerank @@ -92,7 +92,7 @@ We recommend configuring **rerank-english-v3.0** as your reranking model. "reranker": { "name": "cohere", "params": { - "model": "rerank-english-v3.0", + "model": "rerank-v3.5", "apiKey": "" } } diff --git a/docs/docs/customize/model-providers/more/vllm.mdx b/docs/docs/customize/model-providers/more/vllm.mdx index 9bae1880e..4ae25dafc 100644 --- a/docs/docs/customize/model-providers/more/vllm.mdx +++ b/docs/docs/customize/model-providers/more/vllm.mdx @@ -100,6 +100,8 @@ We recommend configuring **Nomic Embed Text** as your embeddings model. ## Reranking model +Continue automatically handles vLLM's response format (which uses `results` instead of `data`). + [Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. The continue implementation uses [OpenAI](../top-level/openai.mdx) under the hood. [View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) diff --git a/docs/docs/customize/model-providers/top-level/anthropic.mdx b/docs/docs/customize/model-providers/top-level/anthropic.mdx index d7d1e325c..4786c3719 100644 --- a/docs/docs/customize/model-providers/top-level/anthropic.mdx +++ b/docs/docs/customize/model-providers/top-level/anthropic.mdx @@ -12,15 +12,15 @@ You can get an API key from the [Anthropic console](https://console.anthropic.co ## Chat model -We recommend configuring **Claude 3.5 Sonnet** as your chat model. +We recommend configuring **Claude 4 Sonnet** as your chat model. ```yaml title="config.yaml" models: - - name: Claude 3.5 Sonnet + - name: Claude 4 Sonnet provider: anthropic - model: claude-3-5-sonnet-latest + model: claude-sonnet-4-20250514 apiKey: ``` @@ -29,9 +29,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. { "models": [ { - "title": "Claude 3.5 Sonnet", + "title": "Claude 4 Sonnet", "provider": "anthropic", - "model": "claude-3-5-sonnet-latest", + "model": "claude-sonnet-4-latest", "apiKey": "" } ] @@ -60,9 +60,16 @@ Anthropic currently does not offer any reranking models. ## Prompt caching -Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching). +Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching), which allows Claude models to cache system messages and conversation history between requests to improve performance and reduce costs. -To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following: +Prompt caching is generally available for: + +- Claude 4 Sonnet +- Claude 3.7 Sonnet +- Claude 3.5 Sonnet +- Claude 3.5 Haiku + +To enable caching of the system message and the turn-by-turn conversation, update your model configuration as follows: @@ -70,13 +77,12 @@ To enable caching of the system message and the turn-by-turn conversation, updat models: - name: Anthropic provider: anthropic - model: claude-3-5-sonnet-latest + model: claude-sonnet-4-20250514 apiKey: roles: - chat - cacheBehavior: - cacheSystemMessage: true - cacheConversation: true + defaultCompletionOptions: + promptCaching: true ``` @@ -90,7 +96,10 @@ To enable caching of the system message and the turn-by-turn conversation, updat }, "title": "Anthropic", "provider": "anthropic", - "model": "claude-3-5-sonnet-latest", + "model": "claude-sonnet-4-latest", + "defaultCompletionOptions": { + "promptCaching": true + }, "apiKey": "" } ] diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index f4e35ce05..d1ee7609b 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -2,6 +2,7 @@ title: Apply Role description: Apply model role keywords: [apply, model, role] +sidebar_position: 4 --- When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. diff --git a/docs/docs/troubleshooting.mdx b/docs/docs/troubleshooting.mdx index 40d68a82e..cc8f90592 100644 --- a/docs/docs/troubleshooting.mdx +++ b/docs/docs/troubleshooting.mdx @@ -162,6 +162,12 @@ Most Continue features will work normally, including autocomplete and chat. Howe 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? You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and 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. diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index b2f511a64..4e873f0db 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -203,6 +203,14 @@ const config = { }, }), plugins: [ + [ + "posthog-docusaurus", + { + apiKey: process.env.POSTHOG_API_KEY || "DEV", + appUrl: "https://us.i.posthog.com", + enableInDevelopment: false, + }, + ], [ "@docusaurus/plugin-client-redirects", { diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md index e69029b00..b33ebc3ba 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md @@ -4,15 +4,15 @@ ## 聊天模型 -我们推荐配置 **Command-R Plus** 作为你的聊天模型。 +我们推荐配置 **Command-A** 作为你的聊天模型。 ```json title="config.json" { "models": [ { - "title": "Cohere", + "title": "Command A 03-2025", "provider": "cohere", - "model": "command-r-plus", + "model": "command-a-03-2025", "apiKey": "YOUR_API_KEY" } ] @@ -27,13 +27,13 @@ Cohere 当前没有提供任何自动补全模型。 ## 嵌入模型 -我们推荐配置 **embed-english-v3.0** 作为你的嵌入模型。 +我们推荐配置 **embed-v4.0** 作为你的嵌入模型。 ```json title="config.json" { "embeddingsProvider": { "provider": "cohere", - "model": "embed-english-v3.0", + "model": "embed-v4.0", "apiKey": "" } } @@ -41,14 +41,14 @@ Cohere 当前没有提供任何自动补全模型。 ## 重排序模型 -我们推荐配置 **rerank-english-v3.0** 作为你的重排序模型。 +我们推荐配置 **rerank-v3.5** 作为你的重排序模型。 ```json title="config.json" { "embeddingsProvider": { "provider": "cohere", "params": { - "model": "rerank-english-v3.0", + "model": "rerank-v3.5", "apiKey": "" } } diff --git a/docs/package-lock.json b/docs/package-lock.json index e96349847..f3a3ea446 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -14,6 +14,7 @@ "@docusaurus/preset-classic": "^3.7.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", + "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" @@ -14990,6 +14991,15 @@ "postcss": "^8.4.31" } }, + "node_modules/posthog-docusaurus": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/posthog-docusaurus/-/posthog-docusaurus-2.0.4.tgz", + "integrity": "sha512-xnEVCBovSuvQvYXGny03CDTc0yZCl7O3Mz21sJpXmE1Gvs21gM33WzWaA9Cm6WvWGYZtQy8t8/g8OjCkmTWlXA==", + "license": "MIT", + "engines": { + "node": ">=10.15.1" + } + }, "node_modules/pretty-error": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz", diff --git a/docs/package.json b/docs/package.json index 8f6ad8c95..67b995070 100644 --- a/docs/package.json +++ b/docs/package.json @@ -22,6 +22,7 @@ "@docusaurus/preset-classic": "^3.7.0", "@mdx-js/react": "^3.0.0", "clsx": "^2.1.0", + "posthog-docusaurus": "^2.0.4", "prism-react-renderer": "^2.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" diff --git a/docs/static/img/mcp-playwright.png b/docs/static/img/mcp-playwright.png new file mode 100644 index 000000000..5dd3c9f16 Binary files /dev/null and b/docs/static/img/mcp-playwright.png differ diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 6ef77a57c..15326353d 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.22 +pluginVersion=1.0.25 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt index 755b16d85..8cb05dc31 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/ApplyToFileHandler.kt @@ -169,7 +169,11 @@ class ApplyToFileHandler( ide: IDE, params: ApplyToFileParams ) { - val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath) + val editorUtils = if (EditorUtils.editorFileExist(params.filepath)) + EditorUtils.getOrOpenEditor(project, params.filepath) + else + EditorUtils.getEditorByCreateFile(project, params.filepath) + val diffStreamService = project.getService(DiffStreamService::class.java) val handler = ApplyToFileHandler( diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index cd2b3b86a..ddbb5f738 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -356,7 +356,7 @@ class IdeProtocolClient( dataElement.toString(), GetSearchResultsParams::class.java ) - val results = ide.getSearchResults(params.query) + val results = ide.getSearchResults(params.query, params.maxResults) respond(results) } @@ -365,7 +365,7 @@ class IdeProtocolClient( dataElement.toString(), GetFileResultsParams::class.java ) - val results = ide.getFileResults(params.pattern) + val results = ide.getFileResults(params.pattern, params.maxResults) respond(results) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 908ba2edd..a692759b9 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -315,11 +315,11 @@ class IntelliJIDE( return getOpenFiles() } - override suspend fun getFileResults(pattern: String): List { + override suspend fun getFileResults(pattern: String, maxResults: Int?): List { val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { try { - val command = GeneralCommandLine( + var commandArgs = mutableListOf( ripgrep, "--files", "--iglob", @@ -327,8 +327,14 @@ class IntelliJIDE( "--ignore-file", ".continueignore", "--ignore-file", - ".gitignore", + ".gitignore" ) + if (maxResults != null) { + commandArgs.add("--max-count") + commandArgs.add(maxResults.toString()) + } + + val command = GeneralCommandLine(commandArgs) command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout @@ -344,11 +350,11 @@ class IntelliJIDE( throw NotImplementedError("Ripgrep not supported, this workspace is remote") } } - override suspend fun getSearchResults(query: String): String { + override suspend fun getSearchResults(query: String, maxResults: Int?): String { val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { try { - val command = GeneralCommandLine( + val commandArgs = mutableListOf( ripgrep, "-i", "--ignore-file", @@ -357,11 +363,21 @@ class IntelliJIDE( ".gitignore", "-C", "2", - "--heading", - "-e", - query, - "." + "--heading" ) + + // Conditionally add maxResults flag + if (maxResults != null) { + commandArgs.add("-m") + commandArgs.add(maxResults.toString()) + } + + // Add the search query and path + commandArgs.add("-e") + commandArgs.add(query) + commandArgs.add(".") + + val command = GeneralCommandLine(commandArgs) command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt index 857c0104f..391c0423d 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/EditorUtils.kt @@ -2,6 +2,7 @@ package com.github.continuedev.continueintellijextension.editor import com.github.continuedev.continueintellijextension.utils.toUriOrNull import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.SelectionModel @@ -14,6 +15,8 @@ import com.intellij.openapi.util.TextRange import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.ui.JBColor import com.intellij.openapi.editor.ScrollType +import com.intellij.openapi.vfs.LocalFileSystem +import java.io.File /** * Utility class for working with Editor instances. @@ -166,5 +169,38 @@ class EditorUtils(val editor: Editor) { val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null return EditorUtils(editor) } + + /** + * Gets editor for the filepath is existed + */ + fun editorFileExist(filepath: String?): Boolean { + return !filepath.isNullOrEmpty() && VirtualFileManager.getInstance().findFileByUrl(filepath) != null + } + + /** + * Gets editor for the no exist filepath and returns an EditorUtils instance + */ + fun getEditorByCreateFile(project: Project, filepath: String?): EditorUtils? { + if (!filepath.isNullOrEmpty()) { + // file not exists and create + val ioFile = File(filepath.replace("file:///", "")) + if (!ioFile.exists()) { + ioFile.parentFile?.mkdirs() + ioFile.createNewFile() + } + // IntelliJ refresh VirtualFile + val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile) + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + runWriteAction { + FileEditorManager.getInstance(project).openFile(virtualFile, true) + } + } + } + } + + val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null + return EditorUtils(editor) + } } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index 4c66fcc0c..bf377e675 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -21,9 +21,9 @@ typealias OpenUrlParam = String typealias getTagsParams = String -data class GetSearchResultsParams(val query: String) +data class GetSearchResultsParams(val query: String, val maxResults: Int?) -data class GetFileResultsParams(val pattern: String) +data class GetFileResultsParams(val pattern: String, val maxResults: Int?) data class SaveFileParams(val filepath: String) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt index 71e7092e0..34b0e25d7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/types.kt @@ -157,9 +157,9 @@ interface IDE { suspend fun getPinnedFiles(): List - suspend fun getSearchResults(query: String): String + suspend fun getSearchResults(query: String, maxResults: Int?): String - suspend fun getFileResults(pattern: String): List + suspend fun getFileResults(pattern: String, maxResults: Int?): List // Note: This should be a `Pair` but we use `List` because the keys of `Pair` // will serialize to `first and `second` rather than `0` and `1` like in JavaScript @@ -239,7 +239,7 @@ data class StreamDiffLinesPayload( ) data class AcceptOrRejectDiffPayload( - val filepath: String, + val filepath: String? = null, val streamId: String? = null ) diff --git a/extensions/vscode/.eslintrc.json b/extensions/vscode/.eslintrc.json index e1e339ce7..ce0283909 100644 --- a/extensions/vscode/.eslintrc.json +++ b/extensions/vscode/.eslintrc.json @@ -6,6 +6,7 @@ "extends": ["../../.eslintrc.shared.json"], "rules": { "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/no-floating-promises": "warn" + "@typescript-eslint/no-floating-promises": "warn", + "@typescript-eslint/no-misused-promises": "warn" } } diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 576c184e9..29d882489 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -868,7 +868,21 @@ "then": { "properties": { "model": { - "enum": ["command-r", "command-r-plus"] + "enum": [ + "c4ai-aya-expanse-8b", + "c4ai-aya-expanse-32b", + "c4ai-aya-vision-8b", + "c4ai-aya-vision-32b", + "command-r", + "command-r-plus", + "command-r-03-2024", + "command-r-plus-04-2024", + "command-r-08-2024", + "command-r-plus-08-2024", + "command-r7b-12-2024", + "command-r7b-arabic-02-2025", + "command-a-03-2025" + ] } } } @@ -2130,6 +2144,29 @@ } } }, + { + "if": { + "properties": { + "name": { + "enum": ["search"] + } + } + }, + "then": { + "properties": { + "params": { + "properties": { + "maxResults": { + "title": "Max Results", + "description": "The maximum number of results to return", + "default": 200, + "type": "integer" + } + } + } + } + } + }, { "if": { "properties": { diff --git a/extensions/vscode/e2e/actions/Autocomplete.actions.ts b/extensions/vscode/e2e/actions/Autocomplete.actions.ts index c35c47a29..9e91355fd 100644 --- a/extensions/vscode/e2e/actions/Autocomplete.actions.ts +++ b/extensions/vscode/e2e/actions/Autocomplete.actions.ts @@ -1,5 +1,5 @@ import { expect } from "chai"; -import { TextEditor } from "vscode-extension-tester"; +import { TextEditor, VSBrowser, Workbench } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; import { AutocompleteSelectors } from "../selectors/Autocomplete.selectors"; @@ -29,4 +29,17 @@ export class AutocompleteActions { ); expect(ghostText1).to.equal(messagePair1.llmResponse); } + + public static async forceCompletion(editor: TextEditor): Promise { + await editor.setText("def main():\n "); + await editor.moveCursor(2, 5); + + await new Workbench().executeCommand("Continue: Force Autocomplete"); + + const ghostText = await TestUtils.waitForSuccess(() => + AutocompleteSelectors.getGhostTextContent(VSBrowser.instance.driver) + ); + + return ghostText; + } } diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index 836c2c60e..7685d52ae 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,3 +1,4 @@ +import { expect } from "chai"; import { EditorView, TextEditor } from "vscode-extension-tester"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; @@ -23,4 +24,8 @@ describe("Autocomplete", () => { it("Should display completions", async () => { await AutocompleteActions.testCompletions(editor); }).timeout(DEFAULT_TIMEOUT.XL); + it("Should force a completion using the command", async () => { + const ghostText = await AutocompleteActions.forceCompletion(editor); + expect(ghostText).to.not.be.empty; + }).timeout(DEFAULT_TIMEOUT.XL); }); diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index f66fd08f3..199c669c7 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.46", + "version": "1.1.48", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.46", + "version": "1.1.48", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -57,6 +57,7 @@ "uuid": "^9.0.1", "uuidv4": "^6.2.13", "vectordb": "^0.4.20", + "vitest": "^3.1.4", "vscode-languageclient": "^8.0.2", "ws": "^8.13.0", "yarn": "^1.22.21" @@ -772,6 +773,22 @@ "node": ">=12.13.0" } }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz", + "integrity": "sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/android-arm": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", @@ -1028,6 +1045,22 @@ "node": ">=12" } }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.5.tgz", + "integrity": "sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/netbsd-x64": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz", @@ -1044,6 +1077,22 @@ "node": ">=12" } }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.5.tgz", + "integrity": "sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, "node_modules/@esbuild/openbsd-x64": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz", @@ -1923,6 +1972,266 @@ } } }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.43.0.tgz", + "integrity": "sha512-Krjy9awJl6rKbruhQDgivNbD1WuLb8xAclM4IR4cN5pHGAs2oIMMQJEiC3IC/9TZJ+QZkmZhlMO/6MBGxPidpw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.43.0.tgz", + "integrity": "sha512-ss4YJwRt5I63454Rpj+mXCXicakdFmKnUNxr1dLK+5rv5FJgAxnN7s31a5VchRYxCFWdmnDWKd0wbAdTr0J5EA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.43.0.tgz", + "integrity": "sha512-eKoL8ykZ7zz8MjgBenEF2OoTNFAPFz1/lyJ5UmmFSz5jW+7XbH1+MAgCVHy72aG59rbuQLcJeiMrP8qP5d/N0A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.43.0.tgz", + "integrity": "sha512-SYwXJgaBYW33Wi/q4ubN+ldWC4DzQY62S4Ll2dgfr/dbPoF50dlQwEaEHSKrQdSjC6oIe1WgzosoaNoHCdNuMg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.43.0.tgz", + "integrity": "sha512-SV+U5sSo0yujrjzBF7/YidieK2iF6E7MdF6EbYxNz94lA+R0wKl3SiixGyG/9Klab6uNBIqsN7j4Y/Fya7wAjQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.43.0.tgz", + "integrity": "sha512-J7uCsiV13L/VOeHJBo5SjasKiGxJ0g+nQTrBkAsmQBIdil3KhPnSE9GnRon4ejX1XDdsmK/l30IYLiAaQEO0Cg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.43.0.tgz", + "integrity": "sha512-gTJ/JnnjCMc15uwB10TTATBEhK9meBIY+gXP4s0sHD1zHOaIh4Dmy1X9wup18IiY9tTNk5gJc4yx9ctj/fjrIw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.43.0.tgz", + "integrity": "sha512-ZJ3gZynL1LDSIvRfz0qXtTNs56n5DI2Mq+WACWZ7yGHFUEirHBRt7fyIk0NsCKhmRhn7WAcjgSkSVVxKlPNFFw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.43.0.tgz", + "integrity": "sha512-8FnkipasmOOSSlfucGYEu58U8cxEdhziKjPD2FIa0ONVMxvl/hmONtX/7y4vGjdUhjcTHlKlDhw3H9t98fPvyA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.43.0.tgz", + "integrity": "sha512-KPPyAdlcIZ6S9C3S2cndXDkV0Bb1OSMsX0Eelr2Bay4EsF9yi9u9uzc9RniK3mcUGCLhWY9oLr6er80P5DE6XA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loongarch64-gnu": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loongarch64-gnu/-/rollup-linux-loongarch64-gnu-4.43.0.tgz", + "integrity": "sha512-HPGDIH0/ZzAZjvtlXj6g+KDQ9ZMHfSP553za7o2Odegb/BEfwJcR0Sw0RLNpQ9nC6Gy8s+3mSS9xjZ0n3rhcYg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-powerpc64le-gnu": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-powerpc64le-gnu/-/rollup-linux-powerpc64le-gnu-4.43.0.tgz", + "integrity": "sha512-gEmwbOws4U4GLAJDhhtSPWPXUzDfMRedT3hFMyRAvM9Mrnj+dJIFIeL7otsv2WF3D7GrV0GIewW0y28dOYWkmw==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.43.0.tgz", + "integrity": "sha512-XXKvo2e+wFtXZF/9xoWohHg+MuRnvO29TI5Hqe9xwN5uN8NKUYy7tXUG3EZAlfchufNCTHNGjEx7uN78KsBo0g==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.43.0.tgz", + "integrity": "sha512-ruf3hPWhjw6uDFsOAzmbNIvlXFXlBQ4nk57Sec8E8rUxs/AI4HD6xmiiasOOx/3QxS2f5eQMKTAwk7KHwpzr/Q==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.43.0.tgz", + "integrity": "sha512-QmNIAqDiEMEvFV15rsSnjoSmO0+eJLoKRD9EAa9rrYNwO/XRCtOGM3A5A0X+wmG+XRrw9Fxdsw+LnyYiZWWcVw==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.43.0.tgz", + "integrity": "sha512-jAHr/S0iiBtFyzjhOkAics/2SrXE092qyqEg96e90L3t9Op8OTzS6+IX0Fy5wCt2+KqeHAkti+eitV0wvblEoQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.43.0.tgz", + "integrity": "sha512-3yATWgdeXyuHtBhrLt98w+5fKurdqvs8B53LaoKD7P7H7FKOONLsBVMNl9ghPQZQuYcceV5CDyPfyfGpMWD9mQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.43.0.tgz", + "integrity": "sha512-wVzXp2qDSCOpcBCT5WRWLmpJRIzv23valvcTwMHEobkjippNf+C3ys/+wf07poPkeNix0paTNemB2XrHr2TnGw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.43.0.tgz", + "integrity": "sha512-fYCTEyzf8d+7diCw8b+asvWDCLMjsCEA8alvtAutqJOJp/wL5hs1rWSqJ1vkjgW0L2NB4bsYJrpKkiIPRR9dvw==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.43.0.tgz", + "integrity": "sha512-SnGhLiE5rlK0ofq8kzuDkM0g7FN1s5VYY+YSMTibP7CqShxCQvqtNxTARS4xX4PFJfHjG0ZQYX9iGzI3FQh5Aw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@sec-ant/readable-stream": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/@sec-ant/readable-stream/-/readable-stream-0.4.1.tgz", @@ -2049,10 +2358,10 @@ "dev": true }, "node_modules/@types/chai": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.0.1.tgz", - "integrity": "sha512-5T8ajsg3M/FOncpLYW7sdOcD6yf4+722sze/tc4KQV0P8Z2rAr3SAuHCIkYmYpt8VbcQlnz8SxlOlPQYefe4cA==", - "dev": true, + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.2.tgz", + "integrity": "sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==", + "license": "MIT", "dependencies": { "@types/deep-eql": "*" } @@ -2098,8 +2407,13 @@ "node_modules/@types/deep-eql": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", - "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", - "dev": true + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==" + }, + "node_modules/@types/estree": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz", + "integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==", + "license": "MIT" }, "node_modules/@types/express": { "version": "4.17.21", @@ -2617,6 +2931,152 @@ "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", "dev": true }, + "node_modules/@vitest/expect": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.3.tgz", + "integrity": "sha512-W2RH2TPWVHA1o7UmaFKISPvdicFJH+mjykctJFoAkUw+SPTJTGjUNdKscFBrqM7IPnCVu6zihtKYa7TkZS1dkQ==", + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.3", + "@vitest/utils": "3.2.3", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/expect/node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/@vitest/expect/node_modules/chai": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz", + "integrity": "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==", + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@vitest/expect/node_modules/check-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", + "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==", + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/@vitest/expect/node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/@vitest/expect/node_modules/loupe": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.3.tgz", + "integrity": "sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug==", + "license": "MIT" + }, + "node_modules/@vitest/expect/node_modules/pathval": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.0.tgz", + "integrity": "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA==", + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.3.tgz", + "integrity": "sha512-yFglXGkr9hW/yEXngO+IKMhP0jxyFw2/qys/CK4fFUZnSltD+MU7dVYGrH8rvPcK/O6feXQA+EU33gjaBBbAng==", + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.3.tgz", + "integrity": "sha512-83HWYisT3IpMaU9LN+VN+/nLHVBCSIUKJzGxC5RWUOsK1h3USg7ojL+UXQR3b4o4UBIWCYdD2fxuzM7PQQ1u8w==", + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.3", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.3.tgz", + "integrity": "sha512-9gIVWx2+tysDqUmmM1L0hwadyumqssOL1r8KJipwLx5JVYyxvVRfxvMq7DaWbZZsCqZnu/dZedaZQh4iYTtneA==", + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.3", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.3.tgz", + "integrity": "sha512-JHu9Wl+7bf6FEejTCREy+DmgWe+rQKbK+y32C/k5f4TBIAlijhJbRBIRIOCEpVevgRsCQR2iHRUH2/qKVM/plw==", + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.3.tgz", + "integrity": "sha512-4zFBCU5Pf+4Z6v+rwnZ1HU1yzOKKvDkMXZrymE2PBlbjKJRlrOxbvpfPSvJTGRIwGoahaOGvp+kbCoxifhzJ1Q==", + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.3", + "loupe": "^3.1.3", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils/node_modules/loupe": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.3.tgz", + "integrity": "sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug==", + "license": "MIT" + }, "node_modules/@vscode/ripgrep": { "version": "1.15.9", "resolved": "https://registry.npmjs.org/@vscode/ripgrep/-/ripgrep-1.15.9.tgz", @@ -3691,6 +4151,15 @@ "node": ">=12" } }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/cacache": { "version": "16.1.3", "resolved": "https://registry.npmjs.org/cacache/-/cacache-16.1.3.tgz", @@ -5337,6 +5806,12 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "license": "MIT" + }, "node_modules/es5-ext": { "version": "0.10.64", "resolved": "https://registry.npmjs.org/es5-ext/-/es5-ext-0.10.64.tgz", @@ -5724,6 +6199,15 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -5802,6 +6286,15 @@ "node": ">=6" } }, + "node_modules/expect-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.2.1.tgz", + "integrity": "sha512-/kP8CAwxzLVEeFrMm4kMmy4CCDlpipyA7MYLVrdJIkV0fYF0UaigQHRsxHiuY/GEea+bh4KSv3TIlgr+2UL6bw==", + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/exponential-backoff": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.1.tgz", @@ -8090,6 +8583,15 @@ "url": "https://github.com/sponsors/wellwelwel" } }, + "node_modules/magic-string": { + "version": "0.30.17", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz", + "integrity": "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0" + } + }, "node_modules/make-dir": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", @@ -9225,9 +9727,9 @@ } }, "node_modules/nanoid": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz", - "integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==", + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", "funding": [ { "type": "github", @@ -10206,6 +10708,12 @@ "node": ">=8" } }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "license": "MIT" + }, "node_modules/pathval": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", @@ -10367,9 +10875,9 @@ } }, "node_modules/postcss": { - "version": "8.4.47", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.47.tgz", - "integrity": "sha512-56rxCq7G/XfB4EkXq9Egn5GCqugWvDFjafDOThIdMBsI15iqPqR5r15TfSr1YPYeEI19YeaXMCbY6u88Y76GLQ==", + "version": "8.5.5", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.5.tgz", + "integrity": "sha512-d/jtm+rdNT8tpXuHY5MMtcbJFBkhXE6593XVR9UoGCH8jSFGci7jGvMGH5RYd5PBJW+00NZQt6gf7CbagJCrhg==", "funding": [ { "type": "opencollective", @@ -10384,9 +10892,10 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "nanoid": "^3.3.7", - "picocolors": "^1.1.0", + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, "engines": { @@ -11715,6 +12224,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "license": "ISC" + }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", @@ -11964,6 +12479,12 @@ "node": "^12.13.0 || ^14.15.0 || >=16.0.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "license": "MIT" + }, "node_modules/statuses": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", @@ -11972,6 +12493,12 @@ "node": ">= 0.8" } }, + "node_modules/std-env": { + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.9.0.tgz", + "integrity": "sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==", + "license": "MIT" + }, "node_modules/stdin-discarder": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.1.0.tgz", @@ -12192,6 +12719,24 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/strip-literal": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.0.0.tgz", + "integrity": "sha512-TcccoMhJOM3OebGhSBEmp3UZ2SfDMZUEBdRA/9ynfLi8yYajyWX3JiXArcJt4Umh4vISpspkQIY8ZZoCqjbviA==", + "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/antfu" + } + }, + "node_modules/strip-literal/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "license": "MIT" + }, "node_modules/strtok3": { "version": "10.2.2", "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.2.2.tgz", @@ -12813,6 +13358,87 @@ "node": ">=0.12" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "license": "MIT" + }, + "node_modules/tinyglobby": { + "version": "0.2.14", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz", + "integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==", + "license": "MIT", + "dependencies": { + "fdir": "^6.4.4", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz", + "integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==", + "license": "MIT", + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", + "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/tinypool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.0.tgz", + "integrity": "sha512-7CotroY9a8DKsKprEy/a14aCCm8jYVmR7aFy4fpkZM8sdpNJbKkixuNjgM50yCmip2ezc8z4N7k3oe2+rfRJCQ==", + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.3.tgz", + "integrity": "sha512-t2T/WLB2WRgZ9EpE4jgPJ9w+i66UZfDc8wHh0xrwiRNN+UwH98GIJkTeZqX9rg0i0ptwzqW+uYeIF0T4F8LR7A==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/tmp": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz", @@ -13579,6 +14205,595 @@ } } }, + "node_modules/vite-node": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.3.tgz", + "integrity": "sha512-gc8aAifGuDIpZHrPjuHyP4dpQmYXqWw7D1GmDnWeNWP654UEXzVfQ5IHPSK5HaHkwB/+p1atpYpSdw/2kOv8iQ==", + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vite-node/node_modules/@esbuild/android-arm": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.5.tgz", + "integrity": "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/android-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.5.tgz", + "integrity": "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/android-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.5.tgz", + "integrity": "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz", + "integrity": "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/darwin-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.5.tgz", + "integrity": "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.5.tgz", + "integrity": "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.5.tgz", + "integrity": "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-arm": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.5.tgz", + "integrity": "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.5.tgz", + "integrity": "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-ia32": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.5.tgz", + "integrity": "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-loong64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.5.tgz", + "integrity": "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.5.tgz", + "integrity": "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.5.tgz", + "integrity": "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.5.tgz", + "integrity": "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-s390x": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.5.tgz", + "integrity": "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/linux-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz", + "integrity": "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.5.tgz", + "integrity": "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.5.tgz", + "integrity": "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/sunos-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.5.tgz", + "integrity": "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/win32-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.5.tgz", + "integrity": "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/win32-ia32": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.5.tgz", + "integrity": "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@esbuild/win32-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.5.tgz", + "integrity": "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vite-node/node_modules/@types/node": { + "version": "24.0.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.1.tgz", + "integrity": "sha512-MX4Zioh39chHlDJbKmEgydJDS3tspMP/lnQC67G3SWsTnb9NeYVWOjkxpOSy4oMfPs4StcWHwBrvUb4ybfnuaw==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "undici-types": "~7.8.0" + } + }, + "node_modules/vite-node/node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/vite-node/node_modules/esbuild": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.5.tgz", + "integrity": "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.5", + "@esbuild/android-arm": "0.25.5", + "@esbuild/android-arm64": "0.25.5", + "@esbuild/android-x64": "0.25.5", + "@esbuild/darwin-arm64": "0.25.5", + "@esbuild/darwin-x64": "0.25.5", + "@esbuild/freebsd-arm64": "0.25.5", + "@esbuild/freebsd-x64": "0.25.5", + "@esbuild/linux-arm": "0.25.5", + "@esbuild/linux-arm64": "0.25.5", + "@esbuild/linux-ia32": "0.25.5", + "@esbuild/linux-loong64": "0.25.5", + "@esbuild/linux-mips64el": "0.25.5", + "@esbuild/linux-ppc64": "0.25.5", + "@esbuild/linux-riscv64": "0.25.5", + "@esbuild/linux-s390x": "0.25.5", + "@esbuild/linux-x64": "0.25.5", + "@esbuild/netbsd-arm64": "0.25.5", + "@esbuild/netbsd-x64": "0.25.5", + "@esbuild/openbsd-arm64": "0.25.5", + "@esbuild/openbsd-x64": "0.25.5", + "@esbuild/sunos-x64": "0.25.5", + "@esbuild/win32-arm64": "0.25.5", + "@esbuild/win32-ia32": "0.25.5", + "@esbuild/win32-x64": "0.25.5" + } + }, + "node_modules/vite-node/node_modules/fdir": { + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz", + "integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==", + "license": "MIT", + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/vite-node/node_modules/picomatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", + "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vite-node/node_modules/rollup": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.43.0.tgz", + "integrity": "sha512-wdN2Kd3Twh8MAEOEJZsuxuLKCsBEo4PVNLK6tQWAn10VhsVewQLzcucMgLolRlhFybGxfclbPeEYBaP6RvUFGg==", + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.7" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.43.0", + "@rollup/rollup-android-arm64": "4.43.0", + "@rollup/rollup-darwin-arm64": "4.43.0", + "@rollup/rollup-darwin-x64": "4.43.0", + "@rollup/rollup-freebsd-arm64": "4.43.0", + "@rollup/rollup-freebsd-x64": "4.43.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.43.0", + "@rollup/rollup-linux-arm-musleabihf": "4.43.0", + "@rollup/rollup-linux-arm64-gnu": "4.43.0", + "@rollup/rollup-linux-arm64-musl": "4.43.0", + "@rollup/rollup-linux-loongarch64-gnu": "4.43.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.43.0", + "@rollup/rollup-linux-riscv64-gnu": "4.43.0", + "@rollup/rollup-linux-riscv64-musl": "4.43.0", + "@rollup/rollup-linux-s390x-gnu": "4.43.0", + "@rollup/rollup-linux-x64-gnu": "4.43.0", + "@rollup/rollup-linux-x64-musl": "4.43.0", + "@rollup/rollup-win32-arm64-msvc": "4.43.0", + "@rollup/rollup-win32-ia32-msvc": "4.43.0", + "@rollup/rollup-win32-x64-msvc": "4.43.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/vite-node/node_modules/undici-types": { + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz", + "integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/vite-node/node_modules/vite": { + "version": "6.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", + "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, "node_modules/vite/node_modules/@esbuild/android-arm": { "version": "0.18.20", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.18.20.tgz", @@ -13968,6 +15183,710 @@ "@esbuild/win32-x64": "0.18.20" } }, + "node_modules/vitest": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.3.tgz", + "integrity": "sha512-E6U2ZFXe3N/t4f5BwUaVCKRLHqUpk1CBWeMh78UT4VaTPH/2dyvH6ALl29JTovEPu9dVKr/K/J4PkXgrMbw4Ww==", + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.3", + "@vitest/mocker": "3.2.3", + "@vitest/pretty-format": "^3.2.3", + "@vitest/runner": "3.2.3", + "@vitest/snapshot": "3.2.3", + "@vitest/spy": "3.2.3", + "@vitest/utils": "3.2.3", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.0", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.3", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.3", + "@vitest/ui": "3.2.3", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/@esbuild/android-arm": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.5.tgz", + "integrity": "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/android-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.5.tgz", + "integrity": "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/android-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.5.tgz", + "integrity": "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/darwin-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.5.tgz", + "integrity": "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/darwin-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.5.tgz", + "integrity": "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.5.tgz", + "integrity": "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/freebsd-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.5.tgz", + "integrity": "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-arm": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.5.tgz", + "integrity": "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.5.tgz", + "integrity": "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-ia32": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.5.tgz", + "integrity": "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-loong64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.5.tgz", + "integrity": "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg==", + "cpu": [ + "loong64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-mips64el": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.5.tgz", + "integrity": "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg==", + "cpu": [ + "mips64el" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-ppc64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.5.tgz", + "integrity": "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ==", + "cpu": [ + "ppc64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-riscv64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.5.tgz", + "integrity": "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-s390x": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.5.tgz", + "integrity": "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ==", + "cpu": [ + "s390x" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/linux-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.5.tgz", + "integrity": "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/netbsd-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.5.tgz", + "integrity": "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/openbsd-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.5.tgz", + "integrity": "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/sunos-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.5.tgz", + "integrity": "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/win32-arm64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.5.tgz", + "integrity": "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/win32-ia32": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.5.tgz", + "integrity": "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@esbuild/win32-x64": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.5.tgz", + "integrity": "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/vitest/node_modules/@vitest/mocker": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.3.tgz", + "integrity": "sha512-cP6fIun+Zx8he4rbWvi+Oya6goKQDZK+Yq4hhlggwQBbrlOQ4qtZ+G4nxB6ZnzI9lyIb+JnvyiJnPC2AGbKSPA==", + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.3", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/vitest/node_modules/chai": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.2.0.tgz", + "integrity": "sha512-mCuXncKXk5iCLhfhwTc0izo0gtEmpz5CtG2y8GiOINBlMVS6v8TMRc5TaLWKS6692m9+dVVfzgeVxR5UxWHTYw==", + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/vitest/node_modules/check-error": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.1.tgz", + "integrity": "sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==", + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, + "node_modules/vitest/node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/vitest/node_modules/esbuild": { + "version": "0.25.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.5.tgz", + "integrity": "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ==", + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.5", + "@esbuild/android-arm": "0.25.5", + "@esbuild/android-arm64": "0.25.5", + "@esbuild/android-x64": "0.25.5", + "@esbuild/darwin-arm64": "0.25.5", + "@esbuild/darwin-x64": "0.25.5", + "@esbuild/freebsd-arm64": "0.25.5", + "@esbuild/freebsd-x64": "0.25.5", + "@esbuild/linux-arm": "0.25.5", + "@esbuild/linux-arm64": "0.25.5", + "@esbuild/linux-ia32": "0.25.5", + "@esbuild/linux-loong64": "0.25.5", + "@esbuild/linux-mips64el": "0.25.5", + "@esbuild/linux-ppc64": "0.25.5", + "@esbuild/linux-riscv64": "0.25.5", + "@esbuild/linux-s390x": "0.25.5", + "@esbuild/linux-x64": "0.25.5", + "@esbuild/netbsd-arm64": "0.25.5", + "@esbuild/netbsd-x64": "0.25.5", + "@esbuild/openbsd-arm64": "0.25.5", + "@esbuild/openbsd-x64": "0.25.5", + "@esbuild/sunos-x64": "0.25.5", + "@esbuild/win32-arm64": "0.25.5", + "@esbuild/win32-ia32": "0.25.5", + "@esbuild/win32-x64": "0.25.5" + } + }, + "node_modules/vitest/node_modules/fdir": { + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.4.6.tgz", + "integrity": "sha512-hiFoqpyZcfNm1yc4u8oWCf9A2c4D3QjCrks3zmoVKVxpQRzmPNar1hUJcBG2RQHvEVGDN+Jm81ZheVLAQMK6+w==", + "license": "MIT", + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/loupe": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.3.tgz", + "integrity": "sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug==", + "license": "MIT" + }, + "node_modules/vitest/node_modules/pathval": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.0.tgz", + "integrity": "sha512-vE7JKRyES09KiunauX7nd2Q9/L7lhok4smP9RZTDeD4MVs72Dp2qNFVz39Nz5a0FVEW0BJR6C0DYrq6unoziZA==", + "license": "MIT", + "engines": { + "node": ">= 14.16" + } + }, + "node_modules/vitest/node_modules/picomatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz", + "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/vitest/node_modules/rollup": { + "version": "4.43.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.43.0.tgz", + "integrity": "sha512-wdN2Kd3Twh8MAEOEJZsuxuLKCsBEo4PVNLK6tQWAn10VhsVewQLzcucMgLolRlhFybGxfclbPeEYBaP6RvUFGg==", + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.7" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.43.0", + "@rollup/rollup-android-arm64": "4.43.0", + "@rollup/rollup-darwin-arm64": "4.43.0", + "@rollup/rollup-darwin-x64": "4.43.0", + "@rollup/rollup-freebsd-arm64": "4.43.0", + "@rollup/rollup-freebsd-x64": "4.43.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.43.0", + "@rollup/rollup-linux-arm-musleabihf": "4.43.0", + "@rollup/rollup-linux-arm64-gnu": "4.43.0", + "@rollup/rollup-linux-arm64-musl": "4.43.0", + "@rollup/rollup-linux-loongarch64-gnu": "4.43.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.43.0", + "@rollup/rollup-linux-riscv64-gnu": "4.43.0", + "@rollup/rollup-linux-riscv64-musl": "4.43.0", + "@rollup/rollup-linux-s390x-gnu": "4.43.0", + "@rollup/rollup-linux-x64-gnu": "4.43.0", + "@rollup/rollup-linux-x64-musl": "4.43.0", + "@rollup/rollup-win32-arm64-msvc": "4.43.0", + "@rollup/rollup-win32-ia32-msvc": "4.43.0", + "@rollup/rollup-win32-x64-msvc": "4.43.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/vitest/node_modules/vite": { + "version": "6.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", + "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, "node_modules/vscode-extension-tester": { "version": "8.14.1", "resolved": "https://registry.npmjs.org/vscode-extension-tester/-/vscode-extension-tester-8.14.1.tgz", @@ -14717,6 +16636,22 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wide-align": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index b151000bf..22c040f40 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.47", + "version": "1.1.50", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -178,7 +178,7 @@ { "command": "continue.focusEdit", "category": "Continue", - "title": "Generate Code", + "title": "Edit Highlighted Code", "group": "Continue" }, { @@ -225,6 +225,11 @@ "title": "Toggle Autocomplete Enabled", "group": "Continue" }, + { + "command": "continue.forceAutocomplete", + "title": "Continue: Force Autocomplete", + "category": "Continue" + }, { "command": "continue.selectFilesAsContext", "category": "Continue", @@ -411,6 +416,12 @@ "key": "ctrl+k ctrl+a", "when": "!terminalFocus" }, + { + "command": "continue.forceAutocomplete", + "key": "ctrl+alt+space", + "mac": "cmd+alt+space", + "when": "editorTextFocus && !editorHasSelection && !editorReadOnly && !inSnippetMode" + }, { "command": "continue.applyCodeFromChat", "mac": "alt+a", @@ -463,6 +474,11 @@ "group": "Continue", "when": "editorHasSelection" }, + { + "command": "continue.focusEdit", + "group": "Continue", + "when": "editorHasSelection && !editorReadonly" + }, { "command": "continue.writeCommentsForCode", "group": "Continue", @@ -608,6 +624,7 @@ "lint:fix": "eslint . --ext ts --fix", "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", + "vitest": "vitest run", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "write-build-timestamp": "node scripts/write-build-timestamp.js", "prepackage": "node scripts/prepackage.js", @@ -716,8 +733,14 @@ "uuid": "^9.0.1", "uuidv4": "^6.2.13", "vectordb": "^0.4.20", + "vitest": "^3.1.4", "vscode-languageclient": "^8.0.2", "ws": "^8.13.0", "yarn": "^1.22.21" + }, + "overrides": { + "vitest": { + "@types/node": "^16.18.119" + } } } diff --git a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts index 585abc287..ed8ad1517 100644 --- a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts @@ -2,7 +2,7 @@ import { ConfigHandler } from "core/config/ConfigHandler"; import * as vscode from "vscode"; import { getTheme } from "./util/getTheme"; -import { getExtensionVersion } from "./util/util"; +import { getExtensionVersion, getvsCodeUriScheme } from "./util/util"; import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; @@ -161,6 +161,7 @@ export class ContinueGUIWebviewViewProvider + diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index dcc17d179..a01ecd515 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -433,8 +433,10 @@ class VsCodeIde implements IDE { }); } - async getFileResults(pattern: string): Promise { - const MAX_FILE_RESULTS = 200; + async getFileResults( + pattern: string, + maxResults?: number, + ): Promise { if (vscode.env.remoteName) { // TODO better tests for this remote search implementation // throw new Error("Ripgrep not supported, this workspace is remote"); @@ -501,7 +503,7 @@ class VsCodeIde implements IDE { const results = await vscode.workspace.findFiles( pattern, ignoreGlobs.size ? `{${ignoreGlobsArray.join(",")}}` : null, - MAX_FILE_RESULTS, + maxResults, ); return results.map((result) => vscode.workspace.asRelativePath(result)); } else { @@ -515,16 +517,24 @@ class VsCodeIde implements IDE { ".continueignore", "--ignore-file", ".gitignore", + ...(maxResults ? ["--max-count", String(maxResults)] : []), ]); results.push(dirResults); } - return results.join("\n").split("\n").slice(0, MAX_FILE_RESULTS); + const allResults = results.join("\n").split("\n"); + if (maxResults) { + // In the case of multiple workspaces, maxResults will be applied to each workspace + // And then the combined results will also be truncated + return allResults.slice(0, maxResults); + } else { + return allResults; + } } } - async getSearchResults(query: string): Promise { + async getSearchResults(query: string, maxResults?: number): Promise { if (vscode.env.remoteName) { throw new Error("Ripgrep not supported, this workspace is remote"); } @@ -539,6 +549,7 @@ class VsCodeIde implements IDE { "-C", "2", // Show 2 lines of context "--heading", // Only show filepath once per result + ...(maxResults ? ["-m", maxResults.toString()] : []), "-e", query, // Pattern to search for ".", // Directory to search in @@ -547,7 +558,20 @@ class VsCodeIde implements IDE { results.push(dirResults); } - return results.join("\n"); + const allResults = results.join("\n"); + if (maxResults) { + // In case of multiple workspaces, do max results per workspace and then truncate to maxResults + // Will prioritize first workspace results, fine for now + // Results are separated by either ./ or -- + const matches = Array.from(allResults.matchAll(/(\n--|\n\.\/)/g)); + if (matches.length > maxResults) { + return allResults.substring(0, matches[maxResults].index); + } else { + return allResults; + } + } else { + return allResults; + } } async getProblems(fileUri?: string | undefined): Promise { diff --git a/extensions/vscode/src/apply/ApplyManager.ts b/extensions/vscode/src/apply/ApplyManager.ts index df5791335..fb446e174 100644 --- a/extensions/vscode/src/apply/ApplyManager.ts +++ b/extensions/vscode/src/apply/ApplyManager.ts @@ -3,6 +3,7 @@ import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; import { getUriPathBasename } from "core/util/uri"; import * as vscode from "vscode"; +import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { VerticalDiffManager } from "../diff/vertical/manager"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -116,11 +117,16 @@ export class ApplyManager { return; } + const fileUri = editor.document.uri.toString(); + const abortManager = ApplyAbortManager.getInstance(); + const abortController = abortManager.get(fileUri); + const { isInstantApply, diffLinesGenerator } = await applyCodeBlock( editor.document.getText(), text, - getUriPathBasename(editor.document.uri.toString()), + getUriPathBasename(fileUri), llm, + abortController, ); if (isInstantApply) { diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index c15897883..963dcedeb 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -189,6 +189,10 @@ export class ContinueCompletionProvider // Handle commit message input box let manuallyPassPrefix: string | undefined = undefined; + // handle manual autocompletion trigger + const wasManuallyTriggered = + context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; + const input: AutocompleteInput = { pos, manuallyPassFileContents, @@ -208,6 +212,7 @@ export class ContinueCompletionProvider await this.completionProvider.provideInlineCompletionItems( input, signal, + wasManuallyTriggered, ); if (!outcome || !outcome.completion) { diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 3aadfadb9..82d045a01 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -28,6 +28,7 @@ import { } from "./autocomplete/statusBar"; import { ContinueConsoleWebviewViewProvider } from "./ContinueConsoleWebviewViewProvider"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; +import { processDiff } from "./diff/processDiff"; import { VerticalDiffManager } from "./diff/vertical/manager"; import EditDecorationManager from "./quickEdit/EditDecorationManager"; import { QuickEdit, QuickEditShowParams } from "./quickEdit/QuickEditQuickPick"; @@ -86,56 +87,6 @@ function hideGUI() { } } -async function processDiff( - action: "accept" | "reject", - sidebar: ContinueGUIWebviewViewProvider, - ide: VsCodeIde, - core: Core, - verticalDiffManager: VerticalDiffManager, - newFileUri?: string, - streamId?: string, - toolCallId?: string, -) { - captureCommandTelemetry(`${action}Diff`); - - const currentFile = await ide.getCurrentFile(); - - let newOrCurrentUri = newFileUri; - if (!newOrCurrentUri) { - newOrCurrentUri = currentFile?.path; - } - if (!newOrCurrentUri) { - console.warn( - `No file provided or current file open while attempting to resolve diff`, - ); - return; - } - - await ide.openFile(newOrCurrentUri); - - // Clear vertical diffs depending on action - verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); - if (action === "reject") { - core.invoke("cancelApply", undefined); - } - - if (streamId) { - const fileContent = await ide.readFile(newOrCurrentUri); - - await sidebar.webviewProtocol.request("updateApplyState", { - fileContent, - filepath: newOrCurrentUri, - streamId, - status: "closed", - numDiffs: 0, - toolCallId, - }); - } - - // Save the file - await ide.saveFile(newOrCurrentUri); -} - function waitForSidebarReady( sidebar: ContinueGUIWebviewViewProvider, timeout: number, @@ -226,8 +177,9 @@ const getCommandsMap: ( } return { - "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => - processDiff( + "continue.acceptDiff": async (newFileUri?: string, streamId?: string) => { + captureCommandTelemetry("acceptDiff"); + void processDiff( "accept", sidebar, ide, @@ -235,10 +187,12 @@ const getCommandsMap: ( verticalDiffManager, newFileUri, streamId, - ), + ); + }, - "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => - processDiff( + "continue.rejectDiff": async (newFileUri?: string, streamId?: string) => { + captureCommandTelemetry("rejectDiff"); + void processDiff( "reject", sidebar, ide, @@ -246,7 +200,8 @@ const getCommandsMap: ( verticalDiffManager, newFileUri, streamId, - ), + ); + }, "continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => { captureCommandTelemetry("acceptVerticalDiffBlock"); verticalDiffManager.acceptRejectVerticalDiffBlock(true, fileUri, index); @@ -624,6 +579,18 @@ const getCommandsMap: ( } } }, + "continue.forceAutocomplete": async () => { + captureCommandTelemetry("forceAutocomplete"); + + // 1. Explicitly hide any existing suggestion. This clears VS Code's cache for the current position. + await vscode.commands.executeCommand("editor.action.inlineSuggest.hide"); + + // 2. Now trigger a new one. VS Code has no cached suggestion, so it's forced to call our provider. + await vscode.commands.executeCommand( + "editor.action.inlineSuggest.trigger", + ); + }, + "continue.openTabAutocompleteConfigMenu": async () => { captureCommandTelemetry("openTabAutocompleteConfigMenu"); diff --git a/extensions/vscode/src/diff/processDiff.ts b/extensions/vscode/src/diff/processDiff.ts new file mode 100644 index 000000000..b78ea966c --- /dev/null +++ b/extensions/vscode/src/diff/processDiff.ts @@ -0,0 +1,52 @@ +import { Core } from "core/core"; +import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider"; +import { VsCodeIde } from "../VsCodeIde"; +import { VerticalDiffManager } from "./vertical/manager"; + +export async function processDiff( + action: "accept" | "reject", + sidebar: ContinueGUIWebviewViewProvider, + ide: VsCodeIde, + core: Core, + verticalDiffManager: VerticalDiffManager, + newFileUri?: string, + streamId?: string, + toolCallId?: string, +) { + let newOrCurrentUri = newFileUri; + if (!newOrCurrentUri) { + const currentFile = await ide.getCurrentFile(); + newOrCurrentUri = currentFile?.path; + } + if (!newOrCurrentUri) { + console.warn( + `No file provided or current file open while attempting to resolve diff`, + ); + return; + } + + await ide.openFile(newOrCurrentUri); + + // Clear vertical diffs depending on action + verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept"); + if (action === "reject") { + // this is so that IDE reject diff command can also cancel apply + core.invoke("cancelApply", undefined); + } + + if (streamId) { + const fileContent = await ide.readFile(newOrCurrentUri); + + await sidebar.webviewProtocol.request("updateApplyState", { + fileContent, + filepath: newOrCurrentUri, + streamId, + status: "closed", + numDiffs: 0, + toolCallId, + }); + } + + // Save the file + await ide.saveFile(newOrCurrentUri); +} diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 104db10c6..aca644c3a 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -10,6 +10,7 @@ import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { handleLLMError } from "../../util/errorHandling"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { ApplyAbortManager } from "core/edit/applyAbortManager"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -437,6 +438,9 @@ export class VerticalDiffManager { this.editDecorationManager.clear(); + const abortManager = ApplyAbortManager.getInstance(); + const abortController = abortManager.get(fileUri); + try { const streamedLines: string[] = []; @@ -451,7 +455,7 @@ export class VerticalDiffManager { language: getMarkdownLanguageTagForFile(fileUri), onlyOneInsertion: !!onlyOneInsertion, overridePrompt, - abortControllerId: fileUri, + abortController, }); for await (const line of stream) { @@ -467,6 +471,10 @@ export class VerticalDiffManager { // enable a listener for user edits to file while diff is open this.enableDocumentChangeListener(); + if (abortController.signal.aborted) { + vscode.commands.executeCommand("continue.rejectDiff"); + } + return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index b0c0a4d7b..5aff7056e 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -321,10 +321,10 @@ export class VsCodeMessenger { await ide.runCommand(msg.data.command); }); this.onWebviewOrCore("getSearchResults", async (msg) => { - return ide.getSearchResults(msg.data.query); + return ide.getSearchResults(msg.data.query, msg.data.maxResults); }); this.onWebviewOrCore("getFileResults", async (msg) => { - return ide.getFileResults(msg.data.pattern); + return ide.getFileResults(msg.data.pattern, msg.data.maxResults); }); this.onWebviewOrCore("subprocess", async (msg) => { return ide.subprocess(msg.data.command, msg.data.cwd); diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 0d4827087..b59abe665 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -76,8 +76,10 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { string, { promise: Promise; cancel: EventEmitter } >(); + private _refreshInterval: NodeJS.Timeout | null = null; private static EXPIRATION_TIME_MS = 1000 * 60 * 15; // 15 minutes + private static REFRESH_INTERVAL_MS = 1000 * 60 * 10; // 10 minutes private secretStorage: SecretStorage; @@ -96,6 +98,14 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { ); this.secretStorage = new SecretStorage(context); + + // Immediately refresh any existing sessions + this.refreshSessions(); + + // Set up a regular interval to refresh tokens + this._refreshInterval = setInterval(() => { + this.refreshSessions(); + }, WorkOsAuthProvider.REFRESH_INTERVAL_MS); } private decodeJwt(jwt: string): Record | null { @@ -110,16 +120,6 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { } } - private getExpirationTimeMs(jwt: string): number { - const decodedToken = this.decodeJwt(jwt); - if (!decodedToken) { - return WorkOsAuthProvider.EXPIRATION_TIME_MS; - } - return decodedToken.exp && decodedToken.iat - ? (decodedToken.exp - decodedToken.iat) * 1000 - : WorkOsAuthProvider.EXPIRATION_TIME_MS; - } - private jwtIsExpiredOrInvalid(jwt: string): boolean { const decodedToken = this.decodeJwt(jwt); if (!decodedToken) { @@ -128,13 +128,14 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { return decodedToken.exp * 1000 < Date.now(); } - private async debugAccessTokenValidity(jwt: string, refreshToken: string) { - const expiredOrInvalid = this.jwtIsExpiredOrInvalid(jwt); - if (expiredOrInvalid) { - console.debug("Invalid JWT"); - } else { - console.debug("Valid JWT"); + private getExpirationTimeMs(jwt: string): number { + const decodedToken = this.decodeJwt(jwt); + if (!decodedToken) { + return WorkOsAuthProvider.EXPIRATION_TIME_MS; } + return decodedToken.exp && decodedToken.iat + ? (decodedToken.exp - decodedToken.iat) * 1000 + : WorkOsAuthProvider.EXPIRATION_TIME_MS; } private async storeSessions(value: ContinueAuthenticationSession[]) { @@ -197,7 +198,12 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { const finalSessions = []; for (const session of sessions) { try { - const newSession = await this._refreshSession(session.refreshToken); + // For expired tokens, don't use retries - if refresh fails, we drop the session + const refreshMethod = this.jwtIsExpiredOrInvalid(session.accessToken) + ? this._refreshSession.bind(this) // Direct refresh for expired tokens + : this._refreshSessionWithRetry.bind(this); // Retry for valid tokens + + const newSession = await refreshMethod(session.refreshToken); finalSessions.push({ ...session, accessToken: newSession.accessToken, @@ -205,36 +211,65 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { expiresInMs: newSession.expiresInMs, }); } catch (e: any) { - // If the refresh token doesn't work, we just drop the session + // If refresh fails (after retries for valid tokens), drop the session console.debug(`Error refreshing session token: ${e.message}`); - await this.debugAccessTokenValidity( - session.accessToken, - session.refreshToken, - ); this._sessionChangeEmitter.fire({ added: [], removed: [session], changed: [], }); - // We don't need to refresh the sessions again, since we'll get a new one when we need it - // setTimeout(() => this._refreshSessions(), 60 * 1000); - // return; } } + await this.storeSessions(finalSessions); this._sessionChangeEmitter.fire({ added: [], removed: [], changed: finalSessions, }); + } - if (finalSessions[0]?.expiresInMs) { - setTimeout( - async () => { - await this._refreshSessions(); - }, - (finalSessions[0].expiresInMs * 2) / 3, - ); + private async _refreshSessionWithRetry( + refreshToken: string, + attempt = 1, + maxAttempts = 3, + baseDelay = 1000, + ): Promise<{ + accessToken: string; + refreshToken: string; + expiresInMs: number; + }> { + try { + return await this._refreshSession(refreshToken); + } catch (error: any) { + // Don't retry for auth errors (401 Unauthorized) or if we've reached max attempts + if ( + error.message?.includes("401") || + error.message?.includes("Invalid refresh token") || + error.message?.includes("Unauthorized") || + attempt >= maxAttempts + ) { + throw error; + } + + // For network errors or transient server issues, retry with backoff + // Calculate exponential backoff delay with jitter + const delay = + baseDelay * Math.pow(2, attempt - 1) * (0.5 + Math.random() * 0.5); + + // Schedule retry after delay + return new Promise((resolve, reject) => { + setTimeout(() => { + this._refreshSessionWithRetry( + refreshToken, + attempt + 1, + maxAttempts, + baseDelay, + ) + .then(resolve) + .catch(reject); + }, delay); + }); } } @@ -323,11 +358,6 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { changed: [], }); - setTimeout( - () => this._refreshSessions(), - (this.getExpirationTimeMs(session.accessToken) * 2) / 3, - ); - return session; } catch (e) { window.showErrorMessage(`Sign in failed: ${e}`); @@ -360,6 +390,10 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { * Dispose the registered services */ public async dispose() { + if (this._refreshInterval) { + clearInterval(this._refreshInterval); + this._refreshInterval = null; + } this._disposable.dispose(); } diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts new file mode 100644 index 000000000..55cac92df --- /dev/null +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.vitest.ts @@ -0,0 +1,805 @@ +// @ts-nocheck +import fetch from "node-fetch"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { EventEmitter } from "vscode"; + +// Don't import WorkOsAuthProvider directly here + +// Mock the modules we need +vi.mock("vscode", () => ({ + authentication: { + registerAuthenticationProvider: vi.fn(), + }, + window: { + registerUriHandler: vi.fn(), + }, + EventEmitter: vi.fn(() => ({ + event: { dispose: vi.fn() }, + fire: vi.fn(), + })), + Disposable: { + from: vi.fn(() => ({ dispose: vi.fn() })), + }, + env: { + uriScheme: "vscode", + }, +})); + +// Properly mock node-fetch +vi.mock("node-fetch", () => { + return { + __esModule: true, + default: vi.fn(), + }; +}); + +vi.mock("core/control-plane/env", () => ({ + getControlPlaneEnvSync: vi.fn(() => ({ + AUTH_TYPE: "workos", + APP_URL: "https://continue.dev", + CONTROL_PLANE_URL: "https://api.continue.dev", + WORKOS_CLIENT_ID: "client_123", + })), +})); + +vi.mock("crypto", () => ({ + createHash: vi.fn(() => ({ + update: vi.fn(() => ({ + digest: vi.fn(() => Buffer.from("test-hash")), + })), + })), +})); + +// Create a simple SecretStorage mock that we can control +const mockSecretStorageGet = vi.fn(); +const mockSecretStorageStore = vi.fn(); + +// Mock SecretStorage class +vi.mock("./SecretStorage", () => { + return { + SecretStorage: vi.fn().mockImplementation(() => ({ + store: mockSecretStorageStore, + get: mockSecretStorageGet, + })), + }; +}); + +// Helper to create valid and expired JWTs +function createJwt({ expired }: { expired: boolean }): string { + const now = Math.floor(Date.now() / 1000); + const header = { alg: "HS256", typ: "JWT" }; + const payload = { + sub: "user123", + iat: now, + exp: expired ? now - 3600 : now + 3600, // Expired 1 hour ago or valid for 1 hour + }; + + const base64Header = Buffer.from(JSON.stringify(header)) + .toString("base64") + .replace(/=/g, ""); + const base64Payload = Buffer.from(JSON.stringify(payload)) + .toString("base64") + .replace(/=/g, ""); + const signature = "dummysignature"; + + return `${base64Header}.${base64Payload}.${signature}`; +} + +beforeEach(() => { + // Set up fake timers before each test + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.clearAllMocks(); + vi.clearAllTimers(); + vi.useRealTimers(); // Restore real timers after each test +}); + +it("should refresh tokens on initialization when sessions exist", async () => { + // Mock setInterval to prevent the refresh interval + const originalSetInterval = global.setInterval; + global.setInterval = vi.fn().mockReturnValue(123 as any); + + // Setup existing sessions with a valid token + const validToken = createJwt({ expired: false }); + const mockSession = { + id: "test-id", + accessToken: validToken, + refreshToken: "refresh-token", + expiresInMs: 3600000, // 1 hour + account: { label: "Test User", id: "user@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Setup successful token refresh + fetchMock.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + accessToken: createJwt({ expired: false }), + refreshToken: "new-refresh-token", + }), + text: async () => "", + }); + + // Create a mock UriHandler + const mockUriHandler = { + event: new EventEmitter(), + handleCallback: vi.fn(), + }; + + // Create a mock ExtensionContext + const mockContext = { + secrets: { + store: vi.fn(), + get: vi.fn(), + }, + subscriptions: [], + }; + + // Set up our SecretStorage mock to return the session + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); + + // Import WorkOsAuthProvider after setting up all mocks + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + + // Create provider instance - this will automatically call refreshSessions + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for all promises to resolve, including any nested promise chains + await new Promise(process.nextTick); + + // Verify that the token refresh endpoint was called + expect(fetchMock).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "POST", + body: expect.stringContaining("refresh-token"), + }), + ); + + // Restore setInterval + global.setInterval = originalSetInterval; + + // Clean up + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should not remove sessions during transient network errors", async () => { + // Setup existing sessions with a valid token + const validToken = createJwt({ expired: false }); + const mockSession = { + id: "test-id", + accessToken: validToken, + refreshToken: "refresh-token", + expiresInMs: 300000, // 5 minutes + account: { label: "Test User", id: "user@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // First refresh attempt fails with network error + fetchMock.mockRejectedValueOnce(new Error("Network error")); + + // Second refresh attempt should succeed + fetchMock.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + accessToken: createJwt({ expired: false }), + refreshToken: "new-refresh-token", + }), + text: async () => "", + }); + + // Create a mock UriHandler + const mockUriHandler = { + event: new EventEmitter(), + handleCallback: vi.fn(), + }; + + // Create a mock ExtensionContext + const mockContext = { + secrets: { + store: vi.fn(), + get: vi.fn(), + }, + subscriptions: [], + }; + + // Set up our SecretStorage mock to return the session + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); + + // Import WorkOsAuthProvider after setting up all mocks + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + + // Allow setInterval to work normally with fake timers + // We're not mocking it anymore, instead we'll control when it fires + + // Create provider instance - this will automatically call refreshSessions with the network error + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Run microtasks to process promises from the initial refresh call + await Promise.resolve(); + + // Check that sessions were not cleared after network error + expect(mockSecretStorageStore).not.toHaveBeenCalledWith( + expect.anything(), + expect.stringMatching(/\[\]/), + ); + + // Reset the fetch mock call count to verify the next call + fetchMock.mockClear(); + + // Advance timers to the next refresh interval to simulate the timer firing + vi.advanceTimersByTime(WorkOsAuthProvider.REFRESH_INTERVAL_MS); + + // Run microtasks to process promises from the interval-triggered refresh + await Promise.resolve(); + + // Verify the second attempt was made via the interval + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "POST", + headers: expect.objectContaining({ + "Content-Type": "application/json", + }), + body: expect.stringContaining("refresh-token"), + }), + ); + + // Clean up + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should refresh tokens at regular intervals rather than based on expiration", async () => { + // Setup existing sessions with a valid token + const validToken = createJwt({ expired: false }); + const mockSession = { + id: "test-id", + accessToken: validToken, + refreshToken: "refresh-token", + expiresInMs: 3600000, // 1 hour + account: { label: "Test User", id: "user@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Setup successful token refresh responses for multiple calls + fetchMock.mockResolvedValue({ + ok: true, + json: async () => ({ + accessToken: createJwt({ expired: false }), + refreshToken: "new-refresh-token", + }), + text: async () => "", + }); + + // Create a mock UriHandler + const mockUriHandler = { + event: new EventEmitter(), + handleCallback: vi.fn(), + }; + + // Create a mock ExtensionContext + const mockContext = { + secrets: { + store: vi.fn(), + get: vi.fn(), + }, + subscriptions: [], + }; + + // Set up our SecretStorage mock to return the session + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); + + // Import WorkOsAuthProvider after setting up all mocks + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + + // Capture the original setInterval to restore it later + const originalSetInterval = global.setInterval; + + // Create our own implementation of setInterval that we can control better + let intervalCallback: Function; + global.setInterval = vi.fn((callback, ms) => { + intervalCallback = callback; + return 123 as any; // Return a dummy interval ID + }); + + // Create provider instance - this will automatically call refreshSessions + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for all promises to resolve, including any nested promise chains + await new Promise(process.nextTick); + + // First refresh should happen immediately on initialization + expect(fetchMock).toHaveBeenCalledTimes(1); + fetchMock.mockClear(); + + // Verify that setInterval was called to set up regular refreshes + expect(global.setInterval).toHaveBeenCalled(); + + // Get the interval time from the call to setInterval + const intervalTime = (global.setInterval as any).mock.calls[0][1]; + + // Should be a reasonable interval (less than the expiration time) + expect(intervalTime).toBeLessThan(mockSession.expiresInMs); + + // Now manually trigger the interval callback - First interval + intervalCallback(); + + // Wait for all promises to resolve + await new Promise(process.nextTick); + + // Verify that refresh was called again when the interval callback fired + expect(fetchMock).toHaveBeenCalledTimes(1); + + // Check that we're making refresh calls to the right endpoint with the right data + expect(fetchMock).toHaveBeenCalledWith( + expect.objectContaining({ pathname: "/auth/refresh" }), + expect.objectContaining({ + method: "POST", + headers: expect.objectContaining({ + "Content-Type": "application/json", + }), + body: expect.stringContaining("refresh-token"), + }), + ); + + // Clear mock calls for the second interval test + fetchMock.mockClear(); + + // Trigger the callback again - Second interval + intervalCallback(); + + // Wait for all promises to resolve + await new Promise(process.nextTick); + + // Verify the refresh was called a second time + expect(fetchMock).toHaveBeenCalledTimes(1); + + // Verify the second call has the same correct parameters + expect(fetchMock).toHaveBeenCalledWith( + expect.objectContaining({ pathname: "/auth/refresh" }), + expect.objectContaining({ + method: "POST", + headers: expect.objectContaining({ + "Content-Type": "application/json", + }), + body: expect.stringContaining("refresh-token"), + }), + ); + + // Restore the original setInterval + global.setInterval = originalSetInterval; + + // Clean up + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should remove session if token refresh fails with authentication error", async () => { + // Setup existing sessions with a valid token + const validToken = createJwt({ expired: false }); + const mockSession = { + id: "test-id", + accessToken: validToken, + refreshToken: "invalid-refresh-token", + expiresInMs: 300000, // 5 minutes + account: { label: "Test User", id: "user@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Setup refresh to fail with 401 unauthorized + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 401, + text: async () => "Invalid refresh token", + }); + + // Create a mock UriHandler + const mockUriHandler = { + event: new EventEmitter(), + handleCallback: vi.fn(), + }; + + // Create a mock ExtensionContext + const mockContext = { + secrets: { + store: vi.fn(), + get: vi.fn(), + }, + subscriptions: [], + }; + + // Mock setInterval to prevent continuous refreshes + const originalSetInterval = global.setInterval; + global.setInterval = vi.fn().mockReturnValue(123 as any); + + // Set up our SecretStorage mock to return the session + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); + mockSecretStorageStore.mockClear(); + + // Import WorkOsAuthProvider after setting up all mocks + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + + // Create provider instance - this will automatically call refreshSessions + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for all promises to resolve, including any nested promise chains + await new Promise(process.nextTick); + + // Verify that the token refresh endpoint was called + expect(fetchMock).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "POST", + body: expect.stringContaining("invalid-refresh-token"), + }), + ); + + // Verify sessions were removed due to auth error + expect(mockSecretStorageStore).toHaveBeenCalledWith( + "workos.sessions", // Use the hard-coded key that matches our mock + expect.stringMatching(/\[\]/), + ); + + // Restore setInterval + global.setInterval = originalSetInterval; + + // Clean up + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should remove session if token refresh returns Unauthorized error message", async () => { + // Setup existing sessions with a valid token + const validToken = createJwt({ expired: false }); + const mockSession = { + id: "test-id", + accessToken: validToken, + refreshToken: "invalid-refresh-token", + expiresInMs: 300000, // 5 minutes + account: { label: "Test User", id: "user@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Setup refresh to return an error containing "Unauthorized" in the message + // Status code doesn't matter here, what matters is the error message text + fetchMock.mockResolvedValueOnce({ + ok: false, + status: 403, // Could be any error code + text: async () => "Unauthorized", + }); + + // Create a mock UriHandler + const mockUriHandler = { + event: new EventEmitter(), + handleCallback: vi.fn(), + }; + + // Create a mock ExtensionContext + const mockContext = { + secrets: { + store: vi.fn(), + get: vi.fn(), + }, + subscriptions: [], + }; + + // Mock setInterval to prevent continuous refreshes + const originalSetInterval = global.setInterval; + global.setInterval = vi.fn().mockReturnValue(123 as any); + + // Set up our SecretStorage mock to return the session + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); + mockSecretStorageStore.mockClear(); + + // Import WorkOsAuthProvider after setting up all mocks + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + + // Create provider instance - this will automatically call refreshSessions + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for all promises to resolve, including any nested promise chains + await new Promise(process.nextTick); + + // Verify that the token refresh endpoint was called + expect(fetchMock).toHaveBeenCalledWith( + expect.any(URL), + expect.objectContaining({ + method: "POST", + body: expect.stringContaining("invalid-refresh-token"), + }), + ); + + // Verify sessions were removed due to Unauthorized error message + expect(mockSecretStorageStore).toHaveBeenCalledWith( + "workos.sessions", // Use the hard-coded key that matches our mock + expect.stringMatching(/\[\]/), + ); + + // Restore setInterval + global.setInterval = originalSetInterval; + + // Clean up + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should preserve valid tokens during network errors by retrying", async () => { + // Mock Date.now to return a fixed timestamp for token validation + const originalDateNow = Date.now; + const currentTimestamp = Date.now(); + Date.now = vi.fn(() => currentTimestamp); + + // Setup with a valid token + const validToken = createJwt({ expired: false }); + const validSession = { + id: "valid-id", + accessToken: validToken, + refreshToken: "valid-refresh-token", + expiresInMs: 3600000, + account: { label: "Valid User", id: "valid@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Create mock objects + const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() }; + const mockContext = { + secrets: { store: vi.fn(), get: vi.fn() }, + subscriptions: [], + }; + + // Mock setInterval and setTimeout + const originalSetInterval = global.setInterval; + global.setInterval = vi.fn().mockReturnValue(123 as any); + + const originalSetTimeout = global.setTimeout; + global.setTimeout = vi.fn((callback) => { + callback(); + return 123 as any; + }); + + // Network error followed by success + fetchMock.mockRejectedValueOnce(new Error("Network error")); + fetchMock.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + accessToken: createJwt({ expired: false }), + refreshToken: "new-refresh-token", + }), + text: async () => "", + }); + + // Setup storage + mockSecretStorageGet.mockResolvedValue(JSON.stringify([validSession])); + mockSecretStorageStore.mockClear(); + + // Import and create provider + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for promises to resolve + await new Promise(process.nextTick); + + // Check that a non-empty session array was stored (session was preserved) + const storeCall = mockSecretStorageStore.mock.calls[0]; + expect(storeCall[0]).toBe("workos.sessions"); + expect(JSON.parse(storeCall[1])).toHaveLength(1); // Should contain one session + + // Restore originals + global.setTimeout = originalSetTimeout; + global.setInterval = originalSetInterval; + Date.now = originalDateNow; + + // Clean up provider + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should remove expired tokens when refresh fails", async () => { + // Mock Date.now to return a time that makes tokens appear expired + const originalDateNow = Date.now; + const futureTime = Date.now() + 7200000; // 2 hours in the future + Date.now = vi.fn(() => futureTime); + + // Setup with an expired token + const expiredToken = createJwt({ expired: true }); + const expiredSession = { + id: "expired-id", + accessToken: expiredToken, + refreshToken: "expired-refresh-token", + expiresInMs: 3600000, + account: { label: "Expired User", id: "expired@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Create mock objects + const mockUriHandler = { event: new EventEmitter(), handleCallback: vi.fn() }; + const mockContext = { + secrets: { store: vi.fn(), get: vi.fn() }, + subscriptions: [], + }; + + // Mock setInterval + const originalSetInterval = global.setInterval; + global.setInterval = vi.fn().mockReturnValue(123 as any); + + // Refresh will fail with network error + fetchMock.mockRejectedValueOnce(new Error("Network error")); + + // Setup storage + mockSecretStorageGet.mockResolvedValue(JSON.stringify([expiredSession])); + mockSecretStorageStore.mockClear(); + + // Import and create provider + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for promises to resolve + await new Promise(process.nextTick); + + // Check that an empty session array was stored (session was removed) + const storeCall = mockSecretStorageStore.mock.calls[0]; + expect(storeCall[0]).toBe("workos.sessions"); + expect(JSON.parse(storeCall[1])).toHaveLength(0); // Should be empty + + // Restore originals + global.setInterval = originalSetInterval; + Date.now = originalDateNow; + + // Clean up provider + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); + +it("should implement exponential backoff for failed refresh attempts", async () => { + // Setup existing sessions with a valid token + const validToken = createJwt({ expired: false }); + const mockSession = { + id: "test-id", + accessToken: validToken, + refreshToken: "refresh-token", + expiresInMs: 300000, // 5 minutes + account: { label: "Test User", id: "user@example.com" }, + scopes: [], + loginNeeded: false, + }; + + // Setup fetch mock + const fetchMock = fetch as any; + fetchMock.mockClear(); + + // Setup repeated network errors followed by success + fetchMock.mockRejectedValueOnce(new Error("Network error 1")); + fetchMock.mockRejectedValueOnce(new Error("Network error 2")); + fetchMock.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + accessToken: createJwt({ expired: false }), + refreshToken: "new-refresh-token", + }), + text: async () => "", + }); + + // Create a mock UriHandler + const mockUriHandler = { + event: new EventEmitter(), + handleCallback: vi.fn(), + }; + + // Create a mock ExtensionContext + const mockContext = { + secrets: { + store: vi.fn(), + get: vi.fn(), + }, + subscriptions: [], + }; + + // Mock setInterval to prevent continuous refreshes + const originalSetInterval = global.setInterval; + global.setInterval = vi.fn().mockReturnValue(123 as any); + + // Track setTimeout calls + const setTimeoutSpy = vi.spyOn(global, "setTimeout"); + + // Set up our SecretStorage mock to return the session + mockSecretStorageGet.mockResolvedValue(JSON.stringify([mockSession])); + + // Import WorkOsAuthProvider after setting up all mocks + const { WorkOsAuthProvider } = await import("./WorkOsAuthProvider"); + + // Create provider instance - this will automatically call refreshSessions + const provider = new WorkOsAuthProvider(mockContext, mockUriHandler); + + // Wait for all promises to resolve for the initial refresh attempt + await new Promise(process.nextTick); + + // Verify the first fetch attempt was made + expect(fetchMock).toHaveBeenCalledTimes(1); + + // Trigger first retry + vi.advanceTimersByTime(1000); // Initial backoff + await new Promise(process.nextTick); + + // Verify the second fetch attempt was made + expect(fetchMock).toHaveBeenCalledTimes(2); + + // Trigger second retry + vi.advanceTimersByTime(2000); // Double the backoff + await new Promise(process.nextTick); + + // Verify the third fetch attempt was made + expect(fetchMock).toHaveBeenCalledTimes(3); + + // Verify setTimeout was called with increasing delays + expect(setTimeoutSpy).toHaveBeenCalledTimes(2); + + // Check that the backoff periods increased + const firstDelay = setTimeoutSpy.mock.calls[0][1]; + const secondDelay = setTimeoutSpy.mock.calls[1][1]; + + // Check that backoff increased + expect(secondDelay).toBeGreaterThan(firstDelay); + + // Restore setInterval + global.setInterval = originalSetInterval; + + // Clean up + if (provider._refreshInterval) { + clearInterval(provider._refreshInterval); + provider._refreshInterval = null; + } +}); diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 916d7b3bc..a7c125ff1 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -122,3 +122,7 @@ export function getExtensionVersion(): string { const extension = vscode.extensions.getExtension("continue.continue"); return extension?.packageJSON.version || "0.1.0"; } + +export function getvsCodeUriScheme(): string { + return vscode.env.uriScheme; +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 5778371a3..013e10d03 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -129,7 +129,7 @@ export class VsCodeWebviewProtocol .showInformationMessage(message, "Add API Key", "Use Local Model") .then((selection) => { if (selection === "Add API Key") { - this.request("addApiKey", undefined); + this.request("setupApiKey", undefined); } else if (selection === "Use Local Model") { this.request("setupLocalConfig", undefined); } diff --git a/extensions/vscode/vitest.config.ts b/extensions/vscode/vitest.config.ts new file mode 100644 index 000000000..7ce267ebb --- /dev/null +++ b/extensions/vscode/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["**/*.vitest.ts"], + environment: "node", + }, +}); diff --git a/gui/.eslintrc.json b/gui/.eslintrc.json index aebab49dd..afdd06ee9 100644 --- a/gui/.eslintrc.json +++ b/gui/.eslintrc.json @@ -1,7 +1,7 @@ { "root": true, "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint", "eslint-plugin-react"], + "plugins": ["@typescript-eslint", "eslint-plugin-react", "no-barrel-files"], "parserOptions": { "project": ["tsconfig.json", "tsconfig.node.json"] }, @@ -13,7 +13,8 @@ ], "rules": { "@typescript-eslint/naming-convention": "off", - "@typescript-eslint/no-floating-promises": "warn" + "@typescript-eslint/no-floating-promises": "warn", + "no-barrel-files/no-barrel-files": "error" }, "overrides": [ { diff --git a/gui/package-lock.json b/gui/package-lock.json index d6996309b..0619e22e5 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -25,10 +25,12 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", + "anser": "^2.3.2", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", + "escape-carriage": "^1.3.1", "lodash": "^4.17.21", "lowlight": "^3.3.0", "minisearch": "^7.0.2", @@ -88,6 +90,7 @@ "@vitest/ui": "^2.1.3", "autoprefixer": "^10.4.13", "eslint": "^8", + "eslint-plugin-no-barrel-files": "^1.2.1", "eslint-plugin-react": "^7.37.2", "jsdom": "^25.0.1", "postcss": "^8.4.21", @@ -212,7 +215,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.88", + "version": "1.0.94", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -3737,6 +3740,12 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/anser": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/anser/-/anser-2.3.2.tgz", + "integrity": "sha512-PMqBCBvrOVDRqLGooQb+z+t1Q0PiPyurUQeZRR5uHBOVZcW8B04KMmnT12USnhpNX2wCPagWzLVppQMUG3u0Dw==", + "license": "MIT" + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -5200,6 +5209,12 @@ "node": ">=6" } }, + "node_modules/escape-carriage": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/escape-carriage/-/escape-carriage-1.3.1.tgz", + "integrity": "sha512-GwBr6yViW3ttx1kb7/Oh+gKQ1/TrhYwxKqVmg5gS+BK+Qe2KrOa/Vh7w3HPBvgGf0LfcDGoY9I6NHKoA5Hozhw==", + "license": "MIT" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -5267,6 +5282,16 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/eslint-plugin-no-barrel-files": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-no-barrel-files/-/eslint-plugin-no-barrel-files-1.2.1.tgz", + "integrity": "sha512-WoZ48JXa99yptWwWWAKmuKNgvgA6tpSol6Cf0GzXs2Lg/JdBqe+CF58Bf8saEpYJRA+6+cTzP90nI7U7zoy5IQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@typescript-eslint/utils": "^8.13.0" + } + }, "node_modules/eslint-plugin-react": { "version": "7.37.2", "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.2.tgz", diff --git a/gui/package.json b/gui/package.json index de6da1959..eb4a5a4d0 100644 --- a/gui/package.json +++ b/gui/package.json @@ -34,10 +34,12 @@ "@tiptap/starter-kit": "^2.1.13", "@tiptap/suggestion": "^2.1.13", "@types/uuid": "^10.0.0", + "anser": "^2.3.2", "clsx": "^2.1.1", "core": "file:../core", "dompurify": "^3.0.6", "downshift": "^7.6.0", + "escape-carriage": "^1.3.1", "lodash": "^4.17.21", "lowlight": "^3.3.0", "minisearch": "^7.0.2", @@ -97,6 +99,7 @@ "@vitest/ui": "^2.1.3", "autoprefixer": "^10.4.13", "eslint": "^8", + "eslint-plugin-no-barrel-files": "^1.2.1", "eslint-plugin-react": "^7.37.2", "jsdom": "^25.0.1", "postcss": "^8.4.21", diff --git a/gui/src/components/ConversationStarters/index.ts b/gui/src/components/ConversationStarters/index.ts index 72b23e0b7..c7a6af018 100644 --- a/gui/src/components/ConversationStarters/index.ts +++ b/gui/src/components/ConversationStarters/index.ts @@ -1 +1 @@ -export * from "./ConversationStarterCards"; +export { ConversationStarterCards } from "./ConversationStarterCards"; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 0d9f66072..1e2134e7a 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -9,7 +9,7 @@ import { LocalStorageProvider } from "../context/LocalStorage"; import { useWebviewListener } from "../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; import { setCodeToEdit } from "../redux/slices/editState"; -import { setShowDialog } from "../redux/slices/uiSlice"; +import { setDialogMessage, setShowDialog } from "../redux/slices/uiSlice"; import { enterEdit, exitEdit } from "../redux/thunks/edit"; import { saveCurrentSession } from "../redux/thunks/session"; import { fontSize, isMetaEquivalentKeyPressed } from "../util"; @@ -20,7 +20,11 @@ import TextDialog from "./dialogs"; import Footer from "./Footer"; import { LumpProvider } from "./mainInput/Lump/LumpContext"; import { useMainEditor } from "./mainInput/TipTapEditor"; -import { isNewUserOnboarding, useOnboardingCard } from "./OnboardingCard"; +import { + isNewUserOnboarding, + OnboardingCard, + useOnboardingCard, +} from "./OnboardingCard"; import OSRContextMenu from "./OSRContextMenu"; import PostHogPageView from "./PosthogPageView"; @@ -130,17 +134,33 @@ const Layout = () => { ); useWebviewListener( - "openOnboardingCard", + "setupLocalConfig", async () => { - onboardingCard.open(OnboardingModes.API_KEY); + onboardingCard.open(OnboardingModes.LOCAL); }, [], ); useWebviewListener( - "setupLocalConfig", + "freeTrialExceeded", async () => { - onboardingCard.open(OnboardingModes.LOCAL); + dispatch(setShowDialog(true)); + onboardingCard.setActiveTab(OnboardingModes.MODELS_ADD_ON); + dispatch( + setDialogMessage( +
+ +
, + ), + ); + }, + [], + ); + + useWebviewListener( + "setupApiKey", + async () => { + onboardingCard.open(OnboardingModes.API_KEY); }, [], ); diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index dbd5cabfe..a5792d721 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -7,12 +7,7 @@ import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; import { getFontSize, getMetaKeyLabel } from "../../util"; import { useMainEditor } from "../mainInput/TipTapEditor"; -import { - Listbox, - ListboxButton, - ListboxOption, - ListboxOptions, -} from "../ui/Listbox"; +import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "../ui"; import { ModeIcon } from "./ModeIcon"; export function ModeSelect() { diff --git a/gui/src/components/ModeSelect/index.ts b/gui/src/components/ModeSelect/index.ts index 04cc20156..82bc8634a 100644 --- a/gui/src/components/ModeSelect/index.ts +++ b/gui/src/components/ModeSelect/index.ts @@ -1 +1 @@ -export * from "./ModeSelect"; +export { ModeSelect } from "./ModeSelect"; diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index eff33936e..b5131916a 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -1,14 +1,14 @@ import { OnboardingModes } from "core/protocol/core"; import { useAppSelector } from "../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; +import Alert from "../gui/Alert"; import { ReusableCard } from "../ReusableCard"; -import { - OnboardingCardLanding, - OnboardingCardTabs, - OnboardingLocalTab, - OnboardingProvidersTab, -} from "./components"; -import { useOnboardingCard } from "./hooks"; +import { OnboardingCardLanding } from "./components/OnboardingCardLanding"; +import { OnboardingCardTabs } from "./components/OnboardingCardTabs"; +import { OnboardingLocalTab } from "./components/OnboardingLocalTab"; +import { OnboardingModelsAddOnTab } from "./components/OnboardingModelsAddOnTab"; +import { OnboardingProvidersTab } from "./components/OnboardingProvidersTab"; +import { useOnboardingCard } from "./hooks/useOnboardingCard"; export interface OnboardingCardState { show?: boolean; @@ -17,9 +17,13 @@ export interface OnboardingCardState { interface OnboardingCardProps { isDialog?: boolean; + showFreeTrialExceededAlert?: boolean; } -export function OnboardingCard({ isDialog }: OnboardingCardProps) { +export function OnboardingCard({ + isDialog, + showFreeTrialExceededAlert, +}: OnboardingCardProps) { const { activeTab, close, setActiveTab } = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); @@ -33,6 +37,8 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { return ; case OnboardingModes.LOCAL: return ; + case OnboardingModes.MODELS_ADD_ON: + return ; default: return ; } @@ -45,7 +51,24 @@ export function OnboardingCard({ isDialog }: OnboardingCardProps) { onClose={close} testId="onboarding-card" > - + {showFreeTrialExceededAlert && ( +
+ +

+ Free trial completed +

+ + To keep using Continue, select an option below to setup your + models + +
+
+ )} + {renderTabContent()} ); diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx index b4448d612..d9eae491c 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -2,13 +2,13 @@ import { useContext } from "react"; import { Button, SecondaryButton } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { selectCurrentOrg } from "../../../redux"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { selectFirstHubProfile } from "../../../redux/thunks"; +import { selectCurrentOrg } from "../../../redux/slices/profilesSlice"; +import { selectFirstHubProfile } from "../../../redux/thunks/selectFirstHubProfile"; import { hasPassedFTL } from "../../../util/freeTrial"; -import ContinueLogo from "../../gui/ContinueLogo"; import { ToolTip } from "../../gui/Tooltip"; -import { useOnboardingCard } from "../hooks"; +import ContinueLogo from "../../svg/ContinueLogo"; +import { useOnboardingCard } from "../hooks/useOnboardingCard"; export function OnboardingCardLanding({ onSelectConfigure, diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx index de881edf4..1d50e6b0a 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx @@ -1,26 +1,64 @@ import { KeyIcon } from "@heroicons/react/24/outline"; import { OnboardingModes } from "core/protocol/core"; +import ContinueSignet from "../../svg/ContinueSignet"; +import OllamaLogo from "../../svg/OllamaLogo"; interface OnboardingCardTabsProps { - /** The currently active tab */ activeTab: OnboardingModes; - /** Callback function called when a tab is clicked */ onTabClick: (tabName: OnboardingModes) => void; + showFreeTrialExceededAlert?: boolean; } -const getTabIcon = (tabTitle: OnboardingModes) => { +const renderTabButton = ( + tabTitle: OnboardingModes, + index: number, + activeTab: OnboardingModes, + onTabClick: (tabName: OnboardingModes) => void, +) => { + const baseButtonClass = `text-foreground -mb-px cursor-pointer rounded-t-sm border-none bg-transparent py-2 font-medium hover:brightness-125 focus:outline-none ${index === 0 ? "pl-1.5 pr-3" : "px-3"} ${activeTab === tabTitle ? "brightness-125" : "brightness-75"}`; + if (tabTitle === OnboardingModes.API_KEY) { - return ; - } - if (tabTitle === OnboardingModes.LOCAL) { return ( - Ollama + ); } + + if (tabTitle === OnboardingModes.LOCAL) { + return ( + + ); + } + + if (tabTitle === OnboardingModes.MODELS_ADD_ON) { + return ( + + ); + } + return null; }; @@ -30,38 +68,44 @@ const getTabIcon = (tabTitle: OnboardingModes) => { export function OnboardingCardTabs({ activeTab, onTabClick, + showFreeTrialExceededAlert, }: OnboardingCardTabsProps) { + /** + * When users initially install, we only render these tabs after they've + * declined the free trial, so we show the upgrade tab last since they've + * indicated they want don't want to use the Hub. + * + * If `showFreeTrialExceededAlert` is true, they've used the Hub, so show + * upgrade first. + */ + const tabs = showFreeTrialExceededAlert + ? [ + OnboardingModes.MODELS_ADD_ON, + OnboardingModes.API_KEY, + OnboardingModes.LOCAL, + ] + : [ + OnboardingModes.API_KEY, + OnboardingModes.LOCAL, + OnboardingModes.MODELS_ADD_ON, + ]; return (
-
+
- {Object.values(OnboardingModes).map((tabTitle) => { - const isActive = activeTab === tabTitle; - - return ( - - ); - })} + {tabs.map((tabTitle, index) => + renderTabButton(tabTitle, index, activeTab, onTabClick), + )}
-
+