refactor: make config loading logic more readable

This commit is contained in:
Nate 2025-07-24 21:11:50 -07:00
parent 5dc8b6de9a
commit 2d285d02ce
6 changed files with 560 additions and 149 deletions

191
spec/config-loading.md Normal file
View file

@ -0,0 +1,191 @@
# Configuration Loading Behavior Specification
## Overview
This document specifies the behavior of the CLI's configuration loading system, including precedence rules, authentication interactions, and error handling.
## Authentication Precedence
**Authentication Source Priority:**
1. **Environment Variable**: `CONTINUE_API_KEY` environment variable
2. **File-Based Auth**: `~/.continue/auth.json` file
3. **No Authentication**: Unauthenticated mode
**Authentication Effects:**
- **Environment Auth**: Always uses personal organization, no config URI persistence
- **File Auth**: Supports organizations, persists config URIs, token refresh
- **No Auth**: Limited to default assistant, no personalization
## Configuration Source Precedence
**When CLI is invoked, config source is determined in this order:**
1. **CLI `--config` Flag** (highest priority)
- File path (starts with `.`, `/`, `~`): Loads local YAML file
- Assistant slug (`owner/package`): Fetches from Continue platform
- Overrides any saved preferences
2. **Saved Config URI** (if no `--config` flag)
- Retrieved from authentication config
- Converts `file://` URIs back to file paths
- Converts `slug://` URIs back to assistant slugs
3. **Default Resolution** (if no flag and no saved URI)
- **Authenticated**: First user assistant from `listAssistants()`
- **config.yaml**: The saved config file at `~/.continue/config.yaml`
- **Unauthenticated**: Falls back to `continuedev/default-agent`
## Authentication State Interactions
### Authenticated Users
**Available Options:**
- Personal assistants
- Organization assistants (if organization selected)
- Local YAML files
- Public assistants
**Behavior:**
- `listAssistants()` returns personalized results
- Config selections are saved as URIs in auth config
- Organization context affects available assistants
### Unauthenticated Users
**Available Options:**
- Local YAML files only
- Default assistant (`continuedev/default-agent`)
**Behavior:**
- No access to personal or organization assistants
- No config URI persistence
- Direct fallback to default when no config specified
### Environment Variable Auth (`CONTINUE_API_KEY`)
**Behavior:**
- Treated as authenticated for API access
- Always uses personal organization context
- No persistence of config URIs
- Cannot switch organizations
## Organization Context
**Organization Selection:**
- **Interactive Mode**: Auto-selects first available organization
- **Headless Mode**: Defaults to personal organization
- **Environment Auth**: Always personal organization
**Effects on Config Loading:**
- Organization ID passed to all API calls
- Affects which assistants appear in `listAssistants()`
- Organization changes trigger complete config reload
## Error Handling Behavior
### Config Loading Errors
**File Not Found:**
- Local file specified but doesn't exist
- **Result**: Error thrown, CLI exits
**Invalid YAML:**
- Local file exists but has syntax errors
- **Result**: Parsing error thrown, CLI exits
**Network Failures:**
- API calls fail for assistant slugs
- **Result**: Network error bubbled up, CLI exits
**Assistant Not Found:**
- Valid slug format but assistant doesn't exist
- **Result**: 404 error from API, CLI exits
### Fallback Scenarios
**No User Assistants:**
- Authenticated user has no personal assistants
- **Result**: Falls back to `continuedev/default-agent`
**Default Agent Unavailable:**
- Fallback to default agent fails
- **Result**: Error thrown, CLI cannot start
**Token Expired:**
- Saved auth token is expired
- **Result**: Automatic refresh attempted, re-auth required if refresh fails
## Config URI Persistence
**When URIs are Saved:**
- Any successful config load via service layer
- File paths converted to `file://path/to/config.yaml`
- Assistant slugs converted to `slug://owner/package`
**When URIs are NOT Saved:**
- Environment variable authentication in use
- Config loading failures
- Unauthenticated sessions
## Rule Integration
**Rule Processing:**
- `--rule` flags processed independently of config loading
- Multiple rules supported, injected into system message
- Rule failures are warnings, don't prevent config loading
- Rule sources: file paths, hub slugs, direct strings
## Session Continuity
**Next Session Behavior:**
- **With Saved URI**: Uses saved config automatically
- **CLI Override**: `--config` flag overrides saved URI and updates it
- **Config Switching**: UI actions update saved URI for future sessions
**Cross-Session State:**
- Authentication persists until logout
- Organization selection persists
- Config URI persists (except for environment auth)
## Complete Decision Flow
```
1. Parse CLI arguments
2. Load authentication state (env var > file > none)
3. Determine config source:
- CLI --config flag provided? Use it
- Saved config URI exists? Use it
- Default resolution based on auth state
4. Load configuration:
- File path? Parse YAML locally
- Assistant slug? Fetch from API
- Default resolution? List assistants or use default
5. Process and inject rules
6. Save config URI (if authenticated via file)
7. Initialize services with loaded config
```
This behavior ensures users get predictable config loading with clear precedence rules while maintaining session continuity and graceful fallbacks.

