fix uri handling, support local blocks

This commit is contained in:
Nate 2025-04-09 11:10:52 -07:00
parent cbc4df275c
commit a30b9699a7
19 changed files with 529 additions and 224 deletions

View file

@ -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/<subDirName>
if (options.includeWorkspace) {
fullDirs = workspaceDirs.map((dir) =>
joinPathsToUri(dir, ".continue", subDirName),
);
}
// ~/.continue/assistants
// ~/.continue/<subDirName>
if (options.includeGlobal) {
fullDirs.push(localPathToUri(getGlobalAssistantsPath()));
fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName)));
}
return fullDirs;

View file

@ -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 {}

View file

@ -55,18 +55,20 @@ export default class LocalProfileLoader implements IProfileLoader {
description: ProfileDescription;
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
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;

View file

@ -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,

View file

@ -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<IdeSettings>;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson?: SerializedContinueConfig;
overrideConfigYaml?: AssistantUnrolled;
profileId: string;
overrideConfigYamlByPath?: string;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
ideSettingsPromise,
controlPlaneClient,
llmLogger,
overrideConfigJson,
overrideConfigYaml,
profileId,
overrideConfigYamlByPath,
orgScopeId,
packageIdentifier,
} = options;
export default async function doLoadConfig(
ide: IDE,
ideSettingsPromise: Promise<IdeSettings>,
controlPlaneClient: ControlPlaneClient,
llmLogger: ILLMLogger,
overrideConfigJson: SerializedContinueConfig | undefined,
overrideConfigYaml: AssistantUnrolled | undefined,
platformConfigMetadata: PlatformConfigMetadata | undefined,
profileId: string,
overrideConfigYamlByPath: string | undefined,
orgScopeId: string | null,
): Promise<ConfigResult<ContinueConfig>> {
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;

View file

@ -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<ConfigResult<AssistantUnrolled>> {
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
controlPlaneClient: ControlPlaneClient;
orgScopeId: string | null;
ideSettings: IdeSettings;
ide: IDE;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<AssistantUnrolled>> {
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<ConfigResult<ContinueConfig>> {
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<ConfigResult<ContinueConfig>> {
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);

View file

@ -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<BaseLLM | undefined> {
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<BaseLLM[]> {
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<BaseLLM[]> {
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;

View file

@ -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);

View file

@ -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",

View file

@ -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",

View file

@ -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",

2
gui/package-lock.json generated
View file

@ -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",

View file

@ -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",

View file

@ -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<string> {
getContent: async function (id: PackageIdentifier): Promise<string> {
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",
},
},
],
},

View file

@ -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<string>;
getContent(fullSlug: PackageIdentifier): Promise<string>;
}
export type SecretNamesMap = Map<FQSN, string>;

View file

@ -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 ?? "",
),

View file

@ -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<string, string> {
const map: Record<string, string> = {};
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<string, string> {
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<AssistantUnrolled> {
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<AssistantUnrolled> {
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<string, string> | undefined,
registry: Registry,
): Promise<AssistantUnrolled> {
// 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<string, string>,
blockSlug: PackageSlug,
blockIdentifier: PackageIdentifier,
): Record<string, string> {
const renderedInputs: Record<string, string> = {};
for (const [key, value] of Object.entries(inputs)) {
renderedInputs[key] = renderTemplateData(value, {
secrets: extractFQSNMap(value, [blockSlug]),
secrets: extractFQSNMap(value, [blockIdentifier]),
});
}
return renderedInputs;

View file

@ -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<void>((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<void>((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");
});
});
});

View file

@ -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<string> {
async getContent(id: PackageIdentifier): Promise<string> {
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<string> {
const response = await fetch(
`${this.apiBase}registry/v1/${fullSlug.ownerSlug}/${fullSlug.packageSlug}/${fullSlug.versionSlug}`,
{