diff --git a/.continue/prompts/update-llm-info.prompt b/.continue/prompts/update-llm-info.prompt new file mode 100644 index 000000000..7264ebf38 --- /dev/null +++ b/.continue/prompts/update-llm-info.prompt @@ -0,0 +1,79 @@ +name: Update LLM Info +description: Updates Gemini blocks with latest information +version: 2 +--- +I need you to update this repo with the latest information about large language models from certain providers. +The information is stored in the `packages/llm-info` directory, which operates as its own npm package. +Information is stored in a simple JSON format, with one file of models per "provider" (e.g. gemini, ollama, openai, etc). +For example, Gemini model information is stored in `packages/llm-info/src/providers/gemini.ts`. + +To make these updates for a given provider, perform the following steps one at a time: + +1. VIEW CURRENT INFORMATION + +To view the current llm info, read the file (e.g. `packages/llm-info/src/providers/gemini.ts`) using the read_file tool. +If you do not see a tool for reading files, let me know. + +For reference, here is the LLMInfo interface used to store the information: + +```typescript +export interface LlmInfo { + model: string; // the model name used to distinguish the model at the API layer, e.g. "gemini-2.5-pro-preview-05-06" + displayName?: string; // A fitting display name, e.g. "Gemini 2.5 Pro Preview" + description?: string; // A short description of the model, as similar as possible to descriptions found on the provider's website + contextLength?: number; // The size of the context window in tokens, often called "max input tokens" or "context length" + maxCompletionTokens?: number; // The maximum number of tokens the model can output + regex?: RegExp; // A regex expression to uniquely match the model name if it had some slight modifications/upgrades, e.g. /gemini-2\.5-pro-preview/i + mediaTypes?: MediaType[]; // Input/output types supported by the model, e.g. [MediaType.Text, MediaType.Image] +} + +export enum MediaType { + Text = "text", + Image = "image", + Audio = "audio", + Video = "video", +} + +export const AllMediaTypes = [ + MediaType.Text, + MediaType.Image, + MediaType.Audio, + MediaType.Video, +]; +``` + +2. EXTRACT NEW INFORMATION + +New information will be pulled from the internet. +If you do not see a web search tool, 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" +// TODO: add info for openai, ollama, etc + +For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement. +Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored. +Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained. + +3. UPDATE THE INFORMATION + +Use the edit file tool to submit updates to the relevant provider file (e.g. `packages/llm-info/src/providers/gemini.ts`). +Let me know if you do not see a tool for editing files. + +Generally, avoid making changes to existing information, as it is probably up to date. +Primarily, focus on adding new models or adding missing information to existing models. +NEVER delete any existing models, but let me know if you think one should be removed. +Stop to ask me if you are unsure about any changes, and let me know if there are updates that seem nuanced, complex, or extremely notable. +Provide a summary of changes after the fact. + +4. ASK IF I WANT TO PUBLISH TO NPM +After you are done updating everything, remind me that I need to publish the changes to npm. + +// TODO too sensitive for now +// If yes, update `packages/llm-info/package.json` with the new version number and then +// - use the terminal tool to commit the changes +// - use the terminal tool to publish changes to npm +// If you do not see a tool for running terminal commands, let me know. + +// User input +Please update LLM Info for the following providers. If "all", update all providers mentioned above: diff --git a/.continue/rules/gui-link-opening.md b/.continue/rules/gui-link-opening.md new file mode 100644 index 000000000..db791e67a --- /dev/null +++ b/.continue/rules/gui-link-opening.md @@ -0,0 +1,10 @@ +--- +globs: gui/**/* +description: Ensures consistent URL opening behavior in GUI components using the + IDE messenger pattern +alwaysApply: false +--- + +# GUI Link Opening + +When adding functionality to open external links in GUI components, use `ideMessenger.post("openUrl", url)` where `ideMessenger` is obtained from `useContext(IdeMessengerContext)` diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 25a1b9a1e..919ae0fe7 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -435,6 +435,8 @@ jobs: 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_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} package-tests: runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index d3ad46eaf..0e528088c 100644 --- a/.gitignore +++ b/.gitignore @@ -146,6 +146,7 @@ Icon? *.notes.md notes.md +*.notes.md manual-testing-sandbox/.idea/** manual-testing-sandbox/.continue/** diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index cf6f3b298..8a579c231 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -114,11 +114,12 @@ export class CompletionProvider { this.loggingService.markDisplayed(completionId, outcome); } - private async _getAutocompleteOptions() { + private async _getAutocompleteOptions(llm: ILLM) { const { config } = await this.configHandler.loadConfig(); const options = { ...DEFAULT_AUTOCOMPLETE_OPTS, ...config?.tabAutocompleteOptions, + ...llm.autocompleteOptions, }; return options; } @@ -136,18 +137,19 @@ export class CompletionProvider { token = controller.signal; } const startTime = Date.now(); - const options = await this._getAutocompleteOptions(); - - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } const llm = await this._prepareLlm(); if (!llm) { return undefined; } + const options = await this._getAutocompleteOptions(llm); + + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; + } + if (llm.promptTemplates?.autocomplete) { options.template = llm.promptTemplates.autocomplete as string; } diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index 8db50cda6..ec18879f7 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,6 +1,10 @@ import ignore from "ignore"; import { IDE } from "../.."; +import { + getGlobalContinueIgArray, + getWorkspaceContinueIgArray, +} from "../../indexing/ignore"; import { getConfigJsonPath } from "../../util/paths"; import { findUriInDirs } from "../../util/uri"; import { HelperVars } from "../util/HelperVars"; @@ -50,7 +54,12 @@ export async function shouldPrefilter( } // Check whether autocomplete is disabled for this file - const disableInFiles = [...(helper.options.disableInFiles ?? []), "*.prompt"]; + const disableInFiles = [ + ...(helper.options.disableInFiles ?? []), + "*.prompt", + ...getGlobalContinueIgArray(), + ...(await getWorkspaceContinueIgArray(ide)), + ]; if (await isDisabledForFile(helper.filepath, disableInFiles, ide)) { return true; } diff --git a/core/config/load.ts b/core/config/load.ts index 9bf8d1466..fe0c4de61 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -640,6 +640,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { capabilities: llm.capabilities, roles: llm.roles, configurationStatus: llm.getConfigurationStatus(), + apiKeyLocation: llm.apiKeyLocation, }; } diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index 9b3826ff8..dde0fefe7 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -8,6 +8,21 @@ export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B"; export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest"; export const LOCAL_ONBOARDING_EMBEDDINGS_TITLE = "Nomic Embed"; +const ANTHROPIC_MODEL_CONFIG = { + slugs: ["anthropic/claude-3-7-sonnet", "anthropic/claude-4-sonnet"], + apiKeyInputName: "ANTHROPIC_API_KEY", +}; +const OPENAI_MODEL_CONFIG = { + slugs: ["openai/gpt-4.1", "openai/o3", "openai/gpt-4.1-mini"], + apiKeyInputName: "OPENAI_API_KEY", +}; + +// TODO: These need updating on the hub +const GEMINI_MODEL_CONFIG = { + slugs: ["google/gemini-2.5-pro", "google/gemini-2.0-flash"], + apiKeyInputName: "GEMINI_API_KEY", +}; + /** * We set the "best" chat + autocopmlete models by default * whenever a user doesn't have a config.json @@ -49,3 +64,45 @@ export function setupLocalConfig(config: ConfigYaml): ConfigYaml { export function setupQuickstartConfig(config: ConfigYaml): ConfigYaml { return config; } + +export function setupProviderConfig( + config: ConfigYaml, + provider: string, + apiKey: string, +): ConfigYaml { + let newModels; + + switch (provider) { + case "openai": + newModels = OPENAI_MODEL_CONFIG.slugs.map((slug) => ({ + uses: slug, + with: { + [OPENAI_MODEL_CONFIG.apiKeyInputName]: apiKey, + }, + })); + break; + case "anthropic": + newModels = ANTHROPIC_MODEL_CONFIG.slugs.map((slug) => ({ + uses: slug, + with: { + [ANTHROPIC_MODEL_CONFIG.apiKeyInputName]: apiKey, + }, + })); + break; + case "gemini": + newModels = GEMINI_MODEL_CONFIG.slugs.map((slug) => ({ + uses: slug, + with: { + [GEMINI_MODEL_CONFIG.apiKeyInputName]: apiKey, + }, + })); + break; + default: + throw new Error(`Unknown provider: ${provider}`); + } + + return { + ...config, + models: [...(config.models ?? []), ...newModels], + }; +} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 863c4d447..dd04d1915 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -27,6 +27,7 @@ import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigDependentToolDefinitions } from "../../tools"; import { encodeMCPToolUri } from "../../tools/callTool"; +import { getMCPToolName } from "../../tools/mcpToolName"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; @@ -156,7 +157,7 @@ export default async function doLoadConfig(options: { displayTitle: server.name + " " + tool.name, function: { description: tool.description, - name: tool.name, + name: getMCPToolName(server, tool), parameters: tool.inputSchema, }, faviconUrl: server.faviconUrl, @@ -164,6 +165,7 @@ export default async function doLoadConfig(options: { type: "function" as const, uri: encodeMCPToolUri(server.id, tool.name), group: server.name, + originalFunctionName: tool.name, })); newConfig.tools.push(...serverTools); diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index aa4c3919a..2217d222c 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -117,10 +117,15 @@ async function loadConfigYaml(options: { // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, // ); - let config = - overrideConfigYaml ?? + const errors: ConfigValidationError[] = []; + + let config: AssistantUnrolled | undefined; + + if (overrideConfigYaml) { + config = overrideConfigYaml; + } else { // This is how we allow use of blocks locally - (await unrollAssistant( + const unrollResult = await unrollAssistant( packageIdentifier, new RegistryClient({ accessToken: await controlPlaneClient.getAccessToken(), @@ -139,17 +144,23 @@ async function loadConfigYaml(options: { ), renderSecrets: true, injectBlocks: allLocalBlocks, + asConfigResult: true, }, - )); + ); + config = unrollResult.config; + if (unrollResult.errors) { + errors.push(...unrollResult.errors); + } + } - const errors = isAssistantUnrolledNonNullable(config) - ? validateConfigYaml(config) - : [ - { + if (config) { + isAssistantUnrolledNonNullable(config) + ? errors.push(...validateConfigYaml(config)) + : errors.push({ fatal: true, message: "Assistant includes blocks that don't exist", - }, - ]; + }); + } if (errors?.some((error) => error.fatal)) { return { diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index ffa891df6..edb47f59e 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -68,6 +68,7 @@ async function modelConfigToBaseLLM({ tools: model.capabilities?.includes("tool_use"), uploadImage: model.capabilities?.includes("image_input"), }, + autocompleteOptions: model.autocompleteOptions, }; // Model capabilities - need to be undefined if not found diff --git a/core/core.ts b/core/core.ts index dbec07062..c90ca9ceb 100644 --- a/core/core.ts +++ b/core/core.ts @@ -34,6 +34,7 @@ import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import { + CompleteOnboardingPayload, ContextItemWithId, IdeSettings, ModelDescription, @@ -47,8 +48,8 @@ import { ConfigYaml } from "@continuedev/config-yaml"; import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache"; import { isLocalAssistantFile } from "./config/loadLocalAssistants"; import { - setupBestConfig, setupLocalConfig, + setupProviderConfig, setupQuickstartConfig, } from "./config/onboarding"; import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks"; @@ -60,6 +61,7 @@ import { walkDirCache } from "./indexing/walkDir"; import { LLMLogger } from "./llm/logger"; 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"; @@ -184,7 +186,7 @@ export class Core { return; } - await this.codeBaseIndexer.refreshCodebaseIndex(dirs); + void this.codeBaseIndexer.refreshCodebaseIndex(dirs); }); }); @@ -509,7 +511,7 @@ export class Core { abortManager.clear(); }); - on("completeOnboarding", this.handleCompleteOnboarding.bind(this)); + on("onboarding/complete", this.handleCompleteOnboarding.bind(this)); on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this)); @@ -876,26 +878,25 @@ export class Core { } } - private async handleCompleteOnboarding(msg: Message<{ mode: string }>) { - const mode = msg.data.mode; - - if (mode === "Custom") { - return; - } + private async handleCompleteOnboarding( + msg: Message, + ) { + const { mode, provider, apiKey } = msg.data; let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml; switch (mode) { - case "Local": + case OnboardingModes.LOCAL: editConfigYamlCallback = setupLocalConfig; break; - case "Quickstart": - editConfigYamlCallback = setupQuickstartConfig; - break; - - case "Best": - editConfigYamlCallback = setupBestConfig; + case OnboardingModes.API_KEY: + if (provider && apiKey) { + editConfigYamlCallback = (config: ConfigYaml) => + setupProviderConfig(config, provider, apiKey); + } else { + editConfigYamlCallback = setupQuickstartConfig; + } break; default: diff --git a/core/core_temp.ts b/core/core_temp.ts new file mode 100644 index 000000000..e69de29bb diff --git a/core/index.d.ts b/core/index.d.ts index ad778d3d8..da9d6fc10 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -94,6 +94,8 @@ export interface ILLM get providerName(): string; get underlyingProviderName(): string; + autocompleteOptions?: Partial; + complete( prompt: string, signal: AbortSignal, @@ -563,6 +565,7 @@ export interface LLMOptions { uniqueId?: string; baseAgentSystemMessage?: string; baseChatSystemMessage?: string; + autocompleteOptions?: Partial; contextLength?: number; maxStopWords?: number; completionOptions?: CompletionOptions; @@ -989,6 +992,7 @@ export interface Tool { uri?: string; faviconUrl?: string; group: string; + originalFunctionName?: string; } interface ToolChoice { @@ -1090,6 +1094,7 @@ export interface RerankerDescription { params?: { [key: string]: any }; } +// TODO: We should consider renaming this to AutocompleteOptions. export interface TabAutocompleteOptions { disable: boolean; maxPromptTokens: number; @@ -1573,3 +1578,9 @@ export interface RuleWithSource { ruleFile?: string; alwaysApply?: boolean; } + +export interface CompleteOnboardingPayload { + mode: OnboardingModes; + provider?: string; + apiKey?: string; +} diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 7f5e8a039..f70633b1b 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -2,6 +2,7 @@ import fs from "fs"; import ignore from "ignore"; +import { IDE } from ".."; import { getGlobalContinueIgnorePath } from "../util/paths"; export const DEFAULT_IGNORE_FILETYPES = [ @@ -129,3 +130,20 @@ export const getGlobalContinueIgArray = () => { const contents = fs.readFileSync(getGlobalContinueIgnorePath(), "utf8"); return gitIgArrayFromFile(contents); }; + +export const getWorkspaceContinueIgArray = async (ide: IDE) => { + const dirs = await ide.getWorkspaceDirs(); + return await dirs.reduce( + async (accPromise, dir) => { + const acc = await accPromise; + try { + const contents = await ide.readFile(`${dir}/.continueignore`); + return [...acc, ...gitIgArrayFromFile(contents)]; + } catch (err) { + console.error(err); + return acc; + } + }, + Promise.resolve([] as string[]), + ); +}; diff --git a/core/llm/index.ts b/core/llm/index.ts index 0d25d882c..ca33b7437 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -25,6 +25,7 @@ import { PromptLog, PromptTemplate, RequestOptions, + TabAutocompleteOptions, TemplateType, } from "../index.js"; import mergeJson from "../util/merge.js"; @@ -96,6 +97,8 @@ export abstract class BaseLLM implements ILLM { return this.providerName; } + autocompleteOptions?: Partial; + supportsFim(): boolean { return false; } @@ -275,6 +278,8 @@ export abstract class BaseLLM implements ILLM { this.maxEmbeddingChunkSize = options.maxEmbeddingChunkSize ?? DEFAULT_MAX_CHUNK_SIZE; this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; + + this.autocompleteOptions = options.autocompleteOptions; } getConfigurationStatus() { diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index e07668ffd..3506dcb32 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -85,7 +85,13 @@ class ContinueProxy extends OpenAI { } supportsCompletions(): boolean { - return true; + // This was a hotfix and contains duplicate logic from class-specific completion support methods + if (this.underlyingProviderName === "vllm") { + return true; + } + // other providers that don't support completions include groq, mistral, nvidia, deepseek, etc. + // For now disabling all except vllm + return false; } supportsFim(): boolean { diff --git a/core/llm/utils/extractPathsFromCodeBlocks.ts b/core/llm/utils/extractPathsFromCodeBlocks.ts index 00f723c7a..99f2764b2 100644 --- a/core/llm/utils/extractPathsFromCodeBlocks.ts +++ b/core/llm/utils/extractPathsFromCodeBlocks.ts @@ -2,8 +2,6 @@ * Extracts file paths from markdown code blocks */ export function extractPathsFromCodeBlocks(content: string): string[] { - console.log("CONTENT", content); - const paths: string[] = []; // Match code block opening patterns: diff --git a/core/package-lock.json b/core/package-lock.json index 8079461a3..a499a0c0c 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -14,9 +14,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", @@ -949,22 +949,6 @@ } } }, - "node_modules/@azure-rest/core-client": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz", - "integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.3.0", - "@azure/core-rest-pipeline": "^1.5.0", - "@azure/core-tracing": "^1.0.1", - "@azure/core-util": "^1.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@azure/abort-controller": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", @@ -1062,17 +1046,6 @@ "node": ">=18.0.0" } }, - "node_modules/@azure/core-sse": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.3.tgz", - "integrity": "sha512-KSSdIKy8kvWCpYr8Hzpu22j3wcXsVTYE0IlgmI1T/aHvBDsLgV91y90UTfVWnuiuApRLCCVC4gS09ApBGOmYQA==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@azure/core-tracing": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.2.0.tgz", @@ -1211,24 +1184,6 @@ "uuid": "dist/bin/uuid" } }, - "node_modules/@azure/openai": { - "version": "1.0.0-beta.13", - "resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.13.tgz", - "integrity": "sha512-oHE5ScnPTXALmyEBgqokZlYVT7F76EfrKjMWF+YcFJdUxk9Adhvht2iL5v+QpmlAIMdkih1q8DkTs/tApDjBpw==", - "deprecated": "The Azure OpenAI client library for JavaScript beta has been retired. Please migrate to the stable OpenAI SDK for JavaScript using the migration guide: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/openai/openai/MIGRATION.md.", - "dependencies": { - "@azure-rest/core-client": "^1.1.7", - "@azure/core-auth": "^1.4.0", - "@azure/core-rest-pipeline": "^1.13.0", - "@azure/core-sse": "^2.0.0", - "@azure/core-util": "^1.4.0", - "@azure/logger": "^1.0.3", - "tslib": "^2.4.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@babel/code-frame": { "version": "7.26.2", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz", @@ -2928,10 +2883,9 @@ "link": true }, "node_modules/@continuedev/fetch": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz", - "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==", - "license": "Apache-2.0", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.13.tgz", + "integrity": "sha512-7vwsefFBozsutv355zD7mEhFfl6UT4KXRH1QXRzjdbCaYneiRdFLe6UAwV2wGnH71Lj76gOLnTlcGoTV357OZg==", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", @@ -2946,15 +2900,13 @@ "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" }, "node_modules/@continuedev/openai-adapters": { - "version": "1.0.25", - "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.25.tgz", - "integrity": "sha512-YG7bcAlUk3BnqIOZw+ClmxmZU6G3OaaZqbhfqgiCnJem5i7oDy0pkAVHjig4iRTQkpvDokKmBXCH9wmQNRbWNw==", - "license": "Apache-2.0", + "version": "1.0.32", + "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.32.tgz", + "integrity": "sha512-teNzbpcsa7Y0eBk+dxlLDo0m43sWI5txTYMIk6ezyS0cZAKFJODDB0Gkp3aEHXbD8mDE7H5dDSlM23ohKCirAA==", "dependencies": { - "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.11", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", diff --git a/core/package.json b/core/package.json index cb2274cc6..84dc95350 100644 --- a/core/package.json +++ b/core/package.json @@ -51,9 +51,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", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index ba3736daa..e34a332bd 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -12,6 +12,7 @@ import { GlobalContextModelSelections } from "../util/GlobalContext"; import { BrowserSerializedContinueConfig, ChatMessage, + CompleteOnboardingPayload, ContextItem, ContextItemWithId, ContextSubmenuItem, @@ -36,7 +37,10 @@ import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager"; import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes"; import { FreeTrialStatus } from "../control-plane/client"; -export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart"; +export enum OnboardingModes { + API_KEY = "API Key", + LOCAL = "Local", +} export interface ListHistoryOptions { offset?: number; @@ -169,12 +173,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { void, ]; "index/indexingProgressBarInitialized": [undefined, void]; - completeOnboarding: [ - { - mode: OnboardingModes; - }, - void, - ]; + "onboarding/complete": [CompleteOnboardingPayload, void]; // File changes "files/changed": [{ uris?: string[] }, void]; @@ -198,7 +197,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { { contextItems: ContextItem[]; errorMessage?: string }, ]; "clipboardCache/add": [{ content: string }, void]; - "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; + "controlPlane/openUrl": [{ path: string; orgSlug?: string }, void]; "controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null]; isItemTooBig: [{ item: ContextItemWithId }, boolean]; didChangeControlPlaneSessionInfo: [ diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 51c8f4a78..014c1a968 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -55,7 +55,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "docs/initStatuses", "docs/getDetails", // - "completeOnboarding", + "onboarding/complete", "addAutocompleteModel", "didChangeSelectedProfile", "didChangeSelectedOrg", @@ -64,6 +64,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "isItemTooBig", "process/markAsBackgrounded", "process/isBackgrounded", + "controlPlane/getFreeTrialStatus", ]; // Message types to pass through from core to webview diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index ac6f98af4..785f4ee30 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -10,13 +10,25 @@ import { const asyncExec = util.promisify(childProcess.exec); +const ENABLED_FOR_REMOTES = [ + "", + "local", + "wsl", + "dev-container", + "devcontainer", + "ssh-remote", + "attached-container", + "codespaces", + "tunnel", +]; + export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // Default to waiting for completion if not specified const waitForCompletion = args.waitForCompletion !== false; const ideInfo = await extras.ide.getIdeInfo(); const toolCallId = extras.toolCallId || ""; - if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") { + if (ENABLED_FOR_REMOTES.includes(ideInfo.remoteName)) { // For streaming output if (extras.onPartialOutput) { return new Promise((resolve, reject) => { diff --git a/core/tools/mcpToolName.ts b/core/tools/mcpToolName.ts new file mode 100644 index 000000000..6440ef5e7 --- /dev/null +++ b/core/tools/mcpToolName.ts @@ -0,0 +1,9 @@ +import { MCPServerStatus, MCPTool } from ".."; + +export function getMCPToolName(server: MCPServerStatus, tool: MCPTool) { + const serverPrefix = server.name.split(" ").join("_").toLowerCase(); + if (tool.name.startsWith(serverPrefix)) { + return tool.name; + } + return `${serverPrefix}_${tool.name}`; +} diff --git a/core/tools/mcpToolName.vitest.ts b/core/tools/mcpToolName.vitest.ts new file mode 100644 index 000000000..8c20f630a --- /dev/null +++ b/core/tools/mcpToolName.vitest.ts @@ -0,0 +1,57 @@ +import { expect, test } from "vitest"; +import { MCPServerStatus, MCPTool } from ".."; +import { getMCPToolName } from "./mcpToolName"; + +const createMcpServer = (name: string): MCPServerStatus => ({ + name, + errors: [], + prompts: [], + tools: [], + resources: [], + resourceTemplates: [], + status: "connected", + id: "", + transport: { + type: "sse", + url: "", + }, +}); + +const createMCPTool = (name: string): MCPTool => ({ + name, + inputSchema: { + type: "object", + }, +}); + +test("getMCPToolName - adds server prefix to tool name when not present", () => { + const server = createMcpServer("Github"); + const tool = createMCPTool("create_pull_request"); + + const result = getMCPToolName(server, tool); + expect(result).toBe("github_create_pull_request"); +}); + +test("getMCPToolName - preserves tool name when it already starts with server prefix", () => { + const server = createMcpServer("Github"); + const tool = createMCPTool("github_create_pull_request"); + + const result = getMCPToolName(server, tool); + expect(result).toBe("github_create_pull_request"); +}); + +test("getMCPToolName - handles server names with spaces", () => { + const server = createMcpServer("Azure DevOps"); + const tool = createMCPTool("create_pipeline"); + + const result = getMCPToolName(server, tool); + expect(result).toBe("azure_devops_create_pipeline"); +}); + +test("getMCPToolName - handles mixed case in server names", () => { + const server = createMcpServer("GitLab"); + const tool = createMCPTool("create_merge_request"); + + const result = getMCPToolName(server, tool); + expect(result).toBe("gitlab_create_merge_request"); +}); diff --git a/docs/docs/agent/how-to-customize.md b/docs/docs/agent/how-to-customize.md index 93f3c6188..495dd9547 100644 --- a/docs/docs/agent/how-to-customize.md +++ b/docs/docs/agent/how-to-customize.md @@ -5,6 +5,12 @@ keywords: [customize, chat] sidebar_position: 5 --- +## Add Rules Blocks + +Adding Rules can be done in your assistant locally or in the Hub. + +[Explore Rules on the Hub](https://hub.continue.dev/explore/rules) and see the [Rules deep dive](../customize/deep-dives/rules.md) for more details and tips on creating rules. + ## Add MCP tools You can add MCP servers to your assistant to give Agent access to more tools. [Explore MCP Servers on the Hub](https://hub.continue.dev/explore/mcp) and see the [MCP guide](../customize/deep-dives/mcp.mdx) for more details. diff --git a/docs/docs/blocks/rules.md b/docs/docs/blocks/rules.md index bc1baaf4b..c43a28b5a 100644 --- a/docs/docs/blocks/rules.md +++ b/docs/docs/blocks/rules.md @@ -6,13 +6,19 @@ keywords: [rules, blocks, standards, practices, guardrails] sidebar_position: 5 --- +Rules allow you to provide specific instructions that guide how the AI assistant behaves when working with your code. Instead of the AI making assumptions about your coding standards, architecture patterns, or project-specific requirements, you can explicitly define guidelines that ensure consistent, contextually appropriate responses. + Think of these as the guardrails for your AI coding assistants: - **Enforce company-specific coding standards** and security practices - **Implement quality checks** that match your engineering culture - **Create paved paths** for developers to follow organizational best practices -![Rules Blocks Overview](/img/rules-blocks-overview.png) +By implementing rules, you transform the AI from a generic coding assistant into a knowledgeable team member that understands your project's unique requirements and constraints. + +### How Rules Work + +Your assistant detects rule blocks and applies the specified rules while in [Agent](../agent/how-to-use-it), [Chat](../chat/how-to-use-it), and [Edit](../edit/how-to-use-it) modes. ## Learn More diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index ec30bb46e..1a567ea4f 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -84,5 +84,3 @@ export function modifyConfig(config: Config): Config { return config; } ``` - -For examples of how to use `config.ts`, see [writing custom slash commands](../tutorials/build-your-own-slash-command.md#custom-slash-commands) or [writing custom context providers](../tutorials/build-your-own-context-provider.mdx). diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 52ea34e0c..36be61127 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -5,9 +5,12 @@ keywords: [rules, .continuerules, system, prompt, message] # Rules -Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. +Rules provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. -Rules are not included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). +:::info Rules are not included in [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). +::: + +## How it works You can view the current rules by clicking the pen icon above the main toolbar: @@ -15,25 +18,52 @@ You can view the current rules by clicking the pen icon above the main toolbar: To form the system message, rules are joined with new lines, in the order they appear in the toolbar. This includes the base chat system message ([see below](#chat-system-message)). -## `rules` blocks +## Quick Start -Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. +Below is a quick example of setting up a new rule file: + +1. Create a folder called `.continue/rules` at the top level of your workspace +2. Add a file called `pirates-rule.yaml` to this folder. +3. Write the following contents to `pirates-rule.prompt` and save. + +```yaml title=".continue/rules/pirates-rule.yaml" +name: Pirate rule +version: 0.0.1 +schema: v1 +rules: + - Talk like a pirate. +``` + +Now test your rules by asking a question about a file in chat. + +![pirate rule test](/img/pirate-rule-test.png) + +## Creating `rules` blocks + +Rules can be added locally using the "Add Rules" button while viewing the Local Assistant's rules. + +![add local rules button](/img/add-local-rules.png) :::info Automatically create local rule blocks -When in Agent mode, you can simply prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled. +When in Agent mode, you can prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled. For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation. ::: +Rules can also be added to an Assistant on the Continue Hub. + +Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. + ### Syntax Rules blocks can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties: - `name` (**required**): A display name/title for the rule - `rule` (**required**): The text content of the rule +- `schema` (**required**): The schema version of the YAML file (e.g., `v1`) - `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). -```yaml title="config.yaml" +```yaml title=".config.yaml" rules: - Always annotate Python functions with their parameter and return types @@ -52,7 +82,47 @@ rules: TONE: concise ``` -## Chat System Message +### `.continue/rules` folder + +You can create project-specific rules by adding a `.continue/rules` folder to the root of your project and adding new rule files. + +```yaml title=".continue/rules/new-rule.yaml" +name: New rule +version: 0.0.1 +schema: v1 +rules: + - Always give concise responses +``` + +This is also done when selecting "Add Rule" in the Assistant settings. This will create a new folder in `.continue/rules` with a default file named `new-rule.yaml`. + +### Examples + +If you want concise answers: + +```yaml title=".continue/rules/concise-rule.yaml" +rules: + - name: Always give concise answers + rule: | + Please provide concise answers. Don't explain obvious concepts. + You can assume that I am knowledgable about most programming topics. +``` + +If you want to ensure certain practices are followed, for example in React: + +```yaml title=".continue/rules/functional-rule.yaml" +rules: + - name: Always use functional components + rule: | + Whenever you are writing React code, make sure to + - use functional components instead of class components + - use hooks for state management + - define an interface for your component props + - use Tailwind CSS for styling + - modularize components into smaller, reusable pieces +``` + +### Chat System Message Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output. @@ -60,25 +130,12 @@ This can be viewed in the rules section of the toolbar (see above), or visit the Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models). -## `.continuerules` +### `.continuerules` + +:::warning + +`.contninuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead. + +::: You can create project-specific rules by adding a `.continuerules` file to the root of your project. This file is raw text and its full contents will be used as rules. - -### Simple Examples - -- If you want concise answers: - -```title=.continuerules -Please provide concise answers. Don't explain obvious concepts. You can assume that I am knowledgable about most programming topics. -``` - -- If you want to ensure certain practices are followed, for example in React: - -```title=.continuerules -Whenever you are writing React code, make sure to -- use functional components instead of class components -- use hooks for state management -- define an interface for your component props -- use Tailwind CSS for styling -- modularize components into smaller, reusable pieces -``` diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 6cce4acbc..f4e35ce05 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -1,3 +1,9 @@ +--- +title: Apply Role +description: Apply model role +keywords: [apply, model, role] +--- + 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. ## Recommended Apply models diff --git a/docs/docs/customize/tutorials/build-your-own-slash-command.md b/docs/docs/customize/tutorials/build-your-own-slash-command.md deleted file mode 100644 index 03543a22f..000000000 --- a/docs/docs/customize/tutorials/build-your-own-slash-command.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Build your own slash command ---- - -:::info -Slash commands can currently only be added using [`config.json`](../../json-reference.md) or `config.ts`. The [`YAML Config Format`](../../reference.md) is the new and preferred format. We recommend looking into [Prompt Files](../deep-dives/prompts.md) to achieve similar functionality. -::: - -There are two ways to add custom slash commands: - -1. With natural language prompts - this is simpler and only requires writing a string or string template. -2. With a custom function - this gives you full access to the Continue SDK and allows you to write arbitrary Typescript code. - -### "Custom Commands" (Use Natural Language) - -You can add custom slash commands by adding to the `customCommands` property in `config.json`. - -- `name`: the name of the command, which will be invoked with `/name` -- `description`: a short description of the command, which will appear in the dropdown -- `prompt`: a templated prompt to send to the LLM - -Custom commands are great when you are frequently reusing a prompt. For example, if you've crafted a great prompt and frequently ask the LLM to check for mistakes in your code, you could add a command like this: - -```json title="config.json" -{ - "customCommands": [ - { - "name": "check", - "description": "Check for mistakes in my code", - "prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found." - } - ] -} -``` - -#### Templating - -The `prompt` property supports templating with Handlebars syntax. You can use the following variables: - -- `input` (used in the example above): any additional input entered with the slash command. For example, if you type `/test only write one test`, `input` will be `only write one test`. This will also include highlighted code blocks. -- File names: You can reference any file by providing an absolute path or a path relative to the current working directory. - -### Custom Slash Commands - -If you want to go a step further than writing custom commands with natural language, you can write a custom function that returns the response. This requires using `config.ts` instead of `config.json`. - -To do this, push a new `SlashCommand` object to the `slashCommands` list. This object contains "name", the name that you will type to invoke the slash command, "description", the description seen in the dropdown menu, and "run". The `run` function is any async generator that should yield strings as you want them to be streamed to the UI. As an argument to the function, you have access to a `ContinueSDK` object with utilities such as access to certain information/actions within the IDE, the current language model, and a few other utilities. For example, here is a slash command that generates a commit message: - -```typescript title="~/.continue/config.ts" -export function modifyConfig(config: Config): Config { - config.slashCommands?.push({ - name: "commit", - description: "Write a commit message", - run: async function* (sdk) { - // The getDiff function takes a boolean parameter that indicates whether - // to include unstaged changes in the diff or not. - const diff = await sdk.ide.getDiff(false); // Pass false to exclude unstaged changes - for await (const message of sdk.llm.streamComplete( - `${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`, - new AbortController().signal, - { - maxTokens: 20, - }, - )) { - yield message; - } - }, - }); - return config; -} -``` diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md index c139a6ca2..cced1e36e 100644 --- a/docs/docs/json-reference.md +++ b/docs/docs/json-reference.md @@ -385,8 +385,6 @@ Example: } ``` -You can also add your own slash command by following [this tutorial](./customize/tutorials/build-your-own-slash-command.md). - ### `customCommands` User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. diff --git a/docs/static/img/add-local-rules.png b/docs/static/img/add-local-rules.png new file mode 100644 index 000000000..67417d302 Binary files /dev/null and b/docs/static/img/add-local-rules.png differ diff --git a/docs/static/img/pirate-rule-test.png b/docs/static/img/pirate-rule-test.png new file mode 100644 index 000000000..13d0c1972 Binary files /dev/null and b/docs/static/img/pirate-rule-test.png differ diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt index 89ca73cd7..66ebac070 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt @@ -121,7 +121,7 @@ class MessageTypes { "docs/initStatuses", "docs/getDetails", // - "completeOnboarding", + "onboarding/complete", "addAutocompleteModel", "didChangeSelectedProfile", "didChangeSelectedOrg", diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index eb0c8b110..576c184e9 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -232,7 +232,8 @@ "relace", "morph", "ovhcloud", - "venice" + "venice", + "inception" ], "markdownEnumDescriptions": [ "### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -281,7 +282,8 @@ "### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys).", "### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard).", "### OVHcloud AI Endpoints is a serverless inference API that provides access to a curated selection of models (e.g., Llama, Mistral, Qwen, Deepseek). It is designed with security and data privacy in mind and is compliant with GDPR. To get started, create an API key on the OVHcloud [AI Endpoints website](https://endpoints.ai.cloud.ovh.net/). For more information, including pricing, visit the OVHcloud [AI Endpoints product page](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/).", - "### Venice\n Venice.AI is a privacy-focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data.\nHosted models support the OpenAI API standard, providing seamless integration for users seeking privacy and flexibility.\nTo get started with the Venice API, either purchase a pro account, stake $VVV for daily inference allotments, or fund your account with USD.\nVisit the [API settings page](https://venice.ai/settings/api) or learn more at the [Venice API documentation](https://venice.ai/api)." + "### Venice\n Venice.AI is a privacy-focused generative AI platform, allowing users to interact with open-source LLMs without storing any private user data.\nHosted models support the OpenAI API standard, providing seamless integration for users seeking privacy and flexibility.\nTo get started with the Venice API, either purchase a pro account, stake $VVV for daily inference allotments, or fund your account with USD.\nVisit the [API settings page](https://venice.ai/settings/api) or learn more at the [Venice API documentation](https://venice.ai/api).", + "### Inception\n Inception Labs offer a new generation of diffusion-based LLMs.\nVisit the [API settings page](https://platform.inceptionlabs.ai/) or learn more at the [Inception docs](https://platform.inceptionlabs.ai/docs)." ], "type": "string" }, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e516f171e..8d4221fa2 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.41", + "version": "1.1.45", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.41", + "version": "1.1.45", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", @@ -107,9 +107,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", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 5b05594ec..6027f17bc 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.42", + "version": "1.1.46", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -18,7 +18,7 @@ "homepage": "https://continue.dev", "qna": "https://github.com/continuedev/continue/issues/new/choose", "license": "Apache-2.0", - "displayName": "Continue - Codestral, Claude, and more", + "displayName": "Continue", "pricing": "Free", "description": "The leading open-source AI code assistant", "publisher": "Continue", @@ -41,15 +41,14 @@ ], "keywords": [ "chatgpt", + "cline", + "roo", "github", "copilot", "claude", - "sonnet", "mistral", "codestral", - "codegpt", - "ai", - "llama" + "ai" ], "activationEvents": [ "onUri", diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index 06fc738e5..0d4827087 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -174,7 +174,7 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { get redirectUri() { if (WorkOsAuthProvider.useOnboardingUri) { const url = new URL(controlPlaneEnv.APP_URL); - url.pathname = `/onboarding/redirect/${env.uriScheme}`; + url.pathname = `/auth/${env.uriScheme}-redirect`; return url.toString(); } return this.ideRedirectUri; @@ -393,6 +393,9 @@ export class WorkOsAuthProvider implements AuthenticationProvider, Disposable { code_challenge: codeChallenge, code_challenge_method: "S256", provider: "authkit", + screen_hint: WorkOsAuthProvider.useOnboardingUri + ? "sign-up" + : "sign-in", }; Object.keys(params).forEach((key) => diff --git a/gui/package-lock.json b/gui/package-lock.json index 1fb8463d7..d6996309b 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -111,9 +111,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", @@ -232,6 +232,16 @@ "zod-to-json-schema": "^3.24.5" } }, + "../packages/llm-info": { + "name": "@continuedev/llm-info", + "version": "1.0.9", + "extraneous": true, + "license": "Apache-2.0", + "devDependencies": { + "@types/node": "^22.15.29", + "typescript": "^5.5.2" + } + }, "node_modules/@adobe/css-tools": { "version": "4.4.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.4.0.tgz", @@ -9800,9 +9810,10 @@ } }, "node_modules/react-hook-form": { - "version": "7.53.0", - "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.53.0.tgz", - "integrity": "sha512-M1n3HhqCww6S2hxLxciEXy2oISPnAzxY7gvwVPrtlczTM/1dDadXgUxDpHMrMTblDOcm/AXtXxHwZ3jpg1mqKQ==", + "version": "7.57.0", + "resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.57.0.tgz", + "integrity": "sha512-RbEks3+cbvTP84l/VXGUZ+JMrKOS8ykQCRYdm5aYsxnDquL0vspsyNhGRO7pcH6hsZqWlPOjLye7rJqdtdAmlg==", + "license": "MIT", "engines": { "node": ">=18.0.0" }, @@ -12377,9 +12388,9 @@ } }, "node_modules/vite": { - "version": "6.3.4", - "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.4.tgz", - "integrity": "sha512-BiReIiMS2fyFqbqNT/Qqt4CVITDU9M9vE+DKcVAsB+ZV0wvTKd+3hMbkpxz1b+NmEDMegpVbisKiAZOnvO92Sw==", + "version": "6.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", + "integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==", "dev": true, "license": "MIT", "dependencies": { @@ -12879,10 +12890,11 @@ } }, "node_modules/vite-node/node_modules/vite": { - "version": "5.4.18", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.18.tgz", - "integrity": "sha512-1oDcnEp3lVyHCuQ2YFelM4Alm2o91xNoMncRm1U7S+JdYfYOvbiGZ3/CxGttrOu2M/KcGz7cRC2DoNUA6urmMA==", + "version": "5.4.19", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.19.tgz", + "integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -13461,10 +13473,11 @@ } }, "node_modules/vitest/node_modules/vite": { - "version": "5.4.18", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.18.tgz", - "integrity": "sha512-1oDcnEp3lVyHCuQ2YFelM4Alm2o91xNoMncRm1U7S+JdYfYOvbiGZ3/CxGttrOu2M/KcGz7cRC2DoNUA6urmMA==", + "version": "5.4.19", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.19.tgz", + "integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx deleted file mode 100644 index aa7ef99b5..000000000 --- a/gui/src/components/AddModelButtonSubtext.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { useContext } from "react"; -import { ButtonSubtext } from "."; -import { IdeMessengerContext } from "../context/IdeMessenger"; - -function AddModelButtonSubtext() { - const ideMessenger = useContext(IdeMessengerContext); - - return ( - - This will update your{" "} - - ideMessenger.post("config/openProfile", { - profileId: undefined, - }) - } - > - config file - - - ); -} - -export default AddModelButtonSubtext; diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index b5e4ebda6..0d9f66072 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -1,3 +1,4 @@ +import { OnboardingModes } from "core/protocol/core"; import { useContext, useEffect } from "react"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import styled from "styled-components"; @@ -131,7 +132,7 @@ const Layout = () => { useWebviewListener( "openOnboardingCard", async () => { - onboardingCard.open("Best"); + onboardingCard.open(OnboardingModes.API_KEY); }, [], ); @@ -139,7 +140,7 @@ const Layout = () => { useWebviewListener( "setupLocalConfig", async () => { - onboardingCard.open("Local"); + onboardingCard.open(OnboardingModes.LOCAL); }, [], ); @@ -179,7 +180,6 @@ const Layout = () => { if (isMetaEquivalentKeyPressed(event) && event.code === "KeyC") { const selection = window.getSelection()?.toString(); if (selection) { - // Copy to clipboard setTimeout(() => { void navigator.clipboard.writeText(selection); }, 100); @@ -199,7 +199,7 @@ const Layout = () => { isNewUserOnboarding() && (location.pathname === "/" || location.pathname === "/index.html") ) { - onboardingCard.open("Quickstart"); + onboardingCard.open(); } }, [location]); diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 75046e476..dbd5cabfe 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -72,7 +72,7 @@ export function ModeSelect() {
diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index aa8be2a29..eff33936e 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -1,13 +1,18 @@ +import { OnboardingModes } from "core/protocol/core"; import { useAppSelector } from "../../redux/hooks"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { ReusableCard } from "../ReusableCard"; -import { OnboardingCardTabs, TabTitle } from "./components/OnboardingCardTabs"; -import { useOnboardingCard } from "./hooks/useOnboardingCard"; -import * as Tabs from "./tabs"; +import { + OnboardingCardLanding, + OnboardingCardTabs, + OnboardingLocalTab, + OnboardingProvidersTab, +} from "./components"; +import { useOnboardingCard } from "./hooks"; export interface OnboardingCardState { show?: boolean; - activeTab?: TabTitle; + activeTab?: OnboardingModes; } interface OnboardingCardProps { @@ -15,37 +20,48 @@ interface OnboardingCardProps { } export function OnboardingCard({ isDialog }: OnboardingCardProps) { - const onboardingCard = useOnboardingCard(); + const { activeTab, close, setActiveTab } = useOnboardingCard(); const config = useAppSelector((store) => store.config.config); - function renderTabContent() { - switch (onboardingCard.activeTab) { - case "Quickstart": - return ; - case "Best": - return ; - case "Local": - return ; - default: - return ; - } - } - if (getLocalStorage("onboardingStatus") === undefined) { setLocalStorage("onboardingStatus", "Started"); } + function renderTabContent() { + switch (activeTab) { + case OnboardingModes.API_KEY: + return ; + case OnboardingModes.LOCAL: + return ; + default: + return ; + } + } + + if (activeTab) { + return ( + + + {renderTabContent()} + + ); + } + return ( onboardingCard.close()} - testId="onboarding-card" + onClose={close} > - - {renderTabContent()} +
+ setActiveTab(OnboardingModes.API_KEY)} + isDialog={isDialog} + /> +
); } diff --git a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx b/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx deleted file mode 100644 index 0929aad8b..000000000 --- a/gui/src/components/OnboardingCard/components/BestExperienceConfigForm.tsx +++ /dev/null @@ -1,171 +0,0 @@ -import { CubeIcon } from "@heroicons/react/24/outline"; -import { FormEventHandler, useContext, useState } from "react"; -import { Button, Input, InputSubtext, lightGray } from "../.."; -import { useAuth } from "../../../context/Auth"; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { models } from "../../../pages/AddNewModel/configs/models"; -import { providers } from "../../../pages/AddNewModel/configs/providers"; -import { useAppDispatch } from "../../../redux/hooks"; -import { updateSelectedModelByRole } from "../../../redux/thunks"; -import AddModelButtonSubtext from "../../AddModelButtonSubtext"; - -const { anthropic, mistral } = providers; -const chatProvider = anthropic!; -const autocompleteProvider = mistral!; - -const { - claude35Sonnet: chatModel, - claude35Haiku: repoMapModel, - codestral: autocompleteModel, -} = models; - -interface BestExperienceConfigFormProps { - onComplete: () => void; -} - -function BestExperienceConfigForm({ - onComplete, -}: BestExperienceConfigFormProps) { - const dispatch = useAppDispatch(); - const { selectedProfile } = useAuth(); - - const ideMessenger = useContext(IdeMessengerContext); - - const [autocompleteApiKey, setAutocompleteApiKey] = useState(""); - const [chatApiKey, setChatApiKey] = useState(""); - - const handleSubmit: FormEventHandler = async (e) => { - e.preventDefault(); - - const chatModelConfig = { - model: chatModel.params.model, - provider: chatProvider.provider, - underlyingProviderName: chatProvider.provider, - apiKey: chatApiKey, - title: chatModel.params.title, - }; - - const repoMapConfig = { - model: repoMapModel.params.model, - provider: chatProvider.provider, - underlyingProviderName: chatProvider.provider, - apiKey: chatApiKey, - title: repoMapModel.params.title, - }; - - const autocompleteModelConfig = { - title: autocompleteModel.params.title, - provider: autocompleteProvider.provider, - underlyingProviderName: autocompleteProvider.provider, - model: autocompleteModel.params.model, - apiKey: autocompleteApiKey, - }; - - ideMessenger.post("config/addModel", { model: chatModelConfig }); - ideMessenger.post("config/addModel", { - model: repoMapConfig, - role: "repoMapFileSelection", - }); - - dispatch( - updateSelectedModelByRole({ - selectedProfile, - role: "chat", - modelTitle: chatModelConfig.title, - }), - ); - - if (!!autocompleteApiKey) { - await ideMessenger.request("addAutocompleteModel", { - model: autocompleteModelConfig, - }); - } - - onComplete(); - }; - - return ( -
-
-
-
- -
- - - {chatModel.title}{" "} - by Anthropic - -
-
- -
- setChatApiKey(e.target.value)} - data-testid="best-chat-api-key-input" - /> - - - Click here - {" "} - to create an Anthropic API key - -
-
- -
-
- -
- - - {autocompleteModel.title}{" "} - by Mistral - -
-
- -
- setAutocompleteApiKey(e.target.value)} - data-testid="best-autocomplete-api-key-input" - /> - - - Click here - {" "} - to create a Mistral API key - -
-
- -
- - -
-
-
- ); -} - -export default BestExperienceConfigForm; diff --git a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx index c98ca6794..abce87d86 100644 --- a/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaModelDownload.tsx @@ -27,7 +27,7 @@ function OllamaModelDownload({ return (
-

{title}

+

{title}

{hasDownloaded ? ( ) : ( diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx new file mode 100644 index 000000000..b4448d612 --- /dev/null +++ b/gui/src/components/OnboardingCard/components/OnboardingCardLanding.tsx @@ -0,0 +1,103 @@ +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 { hasPassedFTL } from "../../../util/freeTrial"; +import ContinueLogo from "../../gui/ContinueLogo"; +import { ToolTip } from "../../gui/Tooltip"; +import { useOnboardingCard } from "../hooks"; + +export function OnboardingCardLanding({ + onSelectConfigure, + isDialog, +}: { + onSelectConfigure: () => void; + isDialog?: boolean; +}) { + const ideMessenger = useContext(IdeMessengerContext); + const onboardingCard = useOnboardingCard(); + const auth = useAuth(); + const currentOrg = useAppSelector(selectCurrentOrg); + const dispatch = useAppDispatch(); + + function onGetStarted() { + void auth.login(true).then((success) => { + if (success) { + onboardingCard.close(isDialog); + + // A new assistant is created when the account is created + // We want to switch to this immediately + void dispatch(selectFirstHubProfile()); + } + }); + } + + function openPastFreeTrialOnboarding() { + ideMessenger.post("controlPlane/openUrl", { + path: "setup-models", + orgSlug: currentOrg?.slug, + }); + onboardingCard.close(isDialog); + } + + const pastFreeTrialLimit = hasPassedFTL(); + + return ( +
+
+ +
+ + {pastFreeTrialLimit ? ( + <> +

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

+ + + ) : ( + <> +

+ Log in to access a free trial of the +
+ + ideMessenger.post("controlPlane/openUrl", { + path: "pricing", + }) + } + > + Models Add-On + + + Free trial includes 50 Chat requests and 2,000 autocomplete + requests + +

+ + + + )} + + + Or, configure your own models + +
+ ); +} diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx index b1543ea58..de881edf4 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx @@ -1,74 +1,32 @@ -import styled from "styled-components"; -import { vscForeground } from "../.."; -import { hasPassedFTL } from "../../../util/freeTrial"; +import { KeyIcon } from "@heroicons/react/24/outline"; +import { OnboardingModes } from "core/protocol/core"; interface OnboardingCardTabsProps { - activeTab: TabTitle; - onTabClick: (tabName: TabTitle) => void; + /** The currently active tab */ + activeTab: OnboardingModes; + /** Callback function called when a tab is clicked */ + onTabClick: (tabName: OnboardingModes) => void; } -export type TabTitle = "Quickstart" | "Best" | "Local" | "ExistingUserHubIntro"; - -export const TabTitles: { [k in TabTitle]: { md: string; default: string } } = { - Quickstart: { - md: "Quickstart", - default: "Quickstart", - }, - Best: { - md: "Best", - default: "Best experience", - }, - Local: { - md: "Local", - default: "Local with Ollama", - }, - ExistingUserHubIntro: { - md: "Try out hub.continue.dev", - default: "Try out hub.continue.dev", - }, +const getTabIcon = (tabTitle: OnboardingModes) => { + if (tabTitle === OnboardingModes.API_KEY) { + return ; + } + if (tabTitle === OnboardingModes.LOCAL) { + return ( + Ollama + ); + } + return null; }; -const StyledSelect = styled.select` - width: 100%; - padding: 0.5rem; - background-color: transparent; - color: ${vscForeground}; - border: none; - border-bottom: 1px solid ${vscForeground}; - border-radius: 0; - font-size: 1rem; - cursor: pointer; - display: block; - - &:focus { - outline: none; - } -`; - -const TabButton = styled.button<{ isActive: boolean }>` - margin-bottom: -1px; - focus: outline-none; - background: transparent; - cursor: pointer; - color: ${vscForeground}; - border: none; - - ${({ isActive }) => - isActive && - ` - border-style: solid; - border-width: 0 0 2.5px 0; - border-color: ${vscForeground}; - font-weight: bold; - `} -`; - -const TabList = styled.div` - border-style: solid; - border-width: 0 0 0.5px 0; - border-color: ${vscForeground}; -`; - +/** + * Tab navigation component for onboarding modes with responsive design + */ export function OnboardingCardTabs({ activeTab, onTabClick, @@ -76,46 +34,41 @@ export function OnboardingCardTabs({ return (
- - {Object.entries(TabTitles).map(([tabType, titles]) => { - if (hasPassedFTL() && tabType === "Quickstart") { - return undefined; - } +
+ {Object.values(OnboardingModes).map((tabTitle) => { + const isActive = activeTab === tabTitle; return ( - onTabClick(tabType as TabTitle)} - data-testid={`onboarding-tab-${tabType}`} + ); })} - +
-
- onTabClick(e.target.value as TabTitle)} - > - {Object.entries(TabTitles).map(([tabType, titles]) => { - if (hasPassedFTL() && tabType === "Quickstart") { - return null; - } +
+
); diff --git a/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx index b0cc6f179..797fcbff0 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingLocalTab.tsx @@ -5,8 +5,9 @@ import { LOCAL_ONBOARDING_FIM_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, } from "core/config/onboarding"; +import { OnboardingModes } from "core/protocol/core"; import { useContext, useEffect, useState } from "react"; -import { Button, ButtonSubtext } from "../.."; +import { Button } from "../.."; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch } from "../../../redux/hooks"; @@ -22,10 +23,13 @@ interface OnboardingLocalTabProps { isDialog?: boolean; } -function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { +export function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); - const { submitOnboarding } = useSubmitOnboarding("Local", isDialog); + const { submitOnboarding } = useSubmitOnboarding( + OnboardingModes.LOCAL, + isDialog, + ); const [hasLoadedChatModel, setHasLoadedChatModel] = useState(false); const [downloadedOllamaModels, setDownloadedOllamaModels] = useState< string[] @@ -109,7 +113,7 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { dispatch(setShowDialog(false)); } - dispatch( + void dispatch( updateSelectedModelByRole({ selectedProfile, role: "chat", @@ -132,48 +136,53 @@ function OnboardingLocalTab({ isDialog }: OnboardingLocalTabProps) { }; return ( -
-
-

- Install Ollama -

- -
+
+
+
+
+

+ Install Ollama +

+ +
- + - + - + -
- - - - Skip and configure manually - - +
+ +
+ + Skip and configure manually + +
+
+
); } - -export default OnboardingLocalTab; diff --git a/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx b/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx new file mode 100644 index 000000000..afbffb854 --- /dev/null +++ b/gui/src/components/OnboardingCard/components/OnboardingProvidersTab.tsx @@ -0,0 +1,128 @@ +import { OnboardingModes } from "core/protocol/core"; +import { FormProvider, useForm } from "react-hook-form"; +import { AddModelForm } from "../../../forms"; +import { providers } from "../../../pages/AddNewModel/configs/providers"; +import { useAppDispatch } from "../../../redux/hooks"; +import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; +import { Button, Input } from "../../index"; +import { useSubmitOnboarding } from "../hooks/useSubmitOnboarding"; + +interface OnboardingProvidersTabProps { + /** Whether this is being shown in a dialog context */ + isDialog?: boolean; +} + +export function OnboardingProvidersTab({ + isDialog, +}: OnboardingProvidersTabProps) { + const formMethods = useForm(); + const dispatch = useAppDispatch(); + const { submitOnboarding } = useSubmitOnboarding( + OnboardingModes.API_KEY, + isDialog, + ); + + const providerConfigs = [ + providers["openai"], + providers["anthropic"], + providers["gemini"], + ]; + + const handleFormSubmit = () => { + // Find the first provider with an API key entered + for (const config of providerConfigs) { + const apiKey = formMethods.watch(`${config?.provider}_apiKey`); + if (apiKey?.trim()) { + submitOnboarding(config?.provider, apiKey); + return; + } + } + }; + + const handleClickMoreProviders = () => { + dispatch(setShowDialog(true)); + dispatch( + setDialogMessage( + { + dispatch(setShowDialog(false)); + submitOnboarding(); + }} + />, + ), + ); + }; + + const hasAnyApiKey = providerConfigs.some((config) => { + const apiKey = formMethods.watch(`${config?.provider}_apiKey`); + return apiKey?.trim(); + }); + + return ( +
+
+ +
+
+ {providerConfigs.map((config) => ( +
+ + + + + Click here + {" "} + to create a {config?.title} API key + +
+ ))} +
+ +
+ + +
+ + + Click here + {" "} + to view more providers + +
+
+
+
+
+
+ ); +} diff --git a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx b/gui/src/components/OnboardingCard/components/ProviderAlert.tsx deleted file mode 100644 index 13e2eae11..000000000 --- a/gui/src/components/OnboardingCard/components/ProviderAlert.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { useDispatch } from "react-redux"; -import AddModelForm from "../../../forms/AddModelForm"; -import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; -import Alert from "../../gui/Alert"; -import { useSubmitOnboarding } from "../hooks"; - -function ProviderAlert() { - const dispatch = useDispatch(); - const { submitOnboarding } = useSubmitOnboarding("Custom"); - - function onClick() { - dispatch(setShowDialog(true)); - dispatch(setDialogMessage()); - } - - return ( -
- -

- Prefer to use a different provider like OpenAI? -

-

- - Click here - {" "} - to add a Chat model from OpenAI, Gemini, and more -

-
-
- ); -} - -export default ProviderAlert; diff --git a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx b/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx deleted file mode 100644 index 3dca0b391..000000000 --- a/gui/src/components/OnboardingCard/components/QuickStartSubmitButton.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { useContext } from "react"; -import { useDispatch } from "react-redux"; -import { Button, ButtonSubtext } from "../.."; -import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useSubmitOnboarding } from "../hooks"; - -interface QuickstartSubmitButtonProps { - isDialog?: boolean; -} - -function QuickstartSubmitButton({ isDialog }: QuickstartSubmitButtonProps) { - const ideMessenger = useContext(IdeMessengerContext); - const dispatch = useDispatch(); - - const { submitOnboarding } = useSubmitOnboarding("Quickstart", isDialog); - - function onComplete() { - submitOnboarding(); - } - - async function onClick() { - // REMOVED THIS LOGIC TO GET GITHUB TOKEN - // SINCE NOW USES THE HUB FOR FREE TRIAL - // AND COMPONENT IS CURRENTLY UNUSED - } - - return ( -
- - Try 50 chat and 2k autocomplete requests -
- ); -} - -export default QuickstartSubmitButton; diff --git a/gui/src/components/OnboardingCard/components/index.ts b/gui/src/components/OnboardingCard/components/index.ts new file mode 100644 index 000000000..7dcf5e7f6 --- /dev/null +++ b/gui/src/components/OnboardingCard/components/index.ts @@ -0,0 +1,7 @@ +export * from "./OllamaCompletedStep"; +export * from "./OllamaModelDownload"; +export * from "./OllamaStatus"; +export * from "./OnboardingCardLanding"; +export * from "./OnboardingCardTabs"; +export * from "./OnboardingLocalTab"; +export * from "./OnboardingProvidersTab"; diff --git a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts index 9622754c4..94a7fb7a8 100644 --- a/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts +++ b/gui/src/components/OnboardingCard/hooks/useOnboardingCard.ts @@ -1,21 +1,19 @@ -import { useDispatch } from "react-redux"; +import { OnboardingModes } from "core/protocol/core"; import { useNavigate } from "react-router-dom"; -import { TabTitle } from "../components/OnboardingCardTabs"; +import { OnboardingCardState } from ".."; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { setDialogMessage, setOnboardingCard, setShowDialog, } from "../../../redux/slices/uiSlice"; -import { OnboardingCardState } from ".."; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; -import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; -import { saveCurrentSession } from "../../../redux/thunks/session"; export interface UseOnboardingCard { show: OnboardingCardState["show"]; activeTab: OnboardingCardState["activeTab"]; - setActiveTab: (tab: TabTitle) => void; - open: (tab: TabTitle) => void; + setActiveTab: (tab: OnboardingModes) => void; + open: (tab?: OnboardingModes) => void; close: (isDialog?: boolean) => void; } @@ -40,9 +38,14 @@ export function useOnboardingCard(): UseOnboardingCard { show = onboardingStatus !== "Completed" && !hasDismissedOnboardingCard; } - async function open(tab: TabTitle) { + async function open(tab?: OnboardingModes) { navigate("/"); - dispatch(setOnboardingCard({ show: true, activeTab: tab })); + dispatch( + setOnboardingCard({ + show: true, + activeTab: tab ?? OnboardingModes.API_KEY, + }), + ); } function close(isDialog = false) { @@ -54,7 +57,7 @@ export function useOnboardingCard(): UseOnboardingCard { } } - function setActiveTab(tab: TabTitle) { + function setActiveTab(tab: OnboardingModes) { dispatch(setOnboardingCard({ show: true, activeTab: tab })); } diff --git a/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts b/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts index 9e1bd8a9b..259dd6392 100644 --- a/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts +++ b/gui/src/components/OnboardingCard/hooks/useSubmitOnboarding.ts @@ -3,20 +3,25 @@ import { usePostHog } from "posthog-js/react"; import { useContext } from "react"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; +import { useLump } from "../../mainInput/Lump/LumpContext"; import { useOnboardingCard } from "./useOnboardingCard"; export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) { const posthog = usePostHog(); const ideMessenger = useContext(IdeMessengerContext); const { close: closeOnboardingCard } = useOnboardingCard(); + const { setSelectedSection } = useLump(); - function submitOnboarding() { + function submitOnboarding(provider?: string, apiKey?: string) { const onboardingStatus = getLocalStorage("onboardingStatus"); - // Always close the onboarding card and update config.json + // Always close the onboarding card and update config.yaml closeOnboardingCard(isDialog); - ideMessenger.post("completeOnboarding", { + + ideMessenger.post("onboarding/complete", { mode, + provider, + apiKey, }); if (onboardingStatus === "Started") { @@ -32,6 +37,9 @@ export function useSubmitOnboarding(mode: OnboardingModes, isDialog = false) { // Move to next step in onboarding ideMessenger.post("showTutorial", undefined); } + + ideMessenger.post("config/openProfile", { profileId: undefined }); + setSelectedSection("models"); } return { diff --git a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx b/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx deleted file mode 100644 index 883ea66d1..000000000 --- a/gui/src/components/OnboardingCard/platform/PlatformOnboardingCard.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { useState } from "react"; -import { useAuth } from "../../../context/Auth"; -import { useAppSelector } from "../../../redux/hooks"; -import { getLocalStorage, setLocalStorage } from "../../../util/localStorage"; -import Alert from "../../gui/Alert"; -import { ReusableCard } from "../../ReusableCard"; -import { TabTitle } from "../components/OnboardingCardTabs"; -import OnboardingLocalTab from "../components/OnboardingLocalTab"; -import { useOnboardingCard } from "../hooks"; -import MainTab from "./tabs/main"; - -export interface OnboardingCardState { - show?: boolean; - activeTab?: TabTitle; -} - -interface OnboardingCardProps { - isDialog: boolean; -} - -export function PlatformOnboardingCard({ isDialog }: OnboardingCardProps) { - const onboardingCard = useOnboardingCard(); - const config = useAppSelector((store) => store.config.config); - const auth = useAuth(); - const [currentTab, setCurrentTab] = useState<"main" | "local">("main"); - - if (getLocalStorage("onboardingStatus") === undefined) { - setLocalStorage("onboardingStatus", "Started"); - } - - function onGetStarted() { - auth.login(true).then((success) => { - if (success) { - onboardingCard.close(isDialog); - } - }); - } - - return ( - onboardingCard.close()} - > -
- {currentTab === "main" ? ( - setCurrentTab("local")} - isDialog={isDialog} - /> - ) : ( -
- - By choosing this option, Continue will be configured by a local - config.yaml file. If you're just looking to use Ollama and still - want to manage your configuration through Continue, click{" "} - - here - - - -
- )} -
-
- ); -} diff --git a/gui/src/components/OnboardingCard/platform/tabs/main.tsx b/gui/src/components/OnboardingCard/platform/tabs/main.tsx deleted file mode 100644 index c5590e7d8..000000000 --- a/gui/src/components/OnboardingCard/platform/tabs/main.tsx +++ /dev/null @@ -1,107 +0,0 @@ -import { ChevronRightIcon } from "@heroicons/react/24/outline"; -import { useContext } from "react"; -import { Button, ButtonSubtext } from "../../.."; -import { useAuth } from "../../../../context/Auth"; -import { IdeMessengerContext } from "../../../../context/IdeMessenger"; -import { selectCurrentOrg } from "../../../../redux"; -import { useAppSelector } from "../../../../redux/hooks"; -import { hasPassedFTL } from "../../../../util/freeTrial"; -import ContinueLogo from "../../../gui/ContinueLogo"; -import { useOnboardingCard } from "../../hooks"; - -export default function MainTab({ - onRemainLocal, - isDialog, -}: { - onRemainLocal: () => void; - isDialog: boolean; -}) { - const ideMessenger = useContext(IdeMessengerContext); - const onboardingCard = useOnboardingCard(); - const auth = useAuth(); - const currentOrg = useAppSelector(selectCurrentOrg); - - function onGetStarted() { - auth.login(true).then((success) => { - if (success) { - onboardingCard.close(isDialog); - } - }); - } - - function openPastFreeTrialOnboarding() { - ideMessenger.post("controlPlane/openUrl", { - path: "setup-models", - orgSlug: currentOrg?.slug, - }); - onboardingCard.close(isDialog); - } - - const pastFreeTrialLimit = hasPassedFTL(); - - return ( -
-
- -
- - {pastFreeTrialLimit ? ( - <> -

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

- - - ) : onboardingCard.activeTab === "ExistingUserHubIntro" ? ( - <> -

- You can now browse and create custom AI code assistants at{" "} - hub.continue.dev -

- - - - ) : ( - <> -

- Log in to quickly build your first custom AI code assistant -

- - - - )} - - {onboardingCard.activeTab === "ExistingUserHubIntro" ? ( - onboardingCard.close(isDialog)}> -
- Or, use Continue as usual - -
-
- ) : ( - -
- Or, remain local - -
-
- )} -
- ); -} diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx deleted file mode 100644 index 17d2ead00..000000000 --- a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx +++ /dev/null @@ -1,22 +0,0 @@ -import BestExperienceConfigForm from "../components/BestExperienceConfigForm"; -import ProviderAlert from "../components/ProviderAlert"; -import { useSubmitOnboarding } from "../hooks"; - -interface OnboardingBestTabProps { - isDialog?: boolean; -} - -function OnboardingBestTab({ isDialog }: OnboardingBestTabProps) { - const { submitOnboarding } = useSubmitOnboarding("Best", isDialog); - - return ( -
-
- -
- -
- ); -} - -export default OnboardingBestTab; diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx deleted file mode 100644 index f291cf7c8..000000000 --- a/gui/src/components/OnboardingCard/tabs/OnboardingQuickstartTab.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import ContinueLogo from "../../gui/ContinueLogo"; -import QuickStartSubmitButton from "../components/QuickStartSubmitButton"; - -interface OnboardingQuickstartTabProps { - isDialog?: boolean; -} - -function OnboardingQuickstartTab({ isDialog }: OnboardingQuickstartTabProps) { - return ( -
-
-
- -
- -

- Quickly get up and running using our API keys. After this trial, we'll - help you set up your own models. -

- -

- To prevent abuse, we'll ask you to sign in to GitHub. -

- - -
-
- ); -} - -export default OnboardingQuickstartTab; diff --git a/gui/src/components/OnboardingCard/tabs/index.ts b/gui/src/components/OnboardingCard/tabs/index.ts deleted file mode 100644 index 1e6aae37d..000000000 --- a/gui/src/components/OnboardingCard/tabs/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export { default as Local } from "../components/OnboardingLocalTab"; -export { default as Best } from "./OnboardingBestTab"; -export { default as Quickstart } from "./OnboardingQuickstartTab"; diff --git a/gui/src/components/OnboardingCard/utils.ts b/gui/src/components/OnboardingCard/utils.ts index 4d2b8ef2c..33d4e59d3 100644 --- a/gui/src/components/OnboardingCard/utils.ts +++ b/gui/src/components/OnboardingCard/utils.ts @@ -24,7 +24,7 @@ export function isNewUserOnboarding() { export const defaultOnboardingCardState: OnboardingCardState = { show: false, - activeTab: "Quickstart", + activeTab: undefined, }; export enum OllamaConnectionStatuses { diff --git a/gui/src/components/PageHeader.tsx b/gui/src/components/PageHeader.tsx index ceb9bd64a..0e935b6a5 100644 --- a/gui/src/components/PageHeader.tsx +++ b/gui/src/components/PageHeader.tsx @@ -1,5 +1,5 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; -import { fontSize } from "../util"; +import { useFontSize } from "./ui/font"; export interface PageHeaderProps { onTitleClick?: () => void; @@ -14,9 +14,11 @@ export function PageHeader({ rightContent, showBorder, }: PageHeaderProps) { + const fontSize = useFontSize(-1); + return (
{title ? (
{title} diff --git a/gui/src/components/dialogs/ConfirmationDialog.tsx b/gui/src/components/dialogs/ConfirmationDialog.tsx index 1a3cd09e7..20024b1f8 100644 --- a/gui/src/components/dialogs/ConfirmationDialog.tsx +++ b/gui/src/components/dialogs/ConfirmationDialog.tsx @@ -1,7 +1,6 @@ import { useDispatch } from "react-redux"; -import styled from "styled-components"; -import { Button, SecondaryButton } from ".."; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { Button } from "../ui/Button"; interface ConfirmationDialogProps { onConfirm: () => void; @@ -26,8 +25,8 @@ function ConfirmationDialog(props: ConfirmationDialogProps) {
{!!props.hideCancelButton || ( - { dispatch(setShowDialog(false)); dispatch(setDialogMessage(undefined)); @@ -35,7 +34,7 @@ function ConfirmationDialog(props: ConfirmationDialogProps) { }} > Cancel - + )}
)} @@ -276,7 +276,7 @@ function AddModelForm({ field.key !== "apiKey", ) .map((field) => ( -
+
<>
diff --git a/gui/src/forms/index.ts b/gui/src/forms/index.ts new file mode 100644 index 000000000..410a55a37 --- /dev/null +++ b/gui/src/forms/index.ts @@ -0,0 +1 @@ +export * from "./AddModelForm"; diff --git a/gui/src/pages/config/AccountButton.tsx b/gui/src/pages/config/AccountButton.tsx index d30e638a0..06c6beba0 100644 --- a/gui/src/pages/config/AccountButton.tsx +++ b/gui/src/pages/config/AccountButton.tsx @@ -1,13 +1,12 @@ import { UserCircleIcon } from "@heroicons/react/24/solid"; - import { isOnPremSession } from "core/control-plane/AuthTypes"; -import { SecondaryButton } from "../../components"; import { Popover, PopoverButton, PopoverPanel, Transition, } from "../../components/ui"; +import { Button } from "../../components/ui/Button"; import { useAuth } from "../../context/Auth"; import { selectCurrentOrg } from "../../redux"; import { useAppSelector } from "../../redux/hooks"; @@ -19,12 +18,13 @@ export function AccountButton() { if (!session) { return ( - login(false)} > Sign in - + ); } @@ -42,7 +42,7 @@ export function AccountButton() { {selectedOrg === null ? "Personal" : selectedOrg.name} - {" "} +
@@ -65,9 +65,13 @@ export function AccountButton() {
)} - +
diff --git a/gui/src/pages/config/HelpCenterSection.tsx b/gui/src/pages/config/HelpCenterSection.tsx index e49a17780..004e5b78a 100644 --- a/gui/src/pages/config/HelpCenterSection.tsx +++ b/gui/src/pages/config/HelpCenterSection.tsx @@ -81,7 +81,12 @@ export function HelpCenterSection() { generateTitle: true, }), ); - dispatch(setOnboardingCard({ show: true, activeTab: "Best" })); + dispatch( + setOnboardingCard({ + show: true, + activeTab: undefined, + }), + ); ideMessenger.post("showTutorial", undefined); }} /> diff --git a/gui/src/pages/config/KeyboardShortcuts.tsx b/gui/src/pages/config/KeyboardShortcuts.tsx index 77d8c2733..489c28456 100644 --- a/gui/src/pages/config/KeyboardShortcuts.tsx +++ b/gui/src/pages/config/KeyboardShortcuts.tsx @@ -11,7 +11,7 @@ interface KeyboardShortcutProps { function KeyboardShortcut(props: KeyboardShortcutProps) { return (
{props.description}: @@ -132,8 +132,8 @@ function KeyboardShortcuts() { }, []); return ( -
-

Keyboard shortcuts

+
+

Keyboard shortcuts

{shortcuts.map((shortcut, i) => { return ( diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index 2214853a4..0065552a8 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -26,6 +26,7 @@ interface ModelRoleSelectorProps { onSelect: (model: ModelDescription | null) => void; displayName: string; description: string; + setupURL: string; } const ModelRoleSelector = ({ @@ -34,6 +35,7 @@ const ModelRoleSelector = ({ onSelect, displayName, description, + setupURL, }: ModelRoleSelectorProps) => { const ideMessenger = useContext(IdeMessengerContext); const [hoveredIdx, setHoveredIdx] = useState(null); @@ -65,102 +67,111 @@ const ModelRoleSelector = ({ return ( <>
- - {displayName} - + {displayName} {description}
+
- - {models.length === 0 || noConfiguredModels ? ( - - {`No ${models.length === 0 ? "" : "valid "}${displayName} models${ - ["Chat", "Apply", "Edit"].includes(displayName) - ? ". Using Chat model" - : "" - }`} - - ) : ( - - {selectedModel?.title ?? `Select ${displayName} model`} - - )} - {models.length ? ( -
-
- ) : null} -
- - - ideMessenger.post("openUrl", setupURL)} + className="bg-vsc-editor-background hover:bg-list-active hover:text-list-active-foreground text-description w-full justify-between px-2 py-1 underline hover:underline" > - {[...models] - .sort((a, b) => a.title.localeCompare(b.title)) - .map((option, idx) => { - const showMissingApiKeyMsg = - option.configurationStatus === - LLMConfigurationStatuses.MISSING_API_KEY; + + Setup {displayName} model + + + ) : ( + <> + + {models.length === 0 || noConfiguredModels ? ( + + {`No ${models.length === 0 ? "" : "valid "}${displayName} models${ + ["Chat", "Apply", "Edit"].includes(displayName) + ? ". Using Chat model" + : "" + }`} + + ) : ( + + {selectedModel?.title ?? `Select ${displayName} model`} + + )} - return ( - setHoveredIdx(idx)} - onMouseLeave={() => setHoveredIdx(null)} - onClick={(e: any) => - handleOptionClick(showMissingApiKeyMsg, e) - } - className={""} - > -
-
-
- - - {option.title} - {showMissingApiKeyMsg && ( - - (Missing API key) + {models.length > 0 && ( +
+
+ )} + + + + {[...models] + .sort((a, b) => a.title.localeCompare(b.title)) + .map((option, idx) => { + const showMissingApiKeyMsg = + option.configurationStatus === + LLMConfigurationStatuses.MISSING_API_KEY; + + return ( + setHoveredIdx(idx)} + onMouseLeave={() => setHoveredIdx(null)} + onClick={(e: any) => + handleOptionClick(showMissingApiKeyMsg, e) + } + className="" + > +
+
+
+ + + {option.title} + {showMissingApiKeyMsg && ( + + (Missing API key) + + )} - )} - +
+ +
+ {hoveredIdx === idx && ( + + )} + {option.title === selectedModel?.title && ( + + )} +
+
-
- {hoveredIdx === idx && ( - - )} - {option.title === selectedModel?.title && ( - - )} -
-
-
- - ); - })} - - + + ); + })} + + + + )}
diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index f2caf727c..b369e0a53 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -49,6 +49,7 @@ import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; +import { OnboardingModes } from "core/protocol/core"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; @@ -201,9 +202,9 @@ export function Chat() { // "You've reached the free trial limit. Please configure a model to continue.", // ); - // // Card in chat will only show if no history - // // Also, note that platform card ignore the "Best", always opens to main tab - // onboardingCard.open("Best"); + // Card in chat will only show if no history + // Also, note that platform card ignore the "Best", always opens to main tab + onboardingCard.open(OnboardingModes.API_KEY); // // If history, show the dialog, which will automatically close if there is not history // if (history.length) { diff --git a/gui/src/pages/gui/EmptyChatBody.tsx b/gui/src/pages/gui/EmptyChatBody.tsx index ac8ba7631..54185f597 100644 --- a/gui/src/pages/gui/EmptyChatBody.tsx +++ b/gui/src/pages/gui/EmptyChatBody.tsx @@ -1,7 +1,6 @@ import { ConversationStarterCards } from "../../components/ConversationStarters"; import { ExploreHubCard } from "../../components/ExploreHubCard"; import { OnboardingCard } from "../../components/OnboardingCard"; -import { PlatformOnboardingCard } from "../../components/OnboardingCard/platform/PlatformOnboardingCard"; export interface EmptyChatBodyProps { showOnboardingCard?: boolean; @@ -11,12 +10,7 @@ export function EmptyChatBody({ showOnboardingCard }: EmptyChatBodyProps) { if (showOnboardingCard) { return (
- {true ? ( - // For now we are excluding local onboarding options other than ollama - - ) : ( - - )} +
); } diff --git a/gui/src/redux/slices/configSlice.ts b/gui/src/redux/slices/configSlice.ts index 0c78a27e0..b26d596c8 100644 --- a/gui/src/redux/slices/configSlice.ts +++ b/gui/src/redux/slices/configSlice.ts @@ -8,7 +8,7 @@ export type ConfigState = { config: BrowserSerializedContinueConfig; }; -const EMPTY_CONFIG: BrowserSerializedContinueConfig = { +export const EMPTY_CONFIG: BrowserSerializedContinueConfig = { slashCommands: [ { name: "share", diff --git a/gui/src/redux/thunks/index.ts b/gui/src/redux/thunks/index.ts index 81c3e937c..43e35fd21 100644 --- a/gui/src/redux/thunks/index.ts +++ b/gui/src/redux/thunks/index.ts @@ -4,6 +4,7 @@ export * from "./cancelStream"; export * from "./edit"; export * from "./gatherContext"; export * from "./resetStateForNewMessage"; +export * from "./selectFirstHubProfile"; export * from "./streamNormalInput"; export * from "./streamResponse"; export * from "./streamResponseAfterToolCall"; diff --git a/gui/src/redux/thunks/selectFirstHubProfile.ts b/gui/src/redux/thunks/selectFirstHubProfile.ts new file mode 100644 index 000000000..d1715ed98 --- /dev/null +++ b/gui/src/redux/thunks/selectFirstHubProfile.ts @@ -0,0 +1,56 @@ +import { createAsyncThunk } from "@reduxjs/toolkit"; +import { setSelectedProfile } from "../slices"; +import { ThunkApiType } from "../store"; + +/** + * If there is a hub profile, select it. + * Used primarily after onboarding when a new profile is created and we + * want to switch to it immediately + */ +export const selectFirstHubProfile = createAsyncThunk< + void, + undefined, + ThunkApiType +>("selectFirstHubProfile", async (_, { dispatch, extra, getState }) => { + let attempts = 0; + const maxAttempts = 3; + + const findAndSelectProfile = () => { + const state = getState(); + + const currentOrgProfiles = state.profiles.organizations.find( + (org) => org.id === (state.profiles.selectedOrganizationId ?? "personal"), + ); + + const firstHubProfile = currentOrgProfiles?.profiles.find( + (profile) => profile.profileType === "platform", + ); + + if (firstHubProfile) { + dispatch(setSelectedProfile(firstHubProfile.id)); + extra.ideMessenger.post("didChangeSelectedProfile", { + id: firstHubProfile.id, + }); + return true; + } + + return false; + }; + + // Try immediately first + if (findAndSelectProfile()) { + return; + } + + // If not found, poll every second for up to maxAttempts + return new Promise((resolve) => { + const interval = setInterval(() => { + attempts++; + + if (findAndSelectProfile() || attempts >= maxAttempts) { + clearInterval(interval); + resolve(); + } + }, 1000); + }); +}); diff --git a/gui/src/util/toolCallState.test.ts b/gui/src/util/toolCallState.test.ts index 86ee6914c..3207b606a 100644 --- a/gui/src/util/toolCallState.test.ts +++ b/gui/src/util/toolCallState.test.ts @@ -57,6 +57,129 @@ describe("addToolCallDeltaToState", () => { expect(result.toolCall.function.name).toBe("searchFiles"); }); + it("should handle name streaming in full progressive chunks", () => { + // Test case where model streams the name progressively but includes full prefix each time + // e.g. "readFi" -> "readFil" -> "readFile" + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "readFi", + arguments: "{}", + }, + }, + toolCallId: "call123", + parsedArgs: {}, + }; + + const delta: ToolCallDelta = { + function: { + name: "readFil", + }, + }; + + const result = addToolCallDeltaToState(delta, currentState); + expect(result.toolCall.function.name).toBe("readFil"); + + // Continue the streaming + const nextDelta: ToolCallDelta = { + function: { + name: "readFile", + }, + }; + + const finalResult = addToolCallDeltaToState(nextDelta, result); + expect(finalResult.toolCall.function.name).toBe("readFile"); + }); + + it("should keep original name when receiving duplicate name chunks", () => { + // Test case where model streams the complete name multiple times + // e.g. "readFile" -> "readFile" -> "readFile" + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "readFile", + arguments: "{}", + }, + }, + toolCallId: "call123", + parsedArgs: {}, + }; + + const delta: ToolCallDelta = { + function: { + name: "readFile", + }, + }; + + const result = addToolCallDeltaToState(delta, currentState); + expect(result.toolCall.function.name).toBe("readFile"); + }); + + it("should handle partial name streaming", () => { + // Test case where model streams the name in parts + // e.g. "read" -> "File" + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "read", + arguments: "{}", + }, + }, + toolCallId: "call123", + parsedArgs: {}, + }; + + const delta: ToolCallDelta = { + function: { + name: "File", + }, + }; + + const result = addToolCallDeltaToState(delta, currentState); + expect(result.toolCall.function.name).toBe("readFile"); + }); + + it("should ignore new tool calls with different IDs", () => { + const currentState: ToolCallState = { + status: "generating", + toolCall: { + id: "call123", + type: "function", + function: { + name: "searchFiles", + arguments: '{"query":"test"}', + }, + }, + toolCallId: "call123", + parsedArgs: { query: "test" }, + }; + + const delta: ToolCallDelta = { + id: "call456", // Different ID + type: "function", + function: { + name: "readFile", + arguments: '{"path":"file.txt"}', + }, + }; + + const result = addToolCallDeltaToState(delta, currentState); + + // Should keep the original state and ignore the new call + expect(result).toBe(currentState); + expect(result.toolCall.id).toBe("call123"); + expect(result.toolCall.function.name).toBe("searchFiles"); + }); + it("should merge function argument deltas correctly", () => { const currentState: ToolCallState = { status: "generating", diff --git a/gui/src/util/toolCallState.ts b/gui/src/util/toolCallState.ts index 1456be3f9..e42ac6430 100644 --- a/gui/src/util/toolCallState.ts +++ b/gui/src/util/toolCallState.ts @@ -8,6 +8,15 @@ export function addToolCallDeltaToState( toolCallDelta: ToolCallDelta, currentState: ToolCallState | undefined, ): ToolCallState { + // This prevents multiple tool calls for now, by ignoring new tool call ids + if ( + toolCallDelta.id && + currentState?.toolCallId && + toolCallDelta.id !== currentState?.toolCallId + ) { + return currentState; + } + const currentCall = currentState?.toolCall; // These will/should not be partially streamed @@ -21,9 +30,18 @@ export function addToolCallDeltaToState( const nameDelta = toolCallDelta.function?.name ?? ""; const argsDelta = toolCallDelta.function?.arguments ?? ""; - // Some models may include the name repeatedly. This doesn't account for an edge case where the name is like "dothisdothis" and it happens to stream name in chunks "dothis" and "dothis" but that's a super edge case - const mergedName = - currentName === nameDelta ? currentName : currentName + nameDelta; + let mergedName = currentName; + if (nameDelta.startsWith(currentName)) { + // Case where model progresssively streams name but full name each time e.g. "readFi" -> "readFil" -> "readFile" + mergedName = nameDelta; + } else if (currentName.startsWith(nameDelta)) { + // Case where model streams in full name each time e.g. readFile -> readFile -> readFile + // do nothing + } else { + // Case where model streams in name in parts e.g. "read" -> "File" + mergedName = currentName + nameDelta; + } + const mergedArgs = currentArgs + argsDelta; const [_, parsedArgs] = incrementalParseJson(mergedArgs || "{}"); diff --git a/manual-testing-sandbox/requirements.txt b/manual-testing-sandbox/requirements.txt index 44147f676..55452b992 100644 --- a/manual-testing-sandbox/requirements.txt +++ b/manual-testing-sandbox/requirements.txt @@ -5,7 +5,7 @@ scipy==1.7.1 # Web development flask==2.0.2 -django==3.2.7 +django==4.2.22 # Request handling requests==2.26.0 diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 0b5003473..9d3040721 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -1,4 +1,5 @@ import * as YAML from "yaml"; +import { ZodError } from "zod"; import { PlatformClient, Registry } from "../interfaces/index.js"; import { encodeSecretLocation } from "../interfaces/SecretResult.js"; import { @@ -17,6 +18,7 @@ import { configYamlSchema, Rule, } from "../schemas/index.js"; +import { ConfigResult, ConfigValidationError } from "../validation.js"; import { packageIdentifierToShorthandSlug, useProxyForUnrenderedSecrets, @@ -30,16 +32,25 @@ export function parseConfigYaml(configYaml: string): ConfigYaml { if (result.success) { return result.data; } - throw new Error( - result.error.errors - .map((e) => `${e.path.join(".")}: ${e.message}`) - .join(""), - ); + + throw new Error(formatZodError(result.error), { + cause: "result.success was false", + }); } catch (e) { - console.log("Failed to parse rolled assistant:", configYaml); - throw new Error( - `Failed to parse assistant:\n${e instanceof Error ? e.message : e}`, - ); + console.error("Failed to parse rolled assistant:", configYaml); + if ( + e instanceof Error && + "cause" in e && + e.cause === "result.success was false" + ) { + throw new Error(`Failed to parse assistant: ${e.message}`); + } else if (e instanceof ZodError) { + throw new Error(`Failed to parse assistant: ${formatZodError(e)}`); + } else { + throw new Error( + `Failed to parse assistant: ${e instanceof Error ? e.message : e}`, + ); + } } } @@ -49,9 +60,10 @@ export function parseAssistantUnrolled(configYaml: string): AssistantUnrolled { const result = assistantUnrolledSchema.parse(parsed); return result; } catch (e: any) { - throw new Error( + console.error( `Failed to parse unrolled assistant: ${e.message}\n\n${configYaml}`, ); + throw new Error(`Failed to parse unrolled assistant: ${formatZodError(e)}`); } } @@ -61,7 +73,7 @@ export function parseBlock(configYaml: string): Block { const result = blockSchema.parse(parsed); return result; } catch (e: any) { - throw new Error(`Failed to parse block: ${e.message}`); + throw new Error(`Failed to parse block: ${formatZodError(e)}`); } } @@ -183,6 +195,7 @@ async function extractRenderedSecretsMap( export interface BaseUnrollAssistantOptions { renderSecrets: boolean; injectBlocks?: PackageIdentifier[]; + asConfigResult?: true; } export interface DoNotRenderSecretsUnrollAssistantOptions @@ -204,14 +217,30 @@ export type UnrollAssistantOptions = | DoNotRenderSecretsUnrollAssistantOptions | RenderSecretsUnrollAssistantOptions; +// Overload to satisfy existing consumers of unrollAssistant. +export async function unrollAssistant( + id: PackageIdentifier, + registry: Registry, + options: UnrollAssistantOptions & { asConfigResult: true }, +): Promise>; + export async function unrollAssistant( id: PackageIdentifier, registry: Registry, options: UnrollAssistantOptions, -): Promise { +): Promise; + +export async function unrollAssistant( + id: PackageIdentifier, + registry: Registry, + options: UnrollAssistantOptions, +): Promise> { // Request the content from the registry const rawContent = await registry.getContent(id); - return unrollAssistantFromContent(id, rawContent, registry, options); + + const result = unrollAssistantFromContent(id, rawContent, registry, options); + + return result; } function renderTemplateData( @@ -236,7 +265,7 @@ export async function unrollAssistantFromContent( rawYaml: string, registry: Registry, options: UnrollAssistantOptions, -): Promise { +): Promise> { // Parse string to Zod-validated YAML let parsedYaml = parseConfigYaml(rawYaml); @@ -245,10 +274,15 @@ export async function unrollAssistantFromContent( parsedYaml, registry, options.injectBlocks, + options.asConfigResult ?? false, ); // Back to a string so we can fill in template variables - const rawUnrolledYaml = YAML.stringify(unrolledAssistant); + const rawUnrolledYaml = options.asConfigResult + ? YAML.stringify( + (unrolledAssistant as ConfigResult).config, + ) + : YAML.stringify(unrolledAssistant); // Convert all of the template variables to FQSNs // Secrets from the block will have the assistant slug prepended to the FQSN @@ -277,6 +311,17 @@ export async function unrollAssistantFromContent( options.orgScopeId, options.onPremProxyUrl, ); + + if (options.asConfigResult) { + return { + config: finalConfig, + errors: (unrolledAssistant as ConfigResult).errors, + configLoadInterrupted: ( + unrolledAssistant as ConfigResult + ).configLoadInterrupted, + }; + } + return finalConfig; } @@ -284,7 +329,10 @@ export async function unrollBlocks( assistant: ConfigYaml, registry: Registry, injectBlocks: PackageIdentifier[] | undefined, -): Promise { + asConfigError: boolean, +): Promise> { + const errors: ConfigValidationError[] = []; + const unrolledAssistant: AssistantUnrolled = { name: assistant.name, version: assistant.version, @@ -316,8 +364,23 @@ export async function unrollBlocks( ); } } catch (err) { + let msg = ""; + if ( + typeof unrolledBlock.uses !== "string" && + "filePath" in unrolledBlock.uses + ) { + msg = `${(err as Error).message}.\n> ${unrolledBlock.uses.filePath}`; + } else { + msg = `${(err as Error).message}.\n> ${JSON.stringify(unrolledBlock.uses)}`; + } + + errors.push({ + fatal: false, + message: msg, + }); + console.error( - `Failed to unroll block ${unrolledBlock.uses}: ${(err as Error).message}`, + `Failed to unroll block ${JSON.stringify(unrolledBlock.uses)}: ${(err as Error).message}`, ); sectionBlocks.push(null); } @@ -349,6 +412,11 @@ export async function unrollBlocks( rules.push(block); } } catch (err) { + errors.push({ + fatal: false, + message: `${(err as Error).message}:\n${rule.uses}`, + }); + console.error( `Failed to unroll block ${rule.uses}: ${(err as Error).message}`, ); @@ -381,12 +449,36 @@ export async function unrollBlocks( ); } } catch (err) { + let msg = ""; + if (injectBlock.uriType === "file") { + msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`; + } else { + msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`; + } + errors.push({ + fatal: false, + message: msg, + }); + console.error( - `Failed to unroll block ${injectBlock}: ${(err as Error).message}`, + `Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`, ); } } + if (asConfigError) { + const configResult: ConfigResult = { + config: undefined, + errors: undefined, + configLoadInterrupted: false, + }; + configResult.config = unrolledAssistant; + if (errors.length > 0) { + configResult.errors = errors; + } + return configResult; + } + return unrolledAssistant; } @@ -439,3 +531,15 @@ export function mergeOverrides>( } return block; } + +function formatZodError(error: any): string { + if (error.errors && Array.isArray(error.errors)) { + return error.errors + .map((e: any) => { + const path = e.path.length > 0 ? `${e.path.join(".")}: ` : ""; + return `${path}${e.message}`; + }) + .join(", "); + } + return error.message || "Validation failed"; +} diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 816697f62..3dbbf5840 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -13,7 +13,7 @@ export const contextSchema = z.object({ const mcpServerSchema = z.object({ name: z.string(), command: z.string().optional(), - type: z.enum(["sse", "stdio"]).optional(), + type: z.enum(["sse", "stdio", "streamable-http"]).optional(), url: z.string().optional(), faviconUrl: z.string().optional(), args: z.array(z.string()).optional(), diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 242baa737..893f7117a 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -106,6 +106,17 @@ const templateSchema = z.enum([ "codestral", ]); +export const autocompleteOptionsSchema = z.object({ + disable: z.boolean().optional(), + maxPromptTokens: z.number().optional(), + debounceDelay: z.number().optional(), + modelTimeout: z.number().optional(), + maxSuffixPercentage: z.number().optional(), + prefixPercentage: z.number().optional(), + template: z.string().optional(), + onlyMyCode: z.boolean().optional(), +}); + /** Prompt templates use Handlebars syntax */ const promptTemplatesSchema = z.object({ apply: z.string().optional(), @@ -133,6 +144,7 @@ const baseModelFields = { env: z .record(z.string(), z.union([z.string(), z.boolean(), z.number()])) .optional(), + autocompleteOptions: autocompleteOptionsSchema.optional(), }; export const modelSchema = z.union([ diff --git a/packages/fetch/package-lock.json b/packages/fetch/package-lock.json index 58a83593b..1bf3a3a0b 100644 --- a/packages/fetch/package-lock.json +++ b/packages/fetch/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/fetch", - "version": "1.0.12", + "version": "1.0.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/fetch", - "version": "1.0.12", + "version": "1.0.13", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.5", @@ -17,8 +17,6 @@ }, "devDependencies": { "@types/follow-redirects": "^1.14.4", - "cross-env": "^7.0.3", - "ts-node": "^10.9.2", "vitest": "^3.2.0" } }, @@ -30,28 +28,6 @@ "zod": "^3.23.8" } }, - "node_modules/@cspotcode/source-map-support": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", - "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", - "dev": true, - "dependencies": { - "@jridgewell/trace-mapping": "0.3.9" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": { - "version": "0.3.9", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", - "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", - "dev": true, - "dependencies": { - "@jridgewell/resolve-uri": "^3.0.3", - "@jridgewell/sourcemap-codec": "^1.4.10" - } - }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz", @@ -452,15 +428,6 @@ "node": ">=18" } }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", @@ -727,30 +694,6 @@ "win32" ] }, - "node_modules/@tsconfig/node10": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz", - "integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==", - "dev": true - }, - "node_modules/@tsconfig/node12": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", - "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", - "dev": true - }, - "node_modules/@tsconfig/node14": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", - "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", - "dev": true - }, - "node_modules/@tsconfig/node16": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", - "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", - "dev": true - }, "node_modules/@types/chai": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.2.tgz", @@ -897,30 +840,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/acorn": { - "version": "8.14.1", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", - "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", - "dev": true, - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-walk": { - "version": "8.3.4", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz", - "integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==", - "dev": true, - "dependencies": { - "acorn": "^8.11.0" - }, - "engines": { - "node": ">=0.4.0" - } - }, "node_modules/agent-base": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz", @@ -932,12 +851,6 @@ "node": ">= 14" } }, - "node_modules/arg": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", - "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", - "dev": true - }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -981,44 +894,6 @@ "node": ">= 16" } }, - "node_modules/create-require": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", - "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", - "dev": true - }, - "node_modules/cross-env": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", - "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.1" - }, - "bin": { - "cross-env": "src/bin/cross-env.js", - "cross-env-shell": "src/bin/cross-env-shell.js" - }, - "engines": { - "node": ">=10.14", - "npm": ">=6", - "yarn": ">=1" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", - "dev": true, - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/data-uri-to-buffer": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", @@ -1052,15 +927,6 @@ "node": ">=6" } }, - "node_modules/diff": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", - "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", - "dev": true, - "engines": { - "node": ">=0.3.1" - } - }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -1215,12 +1081,6 @@ "node": ">= 14" } }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true - }, "node_modules/loupe": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.1.3.tgz", @@ -1236,12 +1096,6 @@ "@jridgewell/sourcemap-codec": "^1.5.0" } }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true - }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -1300,15 +1154,6 @@ "url": "https://opencollective.com/node-fetch" } }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/pathe": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", @@ -1397,27 +1242,6 @@ "fsevents": "~2.3.2" } }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/siginfo": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", @@ -1526,75 +1350,12 @@ "node": ">=14.0.0" } }, - "node_modules/ts-node": { - "version": "10.9.2", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", - "integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==", - "dev": true, - "dependencies": { - "@cspotcode/source-map-support": "^0.8.0", - "@tsconfig/node10": "^1.0.7", - "@tsconfig/node12": "^1.0.7", - "@tsconfig/node14": "^1.0.0", - "@tsconfig/node16": "^1.0.2", - "acorn": "^8.4.1", - "acorn-walk": "^8.1.1", - "arg": "^4.1.0", - "create-require": "^1.1.0", - "diff": "^4.0.1", - "make-error": "^1.1.1", - "v8-compile-cache-lib": "^3.0.1", - "yn": "3.1.1" - }, - "bin": { - "ts-node": "dist/bin.js", - "ts-node-cwd": "dist/bin-cwd.js", - "ts-node-esm": "dist/bin-esm.js", - "ts-node-script": "dist/bin-script.js", - "ts-node-transpile-only": "dist/bin-transpile.js", - "ts-script": "dist/bin-script-deprecated.js" - }, - "peerDependencies": { - "@swc/core": ">=1.2.50", - "@swc/wasm": ">=1.2.50", - "@types/node": "*", - "typescript": ">=2.7" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "@swc/wasm": { - "optional": true - } - } - }, - "node_modules/typescript": { - "version": "5.8.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz", - "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", - "dev": true, - "peer": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, "node_modules/undici-types": { "version": "5.26.5", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", "dev": true }, - "node_modules/v8-compile-cache-lib": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", - "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", - "dev": true - }, "node_modules/vite": { "version": "6.3.5", "resolved": "https://registry.npmjs.org/vite/-/vite-6.3.5.tgz", @@ -1809,21 +1570,6 @@ "node": ">= 8" } }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "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", @@ -1840,15 +1586,6 @@ "node": ">=8" } }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/zod": { "version": "3.23.8", "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz", diff --git a/packages/fetch/package.json b/packages/fetch/package.json index 9300bb2a2..f17bcfc69 100644 --- a/packages/fetch/package.json +++ b/packages/fetch/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/fetch", - "version": "1.0.12", + "version": "1.0.13", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/fetch/src/fetch.ts b/packages/fetch/src/fetch.ts index 9bf0d77ed..3b145012f 100644 --- a/packages/fetch/src/fetch.ts +++ b/packages/fetch/src/fetch.ts @@ -2,8 +2,9 @@ import { RequestOptions } from "@continuedev/config-types"; import * as followRedirects from "follow-redirects"; import { HttpProxyAgent } from "http-proxy-agent"; import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch, { BodyInit, RequestInit, Response } from "node-fetch"; +import { BodyInit, RequestInit, Response } from "node-fetch"; import { getAgentOptions } from "./getAgentOptions.js"; +import fetch from "./node-fetch-patch.js"; import { getProxyFromEnv, shouldBypassProxy } from "./util.js"; const { http, https } = (followRedirects as any).default; diff --git a/packages/fetch/src/node-fetch-patch.js b/packages/fetch/src/node-fetch-patch.js new file mode 100644 index 000000000..10bb96531 --- /dev/null +++ b/packages/fetch/src/node-fetch-patch.js @@ -0,0 +1,518 @@ +/* +This is a patched version of index.js from node-fetch 3.3.2 (see packages/fetch/node_modules/node-fetch/src/index.js) +This is to fix "Premature close" errors caused by chunked encoding assumptions - see https://github.com/continuedev/continue/issues/5502 +The patch adjusts boundary chunk detection logic (see "PATCH" comment next to patch) +And is based on https://github.com/node-fetch/node-fetch/issues/1576 +*/ + +/** + * Index.js + * + * a request API compatible with window.fetch + * + * All spec algorithm step numbers are based on https://fetch.spec.whatwg.org/commit-snapshots/ae716822cb3a61843226cd090eefc6589446c1d2/. + */ + +import { Buffer } from "node:buffer"; +import http from "node:http"; +import https from "node:https"; +import Stream, { PassThrough, pipeline as pump } from "node:stream"; +import zlib from "node:zlib"; + +import dataUriToBuffer from "data-uri-to-buffer"; + +import { + Blob, + blobFrom, + blobFromSync, + File, + fileFrom, + fileFromSync, +} from "fetch-blob/from.js"; +import { FormData } from "formdata-polyfill/esm.min.js"; +import { clone, writeToStream } from "node-fetch/src/body.js"; +import { AbortError } from "node-fetch/src/errors/abort-error.js"; +import { FetchError } from "node-fetch/src/errors/fetch-error.js"; +import Headers, { fromRawHeaders } from "node-fetch/src/headers.js"; +import Request, { getNodeRequestOptions } from "node-fetch/src/request.js"; +import Response from "node-fetch/src/response.js"; +import { isRedirect } from "node-fetch/src/utils/is-redirect.js"; +import { + isDomainOrSubdomain, + isSameProtocol, +} from "node-fetch/src/utils/is.js"; +import { parseReferrerPolicyFromHeader } from "node-fetch/src/utils/referrer.js"; + +export { + AbortError, + Blob, + blobFrom, + blobFromSync, + FetchError, + File, + fileFrom, + fileFromSync, + FormData, + Headers, + isRedirect, + Request, + Response, +}; + +const supportedSchemas = new Set(["data:", "http:", "https:"]); + +/** + * Fetch function + * + * @param {string | URL | import('./request').default} url - Absolute url or Request instance + * @param {*} [options_] - Fetch options + * @return {Promise} + */ +export default async function fetch(url, options_) { + return new Promise((resolve, reject) => { + // Build request object + const request = new Request(url, options_); + const { parsedURL, options } = getNodeRequestOptions(request); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError( + `node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`, + ); + } + + if (parsedURL.protocol === "data:") { + const data = dataUriToBuffer(request.url); + const response = new Response(data, { + headers: { "Content-Type": data.typeFull }, + }); + resolve(response); + return; + } + + // Wrap http.request into fetch + const send = (parsedURL.protocol === "https:" ? https : http).request; + const { signal } = request; + let response = null; + + const abort = () => { + const error = new AbortError("The operation was aborted."); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + request.body.destroy(error); + } + + if (!response || !response.body) { + return; + } + + response.body.emit("error", error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = () => { + abort(); + finalize(); + }; + + // Send request + const request_ = send(parsedURL.toString(), options); + + if (signal) { + signal.addEventListener("abort", abortAndFinalize); + } + + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); + } + }; + + request_.on("error", (error) => { + reject( + new FetchError( + `request to ${request.url} failed, reason: ${error.message}`, + "system", + error, + ), + ); + finalize(); + }); + + fixResponseChunkedTransferBadEnding(request_, (error) => { + if (response && response.body) { + response.body.destroy(error); + } + }); + + /* c8 ignore next 18 */ + if (process.version < "v14") { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + request_.on("socket", (s) => { + let endedWithEventsCount; + s.prependListener("end", () => { + endedWithEventsCount = s._eventsCount; + }); + s.prependListener("close", (hadError) => { + // if end happened before close but the socket didn't emit an error, do it now + if (response && endedWithEventsCount < s._eventsCount && !hadError) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error); + } + }); + }); + } + + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + + // HTTP fetch step 5 + if (isRedirect(response_.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get("Location"); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = + location === null ? null : new URL(location, request.url); + } catch { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== "manual") { + reject( + new FetchError( + `uri requested responds with an invalid redirect URL: ${location}`, + "invalid-redirect", + ), + ); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case "error": + reject( + new FetchError( + `uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, + "no-redirect", + ), + ); + finalize(); + return; + case "manual": + // Nothing to do + break; + case "follow": { + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject( + new FetchError( + `maximum redirect reached at: ${request.url}`, + "max-redirect", + ), + ); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOptions = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: clone(request), + signal: request.signal, + size: request.size, + referrer: request.referrer, + referrerPolicy: request.referrerPolicy, + }; + + // when forwarding sensitive headers like "Authorization", + // "WWW-Authenticate", and "Cookie" to untrusted targets, + // headers will be ignored when following a redirect to a domain + // that is not a subdomain match or exact match of the initial domain. + // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com" + // will forward the sensitive headers, but a redirect to "bar.com" will not. + // headers will also be ignored when following a redirect to a domain using + // a different protocol. For example, a redirect from "https://foo.com" to "http://foo.com" + // will not forward the sensitive headers + if ( + !isDomainOrSubdomain(request.url, locationURL) || + !isSameProtocol(request.url, locationURL) + ) { + for (const name of [ + "authorization", + "www-authenticate", + "cookie", + "cookie2", + ]) { + requestOptions.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if ( + response_.statusCode !== 303 && + request.body && + options_.body instanceof Stream.Readable + ) { + reject( + new FetchError( + "Cannot follow redirect with body being a readable stream", + "unsupported-redirect", + ), + ); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if ( + response_.statusCode === 303 || + ((response_.statusCode === 301 || response_.statusCode === 302) && + request.method === "POST") + ) { + requestOptions.method = "GET"; + requestOptions.body = undefined; + requestOptions.headers.delete("content-length"); + } + + // HTTP-redirect fetch step 14 + const responseReferrerPolicy = + parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + + default: + return reject( + new TypeError( + `Redirect option '${request.redirect}' is not a valid value of RequestRedirect`, + ), + ); + } + } + + // Prepare response + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); + } + + let body = pump(response_, new PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + // see https://github.com/nodejs/node/pull/29376 + /* c8 ignore next 3 */ + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + + const responseOptions = { + url: request.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request.size, + counter: request.counter, + highWaterMark: request.highWaterMark, + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get("Content-Encoding"); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if ( + !request.compress || + request.method === "HEAD" || + codings === null || + response_.statusCode === 204 || + response_.statusCode === 304 + ) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH, + }; + + // For gzip + if (codings === "gzip" || codings === "x-gzip") { + body = pump(body, zlib.createGunzip(zlibOptions), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // For deflate + if (codings === "deflate" || codings === "x-deflate") { + // Handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = pump(response_, new PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + raw.once("data", (chunk) => { + // See http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0f) === 0x08) { + body = pump(body, zlib.createInflate(), (error) => { + if (error) { + reject(error); + } + }); + } else { + body = pump(body, zlib.createInflateRaw(), (error) => { + if (error) { + reject(error); + } + }); + } + + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once("end", () => { + // Some old IIS servers return zero-length OK deflate responses, so + // 'data' is never emitted. See https://github.com/node-fetch/node-fetch/pull/903 + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + + // For br + if (codings === "br") { + body = pump(body, zlib.createBrotliDecompress(), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + + // Otherwise, use response as-is + response = new Response(body, responseOptions); + resolve(response); + }); + + // eslint-disable-next-line promise/prefer-await-to-then + writeToStream(request_, request).catch(reject); + }); +} + +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + const LAST_CHUNK = Buffer.from("0\r\n\r\n"); + + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + + request.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = + headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + + request.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error); + } + }; + + // const onData = buf => { + // properLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + + // // Sometimes final 0-length chunk and end of message code are in separate packets + // if (!properLastChunkReceived && previousChunk) { + // properLastChunkReceived = ( + // Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && + // Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0 + // ); + // } + + // previousChunk = buf; + // }; + + // PATCH - THIS IS WHERE THE PATCH IS - FIXES BOUNDARY CHUNKING ISSUE + // See https://github.com/node-fetch/node-fetch/issues/1576 + const onData = (buf) => { + properLastChunkReceived = Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + + // Sometimes final 0-length chunk and end of message code are in separate packets + if (!properLastChunkReceived && previousChunk) { + if (buf.length < 5) { + properLastChunkReceived = + Buffer.compare( + Buffer.from([...previousChunk.slice(-5), ...buf]).slice(-5), + LAST_CHUNK, + ) === 0; + } + } + + previousChunk = buf; + }; + + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + + request.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} diff --git a/packages/fetch/src/node-fetch-patch.test.js b/packages/fetch/src/node-fetch-patch.test.js new file mode 100644 index 000000000..21f930ecb --- /dev/null +++ b/packages/fetch/src/node-fetch-patch.test.js @@ -0,0 +1,67 @@ +import { Buffer } from "node:buffer"; +import { describe, expect, it } from "vitest"; + +// Tests the boundary chunking patch to node fetch made in node-fetch-patch.js (see that file for details). +describe("Chunked Transfer Encoding Patch Logic", () => { + // The LAST_CHUNK marker "0\r\n\r\n" + const LAST_CHUNK = Buffer.from("0\r\n\r\n"); + + it("should detect complete marker at the end (normal case)", () => { + const normalCase = Buffer.from("data data data 0\r\n\r\n"); + const result = Buffer.compare(normalCase.slice(-5), LAST_CHUNK) === 0; + expect(result).toBe(true); + }); + + it("should handle chunks split across original pattern (0\\r\\n | \\r\\n)", () => { + const previousChunk = Buffer.from("data data 0\r\n"); + const lastChunk = Buffer.from("\r\n"); + + const result = + Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && + Buffer.compare(lastChunk.slice(-2), LAST_CHUNK.slice(3)) === 0; + + expect(result).toBe(true); + }); + + it("should handle problematic case from issue #1576 with new patch", () => { + // The problematic case: data ends with "0\r\n0\r" and the next chunk is "\n\r\n" + const previousChunk = Buffer.from([ + ...Array(10).fill(42), + 48, + 13, + 10, + 48, + 13, + ]); // some data + "0\r\n0\r" + const lastChunk = Buffer.from([10, 13, 10]); // "\n\r\n" + + // Check 1: Direct check for complete marker (should fail) + const check1 = Buffer.compare(lastChunk.slice(-5), LAST_CHUNK) === 0; + expect(check1).toBe(false); + + // Check 2: Original split pattern check (should fail) + const check2 = + Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && + Buffer.compare(lastChunk.slice(-2), LAST_CHUNK.slice(3)) === 0; + expect(check2).toBe(false); + + // Check 3: New patch check (should pass) + const lastChunkLength = lastChunk.length; + const newPatchCheck = + lastChunkLength < 5 && + Buffer.compare( + Buffer.from([...previousChunk.slice(-5), ...lastChunk]).slice(-5), + LAST_CHUNK, + ) === 0; + expect(newPatchCheck).toBe(true); + + // Verification of the combined buffer + const combinedBuffer = Buffer.from([ + ...previousChunk.slice(-5), + ...lastChunk, + ]); + const combinedResult = + Buffer.compare(combinedBuffer.slice(-5), LAST_CHUNK) === 0; + expect(combinedResult).toBe(true); + }); +}); diff --git a/packages/llm-info/package-lock.json b/packages/llm-info/package-lock.json index 80db35a66..e067640dd 100644 --- a/packages/llm-info/package-lock.json +++ b/packages/llm-info/package-lock.json @@ -1,17 +1,28 @@ { "name": "@continuedev/llm-info", - "version": "1.0.6", + "version": "1.0.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/llm-info", - "version": "1.0.6", + "version": "1.0.9", "license": "Apache-2.0", "devDependencies": { + "@types/node": "^22.15.29", "typescript": "^5.5.2" } }, + "node_modules/@types/node": { + "version": "22.15.29", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.15.29.tgz", + "integrity": "sha512-LNdjOkUDlU1RZb8e1kOIUpN1qQUlzGkEtbVNo53vbrwDg5om6oduhm4SiUaPW5ASTXhAiP0jInWG8Qx9fVlOeQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, "node_modules/typescript": { "version": "5.6.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", @@ -24,6 +35,13 @@ "engines": { "node": ">=14.17" } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" } } } diff --git a/packages/llm-info/package.json b/packages/llm-info/package.json index 64061fe97..75989edbb 100644 --- a/packages/llm-info/package.json +++ b/packages/llm-info/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/llm-info", - "version": "1.0.8", + "version": "1.0.9", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -12,7 +12,7 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "devDependencies": { + "@types/node": "^22.15.29", "typescript": "^5.5.2" - }, - "dependencies": {} + } } diff --git a/packages/llm-info/src/providers/gemini.ts b/packages/llm-info/src/providers/gemini.ts index 25af94688..214ad1299 100644 --- a/packages/llm-info/src/providers/gemini.ts +++ b/packages/llm-info/src/providers/gemini.ts @@ -1,10 +1,45 @@ import { AllMediaTypes, ModelProvider } from "../types.js"; +// See https://ai.google.dev/gemini-api/docs/models export const Gemini: ModelProvider = { models: [ { - model: "gemini-2.0-flash", + model: "gemini-2.5-pro-preview-05-06", + displayName: "Gemini 2.5 Pro Preview", + description: + "Google's most advanced model with strong reasoning, multimodal capabilities, and advanced coding skills", + contextLength: 1048576, + maxCompletionTokens: 65536, + mediaTypes: AllMediaTypes, + regex: /gemini-2\.5-pro-preview/i, + recommendedFor: ["chat"], + }, + { + model: "gemini-2.5-pro-exp-03-25", + displayName: "Gemini 2.5 Pro Experimental", + description: + "Experimental release of Gemini 2.5 Pro with 1M token context window", + contextLength: 1048576, + maxCompletionTokens: 65536, + mediaTypes: AllMediaTypes, + regex: /gemini-2\.5-pro-exp/i, + recommendedFor: ["chat"], + }, + { + model: "gemini-2.5-flash-preview-05-20", + displayName: "Gemini 2.5 Flash Preview", + description: + "Fast, token-efficient multimodal model for complex tasks with 1M context window", + contextLength: 1048576, + maxCompletionTokens: 65536, + mediaTypes: AllMediaTypes, + regex: /gemini-2\.5-flash-preview/i, + recommendedFor: ["chat"], + }, + { + model: "gemini-2.0-flash", // stable gemini-2.0-flash-001 displayName: "Gemini 2.0 Flash", + description: "Fast, efficient model with strong multimodal capabilities", contextLength: 1048576, maxCompletionTokens: 8192, mediaTypes: AllMediaTypes, @@ -12,58 +47,94 @@ export const Gemini: ModelProvider = { recommendedFor: ["chat"], }, { - model: "gemini-2.0-flash-lite", + model: "gemini-2.0-flash-lite", // stable gemini-2.0-flash-lite-001 displayName: "Gemini 2.0 Flash Lite", + description: + "Small, fast model with reduced latency and memory requirements", contextLength: 1048576, maxCompletionTokens: 8192, mediaTypes: AllMediaTypes, regex: /gemini-2\.0-flash-lite/i, recommendedFor: ["chat"], }, + { + model: "gemini-2.0-flash-preview-image-generation", + displayName: "Gemini 2.0 Flash Image Generation Preview", + description: + "Model with image generation capabilities and improved visual quality", + contextLength: 32000, + maxCompletionTokens: 8192, + mediaTypes: AllMediaTypes, + regex: /gemini-2\.0-flash-preview-image-generation/i, + recommendedFor: ["chat"], + }, { model: "gemini-2.0-flash-exp-image-generation", - displayName: "Gemini 2.0 Flash Image Generation", - contextLength: 32768, + displayName: "Gemini 2.0 Flash Image Generation Experimental", + description: "Experimental model with image generation capabilities", + contextLength: 32000, maxCompletionTokens: 8192, mediaTypes: AllMediaTypes, regex: /gemini-2\.0-flash-exp-image-generation/i, recommendedFor: ["chat"], }, { - model: "gemini-2.5-pro-exp-03-25", - displayName: "Gemini 2.5 Pro Exp", + model: "gemini-2.0-flash-exp", + displayName: "Gemini 2.0 Flash Experimental", + description: + "Experimental version of Gemini 2.0 Flash with extended capabilities", contextLength: 1048576, - maxCompletionTokens: 65536, + maxCompletionTokens: 8192, mediaTypes: AllMediaTypes, - regex: /gemini-2\.5-pro-exp-03-25/i, + regex: /gemini-2\.0-flash-exp/i, recommendedFor: ["chat"], }, { model: "gemini-1.5-flash", displayName: "Gemini 1.5 Flash", + description: "Fast multimodal model with 1M token context window", contextLength: 1048576, maxCompletionTokens: 8192, mediaTypes: AllMediaTypes, regex: /gemini-1\.5-flash/i, recommendedFor: ["chat"], }, + { + model: "gemini-1.5-flash-8b", + displayName: "Gemini 1.5 Flash 8b", + description: + "Smaller version of Gemini 1.5 Flash optimized for efficiency", + contextLength: 1048576, + maxCompletionTokens: 8192, + mediaTypes: AllMediaTypes, + regex: /gemini-1\.5-flash-8b/i, + recommendedFor: ["chat"], + }, { model: "gemini-1.5-pro", displayName: "Gemini 1.5 Pro", + description: + "Mid-size multimodal model capable of handling extensive inputs and complex reasoning tasks", contextLength: 2097152, maxCompletionTokens: 8192, + mediaTypes: AllMediaTypes, regex: /gemini-1\.5-pro/i, recommendedFor: ["chat"], }, { model: "gemini-1.0-pro", displayName: "Gemini 1.0 Pro", + description: "First generation Gemini pro model", + contextLength: 32768, + maxCompletionTokens: 8192, + mediaTypes: AllMediaTypes, regex: /gemini-1\.0-pro/i, }, // embed { model: "models/text-embedding-004", displayName: "Gemini Text Embedding", + description: "Text embedding model for vectorizing content", recommendedFor: ["embed"], }, ], diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 4eac677b3..1d88a8b5e 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1,18 +1,17 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.22", + "version": "1.0.36", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.22", + "version": "1.0.36", "license": "Apache-2.0", "dependencies": { - "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.11", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", @@ -43,126 +42,6 @@ "node": ">=6.0.0" } }, - "node_modules/@azure-rest/core-client": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz", - "integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.3.0", - "@azure/core-rest-pipeline": "^1.5.0", - "@azure/core-tracing": "^1.0.1", - "@azure/core-util": "^1.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/abort-controller": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", - "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-auth": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.7.2.tgz", - "integrity": "sha512-Igm/S3fDYmnMq1uKS38Ae1/m37B3zigdlZw+kocwEhh5GjyKjPrXKO2J6rzpC1wAxrNil/jX9BJRqBshyjnF3g==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-util": "^1.1.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-rest-pipeline": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.16.2.tgz", - "integrity": "sha512-Hnhm/PG9/SQ07JJyLDv3l9Qr8V3xgAe1hFoBYzt6LaalMxfL/ZqFaZf/bz5VN3pMcleCPwl8ivlS2Fjxq/iC8Q==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.4.0", - "@azure/core-tracing": "^1.0.1", - "@azure/core-util": "^1.9.0", - "@azure/logger": "^1.0.0", - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-sse": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.2.tgz", - "integrity": "sha512-yf+pFIu8yCzXu9RbH2+8kp9vITIKJLHgkLgFNA6hxiDHK3fxeP596cHUj4c8Cm8JlooaUnYdHmF84KCZt3jbmw==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-tracing": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.1.2.tgz", - "integrity": "sha512-dawW9ifvWAWmUm9/h+/UQ2jrdvjCJ7VJEuCJ6XVNudzcOwm53BFZH4Q845vjfgoUAM8ZxokvVNxNxAITc502YA==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-util": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.9.1.tgz", - "integrity": "sha512-OLsq0etbHO1MA7j6FouXFghuHrAFGk+5C1imcpQ2e+0oZhYF07WLA+NW2Vqs70R7d+zOAWiWM3tbE1sXcDN66g==", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/logger": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.3.tgz", - "integrity": "sha512-J8/cIKNQB1Fc9fuYqBVnrppiUtW+5WWJPCj/tAokC5LdSTwkWWttN+jsRgw9BLYD7JDBx7PceiqOBxJJ1tQz3Q==", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/openai": { - "version": "1.0.0-beta.12", - "resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.12.tgz", - "integrity": "sha512-qKblxr6oVa8GsyNzY+/Ub9VmEsPYKhBrUrPaNEQiM+qrxnBPVm9kaeqGFFb/U78Q2zOabmhF9ctYt3xBW0nWnQ==", - "dependencies": { - "@azure-rest/core-client": "^1.1.7", - "@azure/core-auth": "^1.4.0", - "@azure/core-rest-pipeline": "^1.13.0", - "@azure/core-sse": "^2.0.0", - "@azure/core-util": "^1.4.0", - "@azure/logger": "^1.0.3", - "tslib": "^2.4.0" - }, - "engines": { - "node": ">=18.0.0" - } - }, "node_modules/@babel/code-frame": { "version": "7.24.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", @@ -716,9 +595,9 @@ } }, "node_modules/@continuedev/fetch": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz", - "integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==", + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.11.tgz", + "integrity": "sha512-GRYqAdV3DhRxg463zeSzOdVIk/bhjuuxAxzX0fG35Kz6sHUsU2wr7SDY91zO2ataYUkjnbOa3q1xIpnRnOoRHA==", "dependencies": { "@continuedev/config-types": "^1.0.5", "follow-redirects": "^1.15.6", @@ -4271,11 +4150,6 @@ } } }, - "node_modules/tslib": { - "version": "2.6.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz", - "integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==" - }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index ca4e60a12..08c1581b6 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.26", + "version": "1.0.36", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -12,10 +12,9 @@ "author": "Nate Sesti and Ty Dunn", "license": "Apache-2.0", "dependencies": { - "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", - "@continuedev/fetch": "^1.0.10", + "@continuedev/fetch": "^1.0.11", "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", diff --git a/packages/openai-adapters/src/apis/Azure.ts b/packages/openai-adapters/src/apis/Azure.ts new file mode 100644 index 000000000..57f48c3e0 --- /dev/null +++ b/packages/openai-adapters/src/apis/Azure.ts @@ -0,0 +1,108 @@ +import { OpenAI } from "openai/index"; +import { + ChatCompletionChunk, + ChatCompletionCreateParams, + ChatCompletionCreateParamsStreaming, +} from "openai/resources/index"; +import { z } from "zod"; +import { AzureConfigSchema } from "../types.js"; +import { customFetch } from "../util.js"; +import { OpenAIApi } from "./OpenAI.js"; + +export class AzureApi extends OpenAIApi { + constructor(private azureConfig: z.infer) { + super({ + ...azureConfig, + provider: "openai", + }); + + this.openai = new OpenAI({ + apiKey: azureConfig.apiKey, + baseURL: this._getAzureBaseURL(azureConfig), + defaultQuery: azureConfig.env?.apiVersion + ? { "api-version": azureConfig.env.apiVersion } + : {}, + fetch: customFetch(azureConfig.requestOptions), + }); + } + + /** + * Default is `azure-openai`, but previously was `azure` + * @param apiType + * @returns + */ + private _isAzureOpenAI(apiType?: string): boolean { + return apiType === "azure-openai" || apiType === "azure"; + } + + private _getAzureBaseURL(config: z.infer): string { + const baseURL = new URL(this.apiBase).toString().replace(/\/$/, ""); + + // Default is `azure-openai` in docs, but previously was `azure` + if (this._isAzureOpenAI(config.env?.apiType)) { + if (!config.env?.deployment) { + throw new Error( + "Azure deployment is required if `apiType` is `azure-openai` or `azure`", + ); + } + + return `${baseURL}/openai/deployments/${config.env.deployment}`; + } + + return baseURL; + } + + /** + * Filters out empty text content parts from messages. + * + * Azure models may not support empty content parts, which can cause issues. + * This function removes any text content parts that are empty or contain only whitespace. + */ + private _filterEmptyContentParts( + body: T, + ): T { + const result = { ...body }; + + result.messages = result.messages.map((message: any) => { + if (Array.isArray(message.content)) { + const filteredContent = message.content.filter((part: any) => { + return !( + part.type === "text" && + (!part.text || part.text.trim() === "") + ); + }); + return { + ...message, + content: + filteredContent.length > 0 ? filteredContent : message.content, + }; + } + return message; + }) as any; + + return result; + } + + modifyChatBody(body: T): T { + let modifiedBody = super.modifyChatBody(body); + modifiedBody = this._filterEmptyContentParts(modifiedBody); + return modifiedBody; + } + + async *chatCompletionStream( + body: ChatCompletionCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const response = await this.openai.chat.completions.create( + this.modifyChatBody(body), + { signal }, + ); + + for await (const result of response) { + // Skip chunks with no choices (common with Azure content filtering) + if (result.choices && result.choices.length > 0) { + yield result; + } + } + } +} diff --git a/packages/openai-adapters/src/apis/AzureOpenAI.ts b/packages/openai-adapters/src/apis/AzureOpenAI.ts deleted file mode 100644 index fc9fbdda8..000000000 --- a/packages/openai-adapters/src/apis/AzureOpenAI.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { AzureKeyCredential, OpenAIClient } from "@azure/openai"; - -import dotenv from "dotenv"; -import { - Completion, - CompletionCreateParamsNonStreaming, - CompletionCreateParamsStreaming, -} from "openai/resources/completions.js"; -import { - ChatCompletion, - ChatCompletionChunk, - ChatCompletionCreateParamsNonStreaming, - ChatCompletionCreateParamsStreaming, - CreateEmbeddingResponse, - EmbeddingCreateParams, - Model, -} from "openai/resources/index.js"; -import { AzureConfig } from "../types.js"; -import { embedding } from "../util.js"; -import { - BaseLlmApi, - CreateRerankResponse, - FimCreateParamsStreaming, - RerankCreateParams, -} from "./base.js"; - -dotenv.config(); - -const HTTPS_PROXY = process.env.HTTPS_PROXY; -const HTTP_PROXY = process.env.HTTP_PROXY; - -const MS_TOKEN = 30; - -export class AzureOpenAIApi implements BaseLlmApi { - private client: OpenAIClient; - - constructor(private config: AzureConfig) { - let proxyOptions; - const PROXY = HTTPS_PROXY ?? HTTP_PROXY; - if (PROXY) { - const url = new URL(PROXY); - proxyOptions = { - host: (url.protocol ? url.protocol + "//" : "") + url.hostname, - port: Number(url.port || 80), - username: url.username, - password: url.password, - }; - } - - if (!config.apiBase || !config.apiKey) { - throw new Error("Azure OpenAI API requires apiBase and apiKey"); - } - - this.client = new OpenAIClient( - config.apiBase, - new AzureKeyCredential(config.apiKey), - { - proxyOptions, - }, - ); - } - - private _bodyToOptions( - body: - | ChatCompletionCreateParamsStreaming - | ChatCompletionCreateParamsNonStreaming, - signal: AbortSignal, - ) { - return { - maxTokens: body.max_tokens ?? undefined, - temperature: body.temperature ?? undefined, - topP: body.top_p ?? undefined, - frequencyPenalty: body.frequency_penalty ?? undefined, - presencePenalty: body.presence_penalty ?? undefined, - stop: - typeof body.stop === "string" ? [body.stop] : (body.stop ?? undefined), - abortSignal: signal, - }; - } - - async chatCompletionNonStream( - body: ChatCompletionCreateParamsNonStreaming, - signal: AbortSignal, - ): Promise { - const completion = await this.client.getChatCompletions( - body.model, - body.messages, - this._bodyToOptions(body, signal), - ); - return { - ...completion, - object: "chat.completion", - model: body.model, - created: completion.created.getTime(), - usage: completion.usage - ? { - total_tokens: completion.usage.totalTokens, - completion_tokens: completion.usage.completionTokens, - prompt_tokens: completion.usage.promptTokens, - } - : undefined, - choices: completion.choices.map((choice) => ({ - ...choice, - logprobs: null, - finish_reason: "stop", - message: { - role: "assistant", - content: choice.message?.content ?? null, - refusal: null, - }, - })), - }; - } - async *chatCompletionStream( - body: ChatCompletionCreateParamsStreaming, - signal: AbortSignal, - ): AsyncGenerator { - const events = await this.client.streamChatCompletions( - body.model, - body.messages, - this._bodyToOptions(body, signal), - ); - - const eventBuffer: ChatCompletionChunk[] = []; - let done = false; - let tokensOutput = 0; - const ms = MS_TOKEN; - (async () => { - for await (const event of events) { - eventBuffer.push({ - ...event, - object: "chat.completion.chunk", - model: body.model, - created: event.created.getTime(), - choices: event.choices.map((choice: any) => ({ - ...choice, - logprobs: undefined, - finish_reason: null, - delta: { - role: (choice.delta?.role as any) ?? "assistant", - content: choice.delta?.content ?? "", - }, - })), - usage: undefined, - }); - } - done = true; - })(); - - while (!done) { - if (eventBuffer.length > 0) { - const event = eventBuffer.shift()!; - yield event; - tokensOutput += event.choices[0]?.delta.content?.length ?? 0; - } else { - await new Promise((resolve) => setTimeout(resolve, 5)); - continue; - } - - if (tokensOutput < 100 && eventBuffer.length > 30) { - await new Promise((resolve) => setTimeout(resolve, ms / 3)); - } else if (eventBuffer.length < 12) { - await new Promise((resolve) => - setTimeout(resolve, ms + 20 * (12 - eventBuffer.length)), - ); - } else if (eventBuffer.length > 40) { - await new Promise((resolve) => setTimeout(resolve, ms / 2)); - } else { - // await new Promise((resolve) => setTimeout(resolve, Math.max(25, 50 - 2 * eventBuffer.length))); - await new Promise((resolve) => setTimeout(resolve, ms)); - } - } - - for (const event of eventBuffer) yield event; - } - async completionNonStream( - body: CompletionCreateParamsNonStreaming, - signal: AbortSignal, - ): Promise { - const { prompt, logprobs, ...restOfBody } = body; - const messages = [ - { - role: "user" as any, - content: prompt as any, - }, - ]; - const resp = await this.chatCompletionNonStream( - { - messages, - ...restOfBody, - }, - signal, - ); - return { - ...resp, - object: "text_completion", - choices: resp.choices.map((choice) => ({ - ...choice, - text: choice.message.content ?? "", - finish_reason: "stop", - logprobs: null, - })), - }; - } - async *completionStream( - body: CompletionCreateParamsStreaming, - signal: AbortSignal, - ): AsyncGenerator { - const { prompt, logprobs, ...restOfBody } = body; - const messages = [ - { - role: "user" as any, - content: prompt as any, - }, - ]; - for await (const event of this.chatCompletionStream( - { - messages, - ...restOfBody, - }, - signal, - )) { - yield { - ...event, - object: "text_completion", - usage: { - completion_tokens: event.usage?.completion_tokens ?? 0, - prompt_tokens: event.usage?.prompt_tokens ?? 0, - total_tokens: event.usage?.total_tokens ?? 0, - }, - choices: event.choices.map((choice) => ({ - ...choice, - text: choice.delta.content ?? "", - finish_reason: "stop", - logprobs: null, - })), - }; - } - } - fimStream( - body: FimCreateParamsStreaming, - ): AsyncGenerator { - throw new Error( - "Azure OpenAI does not support fill-in-the-middle (FIM) completions.", - ); - } - - async embed(body: EmbeddingCreateParams): Promise { - const input = typeof body.input === "string" ? [body.input] : body.input; - const response = await this.client.getEmbeddings(body.model, input as any, { - dimensions: body.dimensions, - model: body.model, - }); - - const output = embedding({ - data: response.data.map((item) => item.embedding), - model: body.model, - usage: { - prompt_tokens: response.usage.promptTokens, - total_tokens: response.usage.totalTokens, - }, - }); - - return output; - } - - async rerank(body: RerankCreateParams): Promise { - throw new Error("Azure OpenAI does not support reranking."); - } - - list(): Promise { - throw new Error("Method not implemented."); - } -} diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index 745b94186..81a4b1c73 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -33,7 +33,6 @@ export class OpenAIApi implements BaseLlmApi { fetch: customFetch(config.requestOptions), }); } - modifyChatBody(body: T): T { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; @@ -70,6 +69,7 @@ export class OpenAIApi implements BaseLlmApi { ); return response; } + async *chatCompletionStream( body: ChatCompletionCreateParamsStreaming, signal: AbortSignal, diff --git a/packages/openai-adapters/src/apis/WatsonX.ts b/packages/openai-adapters/src/apis/WatsonX.ts index 3962662d2..2f1e197fc 100644 --- a/packages/openai-adapters/src/apis/WatsonX.ts +++ b/packages/openai-adapters/src/apis/WatsonX.ts @@ -35,14 +35,6 @@ export class WatsonXApi implements BaseLlmApi { this.deploymentId = config.env.deploymentId; } - private async getHeaders(): Promise> { - const bearer = await this.getBearerToken(); - return { - "Content-Type": "application/json", - Authorization: `Bearer ${bearer.token}`, - }; - } - async getBearerToken(): Promise<{ token: string; expiration: number }> { if (this.apiBase?.includes("cloud.ibm.com")) { // watsonx SaaS @@ -64,48 +56,80 @@ export class WatsonXApi implements BaseLlmApi { }; } else { // watsonx Software - if (!this.config.apiKey?.includes(":")) { - // Using ZenApiKey auth - return { - token: this.config.apiKey ?? "", - expiration: -1, - }; - } else { - // Using username/password auth - const userPass = this.config.apiKey?.split(":"); - const wxToken = (await ( - await customFetch(this.config.requestOptions)( - `${this.apiBase}/icp4d-api/v1/authorize`, - { - method: "POST", - headers: { - "Content-Type": "application/json", - Accept: "application/json", - }, - body: JSON.stringify({ - username: userPass[0], - password: userPass[1], - }), + // if (this.config.env.bearerTokenRequired) { + // In certain WatsonX environments, ZenApiKey authentication is disabled, + // and it's necessary to call this endpoint with username+api_key to get a bearer token. + // See the docs: https://www.ibm.com/docs/en/watsonx/w-and-w/2.1.0?topic=keys-generating-bearer-token + // Ask @sestinj why the rest is commented out. + const base64Decoded = Buffer.from( + this.config.apiKey ?? "", + "base64", + ).toString(); + const [username, api_key] = base64Decoded.split(":"); + + const wxToken = (await ( + await customFetch(this.config.requestOptions)( + new URL("icp4d-api/v1/authorize", this.apiBase), + { + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", }, - ) - ).json()) as any; - const wxTokenExpiry = (await ( - await customFetch(this.config.requestOptions)( - `${this.apiBase}/usermgmt/v1/user/tokenExpiry`, - { - method: "GET", - headers: { - Accept: "application/json", - Authorization: `Bearer ${wxToken["token"]}`, - }, - }, - ) - ).json()) as any; - return { - token: wxToken["token"], - expiration: wxTokenExpiry["exp"], - }; - } + body: JSON.stringify({ + username: username?.trim(), + api_key: api_key?.trim(), + }), + }, + ) + ).json()) as any; + + return { + token: wxToken["access_token"] ?? wxToken["token"], + expiration: 0, + }; + // } else if (!this.config.apiKey?.includes(":")) { + // // Using ZenApiKey auth + // return { + // token: this.config.apiKey ?? "", + // expiration: -1, + // }; + // } else { + // // Using username/password auth + // const userPass = this.config.apiKey?.split(":"); + // const wxToken = (await ( + // await customFetch(this.config.requestOptions)( + // `${this.apiBase}/icp4d-api/v1/authorize`, + // { + // method: "POST", + // headers: { + // "Content-Type": "application/json", + // Accept: "application/json", + // }, + // body: JSON.stringify({ + // username: userPass[0], + // password: userPass[1], + // }), + // }, + // ) + // ).json()) as any; + // const wxTokenExpiry = (await ( + // await customFetch(this.config.requestOptions)( + // `${this.apiBase}/usermgmt/v1/user/tokenExpiry`, + // { + // method: "GET", + // headers: { + // Accept: "application/json", + // Authorization: `Bearer ${wxToken["token"]}`, + // }, + // }, + // ) + // ).json()) as any; + // return { + // token: wxToken["token"], + // expiration: wxTokenExpiry["exp"], + // }; + // } } } @@ -153,6 +177,17 @@ export class WatsonXApi implements BaseLlmApi { return payload; } + private async getHeaders(): Promise> { + const bearer = await this.getBearerToken(); + // const isZenApiKey = bearer.expiration === -1; + + return { + "Content-Type": "application/json", + // Authorization: `${isZenApiKey ? "ZenApiKey" : "Bearer"} ${bearer.token}`, + Authorization: `Bearer ${bearer.token}`, + }; + } + async chatCompletionNonStream( body: ChatCompletionCreateParamsNonStreaming, signal: AbortSignal, @@ -181,7 +216,11 @@ export class WatsonXApi implements BaseLlmApi { ): AsyncGenerator { const url = this.getEndpoint("chat"); const headers = await this.getHeaders(); - const stringifiedBody = JSON.stringify(this._convertBody(body)); + const stringifiedBody = JSON.stringify({ + time_limit: 8000, + ...this._convertBody(body), + stream: true, + }); const response = await customFetch(this.config.requestOptions)(url, { method: "POST", headers, diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index eea617cf7..9f0cf341c 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -1,7 +1,7 @@ import dotenv from "dotenv"; import { z } from "zod"; import { AnthropicApi } from "./apis/Anthropic.js"; -import { AzureOpenAIApi } from "./apis/AzureOpenAI.js"; +import { AzureApi } from "./apis/Azure.js"; import { CohereApi } from "./apis/Cohere.js"; import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; @@ -32,7 +32,7 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { case "openai": return new OpenAIApi(config); case "azure": - return new AzureOpenAIApi(config); + return new AzureApi(config); case "cohere": return new CohereApi(config); case "anthropic": diff --git a/packages/openai-adapters/src/test/main.test.ts b/packages/openai-adapters/src/test/main.test.ts index 3a5e6f979..c1e1ff29a 100644 --- a/packages/openai-adapters/src/test/main.test.ts +++ b/packages/openai-adapters/src/test/main.test.ts @@ -4,11 +4,16 @@ import { DEEPSEEK_API_BASE } from "../apis/DeepSeek.js"; import { INCEPTION_API_BASE } from "../apis/Inception.js"; import { OpenAIApi } from "../apis/OpenAI.js"; import { constructLlmApi } from "../index.js"; -import { getLlmApi, testChat, testCompletion, testEmbed } from "./util.js"; +import { getLlmApi, testChat, testEmbed } from "./util.js"; dotenv.config(); -function testConfig(config: ModelConfig) { +export interface TestConfigOptions { + skipTools: boolean; +} + +function testConfig(_config: ModelConfig & { options?: TestConfigOptions }) { + const { options, ...config } = _config; const model = config.model; const api = getLlmApi({ provider: config.provider as any, @@ -17,16 +22,12 @@ function testConfig(config: ModelConfig) { env: config.env, }); - if (false) { - testCompletion(api, model); - } - if ( ["chat", "summarize", "edit", "apply"].some((role) => config.roles?.includes(role as any), ) ) { - testChat(api, model); + testChat(api, model, options); } if (config.roles?.includes("embed")) { @@ -38,7 +39,7 @@ function testConfig(config: ModelConfig) { } } -const TESTS: Omit[] = [ +const TESTS: Omit[] = [ { provider: "openai", model: "gpt-4o", @@ -106,6 +107,26 @@ const TESTS: Omit[] = [ // apiKey: process.env.COHERE_API_KEY!, // roles: ["rerank"], // }, + { + provider: "azure", + model: "gpt-4.1", + apiBase: "https://continue-openai.openai.azure.com", + apiKey: process.env.AZURE_OPENAI_GPT41_API_KEY, + env: { + deployment: "gpt-4.1", + apiVersion: "2024-02-15-preview", + apiType: "azure-openai", + }, + roles: ["chat"], + }, + { + provider: "azure", + model: "mistral-small-2503", + apiBase: "https://nate-0276-resource.services.ai.azure.com/models", + apiKey: process.env.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY, + roles: ["chat"], + options: { skipTools: true }, + }, ]; TESTS.forEach((config) => { diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index ba4490f2a..03c3d7f4a 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -1,5 +1,6 @@ import { BaseLlmApi, constructLlmApi } from "../index.js"; import { LLMConfig } from "../types.js"; +import { TestConfigOptions } from "./main.test.js"; export function getLlmApi(config: LLMConfig) { const api = constructLlmApi(config); @@ -8,7 +9,6 @@ export function getLlmApi(config: LLMConfig) { } return api; } - export function testEmbed(api: BaseLlmApi, model: string) { test("should successfully embed", async () => { const response = await api.embed({ @@ -73,7 +73,11 @@ export function testFim(api: BaseLlmApi, model: string) { }); } -export function testChat(api: BaseLlmApi, model: string) { +export function testChat( + api: BaseLlmApi, + model: string, + options?: TestConfigOptions, +) { test("should successfully stream chat", async () => { const stream = api.chatCompletionStream( { @@ -155,7 +159,6 @@ export function testChat(api: BaseLlmApi, model: string) { let completion = ""; for await (const result of stream) { completion += result.choices[0].delta.content ?? ""; - expect(result.choices.length).toBeGreaterThan(0); } expect(completion.length).toBeGreaterThan(0); @@ -201,124 +204,125 @@ export function testChat(api: BaseLlmApi, model: string) { expect(completion?.startsWith("RESPONSE: ")).toBe(true); }); - test("Tool Call works", async () => { - let args = ""; - let isFirstChunk = true; - for await (const chunk of api.chatCompletionStream( - { - messages: [ - { - role: "user", - content: - "Hi, my name is Nate. Please call the say_hello function to respond to me.", - }, - ], - tools: [ - { - function: { - name: "say_hello", - description: "Say Hello", - parameters: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the person to greet", + if (options?.skipTools === false) { + test("Tool Call works", async () => { + let args = ""; + let isFirstChunk = true; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me.", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, }, }, }, + type: "function", }, + ], + tool_choice: { type: "function", + function: { + name: "say_hello", + }, }, - ], - tool_choice: { - type: "function", - function: { - name: "say_hello", - }, + stream: true, + model, }, - stream: true, - model, - }, - new AbortController().signal, - )) { - const toolCall = chunk.choices[0].delta.tool_calls?.[0]; - if (!toolCall) { - continue; + new AbortController().signal, + )) { + const toolCall = chunk.choices[0].delta.tool_calls?.[0]; + if (!toolCall) { + continue; + } + args += toolCall.function?.arguments ?? ""; + + expect(chunk.choices[0].delta.tool_calls).toHaveLength(1); + + if (isFirstChunk) { + isFirstChunk = false; + expect(toolCall.id).toBeDefined(); + expect(toolCall.function!.name).toBe("say_hello"); + } } - args += toolCall.function?.arguments ?? ""; - expect(chunk.choices[0].delta.tool_calls).toHaveLength(1); + const parsedArgs = JSON.parse(args); + expect(parsedArgs.name).toBe("Nate"); + }); - if (isFirstChunk) { - isFirstChunk = false; - expect(toolCall.id).toBeDefined(); - expect(toolCall.function!.name).toBe("say_hello"); - } - } - - const parsedArgs = JSON.parse(args); - expect(parsedArgs.name).toBe("Nate"); - }); - - test("Tool Call second message works", async () => { - let response = ""; - for await (const chunk of api.chatCompletionStream( - { - messages: [ - { - role: "user", - content: - "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", - }, - { - role: "assistant", - tool_calls: [ - { - function: { - arguments: '{"name":"Nate"}', - name: "say_hello", + test("Tool Call second message works", async () => { + let response = ""; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", + }, + { + role: "assistant", + tool_calls: [ + { + function: { + arguments: '{"name":"Nate"}', + name: "say_hello", + }, + id: "tool_call_1", + type: "function", }, - id: "tool_call_1", - type: "function", - }, - ], - }, - { - role: "tool", - tool_call_id: "tool_call_1", - content: "Nate was greeted", - }, - ], - tools: [ - { - function: { - name: "say_hello", - description: "Say Hello", - parameters: { - type: "object", - properties: { - name: { - type: "string", - description: "The name of the person to greet", + ], + }, + { + role: "tool", + tool_call_id: "tool_call_1", + content: "Nate was greeted", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, }, }, }, + type: "function", }, - type: "function", - }, - ], - stream: true, - model, - }, - new AbortController().signal, - )) { - console.log(JSON.stringify(chunk, null, 2)); - response += chunk.choices[0].delta.content ?? ""; - } + ], + stream: true, + model, + }, + new AbortController().signal, + )) { + response += chunk.choices[0].delta.content ?? ""; + } - expect(response.length).toBeGreaterThan(0); - }); + expect(response.length).toBeGreaterThan(0); + }); + } } export function testCompletion(api: BaseLlmApi, model: string) { diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index fd7ad94db..2f26a4c80 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -84,6 +84,19 @@ export type CohereConfig = z.infer; export const AzureConfigSchema = OpenAIConfigSchema.extend({ provider: z.literal("azure"), + env: z + .object({ + apiVersion: z.string().optional(), + apiType: z + .union([ + z.literal("azure-foundry"), + z.literal("azure-openai"), + z.literal("azure"), // Legacy + ]) + .optional(), + deployment: z.string().optional(), + }) + .optional(), }); export type AzureConfig = z.infer; diff --git a/packages/openai-adapters/src/util.ts b/packages/openai-adapters/src/util.ts index 16681e8d4..3fd87e112 100644 --- a/packages/openai-adapters/src/util.ts +++ b/packages/openai-adapters/src/util.ts @@ -1,6 +1,5 @@ import { RequestOptions } from "@continuedev/config-types"; import { fetchwithRequestOptions } from "@continuedev/fetch"; -import fetch from "node-fetch"; import { ChatCompletionChunk, CompletionUsage, @@ -137,13 +136,7 @@ export function model(options: { id: string; owned_by?: string }): Model { }; } -export function maybeCustomFetch(requestOptions: RequestOptions | undefined) { - return requestOptions - ? (url: any, init: any) => - fetchwithRequestOptions(url, init, requestOptions) - : undefined; -} - export function customFetch(requestOptions: RequestOptions | undefined) { - return maybeCustomFetch(requestOptions) ?? fetch; + return (url: any, init: any) => + fetchwithRequestOptions(url, init, requestOptions); } diff --git a/packages/openai-adapters/tsconfig.json b/packages/openai-adapters/tsconfig.json index 63587b995..dad27ccc6 100644 --- a/packages/openai-adapters/tsconfig.json +++ b/packages/openai-adapters/tsconfig.json @@ -16,8 +16,8 @@ "noEmitOnError": false, "types": ["node", "jest"], "outDir": "dist", - "declaration": true - // "sourceMap": true + "declaration": true, + "sourceMap": true }, "include": ["src/**/*"] }