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}`, {