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/130] 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/130] 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 e3c56f81a2d65120478560451bf149f62fc25428 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 8 Apr 2025 14:16:05 -0700 Subject: [PATCH 003/130] 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 004/130] 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 005/130] 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 006/130] 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 007/130] 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 008/130] 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 009/130] 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 010/130] 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 011/130] 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 012/130] 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 013/130] 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 014/130] 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 015/130] 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 016/130] 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 017/130] 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 018/130] 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 019/130] 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 020/130] 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 021/130] 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 022/130] 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 70883e4325e51eb1d655b419b51b1cf55dc4af7c Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 11 Apr 2025 22:14:59 -0700 Subject: [PATCH 023/130] 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 024/130] 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 4e0ac878f7b66bc741a6bc3fb60e180aadcde4f1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 13 Apr 2025 19:43:53 -0700 Subject: [PATCH 025/130] 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 026/130] 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 ef514575eb8c04ae8d5148c7afdf3a0dea0bac9d Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Mon, 14 Apr 2025 11:45:02 -0400 Subject: [PATCH 027/130] 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 a53ce41d914a3b4e0a796711ddfbb05096ca5740 Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Mon, 14 Apr 2025 11:58:13 -0400 Subject: [PATCH 028/130] 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 029/130] 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 030/130] 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 031/130] 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 032/130] 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 033/130] 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 608ca07dfbab6300f235ffe41ecfc2ee11798bac Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 15 Apr 2025 18:39:30 +0530 Subject: [PATCH 034/130] add prompt template for autocomplete --- core/autocomplete/CompletionProvider.ts | 5 +++++ core/index.d.ts | 4 ++-- packages/config-yaml/src/schemas/models.ts | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index b56d153dc..9753ab57a 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -122,6 +122,7 @@ export class CompletionProvider { private async _getAutocompleteOptions() { const { config } = await this.configHandler.loadConfig(); + // console.log('debug1 the config was', config?.selectedModelByRole.autocomplete, config.) const options = { ...DEFAULT_AUTOCOMPLETE_OPTS, ...config?.tabAutocompleteOptions, @@ -154,6 +155,10 @@ export class CompletionProvider { return undefined; } + if (llm.promptTemplates?.autocomplete) { + options.template = llm.promptTemplates.autocomplete as string; + } + const helper = await HelperVars.create( input, options, diff --git a/core/index.d.ts b/core/index.d.ts index 30a977717..2774d9403 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,4 @@ -import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole, PromptTemplates, Rule } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; @@ -566,7 +566,7 @@ export interface LLMOptions { completionOptions?: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; - promptTemplates?: Record; + promptTemplates?: Partial>; templateMessages?: (messages: ChatMessage[]) => string; logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 2334b4c7c..01b66228d 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -65,6 +65,7 @@ export type ChatOptions = z.infer; const promptTemplatesSchema = z.object({ apply: z.string().optional(), edit: z.string().optional(), + autocomplete: z.string().optional() }); export type PromptTemplates = z.infer; From b0e676b5dd15878ccd616e24e2c7c48df802c684 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 15 Apr 2025 18:55:25 +0530 Subject: [PATCH 035/130] update corresponding docs --- core/autocomplete/CompletionProvider.ts | 2 ++ .../customize/model-roles/autocomplete.md | 21 +++++++++++++++++++ docs/docs/reference.md | 2 +- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 9753ab57a..389c45495 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -186,6 +186,8 @@ export class CompletionProvider { helper, }); + console.log('debug1 the prompt was->', prompt) + // Completion let completion: string | undefined = ""; diff --git a/docs/docs/customize/model-roles/autocomplete.md b/docs/docs/customize/model-roles/autocomplete.md index 9641d5dcb..194656ab0 100644 --- a/docs/docs/customize/model-roles/autocomplete.md +++ b/docs/docs/customize/model-roles/autocomplete.md @@ -12,3 +12,24 @@ In Continue, autocomplete models are used to display inline [Autocomplete](../.. ## Recommended Autocomplete models Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete.mdx) for recommended models and more details. + +## Prompt templating + +You can customize the prompt template used when autocomplete happens by setting the `promptTemplates.autocomplete` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the apply template: + +- `{{{prefix}}}` - the code before your cursor +- `{{{suffix}}}` - the code after your cursor +- `{{{filename}}}` - the name of the file your cursor currently is +- `{{{reponame}}}` - the name of the folder where the codebase is +- `{{{language}}}` - the name of the programming language in full (ex. Typescript) + +Example: + +```yaml +models: + - name: My Custom Autocomplete Template + provider: ollama + model: qwen2.5-coder:1.5b +``` \ No newline at end of file diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 6269a1bb7..ac90b8269 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -145,7 +145,7 @@ The `models` section defines the language models used in your configuration. Mod - `apiBase`: Can be used to override the default API base that is specified per model - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. -- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating). +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [autocomplete](./customize/model-roles/autocomplete.md#prompt-templating) - `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: - `baseSystemMessage`: Can be used to override the default system prompt. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: From 4e15497fe7344eb822f08694a1f23cc1ace1ffa7 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 15 Apr 2025 20:27:43 +0530 Subject: [PATCH 036/130] collapse customize page sidebar items by default --- docs/sidebars.js | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/sidebars.js b/docs/sidebars.js index 20a47be93..2fecc448c 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -68,7 +68,6 @@ const sidebars = { { type: "category", label: "Model providers", - collapsed: false, link: { slug: "/customize/model-providers", type: "generated-index", From 280939daaf360da83404206fcc8c718f6cf8a6ce Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Apr 2025 17:14:40 -0700 Subject: [PATCH 037/130] fix path --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 744371c4c..00c64229f 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -689,7 +689,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: e2e-logs-${{ matrix.test_file }}-${{ matrix.command }} - path: e2e.log + path: extensions/vscode/e2e.log gui-tests: needs: [install-gui, install-core, install-config-yaml] From 71e34939cb370d4713dfd6697015f76b12978f95 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Apr 2025 17:26:56 -0700 Subject: [PATCH 038/130] fix --- .github/workflows/pr_checks.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 00c64229f..7969d9753 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -577,7 +577,7 @@ jobs: path: extensions/vscode/e2e/storage vscode-e2e-tests: - name: ${{ matrix.test_file }} (${{ matrix.command }}) + name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }}) needs: [ vscode-download-e2e-dependencies, @@ -688,7 +688,7 @@ jobs: if: always() uses: actions/upload-artifact@v4 with: - name: e2e-logs-${{ matrix.test_file }}-${{ matrix.command }} + name: e2e-logs-${{ matrix.test_file || 'unknown' }}-${{ replace(matrix.command, ':', '-') }} path: extensions/vscode/e2e.log gui-tests: From 31cb0e657df9dfd22d02760ee1cea8df42aa5b64 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 16 Apr 2025 16:27:16 +0530 Subject: [PATCH 039/130] show not allowed cursor when enter button is disabled --- gui/src/components/mainInput/InputToolbar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index f243f5ac4..a58090bfd 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -65,7 +65,7 @@ const EnterButton = styled.button<{ isPrimary?: boolean }>` cursor: pointer; :disabled { - cursor: wait; + cursor: not-allowed; } `; From 3fe57c13aa3b834d8f9125b0108ed6913d1e728a Mon Sep 17 00:00:00 2001 From: Keerthana Panyam Date: Wed, 16 Apr 2025 13:04:45 -0400 Subject: [PATCH 040/130] edit prompt hint text ellipsized by default the edit prompt hint text was too long to fit into the default side bar width. This is shorter (35 characters compared to 55), and the format is consistent with the hint text. --- gui/src/components/mainInput/ContinueInputBox.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 14777acb6..1bcbb3c8c 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -100,7 +100,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const historyKey = props.isEditMode ? "edit" : "chat"; const placeholder = props.isEditMode - ? "Describe how to modify the code - use '#' to add files" + ? "Describe changes, '#' to add files" : undefined; const toolbarOptions: ToolbarOptions = props.isEditMode From 4ede36e3b5abf17be6b4741be4eda89ad9c768df Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Apr 2025 04:58:20 +0000 Subject: [PATCH 041/130] build(deps): bump http-proxy-middleware from 2.0.7 to 2.0.9 in /docs Bumps [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) from 2.0.7 to 2.0.9. - [Release notes](https://github.com/chimurai/http-proxy-middleware/releases) - [Changelog](https://github.com/chimurai/http-proxy-middleware/blob/v2.0.9/CHANGELOG.md) - [Commits](https://github.com/chimurai/http-proxy-middleware/compare/v2.0.7...v2.0.9) --- updated-dependencies: - dependency-name: http-proxy-middleware dependency-version: 2.0.9 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- docs/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/package-lock.json b/docs/package-lock.json index deb0071b8..38e005c4e 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -9521,9 +9521,9 @@ } }, "node_modules/http-proxy-middleware": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz", - "integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz", + "integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==", "license": "MIT", "dependencies": { "@types/http-proxy": "^1.17.8", From e0a432ed363f9697791560ed7ad267d29c652f67 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 17 Apr 2025 11:05:00 +0530 Subject: [PATCH 042/130] refactor AddFileCombobox to update selectedFiles based on codeToEdit changes --- gui/src/components/CodeToEditCard/AddFileCombobox.tsx | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index d096f90a2..da77492ae 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -39,6 +39,17 @@ export default function AddFileCombobox({ } }, []); + useEffect(() => { + // update selectedFiles showing only the files that are in codeToEdit + setSelectedFiles( + (prevSelectedFiles) => + prevSelectedFiles.filter( + (file) => + codeToEdit.findIndex((code) => code.filepath === file.id) !== -1, + ), + ); + }, [codeToEdit]); + const filteredFiles = query === "" ? remainingFiles From 3d243045d03e8d4688bc84ec23147747bcdbb95d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 17 Apr 2025 11:24:11 +0530 Subject: [PATCH 043/130] reset query state after file selection in AddFileCombobox --- gui/src/components/CodeToEditCard/AddFileCombobox.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index d096f90a2..f801ac9c7 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -55,12 +55,14 @@ export default function AddFileCombobox({ setSelectedFiles(files); void onSelect(files.map((file) => file.id)); buttonRef.current?.click(); + setQuery(""); }} > {({ open }) => (
{ if (!open) { From 2f856619574d9ba3657ad7ff8b49c54e75a4b747 Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Wed, 16 Apr 2025 21:44:51 -0700 Subject: [PATCH 044/130] fix-yaml-reasoning-caching --- packages/config-yaml/src/schemas/models.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index ad3318a15..2ae8d9668 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -47,9 +47,17 @@ export const completionOptionsSchema = z.object({ topK: z.number().optional(), stop: z.array(z.string()).optional(), n: z.number().optional(), + reasoning: z.boolean().optional(), + reasoningBudgetTokens: z.number().optional(), }); export type CompletionOptions = z.infer; +export const cacheBehaviorSchema = z.object({ + cacheSystemMessage: z.boolean().optional(), + cacheConversation: z.boolean().optional(), +}) +export type CacheBehavior = z.infer; + export const embedOptionsSchema = z.object({ maxChunkSize: z.number().optional(), maxBatchSize: z.number().optional(), @@ -76,6 +84,7 @@ const baseModelFields = { roles: modelRolesSchema.array().optional(), capabilities: modelCapabilitySchema.array().optional(), defaultCompletionOptions: completionOptionsSchema.optional(), + cacheBehavior: cacheBehaviorSchema.optional(), requestOptions: requestOptionsSchema.optional(), embedOptions: embedOptionsSchema.optional(), chatOptions: chatOptionsSchema.optional(), From d59a331a1fe57f0519804dee7b477507d3380590 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Sat, 19 Apr 2025 14:31:15 +0530 Subject: [PATCH 045/130] explicitly specify that `uses` blocks are pulled from hub.continue.dev --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 22bc742ab..9df2e889e 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b ### Using Blocks -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from https://hub.continue.dev. Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. From a0dc7ab7c139a68a3542578c0b9529d9295355bf Mon Sep 17 00:00:00 2001 From: erweixin <2991552132@qq.com> Date: Mon, 21 Apr 2025 18:14:18 +0800 Subject: [PATCH 046/130] style: set whitespace-nowrap on dropdown items --- gui/src/components/mainInput/AtMentionDropdown/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index 9d5a10bec..d8c7d5316 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -515,7 +515,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { ) : ( )} - {item.title} + {item.title} {" "}
{ ); }) ) : ( - No results + No results )} )} From 1db5144b28a66fe37a808a78415498460f3e4240 Mon Sep 17 00:00:00 2001 From: Peter Dave Hello Date: Tue, 22 Apr 2025 02:01:03 +0800 Subject: [PATCH 047/130] Update Node.js LTS to v20.19.0 Node.js v20 entered Maintenance LTS six months ago. Update the version from 20.11.0 (released over a year ago) to 20.19.0, the latest LTS release from last month. This ensures the project leverages recent Node.js improvements, including security updates, and stays on a supported LTS track. --- .node-version | 2 +- .nvmrc | 2 +- CONTRIBUTING.md | 2 +- binary/package-lock.json | 2 +- core/package-lock.json | 2 +- core/package.json | 2 +- core/vendor/package.json | 2 +- docs/package-lock.json | 2 +- docs/package.json | 2 +- extensions/intellij/CONTRIBUTING.md | 2 +- extensions/vscode/package-lock.json | 4 ++-- extensions/vscode/package.json | 2 +- gui/package-lock.json | 4 ++-- gui/package.json | 2 +- 14 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.node-version b/.node-version index 18c284172..829e9737e 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -20.11.0 \ No newline at end of file +20.19.0 \ No newline at end of file diff --git a/.nvmrc b/.nvmrc index df9385826..3bf34c276 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v20.11.0 \ No newline at end of file +v20.19.0 \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce9686a8b..5b730190a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -102,7 +102,7 @@ We welcome contributions from developers of all experience levels - from first-t #### Pre-requisites -You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project: +You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project: ```bash nvm use diff --git a/binary/package-lock.json b/binary/package-lock.json index 5c2324e82..7320d18fc 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -140,7 +140,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "node_modules/@75lb/deep-merge": { diff --git a/core/package-lock.json b/core/package-lock.json index 2536f0d29..b08d2f718 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -105,7 +105,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "../../../../../documents/code/continuedev/continue/packages/config-yaml": { diff --git a/core/package.json b/core/package.json index 296b8834a..ef8141c4a 100644 --- a/core/package.json +++ b/core/package.json @@ -111,6 +111,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } diff --git a/core/vendor/package.json b/core/vendor/package.json index 856c71f2d..a31c4dfaa 100644 --- a/core/vendor/package.json +++ b/core/vendor/package.json @@ -13,6 +13,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } diff --git a/docs/package-lock.json b/docs/package-lock.json index deb0071b8..9faaeb13a 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -23,7 +23,7 @@ "nodemon": "^3.1.4" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "node_modules/@algolia/autocomplete-core": { diff --git a/docs/package.json b/docs/package.json index 8dac6fa86..8f6ad8c95 100644 --- a/docs/package.json +++ b/docs/package.json @@ -44,6 +44,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index 26f80ee42..145ea59bf 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -52,7 +52,7 @@ notes below). ### Node.js Requirements -This project requires Node.js version 20.11.0 (LTS) or higher. You have two options for installation: +This project requires Node.js version 20.19.0 (LTS) or higher. You have two options for installation: 1. Download and install directly from [nodejs.org](https://nodejs.org/en/download). 2. If you're using NVM (Node Version Manager), set the correct Node.js version for this project by running `nvm use` in diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 4917b02cc..39853e2d4 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -93,7 +93,7 @@ "vscode-extension-tester": "^8.10.0" }, "engines": { - "node": ">=20.11.0", + "node": ">=20.19.0", "vscode": "^1.70.0" } }, @@ -198,7 +198,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "node_modules/@75lb/deep-merge": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index e3065f1b7..9f83a3494 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -24,7 +24,7 @@ "publisher": "Continue", "engines": { "vscode": "^1.70.0", - "node": ">=20.11.0" + "node": ">=20.19.0" }, "engine-strict": true, "galleryBanner": { diff --git a/gui/package-lock.json b/gui/package-lock.json index c65e604e6..c96d38311 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -97,7 +97,7 @@ "vitest": "^2.1.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "../core": { @@ -201,7 +201,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "../packages/config-yaml": { diff --git a/gui/package.json b/gui/package.json index 714f58da7..dad5f5d16 100644 --- a/gui/package.json +++ b/gui/package.json @@ -106,6 +106,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } From fb09b9dc462ef60c54cc9f9feebacbf1f938b530 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 16:21:40 -0700 Subject: [PATCH 048/130] pr checks comment --- .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 2103426d4..7bb87b420 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -1,5 +1,6 @@ name: PR checks +# PR Checks run on all PRs to the main branch and must pass before merging. on: pull_request: branches: From 43d76f2ccc96e98401c3a32c135f2a0ec0ff989e Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 16:40:27 -0700 Subject: [PATCH 049/130] commit --- .gitignore | 7 ------- 1 file changed, 7 deletions(-) diff --git a/.gitignore b/.gitignore index 92cb4b852..90dae4226 100644 --- a/.gitignore +++ b/.gitignore @@ -83,13 +83,6 @@ ipython_config.py # pyenv .python-version -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ From 9d1ef8a8a5850cf5d0cb9382dfa56ed4a6789931 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 16:42:59 -0700 Subject: [PATCH 050/130] commit again --- .gitignore | 3 --- 1 file changed, 3 deletions(-) diff --git a/.gitignore b/.gitignore index 90dae4226..2ca914069 100644 --- a/.gitignore +++ b/.gitignore @@ -83,9 +83,6 @@ ipython_config.py # pyenv .python-version -# PEP 582; used by e.g. github.com/David-OConnor/pyflow -__pypackages__/ - # Celery stuff celerybeat-schedule celerybeat.pid From bbd3b5b2e4509d2d63e22614ccfbe7571c32b8e3 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 16:44:59 -0700 Subject: [PATCH 051/130] fix? --- .github/workflows/pr_checks.yaml | 40 ++++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7bb87b420..0a0ab2c80 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -416,29 +416,29 @@ 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 + # package-tests: + # runs-on: ubuntu-latest + # steps: + # - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version-file: ".nvmrc" + # - 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') }} + # - 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: Install dependencies + # run: | + # cd packages/config-yaml + # npm ci - - name: Run config-yaml tests - run: | - cd packages/config-yaml - npm test + # - name: Run config-yaml tests + # run: | + # cd packages/config-yaml + # npm test vscode-get-test-file-matrix: runs-on: ubuntu-latest @@ -858,7 +858,7 @@ jobs: - install-vscode - vscode-checks - core-tests - - package-tests + # - package-tests - vscode-get-test-file-matrix - vscode-package-extension - vscode-download-e2e-dependencies From c36e3a36f7f23e9e392f49a66dad6807d599476c Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 16:46:53 -0700 Subject: [PATCH 052/130] fix --- .github/workflows/pr_checks.yaml | 52 ++++++++++++++++---------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 0a0ab2c80..4623ca570 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -416,29 +416,29 @@ 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 + package-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 - # - uses: actions/setup-node@v4 - # with: - # node-version-file: ".nvmrc" + - 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') }} + - 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: Install dependencies + run: | + cd packages/config-yaml + npm ci - # - name: Run config-yaml tests - # run: | - # cd packages/config-yaml - # npm test + - name: Run config-yaml tests + run: | + cd packages/config-yaml + npm test vscode-get-test-file-matrix: runs-on: ubuntu-latest @@ -683,12 +683,12 @@ jobs: 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 || 'unknown' }}-${{ replace(matrix.command, ':', '-') }} - path: extensions/vscode/e2e.log + # - name: Upload e2e logs + # if: always() + # uses: actions/upload-artifact@v4 + # with: + # name: e2e-logs-${{ matrix.test_file || 'unknown' }}-${{ replace(matrix.command, ':', '-') }} + # path: extensions/vscode/e2e.log gui-tests: needs: [install-gui, install-core, install-config-yaml] @@ -858,7 +858,7 @@ jobs: - install-vscode - vscode-checks - core-tests - # - package-tests + - package-tests - vscode-get-test-file-matrix - vscode-package-extension - vscode-download-e2e-dependencies From 032c41f94e08314e0b11c6effc0a84342e62e68a Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 17:33:37 -0700 Subject: [PATCH 053/130] settings and stuff --- .idea/compiler.xml | 3 +++ extensions/vscode/package-lock.json | 1 + gui/package-lock.json | 1 + 3 files changed, 5 insertions(+) diff --git a/.idea/compiler.xml b/.idea/compiler.xml index b589d56e9..2a7499c2b 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -3,4 +3,7 @@ + + \ No newline at end of file diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 4917b02cc..38359147b 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -164,6 +164,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/gui/package-lock.json b/gui/package-lock.json index c65e604e6..6c901ece1 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -167,6 +167,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" From 6758e752da7cb2473e4da592af13d0a7a7e432d9 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 17:35:13 -0700 Subject: [PATCH 054/130] try to fix tests --- core/config/profile/doLoadConfig.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index b8a2b7276..1308ca2a0 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -237,13 +237,13 @@ export default async function doLoadConfig(options: { }; if (newConfig.analytics) { - await TeamAnalytics.setup( - newConfig.analytics, - uniqueId, - ideInfo.extensionVersion, - controlPlaneClient, - controlPlaneProxyInfo, - ); + // await TeamAnalytics.setup( + // newConfig.analytics, + // uniqueId, + // ideInfo.extensionVersion, + // controlPlaneClient, + // controlPlaneProxyInfo, + // ); } else { await TeamAnalytics.shutdown(); } From 802c4bd5f283233faabc6611a0936344ee562e65 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 18:01:38 -0700 Subject: [PATCH 055/130] upload e2e logs --- .github/workflows/pr_checks.yaml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 4623ca570..1e8025bb7 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -683,12 +683,12 @@ jobs: 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 || 'unknown' }}-${{ replace(matrix.command, ':', '-') }} - # path: extensions/vscode/e2e.log + - name: Upload e2e logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-logs-${{ matrix.test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} + path: extensions/vscode/e2e.log gui-tests: needs: [install-gui, install-core, install-config-yaml] From 60063fd64e1d5f7f405fdaac4ae2bd77d7e6b4ae Mon Sep 17 00:00:00 2001 From: bright-ren Date: Tue, 22 Apr 2025 09:09:31 +0800 Subject: [PATCH 056/130] fix Inline edit panel can not select edit models --- .../continueintellijextension/editor/InlineEditAction.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index fd910308d..9565b3d1b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -133,8 +133,9 @@ fun openInlineEdit(project: Project?, editor: Editor) { val content = (response as Map)["content"] as Map val result = content["result"] as Map val config = result["config"] as Map - val models = config["models"] as List> - modelTitles.addAll(models.map { it["title"] as String }) + val models = config["modelsByRole"] as Map + val editModels = models["edit"] as List> + modelTitles.addAll(editModels.map { it["title"] as String }) } // This is a hacky way to not complicate getting model titles with coroutines From 1d1f978b709a79f111d62432d2043ebb1ba13b1c Mon Sep 17 00:00:00 2001 From: bright-ren Date: Tue, 22 Apr 2025 09:26:53 +0800 Subject: [PATCH 057/130] fix function.arguments empty issue when use tools call with Qwen2.5 vllm --- core/llm/openaiTypeConverters.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 8e0acef56..a3a6ad895 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -51,7 +51,7 @@ export function toChatMessage( type: toolCall.type!, function: { name: toolCall.function?.name!, - arguments: toolCall.function?.arguments!, + arguments: toolCall.function?.arguments! || "{}", }, })); } From 3cb92e3a7cd1363fa5f18cd7b2939eb0b5005f6d Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 18:55:37 -0700 Subject: [PATCH 058/130] sanitize artifact name --- .github/workflows/pr_checks.yaml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 1e8025bb7..84ec1e18e 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -677,6 +677,14 @@ jobs: name: e2e-failure-screenshots path: extensions/vscode/e2e/storage/screenshots + - name: Sanitize test file name + id: sanitize_filename + run: | + FILENAME="${{ matrix.test_file }}" + SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion + echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT + + - name: Find e2e log file if: always() run: | @@ -687,7 +695,7 @@ jobs: if: always() uses: actions/upload-artifact@v4 with: - name: e2e-logs-${{ matrix.test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} + name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} path: extensions/vscode/e2e.log gui-tests: From b0cc14ae2fbffedcd2b70102e173bf6364e8d14a Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 19:37:59 -0700 Subject: [PATCH 059/130] fix sanitization --- .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 84ec1e18e..b226a6c60 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -679,6 +679,7 @@ jobs: - name: Sanitize test file name id: sanitize_filename + if: always() run: | FILENAME="${{ matrix.test_file }}" SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion From baefa9251c752335bbe4083160baa1b317ab022b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 21:20:17 -0700 Subject: [PATCH 060/130] fix tail configuration --- extensions/intellij/.run/IDE Logs.run.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/.run/IDE Logs.run.xml b/extensions/intellij/.run/IDE Logs.run.xml index 2743ca662..fcded8fe0 100644 --- a/extensions/intellij/.run/IDE Logs.run.xml +++ b/extensions/intellij/.run/IDE Logs.run.xml @@ -1,6 +1,6 @@ -