Elffuss BraidHub

kikocis/continue public

main · 6.8 KiBRawPermalink
1import { z } from "zod";
2import { PlatformClient, SecretStore } from "../interfaces/index.js";
3import {
4 decodeSecretLocation,
5 encodeSecretLocation,
6 SecretLocation,
7} from "../interfaces/SecretResult.js";
8import {
9 decodeFQSN,
10 encodeFQSN,
11 FQSN,
12 PackageIdentifier,
13} from "../interfaces/slugs.js";
14import { AssistantUnrolled } from "../schemas/index.js";
15import {
16 fillTemplateVariables,
17 getTemplateVariables,
18 parseAssistantUnrolled,
19} from "./unroll.js";
20
21export async function renderSecrets(
22 packageIdentifier: PackageIdentifier,
23 unrolledConfigContent: string,
24 clientSecretStore: SecretStore,
25 orgScopeId: string | null, // The "scope" that the user is logged in with
26 onPremProxyUrl: string | null,
27 platformClient?: PlatformClient,
28): Promise<AssistantUnrolled> {
29 // 1. First we need to get a list of all the FQSNs that are required to render the config
30 const secrets = getTemplateVariables(unrolledConfigContent);
31
32 // 2. Then, we will check which of the secrets are found in the local personal secret store. Here we’re checking for anything that matches the last part of the FQSN, not worrying about the owner/package/owner/package slugs
33 const secretsTemplateData: Record<string, string> = {};
34
35 const unresolvedFQSNs: FQSN[] = secrets.map((secret) => {
36 return decodeFQSN(secret.replace("secrets.", ""));
37 });
38
39 // Don't use platform client in local mode
40 if (platformClient) {
41 // 3. For any secrets not found, we send the FQSNs to the Continue Platform at the `/ide/sync-secrets` endpoint. This endpoint replies for each of the FQSNs with the following information (`SecretResult`): `foundAt`: tells which secret store it was found in (this is “user”, “org”, “package” or null if not found anywhere). If it’s found in an org or a package, it tells us the `secretLocation`, which is either just an org slug, or is a full org/package slug. If it’s found in “user” secrets, we send back the `value`. Full definition of `SecretResult` at [2]. The method of resolving an FQSN to a `SecretResult` is detailed at [3]
42 const secretResults = await platformClient.resolveFQSNs(unresolvedFQSNs);
43
44 // 4. (back to the client) Any “user” secrets that were returned back are added to the local secret store so we don’t have to request them again
45 for (const secretResult of secretResults) {
46 if (!secretResult) {
47 continue;
48 }
49
50 if ("value" in secretResult) {
51 // clientSecretStore.set(secretResult.fqsn.secretName, secretResult.value);
52 // const secretValue = await clientSecretStore.get(fqsn.secretName);
53 secretsTemplateData[encodeFQSN(secretResult.fqsn)] = secretResult.value;
54 }
55
56 secretsTemplateData["secrets." + encodeFQSN(secretResult.fqsn)] =
57 "value" in secretResult
58 ? secretResult.value
59 : `\${{ secrets.${encodeSecretLocation(secretResult.secretLocation)} }}`;
60 }
61 }
62
63 // 5. User secrets are rendered in place of the template variable. Others remain templated, but replaced with the specific location where they are to be found (`${{ secrets.<secretLocation> }}` instead of `${{ secrets.<FQSN> }}`)
64 const renderedYaml = fillTemplateVariables(
65 unrolledConfigContent,
66 secretsTemplateData,
67 );
68
69 // 6. The rendered YAML is parsed and validated again
70 const parsedYaml = parseAssistantUnrolled(renderedYaml);
71
72 // 7. We update any of the items with the proxy version if there are un-rendered secrets
73 const finalConfig = useProxyForUnrenderedSecrets(
74 parsedYaml,
75 packageIdentifier,
76 orgScopeId,
77 onPremProxyUrl,
78 );
79 return finalConfig;
80}
81
82export function getUnrenderedSecretLocation(
83 value: string | undefined,
84): SecretLocation | undefined {
85 if (!value) return undefined;
86
87 const templateVars = getTemplateVariables(value);
88 if (templateVars.length === 1) {
89 const secretLocationEncoded = templateVars[0].split("secrets.")[1];
90 try {
91 const secretLocation = decodeSecretLocation(secretLocationEncoded);
92 return secretLocation;
93 } catch (e) {
94 // If it's a templated secret but not a valid secret location, leave it be
95 // in case on-prem proxy has the secret in an env variable
96 if (templateVars[0].startsWith("secrets.")) {
97 return undefined; // TODO
98 }
99 return undefined;
100 }
101 }
102
103 return undefined;
104}
105
106export function packageIdentifierToShorthandSlug(
107 id: PackageIdentifier,
108): string {
109 switch (id.uriType) {
110 case "slug":
111 return `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`;
112 case "file":
113 return "/";
114 }
115}
116
117function getContinueProxyModelName(
118 packageIdentifier: PackageIdentifier,
119 provider: string,
120 model: string,
121): string {
122 return `${packageIdentifierToShorthandSlug(packageIdentifier)}/${provider}/${model}`;
123}
124
125export function useProxyForUnrenderedSecrets(
126 config: AssistantUnrolled,
127 packageIdentifier: PackageIdentifier,
128 orgScopeId: string | null,
129 onPremProxyUrl: string | null,
130): AssistantUnrolled {
131 if (config.models) {
132 for (let i = 0; i < config.models.length; i++) {
133 const apiKeyLocation = getUnrenderedSecretLocation(
134 config.models[i]?.apiKey,
135 );
136 const encodedApiKeyLocation = apiKeyLocation
137 ? encodeSecretLocation(apiKeyLocation)
138 : undefined;
139
140 let encodedEnvSecretLocations: Record<string, string> | undefined =
141 undefined;
142 if (config.models[i]?.env) {
143 Object.entries(config.models[i]?.env!).forEach(([key, value]) => {
144 if (typeof value === "string") {
145 const secretLocation = getUnrenderedSecretLocation(value);
146 if (secretLocation) {
147 encodedEnvSecretLocations = {
148 ...encodedEnvSecretLocations,
149 [key]: encodeSecretLocation(secretLocation),
150 };
151 }
152 }
153 });
154 }
155
156 if (encodedApiKeyLocation || encodedEnvSecretLocations) {
157 config.models[i] = {
158 ...config.models[i],
159 name: config.models[i]?.name ?? "",
160 provider: "continue-proxy",
161 model: getContinueProxyModelName(
162 packageIdentifier,
163 config.models[i]?.provider ?? "",
164 config.models[i]?.model ?? "",
165 ),
166 apiKeyLocation: encodedApiKeyLocation,
167 envSecretLocations: encodedEnvSecretLocations,
168 orgScopeId,
169 onPremProxyUrl,
170 apiKey: undefined,
171 };
172 }
173 }
174 }
175
176 return config;
177}
178
179/** The additional properties that are added to the otherwise OpenAI-compatible body when requesting a Continue proxy */
180export const continuePropertiesSchema = z.object({
181 apiKeyLocation: z.string().optional(),
182 envSecretLocations: z.record(z.string(), z.string()).optional(),
183 apiBase: z.string().optional(),
184 orgScopeId: z.string().nullable(),
185 env: z.record(z.string(), z.any()).optional(),
186});
187
188export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;