Elffuss BraidHub

kikocis/continue public

6ea18b3a4328 · 11.1 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,
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.errors?.length || !result.config) {
233 throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
234 }
235 return result.config as AssistantUnrolled;
236 }
237
238 // No user assistants, fall back to default agent
239 return await loadDefaultAgent(organizationId, apiClient);
240}
241
242/**
243 * Loads default config.yaml from ~/.continue/config.yaml
244 */
245async function loadDefaultConfigYaml(
246 accessToken: string | null,
247 organizationId: string | null,
248 apiClient: DefaultApiInterface,
249): Promise<AssistantUnrolled> {
250 const defaultConfigPath = path.join(env.continueHome, "config.yaml");
251 return await loadConfigYaml(
252 defaultConfigPath,
253 accessToken,
254 organizationId,
255 apiClient,
256 );
257}
258
259/**
260 * Loads the default continuedev/default-agent
261 */
262async function loadDefaultAgent(
263 organizationId: string | null,
264 apiClient: DefaultApiInterface,
265): Promise<AssistantUnrolled> {
266 const resp = await apiClient.getAssistant({
267 ownerSlug: "continuedev",
268 packageSlug: "default-agent",
269 organizationId: organizationId ?? undefined,
270 });
271
272 if (!resp.configResult.config) {
273 throw new Error("Failed to load default agent.");
274 }
275
276 return resp.configResult.config as AssistantUnrolled;
277}
278
279/**
280 * Common function to unroll an assistant with consistent configuration
281 */
282async function unrollAssistantWithConfig(
283 packageIdentifier: PackageIdentifier,
284 accessToken: string | null,
285 organizationId: string | null,
286 apiClient: DefaultApiInterface,
287): Promise<AssistantUnrolled> {
288 const unrollResult = await unrollAssistant(
289 packageIdentifier,
290 new RegistryClient({
291 accessToken: accessToken ?? undefined,
292 apiBase: env.apiBase,
293 rootPath:
294 packageIdentifier.uriType === "file"
295 ? dirname(packageIdentifier.fileUri)
296 : undefined,
297 }),
298 {
299 currentUserSlug: "",
300 alwaysUseProxy: false,
301 orgScopeId: organizationId,
302 renderSecrets: true,
303 platformClient: new CLIPlatformClient(organizationId, apiClient),
304 onPremProxyUrl: null,
305 injectBlocks: [],
306 },
307 );
308
309 const errorDetails = unrollResult.errors;
310 if (!unrollResult.config) {
311 throw new Error(`Failed to load config:\n${errorDetails}`);
312 } else if (errorDetails?.length) {
313 const warnings =
314 errorDetails?.length > 1
315 ? errorDetails.map((d) => `\n- ${d.message}`)
316 : errorDetails[0].message;
317 console.warn(chalk.dim(`Warning: ${warnings}`));
318 }
319
320 return unrollResult.config;
321}
322
323/**
324 * Loads a local YAML configuration file
325 */
326async function loadConfigYaml(
327 filePath: string,
328 accessToken: string | null,
329 organizationId: string | null,
330 apiClient: DefaultApiInterface,
331): Promise<AssistantUnrolled> {
332 return await unrollAssistantWithConfig(
333 { fileUri: filePath, uriType: "file" },
334 accessToken,
335 organizationId,
336 apiClient,
337 );
338}
339
340/**
341 * Loads an assistant by slug from the Continue platform
342 */
343async function loadAssistantSlug(
344 slug: string,
345 organizationId: string | null,
346 apiClient: DefaultApiInterface,
347): Promise<AssistantUnrolled> {
348 const [ownerSlug, packageSlug] = slug.split("/");
349 if (!ownerSlug || !packageSlug) {
350 throw new Error(
351 `Invalid assistant slug format. Expected "owner/package", got: ${slug}`,
352 );
353 }
354
355 // Unroll locally if not logged in
356 if (!(apiClient as any).configuration.accessToken) {
357 return await unrollAssistantWithConfig(
358 {
359 uriType: "slug",
360 fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" },
361 },
362 getAccessToken(loadAuthConfig()),
363 organizationId,
364 apiClient,
365 );
366 }
367
368 const resp = await apiClient.getAssistant({
369 ownerSlug,
370 packageSlug,
371 alwaysUseProxy: "false",
372 organizationId: organizationId ?? undefined,
373 });
374
375 const result = resp.configResult;
376 if (result.errors?.length || !result.config) {
377 throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
378 }
379
380 return result.config as AssistantUnrolled;
381}
382
383/**
384 * Determines if a config path is a file path vs assistant slug
385 */
386function isFilePath(configPath: string): boolean {
387 return (
388 configPath.startsWith(".") ||
389 configPath.startsWith("/") ||
390 configPath.startsWith("~") ||
391 // Windows absolute paths (C:\, D:\, etc.)
392 /^[A-Za-z]:[/\\]/.test(configPath) ||
393 // UNC paths (\\server\share)
394 configPath.startsWith("\\\\") ||
395 // Contains file extension
396 configPath.includes(".yaml") ||
397 configPath.includes(".yml") ||
398 configPath.includes(".json")
399 );
400}
401
402/**
403 * Converts a config source back to a URI for persistence
404 */
405function getUriFromSource(source: ConfigSource): string | null {
406 switch (source.type) {
407 case "cli-flag":
408 return isFilePath(source.path)
409 ? `file://${source.path}`
410 : `slug://${source.path}`;
411 case "saved-uri":
412 return source.uri;
413 case "default-config-yaml":
414 return `file://${path.join(env.continueHome, "config.yaml")}`;
415 default:
416 return null;
417 }
418}