Elffuss BraidHub

kikocis/continue public

d13968478db8 · 11.2 KiBRawPermalink
1import * as fs from "fs";
2import { dirname } from "node:path";
3import * as path from "path";
4
5import {
6 AssistantUnrolled,
7 PackageIdentifier,
8 RegistryClient,
9 unrollAssistant,
10} from "@continuedev/config-yaml";
11import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
12import chalk from "chalk";
13
14import { uriToPath, uriToSlug } from "./auth/uriUtils.js";
15import {
16 AuthConfig,
17 getAccessToken,
18 getConfigUri,
19 getOrganizationId,
20 isEnvironmentAuthConfig,
21 updateConfigUri,
22} from "./auth/workos.js";
23import { CLIPlatformClient } from "./CLIPlatformClient.js";
24import { env } from "./env.js";
25
26export interface ConfigLoadResult {
27 config: AssistantUnrolled;
28 source: ConfigSource;
29}
30
31export type ConfigSource =
32 | { type: "cli-flag"; path: string }
33 | { type: "saved-uri"; uri: string }
34 | { type: "user-assistant"; slug: string }
35 | { type: "default-config-yaml" }
36 | { type: "default-agent" };
37
38/**
39 * Streamlined configuration loader that implements the specification
40 * with clear precedence and fallback logic in a single testable function.
41 */
42export async function loadConfiguration(
43 authConfig: AuthConfig,
44 cliConfigPath: string | undefined,
45 apiClient: DefaultApiInterface,
46): Promise<ConfigLoadResult> {
47 const organizationId = getOrganizationId(authConfig);
48 const accessToken = getAccessToken(authConfig);
49
50 // Step 1: Determine config source using precedence rules
51 const configSource = determineConfigSource(authConfig, cliConfigPath);
52
53 // Step 2: Load configuration from the determined source
54 const config = await loadFromSource(
55 configSource,
56 accessToken,
57 organizationId,
58 apiClient,
59 );
60
61 // Step 3: Save config URI for session continuity (only for file-based auth)
62 if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
63 const uri = getUriFromSource(configSource);
64 if (uri) {
65 updateConfigUri(uri);
66 }
67 }
68
69 return { config, source: configSource };
70}
71
72/**
73 * Determines the configuration source using the specification's precedence rules:
74 * 1. CLI --config flag (highest priority)
75 * 2. Saved config URI (if no CLI flag)
76 * 3. Default resolution (if no flag and no saved URI)
77 */
78function determineConfigSource(
79 authConfig: AuthConfig,
80 cliConfigPath: string | undefined,
81): ConfigSource {
82 // Priority 1: CLI --config flag
83 if (cliConfigPath) {
84 return { type: "cli-flag", path: cliConfigPath };
85 }
86
87 // Priority 2: Saved config URI (only for file-based auth)
88 if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
89 const savedUri = getConfigUri(authConfig);
90 if (savedUri) {
91 return { type: "saved-uri", uri: savedUri };
92 }
93 }
94
95 // Priority 3: Default resolution based on auth state
96 if (authConfig === null) {
97 // Unauthenticated: check for default config.yaml, then fallback to default agent
98 const defaultConfigPath = path.join(env.continueHome, "config.yaml");
99 if (fs.existsSync(defaultConfigPath)) {
100 return { type: "default-config-yaml" };
101 }
102 return { type: "default-agent" };
103 } else {
104 // Authenticated: try user assistants first
105 return { type: "user-assistant", slug: "" }; // Empty slug means "first available"
106 }
107}
108
109/**
110 * Loads configuration from the determined source with appropriate error handling
111 */
112async function loadFromSource(
113 source: ConfigSource,
114 accessToken: string | null,
115 organizationId: string | null,
116 apiClient: DefaultApiInterface,
117): Promise<AssistantUnrolled> {
118 try {
119 switch (source.type) {
120 case "cli-flag":
121 return await loadFromCliFlag(
122 source.path,
123 accessToken,
124 organizationId,
125 apiClient,
126 );
127
128 case "saved-uri":
129 return await loadFromSavedUri(
130 source.uri,
131 accessToken,
132 organizationId,
133 apiClient,
134 );
135
136 case "user-assistant":
137 return await loadUserAssistantWithFallback(organizationId, apiClient);
138
139 case "default-config-yaml":
140 return await loadDefaultConfigYaml(
141 accessToken,
142 organizationId,
143 apiClient,
144 );
145
146 case "default-agent":
147 return await loadDefaultAgent(organizationId, apiClient);
148
149 default:
150 throw new Error(`Unknown config source type: ${(source as any).type}`);
151 }
152 } catch (error) {
153 // If we're trying user assistants and it fails, fall back to default agent
154 if (source.type === "user-assistant") {
155 console.warn(
156 chalk.yellow(
157 "Failed to load user assistants, falling back to default agent",
158 ),
159 );
160 return await loadDefaultAgent(organizationId, apiClient);
161 }
162 throw error;
163 }
164}
165
166/**
167 * Loads configuration from CLI --config flag
168 * Supports both file paths and assistant slugs
169 */
170async function loadFromCliFlag(
171 configPath: string,
172 accessToken: string | null,
173 organizationId: string | null,
174 apiClient: DefaultApiInterface,
175): Promise<AssistantUnrolled> {
176 if (isFilePath(configPath)) {
177 // Load local YAML file
178 return await loadConfigYaml(
179 configPath,
180 accessToken,
181 organizationId,
182 apiClient,
183 );
184 } else {
185 // Load assistant slug
186 return await loadAssistantSlug(configPath, organizationId, apiClient);
187 }
188}
189
190/**
191 * Loads configuration from saved URI in auth config
192 */
193async function loadFromSavedUri(
194 uri: string,
195 accessToken: string | null,
196 organizationId: string | null,
197 apiClient: DefaultApiInterface,
198): Promise<AssistantUnrolled> {
199 const filePath = uriToPath(uri);
200 if (filePath) {
201 return await loadConfigYaml(
202 filePath,
203 accessToken,
204 organizationId,
205 apiClient,
206 );
207 }
208
209 const slug = uriToSlug(uri);
210 if (slug) {
211 return await loadAssistantSlug(slug, organizationId, apiClient);
212 }
213
214 throw new Error(`Invalid saved config URI: ${uri}`);
215}
216
217/**
218 * Loads first available user assistant with fallback to default agent
219 */
220async function loadUserAssistantWithFallback(
221 organizationId: string | null,
222 apiClient: DefaultApiInterface,
223): Promise<AssistantUnrolled> {
224 const assistants = await apiClient.listAssistants({
225 alwaysUseProxy: "false",
226 organizationId: organizationId ?? undefined,
227 });
228
229 if (assistants.length > 0) {
230 const result = assistants[0].configResult;
231 if (result.errors?.length || !result.config) {
232 throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
233 }
234 return result.config as AssistantUnrolled;
235 }
236
237 // No user assistants, fall back to default agent
238 return await loadDefaultAgent(organizationId, apiClient);
239}
240
241/**
242 * Loads default config.yaml from ~/.continue/config.yaml
243 */
244async function loadDefaultConfigYaml(
245 accessToken: string | null,
246 organizationId: string | null,
247 apiClient: DefaultApiInterface,
248): Promise<AssistantUnrolled> {
249 const defaultConfigPath = path.join(env.continueHome, "config.yaml");
250 return await loadConfigYaml(
251 defaultConfigPath,
252 accessToken,
253 organizationId,
254 apiClient,
255 );
256}
257
258/**
259 * Loads the default continuedev/default-agent
260 */
261async function loadDefaultAgent(
262 organizationId: string | null,
263 apiClient: DefaultApiInterface,
264): Promise<AssistantUnrolled> {
265 const resp = await apiClient.getAssistant({
266 ownerSlug: "continuedev",
267 packageSlug: "default-agent",
268 organizationId: organizationId ?? undefined,
269 });
270
271 if (!resp.configResult.config) {
272 throw new Error("Failed to load default agent.");
273 }
274
275 return resp.configResult.config as AssistantUnrolled;
276}
277
278/**
279 * Common function to unroll an assistant with consistent configuration
280 */
281async function unrollAssistantWithConfig(
282 packageIdentifier: PackageIdentifier,
283 accessToken: string | null,
284 organizationId: string | null,
285 apiClient: DefaultApiInterface,
286): Promise<AssistantUnrolled> {
287 const unrollResult = await unrollAssistant(
288 packageIdentifier,
289 new RegistryClient({
290 accessToken: accessToken ?? undefined,
291 apiBase: env.apiBase,
292 rootPath:
293 packageIdentifier.uriType === "file"
294 ? dirname(packageIdentifier.fileUri)
295 : undefined,
296 }),
297 {
298 currentUserSlug: "",
299 alwaysUseProxy: false,
300 orgScopeId: organizationId,
301 renderSecrets: true,
302 platformClient: new CLIPlatformClient(organizationId, apiClient),
303 onPremProxyUrl: null,
304 injectBlocks: [
305 {
306 uriType: "slug",
307 fullSlug: {
308 ownerSlug: "openai",
309 packageSlug: "gpt-5",
310 versionSlug: "latest",
311 },
312 },
313 ],
314 },
315 );
316
317 const errorDetails = unrollResult.errors;
318 if (!unrollResult.config) {
319 throw new Error(`Failed to load config:\n${errorDetails}`);
320 } else if (errorDetails?.length) {
321 const warnings =
322 errorDetails?.length > 1
323 ? errorDetails.map((d) => `\n- ${d.message}`)
324 : errorDetails[0].message;
325 console.warn(chalk.dim(`Warning: ${warnings}`));
326 }
327
328 return unrollResult.config;
329}
330
331/**
332 * Loads a local YAML configuration file
333 */
334async function loadConfigYaml(
335 filePath: string,
336 accessToken: string | null,
337 organizationId: string | null,
338 apiClient: DefaultApiInterface,
339): Promise<AssistantUnrolled> {
340 return await unrollAssistantWithConfig(
341 { fileUri: filePath, uriType: "file" },
342 accessToken,
343 organizationId,
344 apiClient,
345 );
346}
347
348/**
349 * Loads an assistant by slug from the Continue platform
350 */
351async function loadAssistantSlug(
352 slug: string,
353 organizationId: string | null,
354 apiClient: DefaultApiInterface,
355): Promise<AssistantUnrolled> {
356 const [ownerSlug, packageSlug] = slug.split("/");
357 if (!ownerSlug || !packageSlug) {
358 throw new Error(
359 `Invalid assistant slug format. Expected "owner/package", got: ${slug}`,
360 );
361 }
362
363 // Unroll locally if not logged in
364 if (!(apiClient as any).configuration.apiKey) {
365 return await unrollAssistantWithConfig(
366 {
367 uriType: "slug",
368 fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" },
369 },
370 null,
371 organizationId,
372 apiClient,
373 );
374 }
375
376 const resp = await apiClient.getAssistant({
377 ownerSlug,
378 packageSlug,
379 alwaysUseProxy: "false",
380 organizationId: organizationId ?? undefined,
381 });
382
383 const result = resp.configResult;
384 if (result.errors?.length || !result.config) {
385 throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
386 }
387
388 return result.config as AssistantUnrolled;
389}
390
391/**
392 * Determines if a config path is a file path vs assistant slug
393 */
394function isFilePath(configPath: string): boolean {
395 return (
396 configPath.startsWith(".") ||
397 configPath.startsWith("/") ||
398 configPath.startsWith("~") ||
399 // Windows absolute paths (C:\, D:\, etc.)
400 /^[A-Za-z]:[/\\]/.test(configPath) ||
401 // UNC paths (\\server\share)
402 configPath.startsWith("\\\\") ||
403 // Contains file extension
404 configPath.includes(".yaml") ||
405 configPath.includes(".yml") ||
406 configPath.includes(".json")
407 );
408}
409
410/**
411 * Converts a config source back to a URI for persistence
412 */
413function getUriFromSource(source: ConfigSource): string | null {
414 switch (source.type) {
415 case "cli-flag":
416 return isFilePath(source.path)
417 ? `file://${source.path}`
418 : `slug://${source.path}`;
419 case "saved-uri":
420 return source.uri;
421 case "default-config-yaml":
422 return `file://${path.join(env.continueHome, "config.yaml")}`;
423 default:
424 return null;
425 }
426}