View file

@ -22,6 +22,7 @@ import {
getOrganizationId,
} from "./auth/workos.js";
import { CLIPlatformClient } from "./CLIPlatformClient.js";
import { loadConfiguration } from "./configLoader.js";
import { env } from "./env.js";
import { MCPService } from "./mcp.js";
@ -123,79 +124,6 @@ export function getApiClient(
);
}
export async function loadConfig(
authConfig: AuthConfig,
config: string | undefined,
organizationId: string | null,
apiClient?: DefaultApiInterface
): Promise<AssistantUnrolled> {
if (!apiClient) {
apiClient = getApiClient(authConfig?.accessToken);
}
if (!config) {
// Fall back to listing assistants and taking the first one
const assistants = await apiClient.listAssistants({
alwaysUseProxy: "false",
organizationId: organizationId ?? undefined,
});
if (assistants.length === 0) {
// In case the user doesn't have any assistants, we fall back to a default - TODO
const resp = await apiClient.getAssistant({
ownerSlug: "continuedev",
packageSlug: "default-agent",
organizationId: organizationId ?? undefined,
});
if (!resp.configResult.config) {
throw new Error("Failed to load default agent.");
}
return resp.configResult.config as AssistantUnrolled;
}
const result = assistants[0].configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
if (
config.startsWith(".") ||
config.startsWith("/") ||
config.startsWith("~")
) {
// Load from file
const configYaml = await loadConfigYaml(
authConfig?.accessToken ?? null,
config,
organizationId,
apiClient
);
return configYaml;
} else {
// Load from slug
const [ownerSlug, packageSlug] = config.split("/");
const resp = await apiClient.getAssistant({
ownerSlug,
packageSlug,
alwaysUseProxy: "false",
organizationId: organizationId ?? undefined,
});
const result = resp.configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
}
export async function initialize(
authConfig: AuthConfig,
configPath: string | undefined
@ -206,14 +134,9 @@ export async function initialize(
mcpService: MCPService;
apiClient: DefaultApiInterface;
}> {
const organizationId = getOrganizationId(authConfig);
const apiClient = getApiClient(authConfig?.accessToken);
const config = await loadConfig(
authConfig,
configPath,
organizationId,
apiClient
);
const result = await loadConfiguration(authConfig, configPath, apiClient);
const config = result.config;
const [llmApi, model] = getLlmApi(config, authConfig);
const mcpService = await MCPService.create(config);

334
src/configLoader.ts Normal file
View file

@ -0,0 +1,334 @@
import {
AssistantUnrolled,
RegistryClient,
unrollAssistant,
} from "@continuedev/config-yaml";
import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
import chalk from "chalk";
import * as fs from "fs";
import { dirname } from "node:path";
import * as os from "os";
import * as path from "path";
import {
AuthConfig,
getAccessToken,
getConfigUri,
getOrganizationId,
isEnvironmentAuthConfig,
updateConfigUri,
uriToPath,
uriToSlug,
} from "./auth/workos.js";
import { CLIPlatformClient } from "./CLIPlatformClient.js";
import { env } from "./env.js";
export interface ConfigLoadResult {
config: AssistantUnrolled;
source: ConfigSource;
}
export type ConfigSource =
| { type: "cli-flag"; path: string }
| { type: "saved-uri"; uri: string }
| { type: "user-assistant"; slug: string }
| { type: "default-config-yaml" }
| { type: "default-agent" };
/**
* Streamlined configuration loader that implements the specification
* with clear precedence and fallback logic in a single testable function.
*/
export async function loadConfiguration(
authConfig: AuthConfig,
cliConfigPath: string | undefined,
apiClient: DefaultApiInterface
): Promise<ConfigLoadResult> {
const organizationId = getOrganizationId(authConfig);
const accessToken = getAccessToken(authConfig);
// Step 1: Determine config source using precedence rules
const configSource = determineConfigSource(authConfig, cliConfigPath);
// Step 2: Load configuration from the determined source
const config = await loadFromSource(configSource, accessToken, organizationId, apiClient);
// Step 3: Save config URI for session continuity (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const uri = getUriFromSource(configSource);
if (uri) {
updateConfigUri(uri);
}
}
return { config, source: configSource };
}
/**
* Determines the configuration source using the specification's precedence rules:
* 1. CLI --config flag (highest priority)
* 2. Saved config URI (if no CLI flag)
* 3. Default resolution (if no flag and no saved URI)
*/
function determineConfigSource(
authConfig: AuthConfig,
cliConfigPath: string | undefined
): ConfigSource {
// Priority 1: CLI --config flag
if (cliConfigPath) {
return { type: "cli-flag", path: cliConfigPath };
}
// Priority 2: Saved config URI (only for file-based auth)
if (!isEnvironmentAuthConfig(authConfig) && authConfig !== null) {
const savedUri = getConfigUri(authConfig);
if (savedUri) {
return { type: "saved-uri", uri: savedUri };
}
}
// Priority 3: Default resolution based on auth state
if (authConfig !== null) {
// Authenticated: try user assistants first
return { type: "user-assistant", slug: "" }; // Empty slug means "first available"
} else {
// Unauthenticated: check for default config.yaml, then fallback to default agent
const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml");
if (fs.existsSync(defaultConfigPath)) {
return { type: "default-config-yaml" };
}
return { type: "default-agent" };
}
}
/**
* Loads configuration from the determined source with appropriate error handling
*/
async function loadFromSource(
source: ConfigSource,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
try {
switch (source.type) {
case "cli-flag":
return await loadFromCliFlag(source.path, accessToken, organizationId, apiClient);
case "saved-uri":
return await loadFromSavedUri(source.uri, accessToken, organizationId, apiClient);
case "user-assistant":
return await loadUserAssistantWithFallback(organizationId, apiClient);
case "default-config-yaml":
return await loadDefaultConfigYaml(accessToken, organizationId, apiClient);
case "default-agent":
return await loadDefaultAgent(organizationId, apiClient);
default:
throw new Error(`Unknown config source type: ${(source as any).type}`);
}
} catch (error) {
// If we're trying user assistants and it fails, fall back to default agent
if (source.type === "user-assistant") {
console.warn(chalk.yellow("Failed to load user assistants, falling back to default agent"));
return await loadDefaultAgent(organizationId, apiClient);
}
throw error;
}
}
/**
* Loads configuration from CLI --config flag
* Supports both file paths and assistant slugs
*/
async function loadFromCliFlag(
configPath: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
if (isFilePath(configPath)) {
// Load local YAML file
return await loadConfigYaml(configPath, accessToken, organizationId, apiClient);
} else {
// Load assistant slug
return await loadAssistantSlug(configPath, organizationId, apiClient);
}
}
/**
* Loads configuration from saved URI in auth config
*/
async function loadFromSavedUri(
uri: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const filePath = uriToPath(uri);
if (filePath) {
return await loadConfigYaml(filePath, accessToken, organizationId, apiClient);
}
const slug = uriToSlug(uri);
if (slug) {
return await loadAssistantSlug(slug, organizationId, apiClient);
}
throw new Error(`Invalid saved config URI: ${uri}`);
}
/**
* Loads first available user assistant with fallback to default agent
*/
async function loadUserAssistantWithFallback(
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const assistants = await apiClient.listAssistants({
alwaysUseProxy: "false",
organizationId: organizationId ?? undefined,
});
if (assistants.length > 0) {
const result = assistants[0].configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
// No user assistants, fall back to default agent
return await loadDefaultAgent(organizationId, apiClient);
}
/**
* Loads default config.yaml from ~/.continue/config.yaml
*/
async function loadDefaultConfigYaml(
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const defaultConfigPath = path.join(os.homedir(), ".continue", "config.yaml");
return await loadConfigYaml(defaultConfigPath, accessToken, organizationId, apiClient);
}
/**
* Loads the default continuedev/default-agent
*/
async function loadDefaultAgent(
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const resp = await apiClient.getAssistant({
ownerSlug: "continuedev",
packageSlug: "default-agent",
organizationId: organizationId ?? undefined,
});
if (!resp.configResult.config) {
throw new Error("Failed to load default agent.");
}
return resp.configResult.config as AssistantUnrolled;
}
/**
* Loads a local YAML configuration file
*/
async function loadConfigYaml(
filePath: string,
accessToken: string | null,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const unrollResult = await unrollAssistant(
{ filePath, uriType: "file" },
new RegistryClient({
accessToken: accessToken ?? undefined,
apiBase: env.apiBase,
rootPath: dirname(filePath),
}),
{
currentUserSlug: "",
alwaysUseProxy: false,
orgScopeId: organizationId,
renderSecrets: true,
platformClient: new CLIPlatformClient(organizationId, apiClient),
onPremProxyUrl: null,
}
);
const errorDetails = unrollResult.errors;
if (!unrollResult.config) {
throw new Error(`Failed to load config file:\n${errorDetails}`);
} else if (errorDetails?.length) {
const warnings =
errorDetails?.length > 1
? errorDetails.map((d) => `\n- ${d.message}`)
: errorDetails[0].message;
console.warn(chalk.dim(`Warning: ${warnings}`));
}
return unrollResult.config;
}
/**
* Loads an assistant by slug from the Continue platform
*/
async function loadAssistantSlug(
slug: string,
organizationId: string | null,
apiClient: DefaultApiInterface
): Promise<AssistantUnrolled> {
const [ownerSlug, packageSlug] = slug.split("/");
if (!ownerSlug || !packageSlug) {
throw new Error(`Invalid assistant slug format. Expected "owner/package", got: ${slug}`);
}
const resp = await apiClient.getAssistant({
ownerSlug,
packageSlug,
alwaysUseProxy: "false",
organizationId: organizationId ?? undefined,
});
const result = resp.configResult;
if (result.errors?.length || !result.config) {
throw new Error(result.errors?.join("\n") ?? "Failed to load assistant.");
}
return result.config as AssistantUnrolled;
}
/**
* Determines if a config path is a file path vs assistant slug
*/
function isFilePath(configPath: string): boolean {
return (
configPath.startsWith(".") ||
configPath.startsWith("/") ||
configPath.startsWith("~")
);
}
/**
* Converts a config source back to a URI for persistence
*/
function getUriFromSource(source: ConfigSource): string | null {
switch (source.type) {
case "cli-flag":
return isFilePath(source.path)
? `file://${source.path}`
: `slug://${source.path}`;
case "saved-uri":
return source.uri;
case "default-config-yaml":
return `file://${path.join(os.homedir(), ".continue", "config.yaml")}`;
default:
return null;
}
}

View file

@ -49,11 +49,11 @@ describe('Config Switching Implementation Test', () => {
// The updateConfigPath method is key to reactive config switching
});
test('loadConfig function exists for configuration loading', async () => {
const configModule = await import('../config.js');
test('loadConfiguration function exists for configuration loading', async () => {
const configLoaderModule = await import('../configLoader.js');
// Verify loadConfig function exists and is callable
expect(typeof configModule.loadConfig).toBe('function');
// Verify loadConfiguration function exists and is callable
expect(typeof configLoaderModule.loadConfiguration).toBe('function');
// This is what ConfigService.updateConfigPath uses to load new configs
});
@ -76,7 +76,7 @@ describe('Config Switching Implementation Test', () => {
userAction: 'select different configuration',
codeFlow: [
'useConfigSelector calls services.config.updateConfigPath(newPath)',
'ConfigService.updateConfigPath loads new config via loadConfig()',
'ConfigService.updateConfigPath loads new config via loadConfiguration()',
'ConfigService calls serviceContainer.set(CONFIG, newState)',
'ConfigService calls serviceContainer.reload(MODEL)',
'ConfigService calls serviceContainer.reload(MCP)',
@ -107,7 +107,7 @@ describe('Config Switching Implementation Test', () => {
expect(updateConfigPathSource).toContain('serviceContainer.reload');
expect(updateConfigPathSource).toContain('SERVICE_NAMES.MODEL');
expect(updateConfigPathSource).toContain('SERVICE_NAMES.MCP');
expect(updateConfigPathSource).toContain('loadConfig');
expect(updateConfigPathSource).toContain('loadConfiguration');
// This confirms our implementation has the right structure for reactive updates
console.log('✅ ConfigService.updateConfigPath implementation contains required reactive calls');

View file

@ -84,9 +84,9 @@ describe('Local Config Switching Investigation', () => {
});
test('hypothesis: local config loading has different behavior', async () => {
// The loadConfig function has two different code paths:
// The loadConfiguration function has different code paths:
const { loadConfig } = await import('../config.js');
const { loadConfiguration } = await import('../configLoader.js');
// Path 1: Local file loading (lines 176-189 in config.ts)
// if (config.startsWith(".") || config.startsWith("/") || config.startsWith("~")) {
@ -101,10 +101,10 @@ describe('Local Config Switching Investigation', () => {
// return result.config;
// }
// Hypothesis: The loadConfig function works correctly, but something else is different
// Hypothesis: The loadConfiguration function works correctly, but something else is different
// about how local configs are handled in the ConfigService or service container
expect(typeof loadConfig).toBe('function');
expect(typeof loadConfiguration).toBe('function');
// The issue might be:
// 1. Different state management for local vs remote configs
@ -125,7 +125,7 @@ describe('Local Config Switching Investigation', () => {
// Question: Could the assistant slug clearing/setting be interfering
// with the config loading process?
// In loadConfig, when config is undefined, it checks for saved assistant slug:
// In loadConfiguration, when config is undefined, it checks for saved assistant slug:
// const assistantSlug = getAssistantSlug(authConfig);
// if (assistantSlug) { config = assistantSlug; }
@ -137,7 +137,7 @@ describe('Local Config Switching Investigation', () => {
const { ConfigService } = await import('../services/ConfigService.js');
// The ConfigService.updateConfigPath method should work the same for both types:
// 1. Load new config via loadConfig(authConfig, newConfigPath, ...)
// 1. Load new config via loadConfiguration(authConfig, newConfigPath, ...)
// 2. Update this.currentState = { config, configPath: newConfigPath }
// 3. Call serviceContainer.set(CONFIG, this.currentState)
// 4. Call serviceContainer.reload(MODEL) and serviceContainer.reload(MCP)

View file

@ -4,11 +4,7 @@ import { processRule } from "../args.js";
import {
AuthConfig,
loadAuthConfig,
pathToUri,
slugToUri,
updateConfigUri,
} from "../auth/workos.js";
import { loadConfig } from "../config.js";
import logger from "../util/logger.js";
import { serviceContainer } from "./ServiceContainer.js";
import {
@ -39,12 +35,11 @@ export class ConfigService {
rules?: string[]
): Promise<ConfigServiceState> {
try {
let config = await loadConfig(
authConfig,
configPath,
organizationId,
apiClient
);
// Use the new streamlined config loader
const { loadConfiguration } = await import("../configLoader.js");
const result = await loadConfiguration(authConfig, configPath, apiClient);
let config = result.config;
// Inject rules if provided
if (rules && rules.length > 0) {
@ -56,15 +51,7 @@ export class ConfigService {
configPath,
};
// Save config URI to auth config
if (configPath) {
const configUri = this.isFilePath(configPath)
? pathToUri(configPath)
: slugToUri(configPath);
updateConfigUri(configUri);
} else {
updateConfigUri(null);
}
// Config URI persistence is now handled by the streamlined loader
logger.debug("ConfigService initialized successfully");
return this.currentState;
@ -97,12 +84,11 @@ export class ConfigService {
});
try {
let config = await loadConfig(
authConfig,
newConfigPath,
organizationId,
apiClient
);
// Use the new streamlined config loader
const { loadConfiguration } = await import("../configLoader.js");
const result = await loadConfiguration(authConfig, newConfigPath, apiClient);
let config = result.config;
// Inject rules if provided
if (rules && rules.length > 0) {
@ -114,11 +100,7 @@ export class ConfigService {
configPath: newConfigPath,
};
// Save config URI to auth config
const configUri = this.isFilePath(newConfigPath)
? pathToUri(newConfigPath)
: slugToUri(newConfigPath);
updateConfigUri(configUri);
// Config URI persistence is now handled by the streamlined loader
logger.debug("Configuration switched successfully", {
newConfigPath,
@ -223,30 +205,21 @@ export class ConfigService {
throw new Error("API client not available");
}
// Load the new configuration
let config = await loadConfig(
authConfig,
newConfigPath,
authState.organizationId || null,
// Load the new configuration using streamlined loader
const { loadConfiguration } = await import("../configLoader.js");
const result = await loadConfiguration(
authConfig,
newConfigPath,
apiClientState.apiClient
);
// Update internal state
this.currentState = {
config,
config: result.config,
configPath: newConfigPath,
};
// Save config URI to auth config
if (newConfigPath) {
const configUri = this.isFilePath(newConfigPath)
? pathToUri(newConfigPath)
: slugToUri(newConfigPath);
updateConfigUri(configUri);
} else {
// Clear config URI when switching to undefined
updateConfigUri(null);
}
// Config URI persistence is now handled by the streamlined loader
// Update the CONFIG service in the container
serviceContainer.set(SERVICE_NAMES.CONFIG, this.currentState);
@ -257,7 +230,7 @@ export class ConfigService {
logger.debug("Configuration path updated successfully", {
newConfigPath,
configName: config.name,
configName: result.config.name,
});
} catch (error: any) {
logger.error("Failed to update configuration path:", error);
@ -265,14 +238,4 @@ export class ConfigService {
}
}
/**
* Check if a config path is a file path vs assistant slug
*/
private isFilePath(configPath: string): boolean {
return (
configPath.startsWith(".") ||
configPath.startsWith("/") ||
configPath.startsWith("~")
);
}
}