Elffuss BraidHub

kikocis/continue public

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