From 8699786d5a630ddedd02752171b9d750cd6e4c0d Mon Sep 17 00:00:00 2001 From: Gaurav Bhambhani <113461154+GauravVBhambhani@users.noreply.github.com> Date: Thu, 20 Mar 2025 16:15:43 -0400 Subject: [PATCH 001/262] Decorate all active edit ranges If a user selects multiple chunks of code with cmd-I, only the most recent chunk of code is decorated as a selection. This commit addresses that problem by changing setDecorations to addDecorations, and carefully tracking which ranges are currently active in the EditDecorationManager. Additionally, overlapping or adjacent ranges are now merged seamlessly to prevent redundant highlights. --- extensions/vscode/src/commands.ts | 2 +- .../src/quickEdit/EditDecorationManager.ts | 46 +++++++++++++++++-- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index de8f5cd1e..04239ecbf 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -569,7 +569,7 @@ const getCommandsMap: ( const range = args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); - editDecorationManager.setDecoration(editor, range); + editDecorationManager.addDecorations(editor, [range]); const rangeInFileWithContents = getRangeInFileWithContents(true, range); diff --git a/extensions/vscode/src/quickEdit/EditDecorationManager.ts b/extensions/vscode/src/quickEdit/EditDecorationManager.ts index 544287483..18991ac49 100644 --- a/extensions/vscode/src/quickEdit/EditDecorationManager.ts +++ b/extensions/vscode/src/quickEdit/EditDecorationManager.ts @@ -2,6 +2,7 @@ import vscode from "vscode"; class EditDecorationManager { private _lastEditor: vscode.TextEditor | undefined; private decorationType: vscode.TextEditorDecorationType; + private activeRangesMap: Map = new Map(); // Store unique active ranges constructor(context: vscode.ExtensionContext) { this.decorationType = vscode.window.createTextEditorDecorationType({ @@ -23,18 +24,55 @@ class EditDecorationManager { ); } - setDecoration(editor: vscode.TextEditor, range: vscode.Range) { - if (this._lastEditor) { - this._lastEditor.setDecorations(this.decorationType, []); + // Converts each range to a unique string for storing in the map + private rangeToString(range: vscode.Range): string { + return `(${range.start.line},${range.start.character})-(${range.end.line},${range.end.character})`; + } + + // Checks if two ranges are adjacent or overlapping + private rangesCoincide(range1: vscode.Range, range2: vscode.Range): boolean { + return range1.start.isEqual(range2.start) + || range1.end.isEqual(range2.start) + || range2.end.isEqual(range1.start) + || !!range1.intersection(range2); + } + + // Merges new range with existing ranges in the map + private mergeNewRange(newRange: vscode.Range): void { + let mergedRange = newRange; + const rangesToPrune: string[] = []; + + for (const [key, existingRange] of this.activeRangesMap.entries()) { + if (!this.rangesCoincide(mergedRange, existingRange)) continue; + mergedRange = mergedRange.union(existingRange); + rangesToPrune.push(key); + } + + for (const key of rangesToPrune) this.activeRangesMap.delete(key); + this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange); + } + + // Adds a new decoration to the editor and merges it with existing ranges + addDecorations(editor: vscode.TextEditor, ranges: vscode.Range[]): void { + if (this._lastEditor?.document !== editor.document) { + this.clear(); // Clear previous decorations if editor has changed } - editor.setDecorations(this.decorationType, [range]); this._lastEditor = editor; + + for (const range of ranges) this.mergeNewRange(range); + + const activeRanges = Array.from(this.activeRangesMap.values()); + if (activeRanges.length === 0) return; // No ranges to highlight + + // Update active ranges and apply decorations + editor.setDecorations(this.decorationType, activeRanges); this.updateInEditMode(true); } clear() { if (this._lastEditor) { this._lastEditor.setDecorations(this.decorationType, []); + this.activeRangesMap.clear(); this._lastEditor = undefined; this.updateInEditMode(false); } From 0c829fd99d0e898c1afdc90a0957c907dcb7f4e2 Mon Sep 17 00:00:00 2001 From: liuk Date: Sat, 22 Mar 2025 02:29:55 +0800 Subject: [PATCH 002/262] feat: Improve ProtocolClient initialization and GUI loading - Introduce `onProtocolClientInitialized` to handle client initialization events. - Use `Delegates.observable` for `ideProtocolClient` to trigger listeners on changes. - Ensure URL loading is deferred until protocol client is initialized. --- .../services/ContinuePluginService.kt | 26 +++++++++++++++++-- .../toolWindow/ContinueBrowser.kt | 20 +++++++------- 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index cf1005596..6ebb8f41f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -1,6 +1,5 @@ package com.github.continuedev.continueintellijextension.services -import IntelliJIDE import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager import com.github.continuedev.continueintellijextension.`continue`.DiffManager @@ -13,12 +12,16 @@ import com.intellij.openapi.project.DumbAware import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel +import kotlin.properties.Delegates @Service(Service.Level.PROJECT) class ContinuePluginService : Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.Main) var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null - var ideProtocolClient: IdeProtocolClient? = null + var listener: (() -> Unit)? = null + var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ -> + synchronized(this) { listener?.also { listener = null }?.invoke() } + } var coreMessengerManager: CoreMessengerManager? = null val coreMessenger: CoreMessenger? get() = coreMessengerManager?.coreMessenger @@ -41,4 +44,23 @@ class ContinuePluginService : Disposable, DumbAware { ) { continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId) } + + /** + * Add a listener for protocolClient initialization. + * Currently, only one needs to be processed. If there are more than one, + * we can use an array to add listeners to ensure that the message is processed. + */ + fun onProtocolClientInitialized(listener: () -> Unit) { + if (ideProtocolClient == null) { + synchronized(this) { + if (ideProtocolClient == null) { + this.listener = listener + } else { + listener() + } + } + } else { + listener() + } + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 8cb700f15..43a468cf7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -1,7 +1,6 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable -import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings @@ -10,11 +9,11 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* import com.intellij.ui.jcef.JBCefClient.Properties +import com.intellij.util.application import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter @@ -30,8 +29,10 @@ class ContinueBrowser(val project: Project, url: String) { val browser: JBCefBrowser + val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java) + init { - val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { // To avoid using System.setProperty to affect other plugins, @@ -42,7 +43,6 @@ class ContinueBrowser(val project: Project, url: String) { } registerAppSchemeHandler() - browser.loadURL(url) Disposer.register(ContinuePluginDisposable.getInstance(project), browser) // Listen for events sent from browser @@ -55,11 +55,6 @@ class ContinueBrowser(val project: Project, url: String) { val data = json.get("data") val messageId = json.get("messageId")?.asString - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) - val respond = fun(data: Any?) { sendToWebview(messageType, data, messageId ?: uuid()) } @@ -101,6 +96,13 @@ class ContinueBrowser(val project: Project, url: String) { } }, browser.cefBrowser) + // Load the url only after the protocolClient is initialized, + // otherwise some messages will be lost, which are some configurations when the page is loaded. + // Moreover, we should add LoadHandler before loading the url. + continuePluginService.onProtocolClientInitialized { + browser.loadURL(url) + } + } fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) { From a94c178126709c0109c631f99a012f4d1cbee746 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 31 Mar 2025 16:15:40 -0700 Subject: [PATCH 003/262] optional-context-name --- core/config/yaml/loadYaml.ts | 5 ++++- .../providers/ContinueProxyContextProvider.ts | 1 + core/context/providers/HttpContextProvider.ts | 14 ++++++++------ docs/docs/reference.md | 7 ++++++- packages/config-yaml/src/schemas/index.ts | 1 + 5 files changed, 20 insertions(+), 8 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index f2fefbb39..55db94692 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -374,7 +374,10 @@ async function configYamlToContinueConfig( } return undefined; } - const instance: IContextProvider = new cls(context.params ?? {}); + const instance: IContextProvider = new cls({ + name: context.name, + ...context.params, + }); return instance; }) .filter((p) => !!p) ?? []) as IContextProvider[]; diff --git a/core/context/providers/ContinueProxyContextProvider.ts b/core/context/providers/ContinueProxyContextProvider.ts index 278a12678..77e47c9f3 100644 --- a/core/context/providers/ContinueProxyContextProvider.ts +++ b/core/context/providers/ContinueProxyContextProvider.ts @@ -24,6 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider { this.options.title || ContinueProxyContextProvider.description.title, displayTitle: this.options.displayTitle || + this.options.name || ContinueProxyContextProvider.description.displayTitle, description: this.options.description || diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index 067035806..bcca31177 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -16,18 +16,20 @@ class HttpContextProvider extends BaseContextProvider { override get description(): ContextProviderDescription { return { - title: this.options.title || "http", - displayTitle: this.options.displayTitle || "HTTP", + title: this.options.title || HttpContextProvider.description.title, + displayTitle: + this.options.displayTitle || + this.options.name || + HttpContextProvider.description.displayTitle, description: - this.options.description || - "Retrieve a context item from a custom server", - type: "normal", + this.options.description || HttpContextProvider.description.description, + type: HttpContextProvider.description.type, renderInlineAs: this.options.renderInlineAs || HttpContextProvider.description.renderInlineAs, }; } - + async getContextItems( query: string, extras: ContextProviderExtras, diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 69f301366..217c460dd 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -220,7 +220,8 @@ More information about usage/params for each context provider can be found [here **Properties:** -- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). +- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`) +- `name`: Optional name for the provider - `params`: Optional parameters to configure the context provider's behavior. **Example:** @@ -234,6 +235,10 @@ context: nFinal: 10 - provider: docs - provider: diff + - provider: http + name: Context Server 1 + params: + url: "https://api.example.com/server1" - provider: folder - provider: terminal ``` diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1ca03b0b6..c33d02fc4 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -3,6 +3,7 @@ import { dataSchema } from "./data/index.js"; import { modelSchema, partialModelSchema } from "./models.js"; export const contextSchema = z.object({ + name: z.string().optional(), provider: z.string(), params: z.any().optional(), }); From c59c834790011d27558fb983d40171f70e522b59 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 31 Mar 2025 20:42:17 -0700 Subject: [PATCH 004/262] bump config-yaml --- core/package-lock.json | 8 ++++---- core/package.json | 2 +- gui/package-lock.json | 10 +++++----- gui/package.json | 2 +- packages/config-yaml/package.json | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index 50df2a6f3..3283e219e 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -2974,9 +2974,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.68", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.68.tgz", + "integrity": "sha512-rCegSGkv7Ws7LLnYVVGwXsoVZFpNFJnG6b1dVrj/u+2ZsFdA2leQUNtFGoeE/ixyfhUfBpMlgjEyPrmmy7gLjw==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index 205e3b778..b6193d221 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index 78eb2e61d..23fd77734 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -111,7 +111,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.758.0", "@aws-sdk/credential-providers": "^3.758.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -554,9 +554,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.67", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.67.tgz", - "integrity": "sha512-RbJXSH2Z9XmaN1h9Dm0Qfru7UeAdCAEWMiEgJ9A2FGHysR9oxbQDqptk1Y61oDSpYeX+lWsxkz/SFIc2PjNnKg==", + "version": "1.0.68", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.68.tgz", + "integrity": "sha512-rCegSGkv7Ws7LLnYVVGwXsoVZFpNFJnG6b1dVrj/u+2ZsFdA2leQUNtFGoeE/ixyfhUfBpMlgjEyPrmmy7gLjw==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/gui/package.json b/gui/package.json index 3210a55f5..4df8cbec8 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.67", + "@continuedev/config-yaml": "^1.0.68", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index d7d96c4f0..e3d62aeef 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.67", + "version": "1.0.68", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From e3c56f81a2d65120478560451bf149f62fc25428 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 14:16:05 -0700 Subject: [PATCH 005/262] localenv secret type --- packages/config-yaml/package.json | 2 +- .../src/interfaces/SecretResult.ts | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index f32235580..2266a5070 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.79", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/interfaces/SecretResult.ts b/packages/config-yaml/src/interfaces/SecretResult.ts index 5c626c3d0..b89e12e59 100644 --- a/packages/config-yaml/src/interfaces/SecretResult.ts +++ b/packages/config-yaml/src/interfaces/SecretResult.ts @@ -7,6 +7,7 @@ export enum SecretType { NotFound = "not_found", ModelsAddOn = "models_add_on", FreeTrial = "free_trial", + LocalEnv = "local_env", } export interface OrgSecretLocation { @@ -39,6 +40,11 @@ export interface FreeTrialSecretLocation { secretName: string; } +export interface LocalEnvSecretLocation { + secretType: SecretType.LocalEnv; + secretName: string; +} + /** * If not found in user/package/org secrets, then there's a chance it's in * - the on-prem proxy @@ -56,7 +62,8 @@ export type SecretLocation = | UserSecretLocation | NotFoundSecretLocation | ModelsAddOnSecretLocation - | FreeTrialSecretLocation; + | FreeTrialSecretLocation + | LocalEnvSecretLocation; export function encodeSecretLocation(secretLocation: SecretLocation): string { if (secretLocation.secretType === SecretType.Organization) { @@ -71,6 +78,8 @@ export function encodeSecretLocation(secretLocation: SecretLocation): string { return `${SecretType.ModelsAddOn}:${encodePackageSlug(secretLocation.blockSlug)}/${secretLocation.secretName}`; } else if (secretLocation.secretType === SecretType.FreeTrial) { return `${SecretType.FreeTrial}:${encodePackageSlug(secretLocation.blockSlug)}/${secretLocation.secretName}`; + } else if (secretLocation.secretType === SecretType.LocalEnv) { + return `${SecretType.LocalEnv}:${secretLocation.secretName}`; } else { throw new Error(`Invalid secret type: ${secretLocation}`); } @@ -123,6 +132,11 @@ export function decodeSecretLocation(secretLocation: string): SecretLocation { packageSlug: parts[1], }, }; + case SecretType.LocalEnv: + return { + secretType: SecretType.LocalEnv, + secretName, + }; default: throw new Error(`Invalid secret type: ${secretType}`); } @@ -140,7 +154,8 @@ export interface FoundSecretResult { | OrgSecretLocation | PackageSecretLocation | ModelsAddOnSecretLocation - | FreeTrialSecretLocation; + | FreeTrialSecretLocation + | LocalEnvSecretLocation; fqsn: FQSN; } From 2d397ded994b6c8d142c7a38c53c9d202934d05a Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 14:52:12 -0700 Subject: [PATCH 006/262] support for local .env secrets --- core/config/yaml/LocalPlatformClient.ts | 106 ++++++++++++++++++++++++ core/config/yaml/loadYaml.ts | 28 ++----- core/package-lock.json | 11 ++- core/package.json | 2 +- extensions/vscode/package-lock.json | 6 +- gui/package-lock.json | 2 +- packages/config-yaml/package.json | 2 +- 7 files changed, 127 insertions(+), 30 deletions(-) create mode 100644 core/config/yaml/LocalPlatformClient.ts diff --git a/core/config/yaml/LocalPlatformClient.ts b/core/config/yaml/LocalPlatformClient.ts new file mode 100644 index 000000000..3c8cc33bb --- /dev/null +++ b/core/config/yaml/LocalPlatformClient.ts @@ -0,0 +1,106 @@ +import { + FQSN, + PlatformClient, + SecretResult, + SecretType, +} from "@continuedev/config-yaml"; +import * as dotenv from "dotenv"; +import { IDE } from "../.."; +import { ControlPlaneClient } from "../../control-plane/client"; +import { getContinueDotEnv } from "../../util/paths"; +import { joinPathsToUri } from "../../util/uri"; + +export class LocalPlatformClient implements PlatformClient { + constructor( + private orgScopeId: string | null, + private readonly client: ControlPlaneClient, + private readonly ide: IDE, + ) {} + + private async findSecretInEnvFiles( + fqsn: FQSN, + ): Promise { + const secretValue = + this.findSecretInLocalEnvFile(fqsn) ?? + (await this.findSecretInWorkspaceEnvFiles(fqsn)); + + if (secretValue) { + return { + found: true, + fqsn, + value: secretValue, + secretLocation: { + secretName: fqsn.secretName, + secretType: SecretType.LocalEnv, + }, + }; + } + return undefined; + } + + private findSecretInLocalEnvFile(fqsn: FQSN): string | undefined { + try { + const dotEnv = getContinueDotEnv(); + return dotEnv[fqsn.secretName]; + } catch (error) { + console.warn( + `Error reading ~/.continue/.env file: ${error instanceof Error ? error.message : String(error)}`, + ); + return undefined; + } + } + + private async findSecretInWorkspaceEnvFiles( + fqsn: FQSN, + ): Promise { + try { + const workspaceDirs = await this.ide.getWorkspaceDirs(); + + for (const folder of workspaceDirs) { + const envFilePath = joinPathsToUri(folder, ".env"); + try { + const fileExists = await this.ide.fileExists(envFilePath); + if (fileExists) { + const envContent = await this.ide.readFile(envFilePath); + const env = dotenv.parse(envContent); + if (fqsn.secretName in env) { + return env[fqsn.secretName]; + } + } + } catch (error) { + console.warn( + `Error reading workspace .env file at ${envFilePath}: ${error instanceof Error ? error.message : String(error)}`, + ); + // Continue to next workspace folder + } + } + + return undefined; + } catch (error) { + console.warn( + `Error searching workspace .env files: ${error instanceof Error ? error.message : String(error)}`, + ); + return undefined; + } + } + + async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { + if (fqsns.length === 0) { + return []; + } + + const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId); + + // For any secret that isn't found, look in .env files + for (let i = 0; i < results.length; i++) { + if (!results[i]?.found) { + const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]); + if (secretFromEnv?.found) { + results[i] = secretFromEnv; + } + } + } + + return results; + } +} diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 1edb48604..333e3d1c9 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -4,11 +4,8 @@ import { AssistantUnrolled, ConfigResult, ConfigValidationError, - FQSN, ModelRole, - PlatformClient, RegistryClient, - SecretResult, unrollAssistantFromContent, validateConfigYaml, } from "@continuedev/config-yaml"; @@ -43,30 +40,16 @@ import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { getControlPlaneEnvSync } from "../../control-plane/env"; +import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; -export class LocalPlatformClient implements PlatformClient { - constructor( - private orgScopeId: string | null, - private readonly client: ControlPlaneClient, - ) {} - - async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { - if (fqsns.length === 0) { - return []; - } - - const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId); - return response; - } -} - async function loadConfigYaml( rawYaml: string, overrideConfigYaml: AssistantUnrolled | undefined, controlPlaneClient: ControlPlaneClient, orgScopeId: string | null, ideSettings: IdeSettings, + ide: IDE, ): Promise> { let config = overrideConfigYaml ?? @@ -89,7 +72,11 @@ async function loadConfigYaml( currentUserSlug: "", onPremProxyUrl: null, orgScopeId, - platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient), + platformClient: new LocalPlatformClient( + orgScopeId, + controlPlaneClient, + ide, + ), renderSecrets: true, }, )); @@ -435,6 +422,7 @@ export async function loadContinueConfigFromYaml( controlPlaneClient, orgScopeId, ideSettings, + ide, ); if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { diff --git a/core/package-lock.json b/core/package-lock.json index 24aeb4f18..81d4a5870 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.80", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -2977,13 +2977,16 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.71", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.71.tgz", - "integrity": "sha512-c7KVaYfldaYHf2EqeqE9Oo1son33iTp6MAY+WRPJVs9XWmRWOA6Cn7YDf575FpwX6UsPCT/Eb0JJme8AC7UE6g==", + "version": "1.0.80", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.80.tgz", + "integrity": "sha512-fHZLh04aThbgK80+B5O0CBBb0IgJbfM0trBWeDI4/MLpxpTJebxX4QY1RZBOdIULKMDMHnfyWNCe2gSGi/mt9Q==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" } }, "node_modules/@continuedev/fetch": { diff --git a/core/package.json b/core/package.json index a405bad55..947aa6d56 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.80", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 108520e49..6f637302d 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.80", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index 69c571f84..dfa9a4efd 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -109,7 +109,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.80", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 2266a5070..966a6289c 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.79", + "version": "1.0.80", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From aa2aff01c046cf30c19e95c0d22b640d10bcd786 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 15:07:11 -0700 Subject: [PATCH 007/262] include workspace assistants when in org scope --- core/config/ConfigHandler.ts | 70 ++++++++++++++++++++++++------------ 1 file changed, 48 insertions(+), 22 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 2d4a471d5..790bc01d8 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -197,7 +197,11 @@ export class ConfigHandler { private async getNonPersonalHubOrg( org: OrganizationDescription, ): Promise { - const profiles = await this.getHubProfiles(org.id); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: false, + includeWorkspace: true, + }); + const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles]; return this.rectifyProfilesForOrg(org, profiles); } @@ -208,20 +212,29 @@ export class ConfigHandler { slug: undefined, }; private async getPersonalHubOrg() { - const allLocalProfiles = await this.getAllLocalProfiles(); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: true, + includeWorkspace: true, + }); const hubProfiles = await this.getHubProfiles(null); - const profiles = [...hubProfiles, ...allLocalProfiles]; + const profiles = [...hubProfiles, ...localProfiles]; return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles); } private async getLocalOrg() { - const allLocalProfiles = await this.getAllLocalProfiles(); - return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: true, + includeWorkspace: true, + }); + return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles); } async getTeamsOrg(org: OrganizationDescription): Promise { const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = await this.getAllLocalProfiles(); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: true, + includeWorkspace: true, + }); workspaces.forEach((workspace) => { const profileLoader = new ControlPlaneProfileLoader( workspace.id, @@ -233,9 +246,9 @@ export class ConfigHandler { this.reloadConfig.bind(this), ); - profiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); + localProfiles.push(new ProfileLifecycleManager(profileLoader, this.ide)); }); - return this.rectifyProfilesForOrg(org, profiles); + return this.rectifyProfilesForOrg(org, localProfiles); } private async rectifyProfilesForOrg( @@ -282,24 +295,37 @@ export class ConfigHandler { }; } - async getAllLocalProfiles() { + async getLocalProfiles(options: { + includeGlobal: boolean | undefined; + includeWorkspace: boolean | undefined; + }) { /** * Users can define as many local assistants as they want in a `.continue/assistants` folder */ - const assistantFiles = await getAllAssistantFiles(this.ide); - const profiles = assistantFiles.map((assistant) => { - return new LocalProfileLoader( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - assistant, + const localProfiles: ProfileLifecycleManager[] = []; + + if (options.includeGlobal) { + localProfiles.push(this.globalLocalProfileManager); + } + + if (options.includeWorkspace) { + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.llmLogger, + assistant, + ); + }); + const localAssistantProfiles = profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), ); - }); - const localAssistantProfiles = profiles.map( - (profile) => new ProfileLifecycleManager(profile, this.ide), - ); - return [this.globalLocalProfileManager, ...localAssistantProfiles]; + localProfiles.push(...localAssistantProfiles); + } + + return localProfiles; } ////////////////// From b66fe4185bbae2dfa31a400f4afa05095939f145 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 15:17:43 -0700 Subject: [PATCH 008/262] load ~/.continue/assistants --- core/config/ConfigHandler.ts | 12 ++++++------ core/config/loadLocalAssistants.ts | 22 ++++++++++++++++++---- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 790bc01d8..f841a5fdf 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -17,7 +17,10 @@ import { import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getAllAssistantFiles } from "./loadLocalAssistants.js"; +import { + getAllAssistantFiles, + LoadAssistantFilesOptions, +} from "./loadLocalAssistants.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, @@ -295,10 +298,7 @@ export class ConfigHandler { }; } - async getLocalProfiles(options: { - includeGlobal: boolean | undefined; - includeWorkspace: boolean | undefined; - }) { + async getLocalProfiles(options: LoadAssistantFilesOptions) { /** * Users can define as many local assistants as they want in a `.continue/assistants` folder */ @@ -309,7 +309,7 @@ export class ConfigHandler { } if (options.includeWorkspace) { - const assistantFiles = await getAllAssistantFiles(this.ide); + const assistantFiles = await getAllAssistantFiles(this.ide, options); const profiles = assistantFiles.map((assistant) => { return new LocalProfileLoader( this.ide, diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 7faa87d5e..296a8ae30 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -53,18 +53,32 @@ export async function getAssistantFilesFromDir( } } +export interface LoadAssistantFilesOptions { + includeGlobal: boolean; + includeWorkspace: boolean; +} + export async function getAllAssistantFiles( ide: IDE, + options: LoadAssistantFilesOptions, ): Promise<{ path: string; content: string }[]> { const workspaceDirs = await ide.getWorkspaceDirs(); let assistantFiles: { path: string; content: string }[] = []; let dirsToCheck = [ASSISTANTS_FOLDER]; - const fullDirs = workspaceDirs - .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) - .flat(); + let fullDirs: string[] = []; - fullDirs.push(localPathToUri(getGlobalAssistantsPath())); + // Workspace .continue/assistants + if (options.includeWorkspace) { + fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + } + + // ~/.continue/assistants + if (options.includeGlobal) { + fullDirs.push(localPathToUri(getGlobalAssistantsPath())); + } assistantFiles = ( await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) From a807a6b56c8207b1bc8d11676211d64ccea8b982 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 15:41:06 -0700 Subject: [PATCH 009/262] small refactor to make it easy to list .continue/rules, etc. --- core/config/ConfigHandler.ts | 9 ++++-- core/config/loadLocalAssistants.ts | 48 ++++++++++++++++++++++-------- core/util/paths.ts | 8 +++-- 3 files changed, 48 insertions(+), 17 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index f841a5fdf..fb97e88e7 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -18,7 +18,8 @@ import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; import { - getAllAssistantFiles, + ASSISTANTS, + getAllDotContinueYamlFiles, LoadAssistantFilesOptions, } from "./loadLocalAssistants.js"; import { @@ -309,7 +310,11 @@ export class ConfigHandler { } if (options.includeWorkspace) { - const assistantFiles = await getAllAssistantFiles(this.ide, options); + const assistantFiles = await getAllDotContinueYamlFiles( + this.ide, + options, + ASSISTANTS, + ); const profiles = assistantFiles.map((assistant) => { return new LocalProfileLoader( this.ide, diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 296a8ae30..3daf0cd65 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -9,7 +9,8 @@ import { getGlobalAssistantsPath } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; -export const ASSISTANTS_FOLDER = ".continue/assistants"; +export const ASSISTANTS = "assistants"; +export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; export function isLocalAssistantFile(uri: string): boolean { if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) { @@ -20,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean { return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); } -export async function getAssistantFilesFromDir( +export async function listYamlFilesInDir( ide: IDE, dir: string, ): Promise<{ path: string; content: string }[]> { @@ -58,21 +59,19 @@ export interface LoadAssistantFilesOptions { includeWorkspace: boolean; } -export async function getAllAssistantFiles( +export function getDotContinueSubDirs( ide: IDE, options: LoadAssistantFilesOptions, -): Promise<{ path: string; content: string }[]> { - const workspaceDirs = await ide.getWorkspaceDirs(); - let assistantFiles: { path: string; content: string }[] = []; - - let dirsToCheck = [ASSISTANTS_FOLDER]; + workspaceDirs: string[], + subDirName: string, +): string[] { let fullDirs: string[] = []; // Workspace .continue/assistants if (options.includeWorkspace) { - fullDirs = workspaceDirs - .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) - .flat(); + fullDirs = workspaceDirs.map((dir) => + joinPathsToUri(dir, ".continue", subDirName), + ); } // ~/.continue/assistants @@ -80,8 +79,31 @@ export async function getAllAssistantFiles( fullDirs.push(localPathToUri(getGlobalAssistantsPath())); } - assistantFiles = ( - await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + return fullDirs; +} + +/** + * This method searches in both ~/.continue and workspace .continue + * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts + */ +export async function getAllDotContinueYamlFiles( + ide: IDE, + options: LoadAssistantFilesOptions, + subDirName: string, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + + // Get all directories to check for assistant files + const fullDirs = getDotContinueSubDirs( + ide, + options, + workspaceDirs, + subDirName, + ); + + // Get all assistant files from the directories + const assistantFiles = ( + await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir))) ).flat(); return await Promise.all( diff --git a/core/util/paths.ts b/core/util/paths.ts index a277d4977..8c5dbcfc6 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -376,12 +376,16 @@ export function getPromptLogsPath(): string { return path.join(getLogsDirPath(), "prompt.log"); } +export function getGlobalFolderWithName(name: string): string { + return path.join(getContinueGlobalPath(), name); +} + export function getGlobalPromptsPath(): string { - return path.join(getContinueGlobalPath(), "prompts"); + return getGlobalFolderWithName("prompts"); } export function getGlobalAssistantsPath(): string { - return path.join(getContinueGlobalPath(), "assistants"); + return getGlobalFolderWithName("assistants"); } export function readAllGlobalPromptFiles( From 8f707a896b96550b2eddfbdcf64634ad5c4ecc3f Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 17:13:34 -0700 Subject: [PATCH 010/262] first attempt at loading local blocks --- core/config/yaml/loadYaml.ts | 26 +++++++++++++++++++ core/package-lock.json | 8 +++--- core/package.json | 2 +- packages/config-yaml/package.json | 2 +- packages/config-yaml/src/load/getBlockType.ts | 20 ++++++++------ 5 files changed, 44 insertions(+), 14 deletions(-) diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 333e3d1c9..169ca8089 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -2,9 +2,11 @@ import fs from "node:fs"; import { AssistantUnrolled, + BLOCK_TYPES, ConfigResult, ConfigValidationError, ModelRole, + parseAssistantUnrolled, RegistryClient, unrollAssistantFromContent, validateConfigYaml, @@ -40,6 +42,7 @@ import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { getControlPlaneEnvSync } from "../../control-plane/env"; +import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; @@ -433,6 +436,29 @@ export async function loadContinueConfigFromYaml( }; } + // Add local .continue blocks + for (const blockType of BLOCK_TYPES) { + const localBlocks = await getAllDotContinueYamlFiles( + ide, + { includeGlobal: true, includeWorkspace: true }, + blockType, + ); + + for (const block of localBlocks) { + const parsedYaml = parseAssistantUnrolled(block.content); + + const inlineBlock = parsedYaml[blockType]?.[0]; + if (inlineBlock) { + configYamlResult.config[blockType] = [ + ...(configYamlResult.config[blockType] ?? []), + inlineBlock as any, + ]; + } + } + + configYamlResult.config; + } + const { config: continueConfig, errors: localErrors } = await configYamlToContinueConfig( configYamlResult.config, diff --git a/core/package-lock.json b/core/package-lock.json index 81d4a5870..4f1c21ec8 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.80", + "@continuedev/config-yaml": "^1.0.81", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -2977,9 +2977,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.80", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.80.tgz", - "integrity": "sha512-fHZLh04aThbgK80+B5O0CBBb0IgJbfM0trBWeDI4/MLpxpTJebxX4QY1RZBOdIULKMDMHnfyWNCe2gSGi/mt9Q==", + "version": "1.0.81", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.81.tgz", + "integrity": "sha512-KNk1n3hXJWL2PSflN9WXlClGVJMJNNSrkn6Fo3BcVu466MOr/vJsuA2In3ZolBMCpg2jNYKYbCC72N1JDFS6ww==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index 947aa6d56..3701bcb49 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.80", + "@continuedev/config-yaml": "^1.0.81", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index 966a6289c..af76f1951 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.80", + "version": "1.0.81", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/load/getBlockType.ts b/packages/config-yaml/src/load/getBlockType.ts index a2cf56062..c46de0bd4 100644 --- a/packages/config-yaml/src/load/getBlockType.ts +++ b/packages/config-yaml/src/load/getBlockType.ts @@ -1,13 +1,17 @@ +import { z } from "zod"; import { ConfigYaml } from "../schemas/index.js"; -export type BlockType = - | "models" - | "context" - | "docs" - | "mcpServers" - | "data" - | "rules" - | "prompts"; +export const BLOCK_TYPES = [ + "models", + "context", + "data", + "mcpServers", + "rules", + "prompts", + "docs", +] as const; +export type BlockType = (typeof BLOCK_TYPES)[number]; +export const blockTypeSchema = z.enum(BLOCK_TYPES); export function getBlockType(block: ConfigYaml): BlockType | undefined { if (block.context?.length) { From 450b4911285d8cf25f33a0c199aa92250ad1fa1c Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 17:18:46 -0700 Subject: [PATCH 011/262] run config-yaml tests in ci --- .github/workflows/pr_checks.yaml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index c7e37773a..bcb46536b 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -283,6 +283,30 @@ jobs: AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} + package-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: core/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Install dependencies + run: | + cd packages/config-yaml + npm ci + + - name: Run config-yaml tests + run: | + cd packages/config-yaml + npm test + vscode-get-test-file-matrix: runs-on: ubuntu-latest needs: [install-root, install-vscode] From bd6eaaaf5434005825496907b0dee03c32e9eb49 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 17:19:07 -0700 Subject: [PATCH 012/262] same --- .github/workflows/pr_checks.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index bcb46536b..c3a3848f6 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -645,6 +645,7 @@ jobs: - install-vscode - vscode-checks - core-tests + - package-tests - vscode-get-test-file-matrix - vscode-package-extension - vscode-download-e2e-dependencies From 15fa1aee5bd291baf27a95ac7ea7a3a0aa8143dd Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 17:32:23 -0700 Subject: [PATCH 013/262] fix tests --- packages/config-yaml/package-lock.json | 4 ++-- packages/config-yaml/src/__tests__/index.test.ts | 10 ++++------ 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 2a8b83224..fe99eaf1a 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.72", + "version": "1.0.81", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.72", + "version": "1.0.81", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index 0c8f120d7..7a045cfb5 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -207,15 +207,15 @@ describe("E2E Scenarios", () => { injectBlocks: [ { ownerSlug: "test-org", - packageSlug: "docs", + packageSlug: "rules", versionSlug: "latest", }, ], }, ); - // The original docs array should have one item - expect(unrolledConfig.docs?.length).toBe(2); // Now 2 with the injected block + // The original rules array should have two items + expect(unrolledConfig.rules?.length).toBe(3); // Now 3 with the injected block // Check the original doc is still there expect(unrolledConfig.docs?.[0]?.startUrl).toBe( @@ -223,9 +223,7 @@ describe("E2E Scenarios", () => { ); // Check the injected doc block was added - expect(unrolledConfig.docs?.[1]?.startUrl).toBe( - "https://docs.python.org/release/3.13.1", - ); + expect(unrolledConfig.rules?.[2]).toBe("Be kind"); }); it.skip("should prioritize org over user / package secrets", () => {}); From 7ea89dc3fa7ebfdfa41b3bdcfec393f68ebc1c44 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 17:37:21 -0700 Subject: [PATCH 014/262] bump version --- core/package-lock.json | 8 ++++---- core/package.json | 2 +- gui/package-lock.json | 13 ++++++++----- gui/package.json | 2 +- packages/config-yaml/package.json | 2 +- 5 files changed, 15 insertions(+), 12 deletions(-) diff --git a/core/package-lock.json b/core/package-lock.json index 4f1c21ec8..eb97ecc5a 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.81", + "@continuedev/config-yaml": "^1.0.82", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -2977,9 +2977,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.81", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.81.tgz", - "integrity": "sha512-KNk1n3hXJWL2PSflN9WXlClGVJMJNNSrkn6Fo3BcVu466MOr/vJsuA2In3ZolBMCpg2jNYKYbCC72N1JDFS6ww==", + "version": "1.0.82", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.82.tgz", + "integrity": "sha512-IscUcyDoN4DiYEdoAJRo0LcbqgHAWYIUCqNSmjRQuASY4s2Xel2iejmnCj0oHj4DXz/bAlNBLHR6lUBs9tqSDQ==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index 3701bcb49..6a41321d4 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.81", + "@continuedev/config-yaml": "^1.0.82", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index c09ed5189..1f2ce7ae6 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -7,7 +7,7 @@ "name": "gui", "license": "Apache-2.0", "dependencies": { - "@continuedev/config-yaml": "^1.0.77", + "@continuedev/config-yaml": "^1.0.82", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", @@ -109,7 +109,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.80", + "@continuedev/config-yaml": "^1.0.82", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -553,13 +553,16 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.77", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.77.tgz", - "integrity": "sha512-Vke6jp4bENjJc9fO1tavOnbYXRmmSIEzNhYeQ6DzZVl92+8rWwdO6zhbrK0r4FGjHnH0cJgyK/q0zX9/l+6asw==", + "version": "1.0.82", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.82.tgz", + "integrity": "sha512-IscUcyDoN4DiYEdoAJRo0LcbqgHAWYIUCqNSmjRQuASY4s2Xel2iejmnCj0oHj4DXz/bAlNBLHR6lUBs9tqSDQ==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", "zod": "^3.24.2" + }, + "bin": { + "config-yaml": "dist/cli.js" } }, "node_modules/@emotion/is-prop-valid": { diff --git a/gui/package.json b/gui/package.json index 98db617a0..8a28188e8 100644 --- a/gui/package.json +++ b/gui/package.json @@ -15,7 +15,7 @@ "test:watch": "vitest" }, "dependencies": { - "@continuedev/config-yaml": "^1.0.77", + "@continuedev/config-yaml": "^1.0.82", "@headlessui/react": "^2.2.0", "@heroicons/react": "^2.0.18", "@reduxjs/toolkit": "^2.3.0", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index af76f1951..a601d33d2 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.81", + "version": "1.0.82", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From cbc4df275cb0eb4f566e381bea67d6398485f017 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 17:55:43 -0700 Subject: [PATCH 015/262] package identifier --- .../config-yaml/src/interfaces/slugs.test.ts | 79 +++++++++++++++++++ packages/config-yaml/src/interfaces/slugs.ts | 55 +++++++++++++ 2 files changed, 134 insertions(+) diff --git a/packages/config-yaml/src/interfaces/slugs.test.ts b/packages/config-yaml/src/interfaces/slugs.test.ts index cab57e5d2..e07e6f700 100644 --- a/packages/config-yaml/src/interfaces/slugs.test.ts +++ b/packages/config-yaml/src/interfaces/slugs.test.ts @@ -1,9 +1,11 @@ import { decodeFQSN, decodeFullSlug, + decodePackageIdentifier, decodePackageSlug, encodeFQSN, encodeFullSlug, + encodePackageIdentifier, encodePackageSlug, VirtualTags, } from "./slugs.js"; @@ -80,3 +82,80 @@ describe("PackageSlug", () => { ); }); }); + +describe("PackageIdentifier", () => { + it("should encode/decode slug-based package identifier", () => { + const testIdentifier = { + uriType: "slug" as const, + fullSlug: { + ownerSlug: "test-owner", + packageSlug: "test-package", + versionSlug: "2.1.0", + }, + }; + const encoded = encodePackageIdentifier(testIdentifier); + expect(encoded).toBe("test-owner/test-package@2.1.0"); + + const decoded = decodePackageIdentifier(encoded); + expect(decoded).toEqual(testIdentifier); + }); + + it("should encode/decode slug-based package identifier without version", () => { + const encoded = "test-owner/test-package"; + const decoded = decodePackageIdentifier(encoded); + + expect(decoded).toEqual({ + uriType: "slug", + fullSlug: { + ownerSlug: "test-owner", + packageSlug: "test-package", + versionSlug: VirtualTags.Latest, + }, + }); + }); + + it("should encode/decode file-based package identifier with relative path", () => { + const testIdentifier = { + uriType: "file" as const, + filePath: "./path/to/package.yaml", + }; + const encoded = encodePackageIdentifier(testIdentifier); + expect(encoded).toBe("./path/to/package.yaml"); + + const decoded = decodePackageIdentifier(encoded); + expect(decoded).toEqual(testIdentifier); + }); + + it("should encode/decode file-based package identifier with absolute path", () => { + const testIdentifier = { + uriType: "file" as const, + filePath: "/absolute/path/to/package.yaml", + }; + const encoded = encodePackageIdentifier(testIdentifier); + expect(encoded).toBe("/absolute/path/to/package.yaml"); + + const decoded = decodePackageIdentifier(encoded); + expect(decoded).toEqual(testIdentifier); + }); + + it("should decode file-based package identifier with file:// protocol", () => { + const encoded = "file:///path/to/package.yaml"; + const decoded = decodePackageIdentifier(encoded); + + expect(decoded).toEqual({ + uriType: "file" as const, + filePath: "/path/to/package.yaml", + }); + }); + + it("should throw error for unknown URI type", () => { + const invalidIdentifier = { + uriType: "invalid", + data: "something", + }; + + expect(() => encodePackageIdentifier(invalidIdentifier as any)).toThrow( + "Unknown URI type: invalid", + ); + }); +}); diff --git a/packages/config-yaml/src/interfaces/slugs.ts b/packages/config-yaml/src/interfaces/slugs.ts index dd225aa10..5d1f9885f 100644 --- a/packages/config-yaml/src/interfaces/slugs.ts +++ b/packages/config-yaml/src/interfaces/slugs.ts @@ -2,10 +2,65 @@ export interface PackageSlug { ownerSlug: string; packageSlug: string; } + export interface FullSlug extends PackageSlug { versionSlug: string; } +// Identifier roughly equals URI, except that we want to provide shorthand for slugs and filepaths +// Later it is possible to allow URIs as well since they can be uniquely parsed +interface BasePackageIdentifier { + uriType: "file" | "slug"; +} + +interface FullSlugIdentifier extends BasePackageIdentifier { + uriType: "slug"; + fullSlug: FullSlug; +} + +interface FileIdentifier extends BasePackageIdentifier { + uriType: "file"; + filePath: string; +} + +export type PackageIdentifier = FullSlugIdentifier | FileIdentifier; + +export function encodePackageIdentifier(identifier: PackageIdentifier): string { + switch (identifier.uriType) { + case "slug": + return encodeFullSlug(identifier.fullSlug); + case "file": + // For file paths, just return the path directly without a prefix + return identifier.filePath; + default: + throw new Error(`Unknown URI type: ${(identifier as any).uriType}`); + } +} + +export function decodePackageIdentifier(identifier: string): PackageIdentifier { + // Shorthand: if it starts with . or /, then it's a path + if (identifier.startsWith(".") || identifier.startsWith("/")) { + return { + uriType: "file", + filePath: identifier, + }; + } + // Keep support for explicit file:// protocol + else if (identifier.startsWith("file://")) { + return { + uriType: "file", + filePath: identifier.substring(7), + }; + } + // Otherwise, it's a slug + else { + return { + uriType: "slug", + fullSlug: decodeFullSlug(identifier), + }; + } +} + export enum VirtualTags { Latest = "latest", } From 115d069e62067858b10179bd0b2ec7144c771c32 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 9 Apr 2025 10:06:20 -0700 Subject: [PATCH 016/262] token-counts --- core/llm/constants.ts | 22 ------------- core/llm/countTokens.ts | 30 +++++++++-------- core/llm/index.ts | 40 +++++++---------------- packages/llm-info/src/providers/openai.ts | 6 ++++ 4 files changed, 33 insertions(+), 65 deletions(-) diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 333c79e70..1eb81569e 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -7,38 +7,16 @@ const DEFAULT_ARGS = { temperature: DEFAULT_TEMPERATURE, }; -const GPT_4_CTX_LEN = 128_000; - -const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { - "gpt-3.5-turbo": 4096, - "gpt-3.5-turbo-0613": 4096, - "gpt-3.5-turbo-16k": 16_384, - "gpt-35-turbo-16k": 16_384, - "gpt-35-turbo-0613": 4096, - "gpt-35-turbo": 4096, - "gpt-4": 4096, - "gpt-4-32k": 32_000, - "gpt-4-turbo-preview": 32_000, - "gpt-4o": GPT_4_CTX_LEN, - "gpt-4o-mini": GPT_4_CTX_LEN, - "gpt-4-vision": GPT_4_CTX_LEN, - "gpt-4-0125-preview": GPT_4_CTX_LEN, - "gpt-4-1106-preview": GPT_4_CTX_LEN, -}; - -const TOKEN_BUFFER_FOR_SAFETY = 350; const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) const DEFAULT_MAX_BATCH_SIZE = 64; export { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, PROXY_URL, - TOKEN_BUFFER_FOR_SAFETY, }; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2fc01f9b8..0fae50656 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -4,6 +4,7 @@ import { ChatMessage, MessageContent, MessagePart, + Tool, UserChatMessage, } from "../index.js"; @@ -15,7 +16,6 @@ import { LlamaAsyncEncoder, } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; -import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; import { isRuleActive } from "./rules/isRuleActive.js"; import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; @@ -220,6 +220,8 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } +const MAX_TOKEN_BUFFER_FOR_SAFETY = 3000; + function pruneRawPromptFromTop( modelName: string, contextLength: number, @@ -227,20 +229,20 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; + contextLength - tokensForCompletion - Math.max(MAX_TOKEN_BUFFER_FOR_SAFETY, contextLength*; return pruneStringFromTop(modelName, maxTokens, prompt); } -function pruneRawPromptFromBottom( - modelName: string, - contextLength: number, - prompt: string, - tokensForCompletion: number, -): string { - const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; - return pruneStringFromBottom(modelName, maxTokens, prompt); -} +// function pruneRawPromptFromBottom( +// modelName: string, +// contextLength: number, +// prompt: string, +// tokensForCompletion: number, +// ): string { +// const maxTokens = +// contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; +// return pruneStringFromBottom(modelName, maxTokens, prompt); +// } function summarize(message: ChatMessage): string { return `${renderChatMessage(message).substring(0, 100)}...`; @@ -514,7 +516,7 @@ function compileChatMessages({ maxTokens, supportsImages, prompt, - functions, + tools, systemMessage, rules, }: { @@ -524,7 +526,7 @@ function compileChatMessages({ maxTokens: number; supportsImages: boolean; prompt: string | undefined; - functions: any[] | undefined; + tools: Tool[] | undefined; systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { diff --git a/core/llm/index.ts b/core/llm/index.ts index 7544b5292..0c79c6974 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -40,7 +40,6 @@ import { modelSupportsImages, } from "./autodetect.js"; import { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, @@ -278,33 +277,6 @@ export abstract class BaseLLM implements ILLM { return Promise.resolve([]); } - private _compileChatMessages( - options: CompletionOptions, - messages: ChatMessage[], - functions?: any[], - ) { - let contextLength = this.contextLength; - if ( - options.model !== this.model && - options.model in CONTEXT_LENGTH_FOR_MODEL - ) { - contextLength = - CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; - } - - return compileChatMessages({ - modelName: options.model, - msgs: messages, - contextLength, - maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, - supportsImages: this.supportsImages(), - prompt: undefined, - functions, - systemMessage: this.systemMessage, - rules: this.rules ?? [], - }); - } - private _templatePromptLikeMessages(prompt: string): string { if (!this.templateMessages) { return prompt; @@ -913,7 +885,17 @@ export abstract class BaseLLM implements ILLM { completionOptions = this._modifyCompletionOptions(completionOptions); - const messages = this._compileChatMessages(completionOptions, _messages); + const messages = compileChatMessages({ + modelName: completionOptions.model, + msgs: _messages, + contextLength: this.contextLength, + maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + prompt: undefined, + tools: options.tools, + systemMessage: this.systemMessage, + rules: this.rules ?? [], + }); const prompt = this.templateMessages ? this.templateMessages(messages) diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index b96461e4b..a15dd3089 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -8,6 +8,12 @@ export const OpenAi: ModelProvider = { contextLength: 16385, maxCompletionTokens: 4096, }, + { + model: "gpt-3.5-turbo-0613", + displayName: "GPT-3.5 Turbo", + contextLength: 16385, + maxCompletionTokens: 4096, + }, { model: "gpt-3.5-turbo-16k", displayName: "GPT-3.5 Turbo 16K", From a30b9699a7fac138d9641992ba6fd2db348850b2 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 9 Apr 2025 11:10:52 -0700 Subject: [PATCH 017/262] fix uri handling, support local blocks --- core/config/loadLocalAssistants.ts | 8 +- .../profile/ControlPlaneProfileLoader.ts | 25 ++- core/config/profile/LocalProfileLoader.ts | 26 ++- core/config/profile/PlatformProfileLoader.ts | 30 +-- core/config/profile/doLoadConfig.ts | 45 ++-- core/config/yaml/loadYaml.ts | 186 ++++++++-------- core/config/yaml/models.ts | 10 - core/llm/countTokens.ts | 4 + core/package-lock.json | 8 +- core/package.json | 2 +- extensions/vscode/package-lock.json | 2 +- gui/package-lock.json | 2 +- packages/config-yaml/package.json | 2 +- .../config-yaml/src/__tests__/index.test.ts | 46 +++- packages/config-yaml/src/interfaces/index.ts | 9 +- packages/config-yaml/src/load/clientRender.ts | 25 ++- packages/config-yaml/src/load/unroll.ts | 60 +++-- .../config-yaml/src/registryClient.test.ts | 209 ++++++++++++++++++ packages/config-yaml/src/registryClient.ts | 54 ++++- 19 files changed, 529 insertions(+), 224 deletions(-) create mode 100644 packages/config-yaml/src/registryClient.test.ts diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 3daf0cd65..18e24f58d 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -5,7 +5,7 @@ import { DEFAULT_IGNORE_FILETYPES, } from "../indexing/ignore"; import { walkDir } from "../indexing/walkDir"; -import { getGlobalAssistantsPath } from "../util/paths"; +import { getGlobalFolderWithName } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; @@ -67,16 +67,16 @@ export function getDotContinueSubDirs( ): string[] { let fullDirs: string[] = []; - // Workspace .continue/assistants + // Workspace .continue/ if (options.includeWorkspace) { fullDirs = workspaceDirs.map((dir) => joinPathsToUri(dir, ".continue", subDirName), ); } - // ~/.continue/assistants + // ~/.continue/ if (options.includeGlobal) { - fullDirs.push(localPathToUri(getGlobalAssistantsPath())); + fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName))); } return fullDirs; diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 21ea27e14..48634a764 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -62,18 +62,19 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { )) as any); const serializedConfig: SerializedContinueConfig = settings; - return await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - serializedConfig, - undefined, - undefined, - this.workspaceId, - undefined, - null, - ); + return await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigJson: serializedConfig, + profileId: this.workspaceId, + orgScopeId: null, + packageIdentifier: { + uriType: "file", + filePath: "", // TODO + }, + }); } setIsActive(isActive: boolean): void {} diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index f49c8bb7a..466243b3f 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -55,18 +55,20 @@ export default class LocalProfileLoader implements IProfileLoader { description: ProfileDescription; async doLoadConfig(): Promise> { - const result = await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - undefined, - undefined, - undefined, - this.description.id, - this.overrideAssistantFile?.path, - null, - ); + const result = await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + profileId: this.description.id, + overrideConfigYamlByPath: this.overrideAssistantFile?.path, + orgScopeId: null, + packageIdentifier: { + uriType: "file", + filePath: + this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(), + }, + }); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index cf9efb399..70f24a801 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -89,21 +89,23 @@ export default class PlatformProfileLoader implements IProfileLoader { }; } - const results = await doLoadConfig( - this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - undefined, - this.configResult.config, - { - ownerSlug: this.ownerSlug, - packageSlug: this.packageSlug, + const results = await doLoadConfig({ + ide: this.ide, + ideSettingsPromise: this.ideSettingsPromise, + controlPlaneClient: this.controlPlaneClient, + llmLogger: this.llmLogger, + overrideConfigYaml: this.configResult.config, + profileId: this.description.id, + orgScopeId: this.orgScopeId, + packageIdentifier: { + uriType: "slug", + fullSlug: { + ownerSlug: this.ownerSlug, + packageSlug: this.packageSlug, + versionSlug: this.versionSlug, + }, }, - this.description.id, - undefined, - this.orgScopeId, - ); + }); return { config: results.config, diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 626546b74..8674da0a6 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -5,6 +5,7 @@ import { ConfigResult, ConfigValidationError, ModelRole, + PackageIdentifier, } from "@continuedev/config-yaml"; import { @@ -34,20 +35,31 @@ import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; -import { PlatformConfigMetadata } from "./PlatformProfileLoader"; +export default async function doLoadConfig(options: { + ide: IDE; + ideSettingsPromise: Promise; + controlPlaneClient: ControlPlaneClient; + llmLogger: ILLMLogger; + overrideConfigJson?: SerializedContinueConfig; + overrideConfigYaml?: AssistantUnrolled; + profileId: string; + overrideConfigYamlByPath?: string; + orgScopeId: string | null; + packageIdentifier: PackageIdentifier; +}): Promise> { + const { + ide, + ideSettingsPromise, + controlPlaneClient, + llmLogger, + overrideConfigJson, + overrideConfigYaml, + profileId, + overrideConfigYamlByPath, + orgScopeId, + packageIdentifier, + } = options; -export default async function doLoadConfig( - ide: IDE, - ideSettingsPromise: Promise, - controlPlaneClient: ControlPlaneClient, - llmLogger: ILLMLogger, - overrideConfigJson: SerializedContinueConfig | undefined, - overrideConfigYaml: AssistantUnrolled | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - profileId: string, - overrideConfigYamlByPath: string | undefined, - orgScopeId: string | null, -): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); @@ -70,7 +82,7 @@ export default async function doLoadConfig( let configLoadInterrupted = false; if (overrideConfigYaml || fs.existsSync(configYamlPath)) { - const result = await loadContinueConfigFromYaml( + const result = await loadContinueConfigFromYaml({ ide, ideSettings, ideInfo, @@ -78,11 +90,10 @@ export default async function doLoadConfig( llmLogger, workOsAccessToken, overrideConfigYaml, - platformConfigMetadata, controlPlaneClient, - configYamlPath, orgScopeId, - ); + packageIdentifier, + }); newConfig = result.config; errors = result.errors; configLoadInterrupted = result.configLoadInterrupted; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 70c34adc4..15c5ac1fc 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -1,5 +1,3 @@ -import fs from "node:fs"; - import { AssistantUnrolled, BLOCK_TYPES, @@ -7,12 +5,13 @@ import { ConfigValidationError, isAssistantUnrolledNonNullable, ModelRole, - parseAssistantUnrolled, + PackageIdentifier, RegistryClient, - unrollAssistantFromContent, + unrollAssistant, validateConfigYaml, } from "@continuedev/config-yaml"; import { fetchwithRequestOptions } from "@continuedev/fetch"; +import { dirname } from "node:path"; import { ContinueConfig, @@ -37,41 +36,64 @@ import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandF import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; import { allTools } from "../../tools"; import { GlobalContext } from "../../util/GlobalContext"; -import { getConfigYamlPath } from "../../util/paths"; import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; -import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { getControlPlaneEnvSync } from "../../control-plane/env"; +import { getCleanUriPath } from "../../util/uri"; import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; -async function loadConfigYaml( - rawYaml: string, - overrideConfigYaml: AssistantUnrolled | undefined, - controlPlaneClient: ControlPlaneClient, - orgScopeId: string | null, - ideSettings: IdeSettings, - ide: IDE, -): Promise> { +async function loadConfigYaml(options: { + overrideConfigYaml: AssistantUnrolled | undefined; + controlPlaneClient: ControlPlaneClient; + orgScopeId: string | null; + ideSettings: IdeSettings; + ide: IDE; + packageIdentifier: PackageIdentifier; +}): Promise> { + const { + overrideConfigYaml, + controlPlaneClient, + orgScopeId, + ideSettings, + ide, + packageIdentifier, + } = options; + + // Add local .continue blocks + const allLocalBlocks: PackageIdentifier[] = []; + for (const blockType of BLOCK_TYPES) { + const localBlocks = await getAllDotContinueYamlFiles( + ide, + { includeGlobal: true, includeWorkspace: true }, + blockType, + ); + allLocalBlocks.push( + ...localBlocks.map((b) => ({ + uriType: "file" as const, + filePath: b.path, + })), + ); + } + let config = overrideConfigYaml ?? // This is how we allow use of blocks locally - (await unrollAssistantFromContent( - { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - rawYaml, - new RegistryClient( - await controlPlaneClient.getAccessToken(), - getControlPlaneEnvSync( + (await unrollAssistant( + packageIdentifier, + new RegistryClient({ + accessToken: await controlPlaneClient.getAccessToken(), + apiBase: getControlPlaneEnvSync( ideSettings.continueTestEnvironment, ideSettings.enableControlServerBeta, ).CONTROL_PLANE_URL, - ), + rootPath: + packageIdentifier.uriType === "file" + ? dirname(getCleanUriPath(packageIdentifier.filePath)) + : undefined, + }), { currentUserSlug: "", onPremProxyUrl: null, @@ -82,6 +104,7 @@ async function loadConfigYaml( ide, ), renderSecrets: true, + injectBlocks: allLocalBlocks, }, )); @@ -110,17 +133,27 @@ async function loadConfigYaml( }; } -async function configYamlToContinueConfig( - config: AssistantUnrolled, - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - llmLogger: ILLMLogger, - workOsAccessToken: string | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - allowFreeTrial: boolean = true, -): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { +async function configYamlToContinueConfig(options: { + config: AssistantUnrolled; + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + workOsAccessToken: string | undefined; + allowFreeTrial?: boolean; +}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { + let { + config, + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + allowFreeTrial, + } = options; + allowFreeTrial = allowFreeTrial ?? true; + const localErrors: ConfigValidationError[] = []; const continueConfig: ContinueConfig = { @@ -232,7 +265,6 @@ async function configYamlToContinueConfig( uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config: continueConfig, }); @@ -422,35 +454,39 @@ async function configYamlToContinueConfig( return { config: continueConfig, errors: localErrors }; } -export async function loadContinueConfigFromYaml( - ide: IDE, - ideSettings: IdeSettings, - ideInfo: IdeInfo, - uniqueId: string, - llmLogger: ILLMLogger, - workOsAccessToken: string | undefined, - overrideConfigYaml: AssistantUnrolled | undefined, - platformConfigMetadata: PlatformConfigMetadata | undefined, - controlPlaneClient: ControlPlaneClient, - configYamlPath: string | undefined, - orgScopeId: string | null, -): Promise> { - const rawYaml = - overrideConfigYaml === undefined - ? fs.readFileSync( - configYamlPath ?? getConfigYamlPath(ideInfo.ideType), - "utf-8", - ) - : ""; +export async function loadContinueConfigFromYaml(options: { + ide: IDE; + ideSettings: IdeSettings; + ideInfo: IdeInfo; + uniqueId: string; + llmLogger: ILLMLogger; + workOsAccessToken: string | undefined; + overrideConfigYaml: AssistantUnrolled | undefined; + controlPlaneClient: ControlPlaneClient; + orgScopeId: string | null; + packageIdentifier: PackageIdentifier; +}): Promise> { + const { + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + workOsAccessToken, + overrideConfigYaml, + controlPlaneClient, + orgScopeId, + packageIdentifier, + } = options; - const configYamlResult = await loadConfigYaml( - rawYaml, + const configYamlResult = await loadConfigYaml({ overrideConfigYaml, controlPlaneClient, orgScopeId, ideSettings, ide, - ); + packageIdentifier, + }); if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { return { @@ -460,40 +496,16 @@ export async function loadContinueConfigFromYaml( }; } - // Add local .continue blocks - for (const blockType of BLOCK_TYPES) { - const localBlocks = await getAllDotContinueYamlFiles( - ide, - { includeGlobal: true, includeWorkspace: true }, - blockType, - ); - - for (const block of localBlocks) { - const parsedYaml = parseAssistantUnrolled(block.content); - - const inlineBlock = parsedYaml[blockType]?.[0]; - if (inlineBlock) { - configYamlResult.config[blockType] = [ - ...(configYamlResult.config[blockType] ?? []), - inlineBlock as any, - ]; - } - } - - configYamlResult.config; - } - const { config: continueConfig, errors: localErrors } = - await configYamlToContinueConfig( - configYamlResult.config, + await configYamlToContinueConfig({ + config: configYamlResult.config, ide, ideSettings, ideInfo, uniqueId, llmLogger, workOsAccessToken, - platformConfigMetadata, - ); + }); try { const systemPromptDotFile = await getSystemPromptDotFile(ide); diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index fa9c92cac..0bbe19235 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -9,7 +9,6 @@ import { } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; -import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -32,14 +31,12 @@ async function modelConfigToBaseLLM({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }: { model: ModelConfig; uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { const cls = getModelClass(model); @@ -148,7 +145,6 @@ async function autodetectModels({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }: { llm: BaseLLM; @@ -157,7 +153,6 @@ async function autodetectModels({ uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { try { @@ -178,7 +173,6 @@ async function autodetectModels({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }); }), @@ -196,7 +190,6 @@ export async function llmsFromModelConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }: { model: ModelConfig; @@ -204,7 +197,6 @@ export async function llmsFromModelConfig({ uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { const baseLlm = await modelConfigToBaseLLM({ @@ -212,7 +204,6 @@ export async function llmsFromModelConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }); if (!baseLlm) { @@ -227,7 +218,6 @@ export async function llmsFromModelConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }); return models; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2fc01f9b8..bec3cbc13 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -307,6 +307,10 @@ function pruneChatHistory( // 1. Replace beyond last 5 messages with summary let i = 0; while (totalTokens > contextLength && i < chatHistory.length - 5) { + if (chatHistory[i].role !== "assistant") { + i++; + continue; + } const message = chatHistory[i]; totalTokens -= countTokens(message.content, modelName); totalTokens += countTokens(summarize(message), modelName); diff --git a/core/package-lock.json b/core/package-lock.json index eb97ecc5a..ba1113494 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.82", + "@continuedev/config-yaml": "^1.0.85", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", @@ -2977,9 +2977,9 @@ } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.82", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.82.tgz", - "integrity": "sha512-IscUcyDoN4DiYEdoAJRo0LcbqgHAWYIUCqNSmjRQuASY4s2Xel2iejmnCj0oHj4DXz/bAlNBLHR6lUBs9tqSDQ==", + "version": "1.0.85", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.85.tgz", + "integrity": "sha512-yqcoUMlA/qjhVYJt6BBfY6xCpfKar20LfljHMjObG+ndo3MLzPXFxU/+aB4MAQmyn54P5VGbXrALJFo/EErxMA==", "dependencies": { "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", diff --git a/core/package.json b/core/package.json index 6a41321d4..8af64e891 100644 --- a/core/package.json +++ b/core/package.json @@ -47,7 +47,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.82", + "@continuedev/config-yaml": "^1.0.85", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 6f637302d..126df7e51 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.80", + "@continuedev/config-yaml": "^1.0.85", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/package-lock.json b/gui/package-lock.json index 1f2ce7ae6..4cd481b0c 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -109,7 +109,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.82", + "@continuedev/config-yaml": "^1.0.85", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index a601d33d2..bfe7c45a5 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.82", + "version": "1.0.85", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index 7a045cfb5..95f7bf331 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -2,7 +2,8 @@ import * as fs from "fs"; import { decodeSecretLocation, FQSN, - FullSlug, + PackageIdentifier, + packageIdentifierToShorthandSlug, PlatformClient, PlatformSecretStore, Registry, @@ -90,18 +91,24 @@ describe("E2E Scenarios", () => { }; const registry: Registry = { - getContent: async function (fullSlug: FullSlug): Promise { + getContent: async function (id: PackageIdentifier): Promise { + const slug = packageIdentifierToShorthandSlug(id); return fs - .readFileSync( - `./src/__tests__/packages/${fullSlug.ownerSlug}/${fullSlug.packageSlug}.yaml`, - ) + .readFileSync(`./src/__tests__/packages/${slug}.yaml`) .toString(); }, }; it("should unroll assistant with a single block that doesn't exist", async () => { const unrolledConfig = await unrollAssistant( - "test-org/assistant-with-non-existing-block", + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "assistant-with-non-existing-block", + versionSlug: "latest", + }, + }, registry, { renderSecrets: true, @@ -117,7 +124,14 @@ describe("E2E Scenarios", () => { it("should correctly unroll assistant", async () => { const unrolledConfig = await unrollAssistant( - "test-org/assistant", + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "assistant", + versionSlug: "latest", + }, + }, registry, { renderSecrets: true, @@ -195,7 +209,14 @@ describe("E2E Scenarios", () => { it("should correctly unroll assistant with injected blocks", async () => { const unrolledConfig = await unrollAssistant( - "test-org/assistant", + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "assistant", + versionSlug: "latest", + }, + }, registry, { renderSecrets: true, @@ -206,9 +227,12 @@ describe("E2E Scenarios", () => { // Add an injected block injectBlocks: [ { - ownerSlug: "test-org", - packageSlug: "rules", - versionSlug: "latest", + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "rules", + versionSlug: "latest", + }, }, ], }, diff --git a/packages/config-yaml/src/interfaces/index.ts b/packages/config-yaml/src/interfaces/index.ts index a3f32e93a..dd6377230 100644 --- a/packages/config-yaml/src/interfaces/index.ts +++ b/packages/config-yaml/src/interfaces/index.ts @@ -1,11 +1,16 @@ import { SecretLocation, SecretResult, SecretType } from "./SecretResult.js"; -import { FQSN, FullSlug, PackageSlug, packageSlugsEqual } from "./slugs.js"; +import { + FQSN, + PackageIdentifier, + PackageSlug, + packageSlugsEqual, +} from "./slugs.js"; /** * A registry stores the content of packages */ export interface Registry { - getContent(fullSlug: FullSlug): Promise; + getContent(fullSlug: PackageIdentifier): Promise; } export type SecretNamesMap = Map; diff --git a/packages/config-yaml/src/load/clientRender.ts b/packages/config-yaml/src/load/clientRender.ts index ffc62f0fc..18a0aebd0 100644 --- a/packages/config-yaml/src/load/clientRender.ts +++ b/packages/config-yaml/src/load/clientRender.ts @@ -9,7 +9,7 @@ import { decodeFQSN, encodeFQSN, FQSN, - PackageSlug, + PackageIdentifier, } from "../interfaces/slugs.js"; import { AssistantUnrolled } from "../schemas/index.js"; import { @@ -19,7 +19,7 @@ import { } from "./unroll.js"; export async function renderSecrets( - packageSlug: PackageSlug, + packageIdentifier: PackageIdentifier, unrolledConfigContent: string, clientSecretStore: SecretStore, orgScopeId: string | null, // The "scope" that the user is logged in with @@ -72,7 +72,7 @@ export async function renderSecrets( // 7. We update any of the items with the proxy version if there are un-rendered secrets const finalConfig = useProxyForUnrenderedSecrets( parsedYaml, - packageSlug, + packageIdentifier, orgScopeId, onPremProxyUrl, ); @@ -103,17 +103,28 @@ export function getUnrenderedSecretLocation( return undefined; } +export function packageIdentifierToShorthandSlug( + id: PackageIdentifier, +): string { + switch (id.uriType) { + case "slug": + return `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + case "file": + return "/"; + } +} + function getContinueProxyModelName( - packageSlug: PackageSlug, + packageIdentifier: PackageIdentifier, provider: string, model: string, ): string { - return `${packageSlug.ownerSlug}/${packageSlug.packageSlug}/${provider}/${model}`; + return `${packageIdentifierToShorthandSlug(packageIdentifier)}/${provider}/${model}`; } export function useProxyForUnrenderedSecrets( config: AssistantUnrolled, - packageSlug: PackageSlug, + packageIdentifier: PackageIdentifier, orgScopeId: string | null, onPremProxyUrl: string | null, ): AssistantUnrolled { @@ -128,7 +139,7 @@ export function useProxyForUnrenderedSecrets( name: config.models[i]?.name ?? "", provider: "continue-proxy", model: getContinueProxyModelName( - packageSlug, + packageIdentifier, config.models[i]?.provider ?? "", config.models[i]?.model ?? "", ), diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 1e818c4ca..8bd012138 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -3,12 +3,10 @@ import { PlatformClient, Registry } from "../interfaces/index.js"; import { encodeSecretLocation } from "../interfaces/SecretResult.js"; import { decodeFQSN, - decodeFullSlug, + decodePackageIdentifier, encodeFQSN, - encodePackageSlug, FQSN, - FullSlug, - PackageSlug, + PackageIdentifier, } from "../interfaces/slugs.js"; import { AssistantUnrolled, @@ -19,7 +17,10 @@ import { configYamlSchema, Rule, } from "../schemas/index.js"; -import { useProxyForUnrenderedSecrets } from "./clientRender.js"; +import { + packageIdentifierToShorthandSlug, + useProxyForUnrenderedSecrets, +} from "./clientRender.js"; import { getBlockType } from "./getBlockType.js"; export function parseConfigYaml(configYaml: string): ConfigYaml { @@ -116,11 +117,11 @@ function flattenTemplateData( function secretToFQSNMap( secretNames: string[], - parentPackages: PackageSlug[], + parentPackages: PackageIdentifier[], ): Record { const map: Record = {}; for (const secret of secretNames) { - const parentSlugs = parentPackages.map(encodePackageSlug); + const parentSlugs = parentPackages.map(packageIdentifierToShorthandSlug); const parts = [...parentSlugs, secret]; const fqsn = parts.join("/"); map[secret] = `\${{ secrets.${fqsn} }}`; @@ -131,7 +132,7 @@ function secretToFQSNMap( function extractFQSNMap( rawContent: string, - parentPackages: PackageSlug[], + parentPackages: PackageIdentifier[], ): Record { const templateVars = getTemplateVariables(rawContent); const secrets = templateVars @@ -181,7 +182,7 @@ async function extractRenderedSecretsMap( export interface BaseUnrollAssistantOptions { renderSecrets: boolean; - injectBlocks?: FullSlug[]; + injectBlocks?: PackageIdentifier[]; } export interface DoNotRenderSecretsUnrollAssistantOptions @@ -204,20 +205,13 @@ export type UnrollAssistantOptions = | RenderSecretsUnrollAssistantOptions; export async function unrollAssistant( - fullSlug: string, + id: PackageIdentifier, registry: Registry, options: UnrollAssistantOptions, ): Promise { - const assistantSlug = decodeFullSlug(fullSlug); - // Request the content from the registry - const rawContent = await registry.getContent(assistantSlug); - return unrollAssistantFromContent( - assistantSlug, - rawContent, - registry, - options, - ); + const rawContent = await registry.getContent(id); + return unrollAssistantFromContent(id, rawContent, registry, options); } function renderTemplateData( @@ -238,7 +232,7 @@ function renderTemplateData( } export async function unrollAssistantFromContent( - assistantSlug: FullSlug, + id: PackageIdentifier, rawYaml: string, registry: Registry, options: UnrollAssistantOptions, @@ -259,7 +253,7 @@ export async function unrollAssistantFromContent( // Convert all of the template variables to FQSNs // Secrets from the block will have the assistant slug prepended to the FQSN const templatedYaml = renderTemplateData(rawUnrolledYaml, { - secrets: extractFQSNMap(rawUnrolledYaml, [assistantSlug]), + secrets: extractFQSNMap(rawUnrolledYaml, [id]), }); if (!options.renderSecrets) { @@ -279,7 +273,7 @@ export async function unrollAssistantFromContent( // Parse again and replace models with proxy versions where secrets weren't rendered const finalConfig = useProxyForUnrenderedSecrets( parseAssistantUnrolled(renderedYaml), - assistantSlug, + id, options.orgScopeId, options.onPremProxyUrl, ); @@ -289,7 +283,7 @@ export async function unrollAssistantFromContent( export async function unrollBlocks( assistant: ConfigYaml, registry: Registry, - injectBlocks: FullSlug[] | undefined, + injectBlocks: PackageIdentifier[] | undefined, ): Promise { const unrolledAssistant: AssistantUnrolled = { name: assistant.name, @@ -311,7 +305,7 @@ export async function unrollBlocks( if ("uses" in unrolledBlock) { try { const blockConfigYaml = await resolveBlock( - decodeFullSlug(unrolledBlock.uses), + decodePackageIdentifier(unrolledBlock.uses), unrolledBlock.with, registry, ); @@ -346,7 +340,7 @@ export async function unrollBlocks( } else if ("uses" in rule) { try { const blockConfigYaml = await resolveBlock( - decodeFullSlug(rule.uses), + decodePackageIdentifier(rule.uses), rule.with, registry, ); @@ -397,26 +391,24 @@ export async function unrollBlocks( } export async function resolveBlock( - fullSlug: FullSlug, + id: PackageIdentifier, inputs: Record | undefined, registry: Registry, ): Promise { // Retrieve block raw yaml - const rawYaml = await registry.getContent(fullSlug); + const rawYaml = await registry.getContent(id); if (rawYaml === undefined) { - throw new Error( - `Block ${fullSlug.ownerSlug}/${fullSlug.packageSlug} not found`, - ); + throw new Error(`Block ${packageIdentifierToShorthandSlug(id)} not found`); } // Convert any input secrets to FQSNs (they get FQSNs as if they are in the block. This is so that we know when to use models add-on / free trial secrets) - const renderedInputs = inputsToFQSNs(inputs || {}, fullSlug); + const renderedInputs = inputsToFQSNs(inputs || {}, id); // Render template variables const templatedYaml = renderTemplateData(rawYaml, { inputs: renderedInputs, - secrets: extractFQSNMap(rawYaml, [fullSlug]), + secrets: extractFQSNMap(rawYaml, [id]), }); const parsedYaml = parseBlock(templatedYaml); @@ -425,12 +417,12 @@ export async function resolveBlock( function inputsToFQSNs( inputs: Record, - blockSlug: PackageSlug, + blockIdentifier: PackageIdentifier, ): Record { const renderedInputs: Record = {}; for (const [key, value] of Object.entries(inputs)) { renderedInputs[key] = renderTemplateData(value, { - secrets: extractFQSNMap(value, [blockSlug]), + secrets: extractFQSNMap(value, [blockIdentifier]), }); } return renderedInputs; diff --git a/packages/config-yaml/src/registryClient.test.ts b/packages/config-yaml/src/registryClient.test.ts new file mode 100644 index 000000000..d820579ab --- /dev/null +++ b/packages/config-yaml/src/registryClient.test.ts @@ -0,0 +1,209 @@ +import * as fs from "node:fs"; +import * as http from "node:http"; +import { AddressInfo } from "node:net"; +import * as os from "node:os"; +import * as path from "node:path"; +import { PackageIdentifier } from "./interfaces/slugs.js"; +import { RegistryClient } from "./registryClient.js"; + +describe("RegistryClient", () => { + // Create a temp directory for test files + let tempDir: string; + // Setup a test server + let server: http.Server; + let apiBaseUrl: string; + beforeAll(async () => { + // Create a temporary directory for test files + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "registry-client-test-")); + + // Create a simple HTTP server for API testing + server = http.createServer((req, res) => { + if (req.url?.startsWith("/registry/v1/")) { + const authHeader = req.headers.authorization; + const data = { + content: authHeader + ? `auth content for ${req.url}` + : `content for ${req.url}`, + }; + + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(data)); + } else { + res.writeHead(404); + res.end(); + } + }); + + // Start server on a random port + await new Promise((resolve) => { + server.listen(0, "localhost", () => resolve()); + }); + + const address = server.address() as AddressInfo; + apiBaseUrl = `http://localhost:${address.port}`; + }); + + afterAll(async () => { + // Clean up temp directory + fs.rmSync(tempDir, { recursive: true, force: true }); + + // Close the test server + await new Promise((resolve) => { + server.close(() => resolve()); + }); + }); + + describe("constructor", () => { + it("should use default apiBase if not provided", () => { + const client = new RegistryClient(); + expect((client as any).apiBase).toBe("https://api.continue.dev/"); + }); + + it("should append trailing slash to apiBase if missing", () => { + const client = new RegistryClient({ apiBase: "https://example.com" }); + expect((client as any).apiBase).toBe("https://example.com/"); + }); + + it("should keep trailing slash if apiBase already has one", () => { + const client = new RegistryClient({ apiBase: "https://example.com/" }); + expect((client as any).apiBase).toBe("https://example.com/"); + }); + + it("should store the accessToken if provided", () => { + const client = new RegistryClient({ accessToken: "test-token" }); + expect((client as any).accessToken).toBe("test-token"); + }); + + it("should store the rootPath if provided", () => { + const client = new RegistryClient({ rootPath: "/test-path" }); + expect((client as any).rootPath).toBe("/test-path"); + }); + }); + + describe("getContent", () => { + let testFilePath: string; + + beforeEach(() => { + // Create a test file for each test + testFilePath = path.join(tempDir, "test-file.yaml"); + fs.writeFileSync(testFilePath, "file content", "utf8"); + }); + + it("should get content from file path for file uriType", async () => { + const client = new RegistryClient(); + + const id: PackageIdentifier = { + uriType: "file", + filePath: testFilePath, + }; + + const result = await client.getContent(id); + expect(result).toBe("file content"); + }); + + it("should get content from slug for slug uriType", async () => { + const client = new RegistryClient({ + apiBase: apiBaseUrl, + }); + + const id: PackageIdentifier = { + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "1.0.0", + }, + }; + + const result = await client.getContent(id); + expect(result).toBe("content for /registry/v1/owner/package/1.0.0"); + }); + + it("should throw error for unknown uriType", async () => { + const client = new RegistryClient(); + + const id = { + uriType: "unknown", + } as any; + + await expect(client.getContent(id)).rejects.toThrow( + "Unknown package identifier type: unknown", + ); + }); + }); + + describe("getContentFromFilePath", () => { + let absoluteFilePath: string; + let relativeFilePath: string; + + beforeEach(() => { + // Create test files + absoluteFilePath = path.join(tempDir, "absolute-path.yaml"); + fs.writeFileSync(absoluteFilePath, "absolute file content", "utf8"); + + // Create a subdirectory and file in the temp directory + const subDir = path.join(tempDir, "sub"); + fs.mkdirSync(subDir, { recursive: true }); + relativeFilePath = "sub/relative-path.yaml"; + fs.writeFileSync( + path.join(tempDir, relativeFilePath), + "relative file content", + "utf8", + ); + }); + + it("should read from absolute path directly", () => { + const client = new RegistryClient(); + + const result = (client as any).getContentFromFilePath(absoluteFilePath); + + expect(result).toBe("absolute file content"); + }); + + it("should use rootPath for relative paths when provided", () => { + const client = new RegistryClient({ rootPath: tempDir }); + + const result = (client as any).getContentFromFilePath(relativeFilePath); + + expect(result).toBe("relative file content"); + }); + + it("should throw error for relative path without rootPath", () => { + const client = new RegistryClient(); + + expect(() => { + (client as any).getContentFromFilePath("relative/path.yaml"); + }).toThrow("No rootPath provided for relative file path"); + }); + }); + + describe("getContentFromSlug", () => { + it("should fetch content from API without auth token", async () => { + const client = new RegistryClient({ + apiBase: apiBaseUrl, + }); + const result = await (client as any).getContentFromSlug({ + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "1.0.0", + }); + + expect(result).toBe("content for /registry/v1/owner/package/1.0.0"); + }); + + it("should include auth token in request when provided", async () => { + const client = new RegistryClient({ + apiBase: apiBaseUrl, + accessToken: "test-token", + }); + + const result = await (client as any).getContentFromSlug({ + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "1.0.0", + }); + + expect(result).toBe("auth content for /registry/v1/owner/package/1.0.0"); + }); + }); +}); diff --git a/packages/config-yaml/src/registryClient.ts b/packages/config-yaml/src/registryClient.ts index d6d3f28fc..73ca9fefd 100644 --- a/packages/config-yaml/src/registryClient.ts +++ b/packages/config-yaml/src/registryClient.ts @@ -1,16 +1,58 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; import { Registry } from "./interfaces/index.js"; -import { FullSlug } from "./interfaces/slugs.js"; +import { FullSlug, PackageIdentifier } from "./interfaces/slugs.js"; + +interface RegistryClientOptions { + accessToken?: string; + apiBase?: string; + rootPath?: string; +} export class RegistryClient implements Registry { - constructor( - private readonly accessToken?: string, - private readonly apiBase: string = "https://api.continue.dev/", - ) { + private readonly accessToken?: string; + private readonly apiBase: string; + private readonly rootPath?: string; + + constructor(options: RegistryClientOptions = {}) { + this.accessToken = options.accessToken; + this.apiBase = options.apiBase ?? "https://api.continue.dev/"; + this.rootPath = options.rootPath; if (!this.apiBase.endsWith("/")) { this.apiBase += "/"; } } - async getContent(fullSlug: FullSlug): Promise { + + async getContent(id: PackageIdentifier): Promise { + switch (id.uriType) { + case "file": + return this.getContentFromFilePath(id.filePath); + case "slug": + return this.getContentFromSlug(id.fullSlug); + default: + throw new Error( + `Unknown package identifier type: ${(id as any).uriType}`, + ); + } + } + + private getContentFromFilePath(filepath: string): string { + if (filepath.startsWith("file://")) { + const pathWithoutProtocol = filepath.slice(7); + + // For Windows file:///C:/path/to/file, we need to handle it properly + // On other systems, we might have file:///path/to/file + return fs.readFileSync(decodeURIComponent(pathWithoutProtocol), "utf8"); + } else if (path.isAbsolute(filepath)) { + return fs.readFileSync(filepath, "utf8"); + } else if (this.rootPath) { + return fs.readFileSync(path.join(this.rootPath, filepath), "utf8"); + } else { + throw new Error("No rootPath provided for relative file path"); + } + } + + private async getContentFromSlug(fullSlug: FullSlug): Promise { const response = await fetch( `${this.apiBase}registry/v1/${fullSlug.ownerSlug}/${fullSlug.packageSlug}/${fullSlug.versionSlug}`, { From abb27201f69efeb65d8ae4a388f57b2255d274c5 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 9 Apr 2025 11:20:18 -0700 Subject: [PATCH 018/262] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 3948b3c8e..bd056e12e 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.22", + "version": "1.1.24", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From e66bf6e11926577b59130e69ebf5592677712f1b Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 9 Apr 2025 11:28:08 -0700 Subject: [PATCH 019/262] fix type error --- core/config/profile/doLoadConfig.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index eefdf8f9b..702f98a45 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -92,6 +92,7 @@ export default async function doLoadConfig(options: { controlPlaneClient, orgScopeId, packageIdentifier, + workOsAccessToken, }); newConfig = result.config; errors = result.errors; From 92ece90f0dbb18cb1a7ee601cc45c44d0a56cbba Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 9 Apr 2025 17:08:52 -0700 Subject: [PATCH 020/262] fix new type error --- packages/config-yaml/package.json | 2 +- packages/config-yaml/src/load/unroll.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index bfe7c45a5..128cbe99d 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.85", + "version": "1.0.86", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index 8bd012138..b0183482c 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -292,7 +292,7 @@ export async function unrollBlocks( const sections: (keyof Omit< ConfigYaml, - "name" | "version" | "rules" | "schema" + "name" | "version" | "rules" | "schema" | "metadata" >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; // For each section, replace "uses/with" blocks with the real thing From 88e3fbbc98dc2171ef530beea844c767475ecc23 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 10 Apr 2025 10:33:02 +0200 Subject: [PATCH 021/262] Sort models alphabetically in Chat view Signed-off-by: Fred Bricon --- gui/src/components/modelSelection/ModelSelect.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 8191af54b..e7dc1fbf5 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -131,8 +131,9 @@ function ModelSelect() { // Sort so that options without an API key are at the end useEffect(() => { - const enabledOptions = options.filter((option) => option.apiKey !== ""); - const disabledOptions = options.filter((option) => option.apiKey === ""); + const alphaSort = options.sort((a, b) => a.title.localeCompare(b.title)); + const enabledOptions = alphaSort.filter((option) => option.apiKey !== ""); + const disabledOptions = alphaSort.filter((option) => option.apiKey === ""); const sorted = [...enabledOptions, ...disabledOptions]; From 41269e0e151e4f68ed956dda1893660ac9c54e79 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 10 Apr 2025 10:59:37 +0200 Subject: [PATCH 022/262] Sort models alphabetically in Models section Signed-off-by: Fred Bricon --- gui/src/pages/config/ModelRoleSelector.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index e3464a6f2..a4606ad89 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -108,7 +108,7 @@ const ModelRoleSelector = ({ style={{ borderRadius: defaultBorderRadius }} className="min-w-40" > - {models.map((option, idx) => { + {[...models].sort((a,b)=>a.title.localeCompare(b.title)).map((option, idx) => { const showMissingApiKeyMsg = option.configurationStatus === LLMConfigurationStatuses.MISSING_API_KEY; From 9c3d9e678baee03b59f885d14cf558144fbecf32 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Apr 2025 08:57:11 -0700 Subject: [PATCH 023/262] fix type err --- gui/src/components/mainInput/Lump/EditBlockButton.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/EditBlockButton.tsx b/gui/src/components/mainInput/Lump/EditBlockButton.tsx index 53cd82cfb..6cdcac4b0 100644 --- a/gui/src/components/mainInput/Lump/EditBlockButton.tsx +++ b/gui/src/components/mainInput/Lump/EditBlockButton.tsx @@ -4,7 +4,10 @@ import { useContext } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -type SectionKey = Exclude; +type SectionKey = Exclude< + keyof ConfigYaml, + "name" | "version" | "schema" | "metadata" +>; interface EditBlockButtonProps { blockType: T; From 9acc5df354cf91410f78d6e861d2a58e7386cf52 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Apr 2025 11:24:02 -0700 Subject: [PATCH 024/262] remove debugger --- gui/src/hooks/useSetup.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 3f65ecfa3..b29804500 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -50,7 +50,6 @@ function useSetup() { organizations, selectedOrgId, } = result; - debugger; if (isInitial && hasDoneInitialConfigLoad.current) { return; } From 68d4c261966d3e87b5f3d2f1e0e5c97c973fd44b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 11 Apr 2025 17:08:34 -0700 Subject: [PATCH 025/262] clear-sessions --- core/core.ts | 8 +- core/protocol/core.ts | 1 + core/protocol/passThrough.ts | 1 + core/util/history.ts | 10 +- .../constants/MessageTypes.kt | 1 + .../components/History/HistoryTableRow.tsx | 141 +++++++------- gui/src/components/History/index.tsx | 174 ++++++++++++------ gui/src/pages/history/index.tsx | 5 +- 8 files changed, 201 insertions(+), 140 deletions(-) diff --git a/core/core.ts b/core/core.ts index 68aa605ac..71521fa60 100644 --- a/core/core.ts +++ b/core/core.ts @@ -271,7 +271,6 @@ export class Core { } }); - // Special on("abort", (msg) => { this.abortedMessageIds.add(msg.messageId); }); @@ -300,12 +299,14 @@ export class Core { historyManager.save(msg.data); }); - // Dev data + on("history/clear", (msg) => { + historyManager.clearAll(); + }); + on("devdata/log", async (msg) => { void DataLogger.getInstance().logDevData(msg.data); }); - // Edit config on("config/addModel", (msg) => { const model = msg.data.model; addModel(model, msg.data.role); @@ -386,7 +387,6 @@ export class Core { if (!config) { return []; } - const items = await config.contextProviders ?.find((provider) => provider.description.title === msg.data.title) ?.loadSubmenuItems({ diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 7f29c2e25..6581e1607 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -49,6 +49,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "history/delete": [{ id: string }, void]; "history/load": [{ id: string }, Session]; "history/save": [Session, void]; + "history/clear": [undefined, void]; "devdata/log": [DevDataLogEvent, void]; "config/addOpenAiKey": [string, void]; "config/addModel": [ diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index 1d854f948..ffdbb52fe 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -14,6 +14,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "history/delete", "history/load", "history/save", + "history/clear", "devdata/log", "config/addModel", "config/newPromptFile", diff --git a/core/util/history.ts b/core/util/history.ts index 622c2c9ce..ab332a11b 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -4,7 +4,11 @@ import { Session, SessionMetadata } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; import { NEW_SESSION_TITLE } from "./constants.js"; -import { getSessionFilePath, getSessionsListPath } from "./paths.js"; +import { + getSessionFilePath, + getSessionsFolderPath, + getSessionsListPath, +} from "./paths.js"; function safeParseArray( value: string, errorMessage: string = "Error parsing array", @@ -67,6 +71,10 @@ class HistoryManager { ); } + clearAll() { + fs.rmSync(getSessionsFolderPath(), { recursive: true, force: true }); + } + load(sessionId: string): Session { try { const sessionFile = getSessionFilePath(sessionId); 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 100ee2aad..7f0557c57 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 @@ -79,6 +79,7 @@ class MessageTypes { "history/delete", "history/load", "history/save", + "history/clear", "devdata/log", "config/addModel", "config/newPromptFile", diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 11a5a36df..8b7f3ba38 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -1,5 +1,6 @@ import { PencilSquareIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SessionMetadata } from "core"; +import { getUriPathBasename } from "core/util/uri"; import React, { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Input } from ".."; @@ -12,10 +13,6 @@ import { updateSession, } from "../../redux/thunks/session"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; -import { - getLastNUriRelativePathParts, - getUriPathBasename, -} from "core/util/uri"; export function HistoryTableRow({ sessionMetadata, @@ -65,52 +62,48 @@ export function HistoryTableRow({ }; return ( - - setHovered(true)} - onMouseLeave={() => setHovered(false)} - > -
{ - if (sessionMetadata.sessionId !== currentSessionId) { - await dispatch( - loadSession({ - sessionId: sessionMetadata.sessionId, - saveCurrentSession: true, - }), - ); - } - navigate("/"); - }} - > -
- {editing ? ( -
- titleInput && titleInput.focus()} - value={sessionTitleEditValue} - onChange={(e) => setSessionTitleEditValue(e.target.value)} - onKeyUp={(e) => handleKeyUp(e)} - onBlur={() => setEditing(false)} - /> -
- ) : ( - - {sessionMetadata.title} - - )} + setHovered(true)} + onMouseLeave={() => setHovered(false)} + data-testid={`history-row-${index}`} + className="hover:bg-vsc-editor-background relative box-border flex cursor-pointer overflow-hidden rounded-lg p-3" + onClick={async () => { + if (sessionMetadata.sessionId !== currentSessionId) { + await dispatch( + loadSession({ + sessionId: sessionMetadata.sessionId, + saveCurrentSession: true, + }), + ); + } + navigate("/"); + }} + > +
+ {editing ? ( +
+ titleInput && titleInput.focus()} + value={sessionTitleEditValue} + onChange={(e) => setSessionTitleEditValue(e.target.value)} + onKeyUp={(e) => handleKeyUp(e)} + onBlur={() => setEditing(false)} + /> +
+ ) : ( + + {sessionMetadata.title} + + )} -
- - {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} - - {/* Uncomment to show the date */} - {/* +
+ + {getUriPathBasename(sessionMetadata.workspaceDirectory || "")} + + {/* Uncomment to show the date */} + {/* {date.toLocaleString("en-US", { year: "2-digit", month: "2-digit", @@ -120,33 +113,31 @@ export function HistoryTableRow({ hour12: true, })} */} -
-
- - {hovered && !editing && ( -
- { - e.stopPropagation(); - setEditing(true); - }} - > - - - { - e.stopPropagation(); - await dispatch(deleteSession(sessionMetadata.sessionId)); - }} - > - - -
- )}
- +
+ + {hovered && !editing && ( +
+ { + e.stopPropagation(); + setEditing(true); + }} + > + + + { + e.stopPropagation(); + await dispatch(deleteSession(sessionMetadata.sessionId)); + }} + > + + +
+ )} ); } diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index e8d6ef2fd..2ceeea09b 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -1,12 +1,29 @@ import { SessionMetadata } from "core"; import MiniSearch from "minisearch"; -import React, { Fragment, useEffect, useMemo, useRef, useState } from "react"; -import Shortcut from '../gui/Shortcut'; +import React, { + Fragment, + useContext, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import Shortcut from "../gui/Shortcut"; -import { getFontSize, getMetaKeyLabel } from "../../util"; -import { HistoryTableRow } from "./HistoryTableRow"; import { XMarkIcon } from "@heroicons/react/24/solid"; -import { useAppSelector } from "../../redux/hooks"; +import { useNavigate } from "react-router-dom"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { + newSession, + setAllSessionMetadata, +} from "../../redux/slices/sessionSlice"; +import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; +import { refreshSessionMetadata } from "../../redux/thunks/session"; +import { getFontSize, getPlatform } from "../../util"; +import { ROUTES } from "../../util/navigation"; +import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import { HistoryTableRow } from "./HistoryTableRow"; const parseDate = (date: string): Date => { let dateObj = new Date(date); @@ -20,7 +37,10 @@ const HEADER_CLASS = "flex user-select-none pt-2 pb-3 opacity-75 text-center font-bold items-center justify-center sticky h-6"; export function History() { + const dispatch = useAppDispatch(); + const navigate = useNavigate(); const searchInputRef = React.useRef(null); + const ideMessenger = useContext(IdeMessengerContext); const [searchTerm, setSearchTerm] = useState(""); @@ -50,6 +70,8 @@ export function History() { } }, [allSessionMetadata]); + const platform = useMemo(() => getPlatform(), []); + const filteredAndSortedSessions: SessionMetadata[] = useMemo(() => { const sessionIds = minisearch .search(searchTerm, { @@ -73,11 +95,38 @@ export function History() { const lastMonth = new Date(Date.now() - 1000 * 60 * 60 * 24 * 30); const earlier = new Date(0); + const showClearSessionsDialog = () => { + dispatch( + setDialogMessage( + { + // optimistic update + dispatch(setAllSessionMetadata([])); + + // actual update + refresh + await ideMessenger.request("history/clear", undefined); + dispatch(refreshSessionMetadata({})); + + // start a new session + dispatch(newSession()); + navigate(ROUTES.HOME); + }} + />, + ), + ); + dispatch(setShowDialog(true)); + }; + return ( -
-
+
+
)}
+
+ {filteredAndSortedSessions.length === 0 && ( +
+ No past sessions found. To start a new session, either click the "+" + button or use the keyboard shortcut: meta L +
+ )} - {filteredAndSortedSessions.length === 0 && ( -
- No past sessions found. To start a new session, either click the "+" - button or use the keyboard shortcut: meta L -
- - )} - - - - {filteredAndSortedSessions.map((session, index) => { - const prevDate = - index > 0 - ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) - : earlier; - const date = parseDate(session.dateCreated); - return ( - - {index === 0 && date > yesterday && ( - - - - )} - {date < yesterday && - date > lastWeek && - prevDate > yesterday && ( +
Today
+ + {filteredAndSortedSessions.map((session, index) => { + const prevDate = + index > 0 + ? parseDate(filteredAndSortedSessions[index - 1].dateCreated) + : earlier; + const date = parseDate(session.dateCreated); + return ( + + {index === 0 && date > yesterday && ( - + )} - {date < lastWeek && date > lastMonth && prevDate > lastWeek && ( - - - - )} - {date < lastMonth && prevDate > lastMonth && ( - - - - )} + {date < yesterday && + date > lastWeek && + prevDate > yesterday && ( +
+
+ + )} + {date < lastWeek && + date > lastMonth && + prevDate > lastWeek && ( +
+
+ + )} + {date < lastMonth && prevDate > lastMonth && ( +
+
+ + )} - - - ); - })} - -
This WeekToday
This Month
Older
This WeekThis MonthOlder
-
- - All session data is saved in ~/.continue/sessions - + + + ); + })} + + +
+
+ {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} + + Clear session history + +
); } diff --git a/gui/src/pages/history/index.tsx b/gui/src/pages/history/index.tsx index f59da5509..a8be3d92f 100644 --- a/gui/src/pages/history/index.tsx +++ b/gui/src/pages/history/index.tsx @@ -8,7 +8,10 @@ export default function HistoryPage() { const navigate = useNavigate(); return ( -
+
navigate("/")} From 70883e4325e51eb1d655b419b51b1cf55dc4af7c Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Apr 2025 22:14:59 -0700 Subject: [PATCH 026/262] log config errors --- .github/workflows/pr_checks.yaml | 13 +++ core/config/ConfigHandler.ts | 8 +- core/package-lock.json | 191 ++++++++++++++++++++++++++++++- core/package.json | 1 + core/util/logger.ts | 14 +++ 5 files changed, 224 insertions(+), 3 deletions(-) create mode 100644 core/util/logger.ts diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index c3a3848f6..4abb7bc49 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -499,6 +499,19 @@ jobs: name: e2e-failure-screenshots path: extensions/vscode/e2e/storage/screenshots + - name: Find e2e log file + if: always() + run: | + echo "Searching for e2e.log file..." + find $GITHUB_WORKSPACE -name "e2e.log" -type f + + - name: Upload e2e logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-logs-${{ matrix.test_file }}-${{ matrix.command }} + path: e2e.log + gui-tests: needs: [install-gui, install-core] runs-on: ubuntu-latest diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 150104c7e..9f0dc13f1 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -15,6 +15,7 @@ import { } from "../index.js"; import { GlobalContext } from "../util/GlobalContext.js"; +import { logger } from "../util/logger.js"; import { ASSISTANTS, getAllDotContinueYamlFiles, @@ -477,9 +478,14 @@ export class ConfigHandler { configLoadInterrupted: true, }; } - return await this.currentProfile.loadConfig( + const config = await this.currentProfile.loadConfig( this.additionalContextProviders, ); + + if (config.errors?.length) { + logger.warn("Errors loading config: ", config.errors); + } + return config; } async openConfigProfile(profileId?: string) { diff --git a/core/package-lock.json b/core/package-lock.json index ba1113494..8ab0eb882 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -71,6 +71,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" @@ -2968,6 +2969,14 @@ "node": ">=14.21.3" } }, + "node_modules/@colors/colors": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", + "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/@continuedev/config-types": { "version": "1.0.14", "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", @@ -3021,6 +3030,16 @@ "zod": "^3.24.2" } }, + "node_modules/@dabh/diagnostics": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz", + "integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==", + "dependencies": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" + } + }, "node_modules/@esbuild/android-arm": { "version": "0.17.19", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz", @@ -5429,6 +5448,11 @@ "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", "dev": true }, + "node_modules/@types/triple-beam": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", + "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==" + }, "node_modules/@types/uuid": { "version": "9.0.8", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", @@ -6075,8 +6099,7 @@ "node_modules/async": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", - "dev": true + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==" }, "node_modules/async-mutex": { "version": "0.5.0", @@ -6899,6 +6922,37 @@ "color-support": "bin.js" } }, + "node_modules/colorspace": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz", + "integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==", + "dependencies": { + "color": "^3.1.3", + "text-hex": "1.0.x" + } + }, + "node_modules/colorspace/node_modules/color": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz", + "integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==", + "dependencies": { + "color-convert": "^1.9.3", + "color-string": "^1.6.0" + } + }, + "node_modules/colorspace/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/colorspace/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -7619,6 +7673,11 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, + "node_modules/enabled": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" + }, "node_modules/encoding": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", @@ -8521,6 +8580,11 @@ "pend": "~1.2.0" } }, + "node_modules/fecha": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", + "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==" + }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -8647,6 +8711,11 @@ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz", "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==" }, + "node_modules/fn.name": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==" + }, "node_modules/follow-redirects": { "version": "1.15.9", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", @@ -11383,6 +11452,11 @@ "node": ">=6" } }, + "node_modules/kuler": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==" + }, "node_modules/launchdarkly-eventsource": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/launchdarkly-eventsource/-/launchdarkly-eventsource-2.0.3.tgz", @@ -11542,6 +11616,22 @@ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, + "node_modules/logform": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz", + "integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==", + "dependencies": { + "@colors/colors": "1.6.0", + "@types/triple-beam": "^1.3.2", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "safe-stable-stringify": "^2.3.1", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, "node_modules/long": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", @@ -12549,6 +12639,14 @@ "wrappy": "1" } }, + "node_modules/one-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "dependencies": { + "fn.name": "1.x.x" + } + }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", @@ -14192,6 +14290,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "engines": { + "node": ">=10" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -14670,6 +14776,14 @@ "node": ">=8" } }, + "node_modules/stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==", + "engines": { + "node": "*" + } + }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", @@ -15153,6 +15267,11 @@ "b4a": "^1.6.4" } }, + "node_modules/text-hex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==" + }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", @@ -15221,6 +15340,14 @@ "tree-sitter-wasms": "^0.1.11" } }, + "node_modules/triple-beam": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz", + "integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==", + "engines": { + "node": ">= 14.0.0" + } + }, "node_modules/ts-api-utils": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", @@ -16049,6 +16176,66 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" }, + "node_modules/winston": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz", + "integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==", + "dependencies": { + "@colors/colors": "^1.6.0", + "@dabh/diagnostics": "^2.0.2", + "async": "^3.2.3", + "is-stream": "^2.0.0", + "logform": "^2.7.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.9.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz", + "integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==", + "dependencies": { + "logform": "^2.7.0", + "readable-stream": "^3.6.2", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/winston/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/core/package.json b/core/package.json index 8af64e891..1ed7b3e37 100644 --- a/core/package.json +++ b/core/package.json @@ -105,6 +105,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" diff --git a/core/util/logger.ts b/core/util/logger.ts new file mode 100644 index 000000000..faaa05a43 --- /dev/null +++ b/core/util/logger.ts @@ -0,0 +1,14 @@ +import winston from "winston"; + +console.log("NODE_ENV", process.env.NODE_ENV); + +export const logger = winston.createLogger({ + level: "info", + format: winston.format.json(), + transports: [ + // Write all logs with importance level of `info` or higher to `info.log` + new winston.transports.File({ filename: "e2e.log", level: "info" }), + // Normal console.log behavior + new winston.transports.Console(), + ], +}); From 57441dad6696eeb6d4bd6d769aec06e389367a53 Mon Sep 17 00:00:00 2001 From: YUAN Date: Sun, 13 Apr 2025 00:17:54 +0800 Subject: [PATCH 027/262] fix: models and mode are not synced --- .../components/modelSelection/ModelSelect.tsx | 43 ++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 8191af54b..885864d10 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -12,7 +12,9 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectSelectedChatModel } from "../../redux/slices/configSlice"; +import { + selectIsInEditMode, +} from "../../redux/slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { updateSelectedModelByRole } from "../../redux/thunks"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; @@ -120,10 +122,23 @@ function ModelOption({ function ModelSelect() { const dispatch = useAppDispatch(); - const selectedChatModel = useAppSelector(selectSelectedChatModel); - const allChatModels = useAppSelector( - (state) => state.config.config.modelsByRole.chat, - ); + + const isInEditMode = useAppSelector(selectIsInEditMode); + const config = useAppSelector((state) => state.config.config); + + let selectedModel = null; + let allModels = null; + if (isInEditMode) { + allModels = config.modelsByRole.edit; + selectedModel = config.selectedModelByRole.edit; + } + if (!selectedModel) { + selectedModel = config.selectedModelByRole.chat; + } + if (!allModels || allModels.length === 0) { + allModels = config.modelsByRole.chat; + } + const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -141,9 +156,7 @@ function ModelSelect() { useEffect(() => { setOptions( - allChatModels - .filter((m) => !m.roles || m.roles.includes("chat")) - .map((model) => { + allModels.map((model) => { return { value: model.title, title: modelSelectTitle(model), @@ -151,7 +164,7 @@ function ModelSelect() { }; }), ); - }, [allChatModels]); + }, [isInEditMode, config]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { @@ -162,7 +175,7 @@ function ModelSelect() { const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( - (option) => option.value === selectedChatModel?.title, + (option) => option.value === selectedModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; @@ -182,7 +195,7 @@ function ModelSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [options, selectedChatModel]); + }, [options, selectedModel]); function onClickAddModel(e: MouseEvent) { e.stopPropagation(); @@ -207,11 +220,11 @@ function ModelSelect() { return ( { - if (val === selectedChatModel?.title) return; + if (val === selectedModel?.title) return; dispatch( updateSelectedModelByRole({ selectedProfile, - role: "chat", + role: isInEditMode ? "edit" : "chat", modelTitle: val, }), ); @@ -224,7 +237,7 @@ function ModelSelect() { className="h-[18px] gap-1 border-none text-gray-400" > - {modelSelectTitle(selectedChatModel) || "Select model"} + {modelSelectTitle(selectedModel) || "Select model"} ))}
From a4b4395649e9fa7888f8204ddcf56b88632b5b90 Mon Sep 17 00:00:00 2001 From: YUAN Date: Sun, 13 Apr 2025 00:19:15 +0800 Subject: [PATCH 028/262] fix: missing useLegacyCompletionsEndpoint in yaml schema --- packages/config-yaml/src/schemas/models.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 2334b4c7c..ad3318a15 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -80,6 +80,7 @@ const baseModelFields = { embedOptions: embedOptionsSchema.optional(), chatOptions: chatOptionsSchema.optional(), promptTemplates: promptTemplatesSchema.optional(), + useLegacyCompletionsEndpoint: z.boolean().optional(), env: z .record(z.string(), z.union([z.string(), z.boolean(), z.number()])) .optional(), From 7f3ec4bc69f9be00356d5d1bb85639afc84778e2 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Sat, 12 Apr 2025 23:56:55 +0530 Subject: [PATCH 029/262] allow to upload same file more than once --- gui/src/components/mainInput/InputToolbar.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 252126425..36c4dd25d 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -148,6 +148,9 @@ function InputToolbar(props: InputToolbarProps) { for (const file of files) { props.onImageFileSelected?.(file); } + if (fileInputRef.current) { + fileInputRef.current.value = ""; + } }} /> From 785e174086ba6b6913914c94a4a541fed1edda96 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sat, 12 Apr 2025 21:34:20 -0700 Subject: [PATCH 030/262] fix history test --- gui/src/components/History/index.tsx | 5 ++++- gui/src/pages/history/history.test.tsx | 4 +--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/gui/src/components/History/index.tsx b/gui/src/components/History/index.tsx index 2ceeea09b..e51dc45eb 100644 --- a/gui/src/components/History/index.tsx +++ b/gui/src/components/History/index.tsx @@ -200,7 +200,10 @@ export function History() {
- {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} + {`Data is saved in ${platform === "windows" ? "%USERPROFILE%/.continue" : "~/.continue/sessions"}`} { describe("history Page test", () => { it("History text is existed after render", () => { renderWithProviders(); - expect( - screen.getByText("All session data is saved in ~/.continue/sessions"), - ).toBeInTheDocument(); + expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); }); From 3d8291461d4776c6e7053ca40b81406dc4be7641 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 13 Apr 2025 20:32:34 +0000 Subject: [PATCH 031/262] build(deps-dev): bump vite from 4.5.11 to 4.5.13 in /gui Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 4.5.11 to 4.5.13. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/v4.5.13/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v4.5.13/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 4.5.13 dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- gui/package-lock.json | 8 ++++---- gui/package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/gui/package-lock.json b/gui/package-lock.json index 2105fc59b..c0c19d819 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -93,7 +93,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.5.11", + "vite": "^4.5.13", "vitest": "^2.1.3" }, "engines": { @@ -12255,9 +12255,9 @@ } }, "node_modules/vite": { - "version": "4.5.11", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.11.tgz", - "integrity": "sha512-4mVdhLkZ0vpqZLGJhNm+X1n7juqXApEMGlUXcOQawA45UmpxivOYaMBkI/Js3FlBsNA8hCgEnX5X04moFitSGw==", + "version": "4.5.13", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.13.tgz", + "integrity": "sha512-Hgp8IF/yZDzKsN1hQWOuQZbrKiaFsbQud+07jJ8h9m9PaHWkpvZ5u55Xw5yYjWRXwRQ4jwFlJvY7T7FUJG9MCA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/gui/package.json b/gui/package.json index 1a46aa97e..50d2c6122 100644 --- a/gui/package.json +++ b/gui/package.json @@ -101,7 +101,7 @@ "tailwindcss": "^3.2.7", "typescript": "^5.6.3", "typescript-eslint": "^8.16.0", - "vite": "^4.5.11", + "vite": "^4.5.13", "vitest": "^2.1.3" }, "engine-strict": true, From 4e0ac878f7b66bc741a6bc3fb60e180aadcde4f1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 13 Apr 2025 19:43:53 -0700 Subject: [PATCH 032/262] BROKEN - tools updates --- core/.eslintrc.json | 2 +- core/core.ts | 22 +-- core/llm/countTokens.ts | 275 ++++++++++++++++------------ core/llm/index.ts | 1 - core/tools/builtIn.ts | 2 + core/tools/callTool.ts | 73 +++++--- core/tools/toolError.ts | 14 ++ extensions/vscode/package-lock.json | 6 +- gui/src/redux/thunks/callTool.ts | 12 +- 9 files changed, 230 insertions(+), 177 deletions(-) create mode 100644 core/tools/toolError.ts diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 4790b5c45..517558d32 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -13,7 +13,7 @@ "@typescript-eslint/semi": "off", "eqeqeq": "error", "complexity": ["error", { "max": 38 }], - "max-lines-per-function": ["error", { "max": 485 }], + "max-lines-per-function": ["error", { "max": 520 }], "max-statements": ["error", { "max": 114 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], diff --git a/core/core.ts b/core/core.ts index e929a863b..43bfb8cd5 100644 --- a/core/core.ts +++ b/core/core.ts @@ -683,23 +683,13 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - const contextItems = await callTool( + const contextItems = await callTool(tool, toolCall.function.arguments, { + ide: this.ide, + llm, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), tool, - JSON.parse(toolCall.function.arguments || "{}"), - { - ide: this.ide, - llm, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - }, - ); - - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); - } + }); return { contextItems }; }); diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 0fae50656..d3a5f152c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -151,6 +151,51 @@ export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { return flattened; } +// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10 +function countToolsTokens(tools: Tool[], modelName: string): number { + const count = (value: string) => + encodingForModel(modelName).encode(value).length; + + let numTokens = 12; + + for (const tool of tools) { + let functionTokens = count(tool.function.name); + if (tool.function.description) { + functionTokens += count(tool.function.description); + } + const props = tool.function.parameters?.properties; + if (props) { + for (const key in props) { + functionTokens += count(key); + const fields = props[key]; + if (fields) { + const fieldType = fields["type"]; + const fieldDesc = fields["description"]; + const fieldEnum = fields["enum"]; + if (fieldType && typeof fieldType === "string") { + functionTokens += 2; + functionTokens += count(fieldType); + } + if (fieldDesc && typeof fieldDesc === "string") { + functionTokens += 2; + functionTokens += count(fieldDesc); + } + if (fieldEnum && Array.isArray(fieldEnum)) { + functionTokens -= 3; + for (const e of fieldEnum) { + functionTokens += 3; + functionTokens += typeof e === "string" ? count(e) : 5; + } + } + } + } + } + numTokens += functionTokens; + } + + return numTokens + 12; +} + function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, @@ -158,8 +203,38 @@ function countChatMessageTokens( // Doing simpler, safer version of what is here: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb // every message follows <|im_start|>{role/name}\n{content}<|end|>\n - const TOKENS_PER_MESSAGE: number = 4; - return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE; + const BASE_TOKENS = 4; + const TOOL_CALL_EXTRA_TOKENS = 10; + const TOOL_OUTPUT_EXTRA_TOKENS = 10; + let tokens = BASE_TOKENS; + + if (chatMessage.content) { + tokens += countTokens(chatMessage.content, modelName); + } + + if ("toolCalls" in chatMessage && chatMessage.toolCalls) { + for (const call of chatMessage.toolCalls) { + tokens += TOOL_CALL_EXTRA_TOKENS; + tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this + } + } + + if (chatMessage.role === "thinking") { + if (chatMessage.redactedThinking) { + tokens += countTokens(chatMessage.redactedThinking, modelName); + } + if (chatMessage.signature) { + tokens += countTokens(chatMessage.signature, modelName); + } + } + + if (chatMessage.role === "tool") { + tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety + if (chatMessage.toolCallId) { + tokens += countTokens(chatMessage.toolCallId, modelName); + } + } + return tokens; } function pruneLinesFromTop( @@ -220,7 +295,14 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } -const MAX_TOKEN_BUFFER_FOR_SAFETY = 3000; +const MAX_TOKEN_SAFETY_BUFFER = 1000; +const TOKEN_BUFFER_PROPORTION = 0.07; +function getTokenBufferSafety(contextLength: number) { + return Math.min( + MAX_TOKEN_SAFETY_BUFFER, + contextLength * TOKEN_BUFFER_PROPORTION, + ); +} function pruneRawPromptFromTop( modelName: string, @@ -229,7 +311,7 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - Math.max(MAX_TOKEN_BUFFER_FOR_SAFETY, contextLength*; + contextLength - tokensForCompletion - getTokenBufferSafety(contextLength); return pruneStringFromTop(modelName, maxTokens, prompt); } @@ -245,128 +327,97 @@ function pruneRawPromptFromTop( // } function summarize(message: ChatMessage): string { - return `${renderChatMessage(message).substring(0, 100)}...`; + return `(Truncated message): ${renderChatMessage(message).substring(0, 100)}...`; } function pruneChatHistory( modelName: string, chatHistory: ChatMessage[], - contextLength: number, - tokensForCompletion: number, + inputTokensAvailable: number, ): ChatMessage[] { - let totalTokens = - tokensForCompletion + - chatHistory.reduce((acc, message) => { - return acc + countChatMessageTokens(modelName, message); - }, 0); - - // 0. Prune any messages that take up more than 1/3 of the context length - const zippedMessagesAndTokens: [ChatMessage, number][] = []; - - // Zipped ChatMessage with its token counts - chatHistory.forEach((message) => { - const zippedItem: [ChatMessage, number] = [ - message, - countTokens(message.content, modelName), - ]; - zippedMessagesAndTokens.push(zippedItem); + let currentTokens = 0; + const messagesWithTokens = chatHistory.map((message) => { + const tokens = countChatMessageTokens(modelName, message); + currentTokens += tokens; + return { + ...message, + tokens, + }; }); - const zippedLongerThanOneThird = zippedMessagesAndTokens.filter( - ([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3, - ); + const sysMessage = messagesWithTokens.find((msg) => msg.role === "system"); + const sysMessageTokens = sysMessage?.tokens ?? 0; - zippedLongerThanOneThird.sort( - ( - [_messageA, tokensA]: [ChatMessage, number], - [_messageB, tokensB]: [ChatMessage, number], - ) => { - return tokensB - tokensA; - }, - ); + const lastUserMessage = messagesWithTokens.at(-1); + // if (lastMessage?.role === "user") + // General strategy: + // Walk from the oldest messages forward to last 5, removing while still above token limit + // Once at the last 5, attempt to summarize if summarizable + // Then, double check no latent tool responses that don't have their preceding calls + // Until under token count - const longerThanOneThird = zippedLongerThanOneThird.map( - ([message, _token]: [ChatMessage, number]) => message, - ); - const distanceFromThird = zippedLongerThanOneThird.map( - ([_message, token]: [ChatMessage, number]) => token - contextLength / 3, - ); - - for (let i = 0; i < longerThanOneThird.length; i++) { - // Prune line-by-line from the top - const message = longerThanOneThird[i]; - const content = renderChatMessage(message); - const deltaNeeded = totalTokens - contextLength; - const delta = Math.min(deltaNeeded, distanceFromThird[i]); - message.content = pruneStringFromTop( - modelName, - countTokens(message.content, modelName) - delta, - content, - ); - totalTokens -= delta; + // 1. Remove entire messages until the last 5 + while ( + messagesWithTokens.length > 5 && + currentTokens > inputTokensAvailable + ) { + const message = messagesWithTokens.shift()!; + currentTokens -= message.tokens; } - // 1. Replace beyond last 5 messages with summary - let i = 0; - while (totalTokens > contextLength && i < chatHistory.length - 5) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message), modelName); - message.content = summarize(message); - i++; - } - - // 2. Remove entire messages until the last 5 - while (chatHistory.length > 5 && totalTokens > contextLength) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + // At this point make sure no latent tool response without corresponding call + while (messagesWithTokens[0]?.role === "tool") { + const message = messagesWithTokens.shift()!; + currentTokens -= message.tokens; } // 3. Truncate message in the last 5, except last 1 - i = 0; + let i = 0; while ( - totalTokens > contextLength && - chatHistory.length > 0 && - i < chatHistory.length - 1 + totalTokens > inputTokensAvailable && + messagesWithTokens.length > 0 && + i < messagesWithTokens.length - 1 ) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); + const message = messagesWithTokens[i]; + totalTokens -= message.tokens; totalTokens += countTokens(summarize(message), modelName); message.content = summarize(message); i++; } // 4. Remove entire messages in the last 5, except last 1 - while (totalTokens > contextLength && chatHistory.length > 1) { + while (totalTokens > inputTokensAvailable && messagesWithTokens.length > 1) { // If tool call/response detected prune both (can't have response with no call) // TODO prune lines from tool response before pruning both messages if ( - chatHistory.length > 2 && - messageHasToolCalls(chatHistory[0]) && - chatHistory[1].role === "tool" + messagesWithTokens.length > 2 && + messageHasToolCalls(messagesWithTokens[0]) && + messagesWithTokens[1].role === "tool" ) { - const firstMessage = chatHistory.shift()!; - const secondMessage = chatHistory.shift()!; - totalTokens -= countTokens(firstMessage.content, modelName); - totalTokens -= countTokens(secondMessage.content, modelName); + const firstMessage = messagesWithTokens.shift()!; + const secondMessage = messagesWithTokens.shift()!; + totalTokens -= firstMessage.tokens; + totalTokens -= secondMessage.tokens; } else { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + const message = messagesWithTokens.shift()!; + totalTokens -= message.tokens; } } - // 5. Truncate last message - if (totalTokens > contextLength && chatHistory.length > 0) { - const message = chatHistory[0]; - message.content = pruneRawPromptFromTop( - modelName, - contextLength, - renderChatMessage(message), - tokensForCompletion, + if (currentTokens > inputTokensAvailable) { + throw new Error( + "Unable to prune chat history to fit into model's context window", ); - totalTokens = contextLength; } - return chatHistory; + + if (messagesWithTokens.length === 0) { + throw new Error("Error processing chat history"); + } + + return messagesWithTokens.map((msg) => { + const { tokens, ...rest } = msg; + return rest; + }); } function messageIsEmpty(message: ChatMessage): boolean { @@ -515,7 +566,6 @@ function compileChatMessages({ contextLength, maxTokens, supportsImages, - prompt, tools, systemMessage, rules, @@ -525,11 +575,22 @@ function compileChatMessages({ contextLength: number; maxTokens: number; supportsImages: boolean; - prompt: string | undefined; tools: Tool[] | undefined; systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { + let toolTokens = 0; + if (tools) { + toolTokens = countToolsTokens(tools, modelName); + } + + const safetyBuffer = getTokenBufferSafety(contextLength); + if (toolTokens + maxTokens + safetyBuffer >= contextLength) { + throw new Error( + `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response.${toolTokens ? toolTokens + "tools tokens included in the request may also cause this issue" : ""}`, + ); + } + let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) @@ -538,14 +599,6 @@ function compileChatMessages({ msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - if (prompt) { - const promptMsg: ChatMessage = { - role: "user", - content: prompt, - }; - msgsCopy.push(promptMsg); - } - const lastUserMessage = getLastUserMessage(msgsCopy); msgsCopy = addSystemMessage({ @@ -560,19 +613,6 @@ function compileChatMessages({ originalMessages: msgs, }); - let functionTokens = 0; - if (functions) { - for (const func of functions) { - functionTokens += countTokens(JSON.stringify(func), modelName); - } - } - - if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) { - throw new Error( - `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`, - ); - } - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -586,8 +626,7 @@ function compileChatMessages({ const history = pruneChatHistory( modelName, msgsCopy, - contextLength, - functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY, + contextLength - toolTokens - maxTokens - safetyBuffer, ); if (history.length >= 2 && history[history.length - 2].role === "system") { diff --git a/core/llm/index.ts b/core/llm/index.ts index 0c79c6974..c53653aed 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -891,7 +891,6 @@ export abstract class BaseLLM implements ILLM { contextLength: this.contextLength, maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), - prompt: undefined, tools: options.tools, systemMessage: this.systemMessage, rules: this.rules ?? [], diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 7cff1c70e..7afd88615 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -16,3 +16,5 @@ export enum BuiltInToolNames { } export const BUILT_IN_GROUP_NAME = "Built-In"; + +export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 28a8f8c30..524fbaf47 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -12,6 +12,7 @@ import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; +import { toolErrorContextItem } from "./toolError"; async function callHttpTool( url: string, @@ -129,38 +130,54 @@ async function callToolFromUri( } } +// Handles calls for core/non-client tools +// Returns an error context item if the tool call fails export async function callTool( tool: Tool, - args: any, + callArgs: string, extras: ToolExtras, ): Promise { + const args = JSON.parse(callArgs || "{}"); const uri = tool.uri ?? tool.function.name; - - switch (uri) { - case BuiltInToolNames.ReadFile: - return await readFileImpl(args, extras); - // Note: Custom GUI handling for edit - case BuiltInToolNames.CreateNewFile: - return await createNewFileImpl(args, extras); - case BuiltInToolNames.GrepSearch: - return await grepSearchImpl(args, extras); - case BuiltInToolNames.FileGlobSearch: - return await fileGlobSearchImpl(args, extras); - case BuiltInToolNames.RunTerminalCommand: - return await runTerminalCommandImpl(args, extras); - case BuiltInToolNames.SearchWeb: - return await searchWebImpl(args, extras); - case BuiltInToolNames.ViewDiff: - return await viewDiffImpl(args, extras); - case BuiltInToolNames.LSTool: - return await lsToolImpl(args, extras); - case BuiltInToolNames.ReadCurrentlyOpenFile: - return await readCurrentlyOpenFileImpl(args, extras); - // case BuiltInToolNames.ViewRepoMap: - // return await viewRepoMapImpl(args, extras); - // case BuiltInToolNames.ViewSubdirectory: - // return await viewSubdirectoryImpl(args, extras); - default: - return await callToolFromUri(uri, args, extras); + try { + let contextItems: ContextItem[] = []; + switch (uri) { + case BuiltInToolNames.ReadFile: + contextItems = await readFileImpl(args, extras); + case BuiltInToolNames.CreateNewFile: + contextItems = await createNewFileImpl(args, extras); + case BuiltInToolNames.GrepSearch: + contextItems = await grepSearchImpl(args, extras); + case BuiltInToolNames.FileGlobSearch: + contextItems = await fileGlobSearchImpl(args, extras); + case BuiltInToolNames.RunTerminalCommand: + contextItems = await runTerminalCommandImpl(args, extras); + case BuiltInToolNames.SearchWeb: + contextItems = await searchWebImpl(args, extras); + case BuiltInToolNames.ViewDiff: + contextItems = await viewDiffImpl(args, extras); + case BuiltInToolNames.LSTool: + contextItems = await lsToolImpl(args, extras); + case BuiltInToolNames.ReadCurrentlyOpenFile: + contextItems = await readCurrentlyOpenFileImpl(args, extras); + // case BuiltInToolNames.ViewRepoMap: + // contextItems = await viewRepoMapImpl(args, extras); + // case BuiltInToolNames.ViewSubdirectory: + // contextItems = await viewSubdirectoryImpl(args, extras); + default: + contextItems = await callToolFromUri(uri, args, extras); + } + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + return contextItems; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return [toolErrorContextItem(uri, errorMessage)]; } } diff --git a/core/tools/toolError.ts b/core/tools/toolError.ts new file mode 100644 index 000000000..5cffc25d5 --- /dev/null +++ b/core/tools/toolError.ts @@ -0,0 +1,14 @@ +import { ContextItem } from ".."; + +export const toolErrorContextItem = ( + functionName: string, + errorMessage: string, +): ContextItem => { + return { + icon: "problems", + name: "Tool Call Error", + description: "Tool Call Failed", + content: `${functionName} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, + hidden: false, + }; +}; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 108520e49..19b4e5384 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.77", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index bf15e7ae8..d75fa5897 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -58,7 +58,7 @@ export const callTool = createAsyncThunk( toolCallState.toolCallId, ); } catch (e) { - errorMessage = "Failed to call edit tool"; + errorMessage = `Failed to call ${toolCallState.toolCall.function.name} tool`; if (e instanceof Error) { errorMessage = e.message; } @@ -92,15 +92,7 @@ export const callTool = createAsyncThunk( const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - icon: "problems", - name: "Tool Call Error", - description: "Tool Call Failed", - content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, - hidden: false, - }, - ], + toolOutput: [], }), ); unwrapResult(wrapped); From a0d9d6307fa05b2b70fbf98b0e3db2da2ca8d691 Mon Sep 17 00:00:00 2001 From: WEC Date: Mon, 14 Apr 2025 20:07:03 +0800 Subject: [PATCH 033/262] fix:recently edited files change ignore bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit function shouldIgnore return promise,if dont await,nothing can set in recentlyEditedFilesCache --- core/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index 68aa605ac..14c45727c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -642,7 +642,7 @@ export class Core { on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { try { - const ignore = shouldIgnore(filepath, this.ide); + const ignore = await shouldIgnore(filepath, this.ide); if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } From 928cf2c73752a23fe3fc026bbf3957c5c80d5604 Mon Sep 17 00:00:00 2001 From: Minipeps Date: Mon, 14 Apr 2025 17:41:16 +0200 Subject: [PATCH 034/262] feat: add support for Mistral models in toolSupport.ts --- core/llm/toolSupport.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 3d0d72cc8..de5566ff1 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -72,6 +72,17 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + mistral: (model) => { + // https://docs.mistral.ai/capabilities/function_calling/ + return [ + "codestral", + "mistral-large", + "mistral-small", + "pixtral", + "ministral", + "mistral-nemo" + ].some((part) => model.toLowerCase().includes(part)); + }, // https://ollama.com/search?c=tools ollama: (model) => { let modelName = ""; From ef514575eb8c04ae8d5148c7afdf3a0dea0bac9d Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Mon, 14 Apr 2025 11:45:02 -0400 Subject: [PATCH 035/262] Provide model name for tokens counting Although Continue now uses the Llama tokenizer for most models, it's still important to provide the model name to the countTokens function. This ensures flexibility in case we introduce more specialized tokenizers for different models in the future. --- core/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index 68aa605ac..c331e7273 100644 --- a/core/core.ts +++ b/core/core.ts @@ -709,7 +709,7 @@ export class Core { throw new Error("No chat model selected"); } - const tokens = countTokens(item.content); + const tokens = countTokens(item.content, llm.model); if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { return true; From aa30a826d832e73a782ce6642038b8e58cdc46b3 Mon Sep 17 00:00:00 2001 From: Minipeps Date: Mon, 14 Apr 2025 17:57:54 +0200 Subject: [PATCH 036/262] docs: update model-setup.mdx to include Mistral support --- docs/docs/agent/model-setup.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/docs/agent/model-setup.mdx b/docs/docs/agent/model-setup.mdx index 89e1cdf7e..f0acf6f85 100644 --- a/docs/docs/agent/model-setup.mdx +++ b/docs/docs/agent/model-setup.mdx @@ -15,5 +15,6 @@ Currently the following providers are supported: - [Ollama](../customize/model-providers/top-level/ollama.mdx) - we recommend [Qwen 2.5 Coder 7b](https://hub.continue.dev/ollama/qwen2.5-coder-7b). Also see all Ollama models that support tools [here](https://ollama.com/search?c=tools). - [OpenAI](../customize/model-providers/top-level/openai.mdx) - we recommend [GPT-4o](https://hub.continue.dev/openai/gpt-4o) - [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.0 Flash](https://hub.continue.dev/google/gemini-2.0-flash) +- [Mistral](../customize/model-providers/top-level/mistral.mdx) - we recommend [Codestral](https://hub.continue.dev/mistral/codestral) The best chat models generally support tool usage. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more. From a53ce41d914a3b4e0a796711ddfbb05096ca5740 Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Mon, 14 Apr 2025 11:58:13 -0400 Subject: [PATCH 037/262] Fix typo in error dialog Fixed typo from "connot" to "cannot" --- gui/src/components/mainInput/AtMentionDropdown/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index 9d5a10bec..41df0112e 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -251,7 +251,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { modal: true, detail: fileSize > 0 - ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model` + ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model` : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`, }, ); From 8bb18fd2ee4a0fb81b2f24903e47fb1b0beade36 Mon Sep 17 00:00:00 2001 From: Muli Yulzary <8338082+muliyul@users.noreply.github.com> Date: Mon, 14 Apr 2025 19:02:39 +0300 Subject: [PATCH 038/262] feat: support o3/o4 as agents --- core/llm/toolSupport.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 3d0d72cc8..64b604e6d 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -31,6 +31,14 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + azure: (model) => { + if ( + model.toLowerCase().startsWith("gpt-4") || + model.toLowerCase().startsWith("o3") + ) { + return true; + return false; + } openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling if ( From 73c0c206820ffc6465f75c84f2b3326a5675426b Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Mon, 14 Apr 2025 12:03:49 -0400 Subject: [PATCH 039/262] Delete redundant calling of loadConfig Config has already been gathered at the top of this function, so we can directly use this config instead of calling loadConfig again. --- core/core.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index c331e7273..bb11ac5ed 100644 --- a/core/core.ts +++ b/core/core.ts @@ -702,8 +702,7 @@ export class Core { return false; } - const llm = (await this.configHandler.loadConfig()).config - ?.selectedModelByRole.chat; + const llm = config?.selectedModelByRole.chat; if (!llm) { throw new Error("No chat model selected"); From 4d7fbc0a0e9f12048e33ba42cef5212a10d350a6 Mon Sep 17 00:00:00 2001 From: Muli Yulzary <8338082+muliyul@users.noreply.github.com> Date: Mon, 14 Apr 2025 19:04:30 +0300 Subject: [PATCH 040/262] fix formatting --- core/llm/toolSupport.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 64b604e6d..74ad78d46 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -35,9 +35,8 @@ export const PROVIDER_TOOL_SUPPORT: Record< if ( model.toLowerCase().startsWith("gpt-4") || model.toLowerCase().startsWith("o3") - ) { - return true; - return false; + ) return true; + return false; } openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling From a1a35040d77ce0d6103fb79ef4600174f35f6bbd Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 14 Apr 2025 10:26:44 -0700 Subject: [PATCH 041/262] hot refresh when editing local blocks --- core/core.ts | 3 ++- core/package-lock.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/core/core.ts b/core/core.ts index 68aa605ac..6ace62ea5 100644 --- a/core/core.ts +++ b/core/core.ts @@ -782,7 +782,8 @@ export class Core { if ( uri.endsWith(".continuerc.json") || uri.endsWith(".prompt") || - uri.endsWith(SYSTEM_PROMPT_DOT_FILE) + uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || + (uri.includes(".continue") && uri.endsWith(".yaml")) ) { await this.configHandler.reloadConfig(); } else if ( diff --git a/core/package-lock.json b/core/package-lock.json index 3df30cd17..724f815da 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -111,7 +111,7 @@ }, "../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.86", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", From 7557bf2e2bd3eb9263ee4a46a9756b15dea5d0e7 Mon Sep 17 00:00:00 2001 From: Muli Yulzary Date: Mon, 14 Apr 2025 22:22:17 +0300 Subject: [PATCH 042/262] formating --- core/llm/toolSupport.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 74ad78d46..46abd83c0 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -36,8 +36,8 @@ export const PROVIDER_TOOL_SUPPORT: Record< model.toLowerCase().startsWith("gpt-4") || model.toLowerCase().startsWith("o3") ) return true; - return false; - } + return false; + }, openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling if ( From 8eb1ccaf509f04852a6c8e142dc6585cfc47f7db Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 13:39:05 -0700 Subject: [PATCH 043/262] gemini json conversions --- core/llm/llms/Gemini.ts | 80 +-------- core/llm/llms/gemini-types.ts | 164 ++++++++++++++++-- packages/openai-adapters/src/apis/Gemini.ts | 75 ++------ .../openai-adapters/src/util/gemini-types.ts | 164 ++++++++++++++++-- 4 files changed, 323 insertions(+), 160 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1c5d24aee..1f810723a 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -12,12 +12,13 @@ import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; import { + convertContinueToolToGeminiFunction, GeminiChatContentPart, GeminiChatRequestBody, GeminiChatResponse, GeminiGenerationConfig, GeminiToolFunctionDeclaration, -} from "./gemini-types.js"; +} from "./gemini-types"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -276,77 +277,12 @@ class Gemini extends BaseLLM { // Same difference const functions: GeminiToolFunctionDeclaration[] = []; options.tools.forEach((tool) => { - if (tool.function.description && tool.function.name) { - const fn: GeminiToolFunctionDeclaration = { - description: tool.function.description, - name: tool.function.name, - }; - - if ( - tool.function.parameters && - "type" in tool.function.parameters - // && typeof tool.function.parameters.type === "string" - ) { - // const paramType = "TYPE_UNSPECIFIED" - // | "STRING" - // | "NUMBER" - // | "INTEGER" - // | "BOOLEAN" - // | "ARRAY" - // | "OBJECT" - - if (tool.function.parameters.type === "object") { - // Gemini can't take an empty object - // So if empty object param is present just don't add parameters - if ( - JSON.stringify(tool.function.parameters.properties) === "{}" - ) { - functions.push(fn); - return; - } - } - // Helper function to recursively clean JSON Schema objects - const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== "object") return schema; - - if (Array.isArray(schema)) { - return schema.map(cleanJsonSchema); - } - - const { - $schema, - additionalProperties, - default: defaultValue, - ...rest - } = schema; - - // Recursively clean nested properties - if (rest.properties) { - rest.properties = Object.entries(rest.properties).reduce( - (acc, [key, value]) => ({ - ...acc, - [key]: cleanJsonSchema(value), - }), - {}, - ); - } - - // Clean items in arrays - if (rest.items) { - rest.items = cleanJsonSchema(rest.items); - } - - return rest; - }; - - // Clean the parameters and convert type to uppercase - const cleanedParams = cleanJsonSchema(tool.function.parameters); - fn.parameters = { - ...cleanedParams, - type: tool.function.parameters.type.toUpperCase(), - }; - } - functions.push(fn); + try { + functions.push(convertContinueToolToGeminiFunction(tool)); + } catch (e) { + console.warn( + `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`, + ); } }); if (functions.length) { diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts index b9fb52c1d..d37fad121 100644 --- a/core/llm/llms/gemini-types.ts +++ b/core/llm/llms/gemini-types.ts @@ -1,4 +1,5 @@ import { JSONSchema7Object } from "json-schema"; +import { Tool } from "../.."; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -16,24 +17,162 @@ export interface GeminiGenerationConfig { // responseSchema?: object; // https://ai.google.dev/api/caching#Schema } -export interface GeminiFunctionSchema { - type: - | "TYPE_UNSPECIFIED" - | "STRING" - | "NUMBER" - | "INTEGER" - | "BOOLEAN" - | "ARRAY" - | "OBJECT"; +export type GeminiObjectSchemaType = + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + +export interface GeminiObjectSchema { + type: GeminiObjectSchemaType; format?: string; + title?: string; description?: string; nullable?: boolean; enum?: string[]; maxItems?: string; minItems?: string; - properties?: Record; + properties?: Record; required?: string[]; - items?: GeminiFunctionSchema; + anyOf?: GeminiObjectSchema[]; + propertyOrdering?: string[]; + items?: GeminiObjectSchema; + minimum?: number; + maximum?: number; +} + +const jsonSchemaTypeToGeminiType = ( + jsonSchemaType: string, +): GeminiObjectSchemaType => { + switch (jsonSchemaType.toLowerCase()) { + case "string": + return "STRING"; + case "object": + return "OBJECT"; + case "number": + return "NUMBER"; + case "integer": + return "INTEGER"; + case "array": + return "ARRAY"; + case "boolean": + return "BOOLEAN"; + default: + return "TYPE_UNSPECIFIED"; + } +}; + +function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { + const jsonSchemaType = jsonSchema["type"]; + if (!jsonSchemaType || typeof jsonSchema.type !== "string") { + throw new Error( + `Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`, + ); + } + const geminiSchema: GeminiObjectSchema = { + type: jsonSchemaTypeToGeminiType(jsonSchemaType), + }; + + // if (jsonSchema.format) geminiSchema.format = jsonSchema.format; + if (jsonSchema.title) geminiSchema.title = jsonSchema.title; + if (jsonSchema.description) geminiSchema.description = jsonSchema.description; + + // Handle nullable + if (jsonSchemaType === "null" || jsonSchema.nullable) { + geminiSchema.nullable = true; + } + + // Handle enum values + if (Array.isArray(jsonSchema.enum)) { + geminiSchema.enum = jsonSchema.enum.map(String); + } + + // Handle array constraints + if (jsonSchemaType === "array") { + if (typeof jsonSchema.maxItems !== "undefined") { + geminiSchema.maxItems = String(jsonSchema.maxItems); + } + if (typeof jsonSchema.minItems !== "undefined") { + geminiSchema.minItems = String(jsonSchema.minItems); + } + // Handle array items + if (jsonSchema.items) { + geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items); + } + } + + // Handle numeric constraints + if (typeof jsonSchema.minimum !== "undefined") { + geminiSchema.minimum = Number(jsonSchema.minimum); + } + if (typeof jsonSchema.maximum !== "undefined") { + geminiSchema.maximum = Number(jsonSchema.maximum); + } + + // Handle properties for objects + if (jsonSchema.properties) { + geminiSchema.properties = {}; + for (const [key, value] of Object.entries(jsonSchema.properties)) { + geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value); + } + } + + // Handle required properties + if (Array.isArray(jsonSchema.required)) { + geminiSchema.required = jsonSchema.required; + } + + // Handle anyOf + if (Array.isArray(jsonSchema.anyOf)) { + geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema); + } + + // TODO/UNSUPPORTED: + // format + // property ordering: + // if (Array.isArray(jsonSchema.propertyOrdering)) { + // geminiSchema.propertyOrdering = jsonSchema.propertyOrdering; + // } + + return geminiSchema; +} + +// https://ai.google.dev/api/caching#FunctionDeclaration +// Note "reponse" field (schema showing function output structure) is not supported at the moment +export function convertContinueToolToGeminiFunction( + tool: Tool, +): GeminiToolFunctionDeclaration { + if (!tool.function.name) { + throw new Error("Function name required"); + } + const description = tool.function.description ?? ""; + const name = tool.function.name; + + const fn: GeminiToolFunctionDeclaration = { + description, + name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters && + typeof tool.function.parameters.type === "string" + ) { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if (tool.function.parameters.type === "object") { + if (JSON.stringify(tool.function.parameters.properties) === "{}") { + return fn; + } + } + + fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters); + } + + return fn; } export type GeminiChatContentPart = @@ -88,7 +227,8 @@ export interface GeminiChatContent { export interface GeminiToolFunctionDeclaration { name: string; description: string; - parameters?: GeminiFunctionSchema; + parameters?: GeminiObjectSchema; + response?: GeminiObjectSchema; } export interface GeminiTool { functionDeclarations?: GeminiToolFunctionDeclaration[]; diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index c17527674..336dee644 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -21,7 +21,10 @@ import { customFetch, embedding, } from "../util.js"; -import { GeminiToolFunctionDeclaration } from "../util/gemini-types.js"; +import { + convertOpenAIToolToGeminiFunction, + GeminiToolFunctionDeclaration, +} from "../util/gemini-types.js"; import { BaseLlmApi, CreateRerankResponse, @@ -164,71 +167,15 @@ export class GeminiApi implements BaseLlmApi { // Same difference const functions: GeminiToolFunctionDeclaration[] = []; oaiBody.tools.forEach((tool) => { - if (tool.function.description && tool.function.name) { - const fn: GeminiToolFunctionDeclaration = { - description: tool.function.description, - name: tool.function.name, - }; - - if ( - tool.function.parameters && - "type" in tool.function.parameters - // && typeof tool.function.parameters.type === "string" - ) { - if (tool.function.parameters.type === "object") { - // Gemini can't take an empty object - // So if empty object param is present just don't add parameters - if ( - JSON.stringify(tool.function.parameters.properties) === "{}" - ) { - functions.push(fn); - return; - } - } - // Helper function to recursively clean JSON Schema objects - const cleanJsonSchema = (schema: any): any => { - if (!schema || typeof schema !== "object") return schema; - - if (Array.isArray(schema)) { - return schema.map(cleanJsonSchema); - } - - const { - $schema, - additionalProperties, - default: defaultValue, - ...rest - } = schema; - - // Recursively clean nested properties - if (rest.properties) { - rest.properties = Object.entries(rest.properties).reduce( - (acc, [key, value]) => ({ - ...acc, - [key]: cleanJsonSchema(value), - }), - {}, - ); - } - - // Clean items in arrays - if (rest.items) { - rest.items = cleanJsonSchema(rest.items); - } - - return rest; - }; - - // Clean the parameters and convert type to uppercase - const cleanedParams = cleanJsonSchema(tool.function.parameters); - fn.parameters = { - ...cleanedParams, - type: (tool.function.parameters as any)?.type?.toUpperCase(), - }; - } - functions.push(fn); + try { + functions.push(convertOpenAIToolToGeminiFunction(tool)); + } catch (e) { + console.warn( + `Failed to convert tool to gemini function definition. Skipping: ${JSON.stringify(tool, null, 2)}`, + ); } }); + if (functions.length) { finalBody.tools = [ { diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index b9fb52c1d..4dbae03a7 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -1,4 +1,5 @@ import { JSONSchema7Object } from "json-schema"; +import { Tool } from "../../../../core/index.js"; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -16,24 +17,162 @@ export interface GeminiGenerationConfig { // responseSchema?: object; // https://ai.google.dev/api/caching#Schema } -export interface GeminiFunctionSchema { - type: - | "TYPE_UNSPECIFIED" - | "STRING" - | "NUMBER" - | "INTEGER" - | "BOOLEAN" - | "ARRAY" - | "OBJECT"; +export type GeminiObjectSchemaType = + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + +export interface GeminiObjectSchema { + type: GeminiObjectSchemaType; format?: string; + title?: string; description?: string; nullable?: boolean; enum?: string[]; maxItems?: string; minItems?: string; - properties?: Record; + properties?: Record; required?: string[]; - items?: GeminiFunctionSchema; + anyOf?: GeminiObjectSchema[]; + propertyOrdering?: string[]; + items?: GeminiObjectSchema; + minimum?: number; + maximum?: number; +} + +const jsonSchemaTypeToGeminiType = ( + jsonSchemaType: string, +): GeminiObjectSchemaType => { + switch (jsonSchemaType.toLowerCase()) { + case "string": + return "STRING"; + case "object": + return "OBJECT"; + case "number": + return "NUMBER"; + case "integer": + return "INTEGER"; + case "array": + return "ARRAY"; + case "boolean": + return "BOOLEAN"; + default: + return "TYPE_UNSPECIFIED"; + } +}; + +function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { + const jsonSchemaType = jsonSchema["type"]; + if (!jsonSchemaType || typeof jsonSchema.type !== "string") { + throw new Error( + `Invalid type property in function declaration\n${JSON.stringify(jsonSchema, null, 2)}`, + ); + } + const geminiSchema: GeminiObjectSchema = { + type: jsonSchemaTypeToGeminiType(jsonSchemaType), + }; + + // if (jsonSchema.format) geminiSchema.format = jsonSchema.format; + if (jsonSchema.title) geminiSchema.title = jsonSchema.title; + if (jsonSchema.description) geminiSchema.description = jsonSchema.description; + + // Handle nullable + if (jsonSchemaType === "null" || jsonSchema.nullable) { + geminiSchema.nullable = true; + } + + // Handle enum values + if (Array.isArray(jsonSchema.enum)) { + geminiSchema.enum = jsonSchema.enum.map(String); + } + + // Handle array constraints + if (jsonSchemaType === "array") { + if (typeof jsonSchema.maxItems !== "undefined") { + geminiSchema.maxItems = String(jsonSchema.maxItems); + } + if (typeof jsonSchema.minItems !== "undefined") { + geminiSchema.minItems = String(jsonSchema.minItems); + } + // Handle array items + if (jsonSchema.items) { + geminiSchema.items = convertJsonSchemaToGeminiSchema(jsonSchema.items); + } + } + + // Handle numeric constraints + if (typeof jsonSchema.minimum !== "undefined") { + geminiSchema.minimum = Number(jsonSchema.minimum); + } + if (typeof jsonSchema.maximum !== "undefined") { + geminiSchema.maximum = Number(jsonSchema.maximum); + } + + // Handle properties for objects + if (jsonSchema.properties) { + geminiSchema.properties = {}; + for (const [key, value] of Object.entries(jsonSchema.properties)) { + geminiSchema.properties[key] = convertJsonSchemaToGeminiSchema(value); + } + } + + // Handle required properties + if (Array.isArray(jsonSchema.required)) { + geminiSchema.required = jsonSchema.required; + } + + // Handle anyOf + if (Array.isArray(jsonSchema.anyOf)) { + geminiSchema.anyOf = jsonSchema.anyOf.map(convertJsonSchemaToGeminiSchema); + } + + // TODO/UNSUPPORTED: + // format + // property ordering: + // if (Array.isArray(jsonSchema.propertyOrdering)) { + // geminiSchema.propertyOrdering = jsonSchema.propertyOrdering; + // } + + return geminiSchema; +} + +// https://ai.google.dev/api/caching#FunctionDeclaration +// Note "reponse" field (schema showing function output structure) is not supported at the moment +export function convertContinueToolToGeminiFunction( + tool: Tool, +): GeminiToolFunctionDeclaration { + if (!tool.function.name) { + throw new Error("Function name required"); + } + const description = tool.function.description ?? ""; + const name = tool.function.name; + + const fn: GeminiToolFunctionDeclaration = { + description, + name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters && + typeof tool.function.parameters.type === "string" + ) { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if (tool.function.parameters.type === "object") { + if (JSON.stringify(tool.function.parameters.properties) === "{}") { + return fn; + } + } + + fn.parameters = convertJsonSchemaToGeminiSchema(tool.function.parameters); + } + + return fn; } export type GeminiChatContentPart = @@ -88,7 +227,8 @@ export interface GeminiChatContent { export interface GeminiToolFunctionDeclaration { name: string; description: string; - parameters?: GeminiFunctionSchema; + parameters?: GeminiObjectSchema; + response?: GeminiObjectSchema; } export interface GeminiTool { functionDeclarations?: GeminiToolFunctionDeclaration[]; From 30f009b8d0509dcedd076387605ff3cecc629aa3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 13:40:24 -0700 Subject: [PATCH 044/262] types --- packages/openai-adapters/src/util/gemini-types.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index 4dbae03a7..d1921302e 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -1,5 +1,5 @@ import { JSONSchema7Object } from "json-schema"; -import { Tool } from "../../../../core/index.js"; +import { ChatCompletionTool } from "openai/resources/index.mjs"; // https://ai.google.dev/api/generate-content export interface GeminiGenerationConfig { @@ -142,8 +142,8 @@ function convertJsonSchemaToGeminiSchema(jsonSchema: any): GeminiObjectSchema { // https://ai.google.dev/api/caching#FunctionDeclaration // Note "reponse" field (schema showing function output structure) is not supported at the moment -export function convertContinueToolToGeminiFunction( - tool: Tool, +export function convertOpenAIToolToGeminiFunction( + tool: ChatCompletionTool, ): GeminiToolFunctionDeclaration { if (!tool.function.name) { throw new Error("Function name required"); From ff177721cb5504e94b1eefa5438872d8e2c19dbf Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 14:45:49 -0700 Subject: [PATCH 045/262] gemini tool ids --- core/llm/llms/Gemini.ts | 30 ++--- core/llm/llms/gemini-types.ts | 103 ++++++++++-------- packages/openai-adapters/package-lock.json | 13 +++ packages/openai-adapters/package.json | 1 + packages/openai-adapters/src/apis/Gemini.ts | 41 +++++-- .../openai-adapters/src/util/gemini-types.ts | 103 ++++++++++-------- 6 files changed, 181 insertions(+), 110 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 1f810723a..254afd6fa 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,5 +1,5 @@ +import { v4 as uuidv4 } from "uuid"; import { - AssistantChatMessage, ChatMessage, CompletionOptions, LLMOptions, @@ -7,7 +7,6 @@ import { TextMessagePart, ToolCallDelta, } from "../../index.js"; -import { findLast } from "../../util/findLast.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; @@ -205,20 +204,24 @@ class Gemini extends BaseLLM { options: CompletionOptions, isV1API: boolean, ): GeminiChatRequestBody { + const toolCallIdToNameMap = new Map(); + messages.forEach((msg) => { + if (msg.role === "assistant" && msg.toolCalls) { + msg.toolCalls.forEach((call) => { + if (call.id && call.function?.name) { + toolCallIdToNameMap.set(call.id, call.function.name); + } + }); + } + }); + const body: GeminiChatRequestBody = { contents: messages .filter((msg) => !(msg.role === "system" && isV1API)) .map((msg) => { if (msg.role === "tool") { - let fn_name = ""; - const lastToolCallMessage = findLast( - messages, - (msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name, - ) as AssistantChatMessage; - if (lastToolCallMessage) { - fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!; - } - if (!fn_name) { + let functionName = toolCallIdToNameMap.get(msg.toolCallId); + if (!functionName) { console.warn( "Sending tool call response for unidentified tool call", ); @@ -228,7 +231,8 @@ class Gemini extends BaseLLM { parts: [ { functionResponse: { - name: fn_name || "unknown", + id: msg.toolCallId, + name: functionName || "unknown", response: { output: msg.content, // "output" key is opinionated - not all functions will output objects }, @@ -358,7 +362,7 @@ class Gemini extends BaseLLM { type: "toolCall", data: { type: "function", - id: "", // Not supported by gemini + id: part.functionCall.id ?? uuidv4(), function: { name: part.functionCall.name, arguments: diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts index d37fad121..355d1c942 100644 --- a/core/llm/llms/gemini-types.ts +++ b/core/llm/llms/gemini-types.ts @@ -175,50 +175,67 @@ export function convertContinueToolToGeminiFunction( return fn; } +export type GeminiTextContentPart = { + text: string; +}; + +export type GeminiInlineDataContentPart = { + inlineData: { + mimeType: string; + data: string; + }; +}; + +export type GeminiFunctionCallContentPart = { + functionCall: { + id?: string; + name: string; + args: JSONSchema7Object; + }; +}; + +export type GeminiFunctionResponseContentPart = { + functionResponse: { + id?: string; + name: string; + response: JSONSchema7Object; + }; +}; + +export type GeminiFileDataContentPart = { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; +}; + +export type GeminiExecutableCodeContentPart = { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; +}; + +export type GeminiCodeExecutionResultContentPart = { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; +}; + export type GeminiChatContentPart = - | { - text: string; - } - | { - inlineData: { - mimeType: string; - data: string; - }; - } - | { - functionCall: { - name: string; - args: JSONSchema7Object; - }; - } - | { - functionResponse: { - name: string; - response: JSONSchema7Object; - }; - } - | { - fileData: { - fileUri: string; - mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata - }; - } - | { - executableCode: { - language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; - code: string; - }; - } - | { - codeExecutionResult: { - outcome: - | "OUTCOME_UNSPECIFIED" - | "OUTCOME_OK" - | "OUTCOME_FAILED" - | "OUTCOME_DEADLINE_EXCEEDED"; - output: string; - }; - }; + | GeminiTextContentPart + | GeminiInlineDataContentPart + | GeminiFunctionCallContentPart + | GeminiFunctionResponseContentPart + | GeminiFileDataContentPart + | GeminiExecutableCodeContentPart + | GeminiCodeExecutionResultContentPart; + export interface GeminiChatContent { role?: "user" | "model"; parts: GeminiChatContentPart[]; diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 1fa921da5..08d52d3b9 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -16,6 +16,7 @@ "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" }, "devDependencies": { @@ -4356,6 +4357,18 @@ "browserslist": ">= 4.21.0" } }, + "node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "bin": { + "uuid": "dist/esm/bin/uuid" + } + }, "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", diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 478b50f0d..82ba2509b 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -19,6 +19,7 @@ "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" }, "devDependencies": { diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index 336dee644..ab76a28d0 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -14,6 +14,7 @@ import { Model, } from "openai/resources/index"; +import { v4 as uuidv4 } from "uuid"; import { GeminiConfig } from "../types.js"; import { chatChunk, @@ -23,6 +24,8 @@ import { } from "../util.js"; import { convertOpenAIToolToGeminiFunction, + GeminiChatContent, + GeminiChatContentPart, GeminiToolFunctionDeclaration, } from "../util/gemini-types.js"; import { @@ -51,9 +54,15 @@ export class GeminiApi implements BaseLlmApi { } private _oaiPartToGeminiPart( - part: OpenAI.Chat.Completions.ChatCompletionContentPart, - ) { + part: + | OpenAI.Chat.Completions.ChatCompletionContentPart + | OpenAI.Chat.Completions.ChatCompletionContentPartRefusal, + ): GeminiChatContentPart { switch (part.type) { + case "refusal": + return { + text: part.refusal, + }; case "text": return { text: part.text, @@ -91,7 +100,15 @@ export class GeminiApi implements BaseLlmApi { const isV1API = url.includes("/v1/"); const toolCallIdToNameMap = new Map(); - const contents = oaiBody.messages + oaiBody.messages.forEach((msg) => { + if (msg.role === "assistant" && msg.tool_calls) { + msg.tool_calls.forEach((call) => { + toolCallIdToNameMap.set(call.id, call.function.name); + }); + } + }); + + const contents: (GeminiChatContent | null)[] = oaiBody.messages .map((msg) => { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents @@ -103,9 +120,10 @@ export class GeminiApi implements BaseLlmApi { } return { - role: "model", + role: "model" as const, parts: msg.tool_calls.map((toolCall) => ({ functionCall: { + id: toolCall.id, name: toolCall.function.name, args: JSON.parse(toolCall.function.arguments || "{}"), }, @@ -114,14 +132,15 @@ export class GeminiApi implements BaseLlmApi { } if (msg.role === "tool") { + const functionName = toolCallIdToNameMap.get(msg.tool_call_id); return { - role: "user", + role: "user" as const, parts: [ { functionResponse: { - name: msg.tool_call_id, + id: msg.tool_call_id, + name: functionName ?? "unknown", response: { - name: toolCallIdToNameMap.get(msg.tool_call_id), content: typeof msg.content === "string" ? msg.content @@ -138,12 +157,12 @@ export class GeminiApi implements BaseLlmApi { } return { - role: msg.role === "assistant" ? "model" : "user", + role: + msg.role === "assistant" ? ("model" as const) : ("user" as const), parts: typeof msg.content === "string" ? [{ text: msg.content }] - : // @ts-ignore - msg.content.map(this._oaiPartToGeminiPart), + : msg.content.map(this._oaiPartToGeminiPart), }; }) .filter((c) => c !== null); @@ -283,7 +302,7 @@ export class GeminiApi implements BaseLlmApi { tool_calls: [ { index: 0, - id: "", // Not supported by Gemini + id: part.functionCall.id ?? uuidv4(), type: "function", function: { name: part.functionCall.name, diff --git a/packages/openai-adapters/src/util/gemini-types.ts b/packages/openai-adapters/src/util/gemini-types.ts index d1921302e..44f752f40 100644 --- a/packages/openai-adapters/src/util/gemini-types.ts +++ b/packages/openai-adapters/src/util/gemini-types.ts @@ -175,50 +175,67 @@ export function convertOpenAIToolToGeminiFunction( return fn; } +export type GeminiTextContentPart = { + text: string; +}; + +export type GeminiInlineDataContentPart = { + inlineData: { + mimeType: string; + data: string; + }; +}; + +export type GeminiFunctionCallContentPart = { + functionCall: { + id?: string; + name: string; + args: JSONSchema7Object; + }; +}; + +export type GeminiFunctionResponseContentPart = { + functionResponse: { + id?: string; + name: string; + response: JSONSchema7Object; + }; +}; + +export type GeminiFileDataContentPart = { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; +}; + +export type GeminiExecutableCodeContentPart = { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; +}; + +export type GeminiCodeExecutionResultContentPart = { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; +}; + export type GeminiChatContentPart = - | { - text: string; - } - | { - inlineData: { - mimeType: string; - data: string; - }; - } - | { - functionCall: { - name: string; - args: JSONSchema7Object; - }; - } - | { - functionResponse: { - name: string; - response: JSONSchema7Object; - }; - } - | { - fileData: { - fileUri: string; - mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata - }; - } - | { - executableCode: { - language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; - code: string; - }; - } - | { - codeExecutionResult: { - outcome: - | "OUTCOME_UNSPECIFIED" - | "OUTCOME_OK" - | "OUTCOME_FAILED" - | "OUTCOME_DEADLINE_EXCEEDED"; - output: string; - }; - }; + | GeminiTextContentPart + | GeminiInlineDataContentPart + | GeminiFunctionCallContentPart + | GeminiFunctionResponseContentPart + | GeminiFileDataContentPart + | GeminiExecutableCodeContentPart + | GeminiCodeExecutionResultContentPart; + export interface GeminiChatContent { role?: "user" | "model"; parts: GeminiChatContentPart[]; From 397be9daa24dd8c86e5a9514186ddc7bf308db96 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 14 Apr 2025 15:20:51 -0700 Subject: [PATCH 046/262] bump version number --- packages/config-yaml/package-lock.json | 4 ++-- packages/config-yaml/package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/config-yaml/package-lock.json b/packages/config-yaml/package-lock.json index 4e5b8df05..58250c2d5 100644 --- a/packages/config-yaml/package-lock.json +++ b/packages/config-yaml/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.87", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.87", "license": "Apache-2.0", "dependencies": { "@continuedev/config-types": "^1.0.14", diff --git a/packages/config-yaml/package.json b/packages/config-yaml/package.json index f32235580..ab9bbd2af 100644 --- a/packages/config-yaml/package.json +++ b/packages/config-yaml/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/config-yaml", - "version": "1.0.78", + "version": "1.0.87", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", From 91043f6f2c4341f0bb1959908f4138c304b91c45 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Mon, 14 Apr 2025 16:10:36 -0700 Subject: [PATCH 047/262] fix parallel parts not working --- core/llm/llms/Gemini.ts | 77 +++++++++++------------------------------ 1 file changed, 21 insertions(+), 56 deletions(-) diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 254afd6fa..b912564dc 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,5 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import { + AssistantChatMessage, ChatMessage, CompletionOptions, LLMOptions, @@ -337,75 +338,39 @@ class Gemini extends BaseLLM { // Check for existence of each level before accessing the final 'text' property const content = data?.candidates?.[0]?.content; if (content) { - const supportedParts: MessagePart[] = []; + const textParts: MessagePart[] = []; const toolCalls: ToolCallDelta[] = []; - // Process all parts first to maintain order - const processedParts: Array<{ - type: "content" | "tool" | "toolCall"; - data: any; - }> = []; - for (const part of content.parts) { if ("text" in part) { - supportedParts.push({ type: "text", text: part.text }); - } else if ("inlineData" in part) { - supportedParts.push({ - type: "imageUrl", - imageUrl: { - url: `data:image/jpeg;base64,${part.inlineData.data}`, - }, - }); + textParts.push({ type: "text", text: part.text }); } else if ("functionCall" in part) { - // Queue function call - processedParts.push({ - type: "toolCall", - data: { - type: "function", - id: part.functionCall.id ?? uuidv4(), - function: { - name: part.functionCall.name, - arguments: - typeof part.functionCall.args === "string" - ? part.functionCall.args - : JSON.stringify(part.functionCall.args), - }, - }, - }); - } else if ("functionResponse" in part) { - // Queue function response - processedParts.push({ - type: "tool", - data: { - role: "tool", - content: part.functionResponse.response.output as string, - toolCallId: part.functionResponse.name, + toolCalls.push({ + type: "function", + id: part.functionCall.id ?? uuidv4(), + function: { + name: part.functionCall.name, + arguments: + typeof part.functionCall.args === "string" + ? part.functionCall.args + : JSON.stringify(part.functionCall.args), }, }); } else { + // Note: function responses shouldn't be streamed, images not supported console.warn("Unsupported gemini part type received", part); } } - // If we have supported content parts, yield them first - if (supportedParts.length) { - yield { - role: "assistant", - content: supportedParts, - }; + const assistantMessage: AssistantChatMessage = { + role: "assistant", + content: textParts.length ? textParts : "", + }; + if (toolCalls.length > 0) { + assistantMessage.toolCalls = toolCalls; } - - // Then process tool calls and responses in order - for (const part of processedParts) { - if (part.type === "toolCall") { - yield { - role: "assistant", - content: "", - toolCalls: [part.data], - }; - } else if (part.type === "tool") { - yield part.data; - } + if (textParts.length || toolCalls.length) { + yield assistantMessage; } } else { // Handle the case where the expected data structure is not found From 12b3ed9291b4f46e920f8417f1e6585e45b7edd9 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Mon, 14 Apr 2025 22:55:24 -0700 Subject: [PATCH 048/262] feat: apply e2e tests --- .../vscode/e2e/actions/Apply.actions.ts | 16 ++++ .../vscode/e2e/actions/Global.actions.ts | 50 +++++++++- .../e2e/actions/KeyboardShortcuts.actions.ts | 25 ++++- .../vscode/e2e/selectors/Apply.selectors.ts | 15 +++ extensions/vscode/e2e/tests/Apply.test.ts | 92 +++++++++++++++++++ .../vscode/e2e/tests/Autocomplete.test.ts | 7 +- extensions/vscode/e2e/tests/Edit.test.ts | 6 +- .../e2e/tests/KeyboardShortcuts.test.ts | 21 +++-- .../StepContainerPreToolbar/ApplyActions.tsx | 3 + .../CreateFileButton.tsx | 1 + .../ToolbarButtonWithTooltip.tsx | 3 + .../StepContainerPreToolbar/index.tsx | 2 +- 12 files changed, 219 insertions(+), 22 deletions(-) create mode 100644 extensions/vscode/e2e/actions/Apply.actions.ts create mode 100644 extensions/vscode/e2e/selectors/Apply.selectors.ts create mode 100644 extensions/vscode/e2e/tests/Apply.test.ts diff --git a/extensions/vscode/e2e/actions/Apply.actions.ts b/extensions/vscode/e2e/actions/Apply.actions.ts new file mode 100644 index 000000000..44aa87e85 --- /dev/null +++ b/extensions/vscode/e2e/actions/Apply.actions.ts @@ -0,0 +1,16 @@ +import { WebView } from "vscode-extension-tester"; + +import { ApplySelectors } from "../selectors/Apply.selectors"; +import { TestUtils } from "../TestUtils"; + +export class ApplyActions { + static async performAction( + view: WebView, + action: "apply" | "accept" | "reject" | "create", + ) { + let applyButton = await TestUtils.waitForSuccess( + async () => await ApplySelectors.getCodeblockToolbarAction(view, action), + ); + applyButton.click(); + } +} diff --git a/extensions/vscode/e2e/actions/Global.actions.ts b/extensions/vscode/e2e/actions/Global.actions.ts index aafd1040a..d418fece3 100644 --- a/extensions/vscode/e2e/actions/Global.actions.ts +++ b/extensions/vscode/e2e/actions/Global.actions.ts @@ -7,12 +7,18 @@ import { } from "vscode-extension-tester"; import { DEFAULT_TIMEOUT } from "../constants"; +import { TestUtils } from "../TestUtils"; export class GlobalActions { public static async openTestWorkspace() { - return VSBrowser.instance.openResources("e2e/test-continue"); + await VSBrowser.instance.openResources("e2e/test-continue"); + await new Workbench().executeCommand( + "Notifications: Clear All Notifications", + ); } + public static defaultNewFilename = "test.py"; + public static async createAndOpenNewTextFile(): Promise<{ editor: TextEditor; }> { @@ -26,4 +32,46 @@ export class GlobalActions { return { editor }; } + + public static async createAndSaveNewFile( + filename = GlobalActions.defaultNewFilename, + ): Promise<{ + editor: TextEditor; + }> { + let { editor } = await GlobalActions.createAndOpenNewTextFile(); + + await new Workbench().executeCommand("File: Save As..."); + const inputBox = await InputBox.create(DEFAULT_TIMEOUT.MD); + + // Get current path and replace filename + const currentPath = await inputBox.getText(); + const pathParts = currentPath.split(/[\/\\]/); + pathParts[pathParts.length - 1] = filename; + const newPath = pathParts.join("/"); + + await inputBox.setText(newPath); + + await inputBox.confirm(); + await TestUtils.waitForTimeout(DEFAULT_TIMEOUT.XS); + + editor = (await new EditorView().openEditor(filename)) as TextEditor; + + return { editor }; + } + + public static async deleteFile( + filename = GlobalActions.defaultNewFilename, + ): Promise { + const fs = require("fs"); + const path = require("path"); + + const workspacePath = path.join(process.cwd(), "e2e", "test-continue"); + const filePath = path.join(workspacePath, filename); + + try { + await fs.promises.unlink(filePath); + } catch (error) { + console.warn(`Failed to delete file ${filePath}:`, error); + } + } } diff --git a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts index 358d883bd..cac1097c7 100644 --- a/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts +++ b/extensions/vscode/e2e/actions/KeyboardShortcuts.actions.ts @@ -1,4 +1,4 @@ -import { TextEditor } from "vscode-extension-tester"; +import { Key, TextEditor, WebElement } from "vscode-extension-tester"; export class KeyboardShortcutsActions { /** @@ -10,4 +10,27 @@ export class KeyboardShortcutsActions { await editor.selectText(text); await editor.typeText(text); } + + /** + * Types each string in the array with a newline (Shift+Enter) between them. + * Optionally adds a final Enter key press to submit. + */ + public static async typeWithNewlines({ + input, + lines, + submit, + }: { + input: TextEditor | WebElement; + lines: string[]; + submit?: boolean; + }) { + for (let i = 0; i < lines.length - 1; i++) { + await input.sendKeys(lines[i]); + await input.sendKeys(Key.chord(Key.SHIFT, Key.ENTER)); + } + await input.sendKeys(lines[lines.length - 1]); + if (submit) { + await input.sendKeys(Key.ENTER); + } + } } diff --git a/extensions/vscode/e2e/selectors/Apply.selectors.ts b/extensions/vscode/e2e/selectors/Apply.selectors.ts new file mode 100644 index 000000000..4d14f7ff5 --- /dev/null +++ b/extensions/vscode/e2e/selectors/Apply.selectors.ts @@ -0,0 +1,15 @@ +import { WebView } from "vscode-extension-tester"; + +import { SelectorUtils } from "./SelectorUtils"; + +export class ApplySelectors { + static getCodeblockToolbarAction( + view: WebView, + action: "apply" | "accept" | "reject" | "create", + ) { + return SelectorUtils.getElementByDataTestId( + view, + `codeblock-toolbar-${action}`, + ); + } +} diff --git a/extensions/vscode/e2e/tests/Apply.test.ts b/extensions/vscode/e2e/tests/Apply.test.ts new file mode 100644 index 000000000..6d893c835 --- /dev/null +++ b/extensions/vscode/e2e/tests/Apply.test.ts @@ -0,0 +1,92 @@ +import { TextEditor, VSBrowser, WebView } from "vscode-extension-tester"; + +import { ApplyActions } from "../actions/Apply.actions"; +import { GlobalActions } from "../actions/Global.actions"; +import { GUIActions } from "../actions/GUI.actions"; +import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; +import { DEFAULT_TIMEOUT } from "../constants"; +import { GUISelectors } from "../selectors/GUI.selectors"; +import { TestUtils } from "../TestUtils"; + +describe("Apply Test", () => { + let view: WebView; + let editor: TextEditor; + let fileContent = "hello = 'world'"; + + before(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await GUIActions.moveContinueToSidebar(VSBrowser.instance.driver); + await GlobalActions.openTestWorkspace(); + + ({ editor } = await GlobalActions.createAndSaveNewFile()); + }); + + beforeEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.typeTextAt(1, 1, fileContent); + await GUIActions.toggleGui(); + + ({ view } = await GUIActions.switchToReactIframe()); + await GUIActions.selectModelFromDropdown(view, "TEST LLM"); + }); + + afterEach(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + + await editor.clearText(); + + ({ view } = await GUIActions.switchToReactIframe()); + const tipTapEditor = await GUISelectors.getMessageInputFieldAtIndex( + view, + 0, + ); + await tipTapEditor.clear(); + }); + + after(async function () { + this.timeout(DEFAULT_TIMEOUT.XL); + await GlobalActions.deleteFile(); + }); + + it("Can reject and apply changes from sidebar", async () => { + const newFileContent = fileContent + "!"; + + const [messageInput] = await GUISelectors.getMessageInputFields(view); + + await KeyboardShortcutsActions.typeWithNewlines({ + submit: true, + input: messageInput, + lines: [ + "```py " + GlobalActions.defaultNewFilename, + newFileContent, + "```", + "_", // To avoid extra lines getting included in the block + ], + }); + + await ApplyActions.performAction(view, "apply"); + await ApplyActions.performAction(view, "reject"); + await view.switchBack(); + + let editorText = await editor.getText(); + + await TestUtils.waitForSuccess(async () => editorText === fileContent); + // expect(editorText).to.equal(fileContent); + + ({ view } = await GUIActions.switchToReactIframe()); + + await ApplyActions.performAction(view, "apply"); + await ApplyActions.performAction(view, "accept"); + await view.switchBack(); + + // Note that the editor after accpeting contains additional text + // from the default output of the test LLM, so instead of checking + // for an exact text match on the new content we just do a `.includes()` + editorText = await editor.getText(); + await TestUtils.waitForSuccess(async () => + editorText.includes(newFileContent), + ); + }).timeout(DEFAULT_TIMEOUT.XL); +}); diff --git a/extensions/vscode/e2e/tests/Autocomplete.test.ts b/extensions/vscode/e2e/tests/Autocomplete.test.ts index e6444c80c..836c2c60e 100644 --- a/extensions/vscode/e2e/tests/Autocomplete.test.ts +++ b/extensions/vscode/e2e/tests/Autocomplete.test.ts @@ -1,9 +1,4 @@ -import { - EditorView, - InputBox, - TextEditor, - Workbench, -} from "vscode-extension-tester"; +import { EditorView, TextEditor } from "vscode-extension-tester"; import { AutocompleteActions } from "../actions/Autocomplete.actions"; import { GlobalActions } from "../actions/Global.actions"; diff --git a/extensions/vscode/e2e/tests/Edit.test.ts b/extensions/vscode/e2e/tests/Edit.test.ts index 66b82aaf3..6d8812ff1 100644 --- a/extensions/vscode/e2e/tests/Edit.test.ts +++ b/extensions/vscode/e2e/tests/Edit.test.ts @@ -1,9 +1,9 @@ import { expect } from "chai"; import { - WebView, - VSBrowser, - TextEditor, CodeLens, + TextEditor, + VSBrowser, + WebView, } from "vscode-extension-tester"; import { EditActions } from "../actions/Edit.actions"; diff --git a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts index 0191d1d63..e9b79472f 100644 --- a/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts +++ b/extensions/vscode/e2e/tests/KeyboardShortcuts.test.ts @@ -1,21 +1,22 @@ +import { expect } from "chai"; import { - WebDriver, - VSBrowser, EditorView, InputBox, - TextEditor, - Workbench, - WebView, - WebElement, - until, Key, + TextEditor, + VSBrowser, + WebDriver, + WebElement, + WebView, + Workbench, + until, } from "vscode-extension-tester"; + +import { GUIActions } from "../actions/GUI.actions"; +import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; import { DEFAULT_TIMEOUT } from "../constants"; import { GUISelectors } from "../selectors/GUI.selectors"; -import { GUIActions } from "../actions/GUI.actions"; -import { expect } from "chai"; import { TestUtils } from "../TestUtils"; -import { KeyboardShortcutsActions } from "../actions/KeyboardShortcuts.actions"; describe("Keyboard Shortcuts", () => { let driver: WebDriver; diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index e645e68c9..7131e6ad9 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -36,6 +36,7 @@ export function ApplyActions(props: ApplyActionsProps) { const applyButton = (text: string) => (