Elffuss BraidHub

kikocis/continue public

e0b45db6ff5d · 11.0 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.filePath)
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 },
305 );
306
307 const errorDetails = unrollResult.errors;
308 if (!unrollResult.config) {
309 throw new Error(`Failed to load config:\n${errorDetails}`);
310 } else if (errorDetails?.length) {
311 const warnings =
312 errorDetails?.length > 1
313 ? errorDetails.map((d) => `\n- ${d.message}`)
314 : errorDetails[0].message;
315 console.warn(chalk.dim(`Warning: ${warnings}`));
316 }
317
318 return unrollResult.config;
319}
320
321/**
322 * Loads a local YAML configuration file
323 */
324async function loadConfigYaml(
325 filePath: string,
326 accessToken: string | null,
327 organizationId: string | null,
328 apiClient: DefaultApiInterface,
329): Promise<AssistantUnrolled> {
330 return await unrollAssistantWithConfig(
331 { filePath, uriType: "file" },
332 accessToken,
333 organizationId,
334 apiClient,
335 );
336}
337
338/**
339 * Loads an assistant by slug from the Continue platform
340 */
341async function loadAssistantSlug(
342 slug: string,
343 organizationId: string | null,
344 apiClient: DefaultApiInterface,
345): Promise<AssistantUnrolled> {
346 const [ownerSlug, packageSlug] = slug.split("/");
347 if (!ownerSlug || !packageSlug) {
348 throw new Error(
349 `Invalid assistant slug format. Expected "owner/package", got: ${slug}`,
350 );
351 }
352
353 // Unroll locally if not logged in
354 if (!(apiClient as any).configuration.apiKey) {
355 return await unrollAssistantWithConfig(
356 {
357 uriType: "slug",
358 fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" },
359 },
360 null,
361 organizationId,
362 apiClient,
363 );
364 }
365
366 const resp = await apiClient.getAssistant({
367 ownerSlug,
368 packageSlug,
369 alwaysUseProxy: "false",
370 organizationId: organizationId ?? undefined,
371 });
372
373 const result = resp.configResult;
374 if (result.errors?.length || !result.config) {
375 throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
376 }
377
378 return result.config as AssistantUnrolled;
379}
380
381/**
382 * Determines if a config path is a file path vs assistant slug
383 */
384function isFilePath(configPath: string): boolean {
385 return (
386 configPath.startsWith(".") ||
387 configPath.startsWith("/") ||
388 configPath.startsWith("~") ||
389 // Windows absolute paths (C:\, D:\, etc.)
390 /^[A-Za-z]:[/\\]/.test(configPath) ||
391 // UNC paths (\\server\share)
392 configPath.startsWith("\\\\") ||
393 // Contains file extension
394 configPath.includes(".yaml") ||
395 configPath.includes(".yml") ||
396 configPath.includes(".json")
397 );
398}
399
400/**
401 * Converts a config source back to a URI for persistence
402 */
403function getUriFromSource(source: ConfigSource): string | null {
404 switch (source.type) {
405 case "cli-flag":
406 return isFilePath(source.path)
407 ? `file://${source.path}`
408 : `slug://${source.path}`;
409 case "saved-uri":
410 return source.uri;
411 case "default-config-yaml":
412 return `file://${path.join(env.continueHome, "config.yaml")}`;
413 default:
414 return null;
415 }
416}