From f3148cd91ce85e30689e58f8246123ee98b93de7 Mon Sep 17 00:00:00 2001 From: Nate Date: Tue, 15 Jul 2025 20:31:41 -0700 Subject: [PATCH] unroll local config.yaml --- src/CLIPlatformClient.ts | 169 +++++++++++++++++++++++++++++++++++++++ src/config.ts | 61 ++++++++++++-- 2 files changed, 223 insertions(+), 7 deletions(-) create mode 100644 src/CLIPlatformClient.ts diff --git a/src/CLIPlatformClient.ts b/src/CLIPlatformClient.ts new file mode 100644 index 000000000..ebb3fb1ac --- /dev/null +++ b/src/CLIPlatformClient.ts @@ -0,0 +1,169 @@ +import { + FQSN, + PlatformClient, + SecretResult, + SecretType, +} from "@continuedev/config-yaml"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api"; +import * as dotenv from "dotenv"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +function getContinueDotEnv() { + const homeDir = os.homedir(); + if (!homeDir) return {}; + const envPath = path.join(homeDir, ".continue", ".env"); + if (!fs.existsSync(envPath)) return {}; + const envContent = fs.readFileSync(envPath, "utf8"); + return dotenv.parse(envContent); +} + +export class CLIPlatformClient implements PlatformClient { + constructor( + private orgScopeId: string | null, + private readonly apiClient: DefaultApiInterface + ) {} + + // Add any additional methods required by the PlatformClient interface here + + /** + * Gets the paths to check for workspace files + * By default, this is just the current working directory + */ + private getWorkspaceDirs(): string[] { + return [process.cwd()]; + } + + /** + * searches for the first valid secret file in order of ~/.continue/.env, /.continue/.env, /.env + */ + private async findSecretInEnvFiles( + fqsn: FQSN + ): Promise { + const secretValue = + this.findSecretInLocalEnvFile(fqsn) ?? + (await this.findSecretInWorkspaceEnvFiles(fqsn, true)) ?? + (await this.findSecretInWorkspaceEnvFiles(fqsn, false)); + + 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 findSecretInWorkspaceEnvFiles( + fqsn: FQSN, + insideContinue: boolean + ): string | undefined { + try { + // Get workspaces to check + const workspaceDirs = this.getWorkspaceDirs(); + + for (const workspaceDir of workspaceDirs) { + const envFilePath = path.join( + workspaceDir, + insideContinue ? ".continue" : "", + ".env" + ); + + try { + // Check if file exists using fs + if (fs.existsSync(envFilePath)) { + // Read the file + const envContent = fs.readFileSync(envFilePath, "utf8"); + 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 []; + } + + // Initialize results array with undefined values + const results: (SecretResult | undefined)[] = new Array(fqsns.length).fill( + undefined + ); + + // Try to resolve secrets through the API client if available + try { + const apiResults: any = await this.apiClient.syncSecrets({ + syncSecretsRequest: { + fqsns, + orgScopeId: this.orgScopeId, + }, + }); + + // Merge API results into our results array + for (let i = 0; i < apiResults.length; i++) { + if (apiResults[i]?.found) { + results[i] = apiResults[i]; + } + } + } catch (error) { + console.warn( + `Error resolving FQSNs through API: ${ + error instanceof Error ? error.message : String(error) + }` + ); + } + + // For any secret that isn't found, look in .env files + for (let i = 0; i < fqsns.length; i++) { + if (!results[i]?.found) { + const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]); + if (secretFromEnv?.found) { + results[i] = secretFromEnv; + } + } + } + + return results; + } +} diff --git a/src/config.ts b/src/config.ts index 18448339e..f5331d5fe 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,4 +1,8 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { + AssistantUnrolled, + RegistryClient, + unrollAssistant, +} from "@continuedev/config-yaml"; import { BaseLlmApi, constructLlmApi, @@ -7,8 +11,12 @@ import { import { Configuration, DefaultApi, + DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; +import { dirname } from "node:path"; import { AuthConfig } from "./auth/workos.js"; +import { CLIPlatformClient } from "./CLIPlatformClient.js"; +import { env } from "./env.js"; import { MCPService } from "./mcp.js"; export function getLlmApi( @@ -58,10 +66,42 @@ export function getLlmApi( return [llmApi, model.model]; } +async function loadConfigYaml( + accessToken: string | undefined, + currentUserSlug: string, + filePath: string, + organizationId: string | null, + apiClient: DefaultApiInterface +): Promise { + const unrollResult = await unrollAssistant( + { filePath, uriType: "file" }, + new RegistryClient({ + accessToken, + apiBase: env.apiBase, + rootPath: dirname(filePath), + }), + { + currentUserSlug, + alwaysUseProxy: false, + orgScopeId: organizationId, + renderSecrets: true, + platformClient: new CLIPlatformClient(organizationId, apiClient), + onPremProxyUrl: null, + } + ); + + if (unrollResult.errors?.length || !unrollResult.config) { + const errorDetails = unrollResult.errors?.join("\n") ?? "Unknown error"; + throw new Error(`Failed to load config file:\n${errorDetails}`); + } + + return unrollResult.config; +} + export async function loadConfig( accessToken: string | undefined, config: string | undefined, - organizationId: string | undefined + organizationId: string | null ): Promise { const apiClient = new DefaultApi( new Configuration({ @@ -73,7 +113,7 @@ export async function loadConfig( // Fall back to listing assistants and taking the first one const assistants = await apiClient.listAssistants({ alwaysUseProxy: "false", - organizationId, + organizationId: organizationId ?? undefined, }); const result = assistants[0].configResult; @@ -84,8 +124,15 @@ export async function loadConfig( return result.config as AssistantUnrolled; } else if (config.startsWith(".") || config.startsWith("/")) { // Load from file - throw new Error("Loading from file is not supported yet."); - // return loadAssistantFromFile(config); + const configYaml = await loadConfigYaml( + accessToken, + "TODO", // TODO currentUserSlug + config, + organizationId, + apiClient + ); + + return configYaml; } else { // Load from slug const [ownerSlug, packageSlug] = config.split("/"); @@ -93,7 +140,7 @@ export async function loadConfig( ownerSlug, packageSlug, alwaysUseProxy: "false", - organizationId, + organizationId: organizationId ?? undefined, }); const result = resp.configResult; @@ -117,7 +164,7 @@ export async function initialize( const config = await loadConfig( authConfig.accessToken, configPath, - authConfig.organizationId ?? undefined + authConfig.organizationId ?? null ); const [llmApi, model] = getLlmApi(config, authConfig); const mcpService = await MCPService.create(config);