Merge pull request #148 from continuedev/audit-command-line-flags

Audit and refactor command line flags
This commit is contained in:
Tomasz Stefaniak 2025-08-05 23:35:43 -07:00 • committed by GitHub
commit 686d106fb8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 884 additions and 98 deletions

5
.gitignore vendored
View file

@ -5,4 +5,7 @@ dist
chat.log
*notes.md
*notes.md
# Local config files (users should not commit their personal configs)
config.yaml

View file

@ -0,0 +1,97 @@
# Continue CLI Command Line Options
Quick reference for using `cn` command line options.
## Basic Usage
```bash
cn # Start interactive chat
cn "analyze my code" # Chat with prompt
cn -p "review this file" # Print response and exit (headless)
```
## Configuration
- `--config <path>` - Use specific config file
- `--verbose` - Show detailed logging
```bash
cn --config ./my-config.yaml
cn --verbose -p "debug this issue"
```
## Permission Modes
- `--readonly` - Only allow read operations (safe mode)
- `--auto` - Allow all tools without asking (careful!)
```bash
cn --readonly -p "analyze the codebase" # Safe: can't modify files
cn --auto -p "fix the failing tests" # Dangerous: will modify files
```
## Fine-grained Permissions
- `--allow <tool>` - Allow specific tools
- `--ask <tool>` - Ask before using tools
- `--exclude <tool>` - Block specific tools
```bash
cn --allow readFile --allow searchCode -p "find todos"
cn --exclude Write -p "help me understand this code" # Can't modify files
cn --ask writeFile -p "suggest fixes" # Will ask before writing
```
## Headless Mode (for scripts)
Use `-p` for non-interactive output:
```bash
cn -p "summarize the main function"
echo "error log" | cn -p "what caused this error?"
cn -p --format json "list main files" | jq '.response'
cn -p --silent "get summary" | grep -v "^$" # Clean output
```
## Server Mode
Run Continue as a server:
```bash
cn serve # Start server on port 8000
cn serve --port 3000 # Custom port
cn serve --timeout 600 # 10 minute timeout
```
## Remote Development
```bash
cn remote "help debug this" # Create new remote environment
cn remote --url https://my-server.com "work" # Connect to existing server
```
## Common Examples
```bash
# Safe code analysis
cn --readonly -p "review my git diff"
# Let AI fix tests (with permission)
cn --ask writeFile -p "fix failing tests"
# Scripted code review
git diff | cn -p "review this change" --format json
# Remote pair programming
cn remote "help me implement user auth"
# Run as code review server
cn serve --readonly --port 8080
```
## Notes
- Use `--readonly` when you want AI to analyze but not modify code
- Use `--auto` only when you trust the AI to make changes
- Pipe input works: `cat file.py | cn -p "explain this"`
- `--format json` and `--silent` only work with `-p`

View file

@ -4,15 +4,16 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs";
import * as readlineSync from "readline-sync";
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
import { loadAuthConfig } from "../auth/workos.js";
import {
compactChatHistory,
findCompactionIndex,
getHistoryForLLM,
} from "../compaction.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { configureLogger } from "../logger.js";
import * as logging from "../logging.js";
import { initializeWithOnboarding } from "../onboarding.js";
// initializeWithOnboarding is now handled internally by initializeServices
// import { initializeWithOnboarding } from "../onboarding.js";
import { sentryService } from "../sentry.js";
import { initializeServices } from "../services/index.js";
import { serviceContainer } from "../services/ServiceContainer.js";
@ -321,24 +322,13 @@ async function runHeadlessMode(
options: ChatOptions
): Promise<void> {
// Initialize services for headless mode
// Convert legacy flags to mode
let mode: any = undefined;
if (options.readonly) {
mode = "plan";
} else if (options.auto) {
mode = "auto";
}
const { permissionOverrides } = processCommandFlags(options);
await initializeServices({
configPath: options.config,
rules: options.rule,
headless: true,
toolPermissionOverrides: {
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
mode: mode,
},
toolPermissionOverrides: permissionOverrides,
});
// Get required services from the service container
@ -408,41 +398,36 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// Start active time tracking
telemetryService.startActiveTime();
// If not in headless mode, check for onboarding first
// If not in headless mode, use unified initialization with TUI
if (!options.headless) {
// Load auth config to check for onboarding
const authConfig = loadAuthConfig();
// Process flags for TUI mode
const { permissionOverrides } = processCommandFlags(options);
// Run onboarding check - this will handle first-time setup
const onboardingResult = await initializeWithOnboarding(
authConfig,
options.config,
options.rule
);
// Initialize services with onboarding handled internally
const initResult = await initializeServices({
configPath: options.config,
rules: options.rule,
headless: false,
toolPermissionOverrides: permissionOverrides,
});
// If onboarding was completed (user just went through setup), show success message
if (onboardingResult.wasOnboarded) {
// If onboarding was completed, show success message
if (initResult.wasOnboarded) {
console.log(chalk.green("✓ Setup complete! Starting chat..."));
}
// Show ASCII art and version for TUI mode
console.log(CONTINUE_ASCII_ART);
// Convert legacy flags to mode for TUI
let mode: any = undefined;
if (options.readonly) {
mode = "plan";
} else if (options.auto) {
mode = "auto";
}
// Start TUI immediately - it will handle service loading
await startTUIChat(prompt, options.resume, options.config, options.rule, {
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
mode: mode,
});
// Start TUI with skipOnboarding since we already handled it
await startTUIChat(
prompt,
options.resume,
options.config,
options.rule,
permissionOverrides,
true
);
return;
}

View file

@ -8,6 +8,7 @@ import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import { getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import {
getService,
@ -67,19 +68,10 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
const port = parseInt(options.port || "8000", 10);
// Initialize services with tool permission overrides
// Convert legacy flags to mode
let mode: any = undefined;
if (options.readonly) {
mode = "plan";
}
const { permissionOverrides } = processCommandFlags(options);
await initializeServices({
toolPermissionOverrides: {
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
mode: mode,
},
toolPermissionOverrides: permissionOverrides,
configPath: options.config,
rules: options.rule,
headless: true, // Skip onboarding in serve mode

View file

@ -0,0 +1,145 @@
import {
convertLegacyModeFlags,
buildPermissionOverrides,
processCommandFlags,
} from "./flagProcessor.js";
describe("convertLegacyModeFlags", () => {
test("should return 'plan' when readonly is true", () => {
expect(convertLegacyModeFlags(true, false)).toBe("plan");
});
test("should return 'auto' when auto is true", () => {
expect(convertLegacyModeFlags(false, true)).toBe("auto");
});
test("should return undefined when both flags are false", () => {
expect(convertLegacyModeFlags(false, false)).toBeUndefined();
});
test("should return undefined when no flags provided", () => {
expect(convertLegacyModeFlags()).toBeUndefined();
});
test("should throw error when both readonly and auto are true", () => {
expect(() => convertLegacyModeFlags(true, true)).toThrow(
"Cannot use both --readonly and --auto flags together"
);
});
});
describe("buildPermissionOverrides", () => {
test("should build permission overrides with all parameters", () => {
const result = buildPermissionOverrides(
["readFile"],
["writeFile"],
["runTerminalCommand"],
"plan"
);
expect(result).toEqual({
allow: ["readFile"],
ask: ["writeFile"],
exclude: ["runTerminalCommand"],
mode: "plan",
});
});
test("should handle undefined parameters", () => {
const result = buildPermissionOverrides();
expect(result).toEqual({
allow: undefined,
ask: undefined,
exclude: undefined,
mode: undefined,
});
});
test("should handle partial parameters", () => {
const result = buildPermissionOverrides(["readFile"], undefined, ["Write"]);
expect(result).toEqual({
allow: ["readFile"],
ask: undefined,
exclude: ["Write"],
mode: undefined,
});
});
});
describe("processCommandFlags", () => {
test("should process readonly flag correctly", () => {
const result = processCommandFlags({
readonly: true,
allow: ["readFile"],
exclude: ["Write"],
});
expect(result).toEqual({
mode: "plan",
permissionOverrides: {
allow: ["readFile"],
ask: undefined,
exclude: ["Write"],
mode: "plan",
},
});
});
test("should process auto flag correctly", () => {
const result = processCommandFlags({
auto: true,
ask: ["writeFile"],
});
expect(result).toEqual({
mode: "auto",
permissionOverrides: {
allow: undefined,
ask: ["writeFile"],
exclude: undefined,
mode: "auto",
},
});
});
test("should handle no mode flags", () => {
const result = processCommandFlags({
allow: ["readFile", "searchCode"],
});
expect(result).toEqual({
mode: undefined,
permissionOverrides: {
allow: ["readFile", "searchCode"],
ask: undefined,
exclude: undefined,
mode: undefined,
},
});
});
test("should throw error for conflicting flags", () => {
expect(() =>
processCommandFlags({
readonly: true,
auto: true,
})
).toThrow("Cannot use both --readonly and --auto flags together");
});
test("should handle empty options", () => {
const result = processCommandFlags({});
expect(result).toEqual({
mode: undefined,
permissionOverrides: {
allow: undefined,
ask: undefined,
exclude: undefined,
mode: undefined,
},
});
});
});

View file

@ -0,0 +1,83 @@
/**
* Shared flag processing utilities to eliminate duplication between TUI and headless modes
*/
import { PermissionMode } from "../permissions/types.js";
export interface PermissionOverrides {
allow?: string[];
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
}
export interface ProcessedFlags {
mode?: PermissionMode;
permissionOverrides: PermissionOverrides;
}
/**
* Converts legacy readonly/auto flags to the new mode system
* This logic was previously duplicated in chat.ts lines 168-173 and 259-264
*/
export function convertLegacyModeFlags(readonly?: boolean, auto?: boolean): PermissionMode | undefined {
if (readonly && auto) {
throw new Error("Cannot use both --readonly and --auto flags together");
}
if (readonly) {
return "plan";
}
if (auto) {
return "auto";
}
return undefined;
}
/**
* Structures permission overrides for service initialization
* This logic was previously duplicated between TUI and headless paths
*/
export function buildPermissionOverrides(
allow?: string[],
ask?: string[],
exclude?: string[],
mode?: PermissionMode
): PermissionOverrides {
return {
allow,
ask,
exclude,
mode,
};
}
/**
* Processes all command line flags into a consistent structure
* Eliminates duplication and provides single source of truth for flag processing
*/
export function processCommandFlags(options: {
readonly?: boolean;
auto?: boolean;
allow?: string[];
ask?: string[];
exclude?: string[];
}): ProcessedFlags {
// Convert legacy flags to mode
const mode = convertLegacyModeFlags(options.readonly, options.auto);
// Build permission overrides
const permissionOverrides = buildPermissionOverrides(
options.allow,
options.ask,
options.exclude,
mode
);
return {
mode,
permissionOverrides,
};
}

View file

@ -0,0 +1,209 @@
import { validateFlags, handleValidationErrors } from './flagValidator.js';
describe('validateFlags', () => {
describe('format flag validation', () => {
test('should pass when format is used with print', () => {
const result = validateFlags({
format: 'json',
print: true,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail when format is used without print', () => {
const result = validateFlags({
format: 'json',
print: false,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('FORMAT_REQUIRES_PRINT');
expect(result.errors[0].message).toContain('--format flag can only be used with -p/--print');
});
test('should fail when format value is invalid', () => {
const result = validateFlags({
format: 'xml',
print: true,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('INVALID_FORMAT_VALUE');
expect(result.errors[0].message).toContain("--format currently only supports 'json'");
});
});
describe('silent flag validation', () => {
test('should pass when silent is used with print', () => {
const result = validateFlags({
silent: true,
print: true,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail when silent is used without print', () => {
const result = validateFlags({
silent: true,
print: false,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('SILENT_REQUIRES_PRINT');
expect(result.errors[0].message).toContain('--silent flag can only be used with -p/--print');
});
});
describe('mode flags validation', () => {
test('should pass with readonly only', () => {
const result = validateFlags({
readonly: true,
auto: false,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should pass with auto only', () => {
const result = validateFlags({
readonly: false,
auto: true,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail when both readonly and auto are used', () => {
const result = validateFlags({
readonly: true,
auto: true,
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('CONFLICTING_MODE_FLAGS');
expect(result.errors[0].message).toContain('Cannot use both --readonly and --auto');
});
});
describe('permission flags validation', () => {
test('should pass with valid permission flags', () => {
const result = validateFlags({
allow: ['readFile', 'searchCode'],
ask: ['writeFile'],
exclude: ['Write', 'Bash'],
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should fail with empty tool names in allow', () => {
const result = validateFlags({
allow: ['readFile', '', 'searchCode'],
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('EMPTY_ALLOW_TOOL');
expect(result.errors[0].message).toContain('--allow requires a tool name');
});
test('should fail with empty tool names in ask', () => {
const result = validateFlags({
ask: ['writeFile', ' ', 'editFile'],
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('EMPTY_ASK_TOOL');
expect(result.errors[0].message).toContain('--ask requires a tool name');
});
test('should fail with empty tool names in exclude', () => {
const result = validateFlags({
exclude: ['Write', '', 'Bash'],
});
expect(result.isValid).toBe(false);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('EMPTY_EXCLUDE_TOOL');
expect(result.errors[0].message).toContain('--exclude requires a tool name');
});
});
describe('multiple errors', () => {
test('should return all validation errors', () => {
const result = validateFlags({
format: 'xml',
print: false,
silent: true,
readonly: true,
auto: true,
allow: ['readFile', ''],
});
expect(result.isValid).toBe(false);
expect(result.errors.length).toBeGreaterThan(1);
const errorCodes = result.errors.map(e => e.code);
expect(errorCodes).toContain('FORMAT_REQUIRES_PRINT');
expect(errorCodes).toContain('INVALID_FORMAT_VALUE');
expect(errorCodes).toContain('SILENT_REQUIRES_PRINT');
expect(errorCodes).toContain('CONFLICTING_MODE_FLAGS');
expect(errorCodes).toContain('EMPTY_ALLOW_TOOL');
});
});
describe('config path validation', () => {
test('should pass with valid config path', () => {
const result = validateFlags({
config: './my-config.yaml',
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
test('should pass with undefined config', () => {
const result = validateFlags({
config: undefined,
});
expect(result.isValid).toBe(true);
expect(result.errors).toHaveLength(0);
});
});
});
describe('handleValidationErrors', () => {
test('should be a function that accepts validation errors', () => {
// Test function signature without calling it (since it calls process.exit)
expect(typeof handleValidationErrors).toBe('function');
expect(handleValidationErrors.length).toBe(1);
});
test('should accept proper error format', () => {
const validErrors = [
{ code: 'TEST_ERROR', message: 'Test message' },
{ code: 'ANOTHER_ERROR', message: 'Another message' }
];
// Verify the function exists and would accept this format
// We don't call it since it would exit the process
expect(() => {
const errorArray = validErrors;
expect(Array.isArray(errorArray)).toBe(true);
expect(errorArray.every(e => e.code && e.message)).toBe(true);
}).not.toThrow();
});
});

191
src/flags/flagValidator.ts Normal file
View file

@ -0,0 +1,191 @@
/**
* Centralized command line flag validation
* Provides consistent validation across all commands and proper error reporting
*/
export interface ValidationOptions {
// Root command specific flags
print?: boolean;
format?: string;
silent?: boolean;
// Common flags
readonly?: boolean;
auto?: boolean;
config?: string;
// Permission flags
allow?: string[];
ask?: string[];
exclude?: string[];
// Command context
isRootCommand?: boolean;
commandName?: string;
}
export interface ValidationError {
message: string;
code: string;
}
export interface ValidationResult {
isValid: boolean;
errors: ValidationError[];
}
/**
* Validate that --format flag only works with -p/--print
*/
function validateFormatFlag(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.format && !options.print) {
errors.push({
code: 'FORMAT_REQUIRES_PRINT',
message: 'Error: --format flag can only be used with -p/--print flag'
});
}
return errors;
}
/**
* Validate that --silent flag only works with -p/--print
*/
function validateSilentFlag(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.silent && !options.print) {
errors.push({
code: 'SILENT_REQUIRES_PRINT',
message: 'Error: --silent flag can only be used with -p/--print flag'
});
}
return errors;
}
/**
* Validate format value is supported
*/
function validateFormatValue(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.format && options.format !== 'json') {
errors.push({
code: 'INVALID_FORMAT_VALUE',
message: "Error: --format currently only supports 'json'"
});
}
return errors;
}
/**
* Validate that --readonly and --auto are mutually exclusive
* This validation is now handled in flagProcessor.ts, but we keep it here for completeness
*/
function validateModeFlags(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
if (options.readonly && options.auto) {
errors.push({
code: 'CONFLICTING_MODE_FLAGS',
message: 'Error: Cannot use both --readonly and --auto flags together'
});
}
return errors;
}
/**
* Validate config path exists (basic check)
*/
function validateConfigPath(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
// Note: We don't check file existence here since the config loader handles that
// and provides better error messages. This is just for basic validation.
if (options.config && typeof options.config !== 'string') {
errors.push({
code: 'INVALID_CONFIG_PATH',
message: 'Error: --config must be a valid path'
});
}
return errors;
}
/**
* Validate permission flag combinations
*/
function validatePermissionFlags(options: ValidationOptions): ValidationError[] {
const errors: ValidationError[] = [];
// Check for empty permission arrays (likely user error)
if (options.allow?.some(tool => !tool.trim())) {
errors.push({
code: 'EMPTY_ALLOW_TOOL',
message: 'Error: --allow requires a tool name (e.g., --allow readFile)'
});
}
if (options.ask?.some(tool => !tool.trim())) {
errors.push({
code: 'EMPTY_ASK_TOOL',
message: 'Error: --ask requires a tool name (e.g., --ask writeFile)'
});
}
if (options.exclude?.some(tool => !tool.trim())) {
errors.push({
code: 'EMPTY_EXCLUDE_TOOL',
message: 'Error: --exclude requires a tool name (e.g., --exclude Write)'
});
}
return errors;
}
/**
* Run all validation checks on the provided options
*/
export function validateFlags(options: ValidationOptions): ValidationResult {
const allErrors: ValidationError[] = [];
// Run all validation functions
const validators = [
validateFormatFlag,
validateSilentFlag,
validateFormatValue,
validateModeFlags,
validateConfigPath,
validatePermissionFlags,
];
for (const validator of validators) {
allErrors.push(...validator(options));
}
return {
isValid: allErrors.length === 0,
errors: allErrors,
};
}
/**
* Display validation errors and exit process
* Provides consistent error formatting across all commands
*/
export function handleValidationErrors(errors: ValidationError[]): never {
for (const error of errors) {
console.error(error.message);
}
if (errors.length > 1) {
console.error(`\nFound ${errors.length} validation errors.`);
}
process.exit(1);
}

View file

@ -8,6 +8,10 @@ import { logout } from "./commands/logout.js";
import { remoteTest } from "./commands/remote-test.js";
import { remote } from "./commands/remote.js";
import { serve } from "./commands/serve.js";
import {
validateFlags,
handleValidationErrors,
} from "./flags/flagValidator.js";
import { sentryService } from "./sentry.js";
import { addCommonOptions, mergeParentOptions } from "./shared-options.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
@ -62,26 +66,23 @@ addCommonOptions(program)
configureConsoleForHeadless(isHeadless);
logger.configureHeadlessMode(isHeadless);
// Validate --format flag only works with -p/--print
if (options.format && !options.print) {
console.error(
"Error: --format flag can only be used with -p/--print flag"
);
process.exit(1);
}
// Validate all command line flags
const validation = validateFlags({
print: options.print,
format: options.format,
silent: options.silent,
readonly: options.readonly,
auto: options.auto,
config: options.config,
allow: options.allow,
ask: options.ask,
exclude: options.exclude,
isRootCommand: true,
commandName: "cn",
});
// Validate --silent flag only works with -p/--print
if (options.silent && !options.print) {
console.error(
"Error: --silent flag can only be used with -p/--print flag"
);
process.exit(1);
}
// Validate format value
if (options.format && options.format !== "json") {
console.error("Error: --format currently only supports 'json'");
process.exit(1);
if (!validation.isValid) {
handleValidationErrors(validation.errors);
}
if (options.verbose) {

View file

@ -12,7 +12,10 @@ import { processRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { MCPService } from "./mcp.js";
import { isValidAnthropicApiKey, getApiKeyValidationError } from "./util/apiKeyValidation.js";
import {
isValidAnthropicApiKey,
getApiKeyValidationError,
} from "./util/apiKeyValidation.js";
import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml");
@ -48,10 +51,10 @@ export async function createOrUpdateConfig(apiKey: string): Promise<void> {
fs.mkdirSync(configDir, { recursive: true });
}
const existingContent = fs.existsSync(CONFIG_PATH)
const existingContent = fs.existsSync(CONFIG_PATH)
? fs.readFileSync(CONFIG_PATH, "utf8")
: "";
const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
fs.writeFileSync(CONFIG_PATH, updatedContent);
}
@ -66,14 +69,16 @@ export async function runOnboardingFlow(
return { ...result, wasOnboarded: false };
}
// Step 2: Check if we're in a test environment (NODE_ENV is test or CI environment)
const isTestEnv = process.env.NODE_ENV === "test" ||
process.env.CI === "true" ||
process.env.VITEST === "true" ||
!process.stdin.isTTY;
// Step 2: Check if we're in a test/CI environment - if so, skip interactive prompts
const isTestEnv =
process.env.NODE_ENV === "test" ||
process.env.CI === "true" ||
process.env.VITEST === "true" ||
process.env.GITHUB_ACTIONS === "true" ||
!process.stdin.isTTY;
if (isTestEnv) {
// In test environment, return a minimal working configuration
// In test/CI environment, return a minimal working configuration
const result = await initialize(authConfig, undefined);
return { ...result, wasOnboarded: false };
}
@ -133,8 +138,11 @@ export async function runNormalFlow(
return { ...result, wasOnboarded: false };
} catch (error) {
// If user explicitly provided --config flag, fail loudly instead of falling back
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to load config from "${configPath}": ${errorMessage}`);
const errorMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to load config from "${configPath}": ${errorMessage}`
);
}
}
@ -274,4 +282,4 @@ export async function initializeWithOnboarding(
}
return result;
}
}

View file

@ -1,11 +1,23 @@
import { vi } from "vitest";
import { modeService } from "./ModeService.js";
import { serviceContainer } from "./ServiceContainer.js";
import { initializeServices } from "./index.js";
// Mock the onboarding module
vi.mock("../onboarding.js", () => ({
initializeWithOnboarding: vi.fn().mockResolvedValue({ wasOnboarded: false }),
}));
// Mock auth module
vi.mock("../auth/workos.js", () => ({
loadAuthConfig: vi.fn().mockReturnValue({}),
}));
describe("initializeServices", () => {
let mockModeService: any;
let mockServiceContainer: any;
beforeEach(() => {
// Reset all mocks
@ -15,11 +27,31 @@ describe("initializeServices", () => {
mockModeService = {
initialize: vi.fn(),
getCurrentMode: vi.fn(),
getToolPermissionService: vi.fn().mockReturnValue({
getState: vi.fn().mockReturnValue({
currentMode: "normal",
isHeadless: false,
permissions: { policies: [] },
}),
}),
};
// Set up modeService mock
// Create mock service container
mockServiceContainer = {
registerValue: vi.fn(),
register: vi.fn(),
initializeAll: vi.fn().mockResolvedValue(undefined),
};
// Set up mocks
(modeService as any).initialize = mockModeService.initialize;
(modeService as any).getCurrentMode = mockModeService.getCurrentMode;
(modeService as any).getToolPermissionService = mockModeService.getToolPermissionService;
// Mock serviceContainer methods
(serviceContainer as any).registerValue = mockServiceContainer.registerValue;
(serviceContainer as any).register = mockServiceContainer.register;
(serviceContainer as any).initializeAll = mockServiceContainer.initializeAll;
});
afterEach(() => {
@ -29,6 +61,7 @@ describe("initializeServices", () => {
describe("mode conversion", () => {
it("should pass only readonly flag for plan mode", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
mode: "plan",
allow: ["tool1"],
@ -42,12 +75,14 @@ describe("initializeServices", () => {
ask: ["tool2"],
exclude: ["tool3"],
readonly: true,
isHeadless: true,
// auto should NOT be set
});
});
it("should pass only auto flag for auto mode", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
mode: "auto",
allow: ["tool1"],
@ -61,12 +96,14 @@ describe("initializeServices", () => {
ask: ["tool2"],
exclude: ["tool3"],
auto: true,
isHeadless: true,
// readonly should NOT be set
});
});
it("should pass no mode flags for normal mode", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
mode: "normal",
allow: ["tool1"],
@ -79,12 +116,14 @@ describe("initializeServices", () => {
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
isHeadless: true,
// Neither readonly nor auto should be set
});
});
it("should pass no mode flags when mode is undefined", async () => {
await initializeServices({
headless: true, // Skip onboarding
toolPermissionOverrides: {
allow: ["tool1"],
ask: ["tool2"],
@ -96,15 +135,18 @@ describe("initializeServices", () => {
allow: ["tool1"],
ask: ["tool2"],
exclude: ["tool3"],
isHeadless: true,
// Neither readonly nor auto should be set
});
});
it("should call initialize with defaults when no toolPermissionOverrides provided", async () => {
await initializeServices({});
await initializeServices({
headless: true, // Skip onboarding
});
expect(mockModeService.initialize).toHaveBeenCalledWith({
isHeadless: undefined,
isHeadless: true,
});
});
});

View file

@ -1,3 +1,5 @@
import { loadAuthConfig } from "../auth/workos.js";
import { initializeWithOnboarding } from "../onboarding.js";
import { logger } from "../util/logger.js";
import { ApiClientService } from "./ApiClientService.js";
@ -13,6 +15,7 @@ import {
ConfigServiceState,
SERVICE_NAMES,
ServiceInitOptions,
ServiceInitResult,
} from "./types.js";
// Service instances
@ -24,9 +27,23 @@ const mcpServiceWrapper = new MCPServiceWrapper();
/**
* Initialize all services and register them with the service container
* Handles onboarding internally for TUI mode unless skipOnboarding is true
*/
export async function initializeServices(options: ServiceInitOptions = {}) {
export async function initializeServices(options: ServiceInitOptions = {}): Promise<ServiceInitResult> {
logger.debug("Initializing service registry");
let wasOnboarded = false;
// Handle onboarding for TUI mode (headless: false) unless explicitly skipped
if (!options.headless && !options.skipOnboarding) {
const authConfig = loadAuthConfig();
const onboardingResult = await initializeWithOnboarding(
authConfig,
options.configPath,
options.rules
);
wasOnboarded = onboardingResult.wasOnboarded;
}
// Initialize mode service with tool permission overrides
if (options.toolPermissionOverrides) {
@ -178,6 +195,8 @@ export async function initializeServices(options: ServiceInitOptions = {}) {
await serviceContainer.initializeAll();
logger.debug("Service registry initialized");
return { wasOnboarded };
}
/**

View file

@ -84,10 +84,18 @@ export interface ServiceInitOptions {
configPath?: string;
rules?: string[];
headless?: boolean;
skipOnboarding?: boolean; // Skip onboarding check even in TUI mode
toolPermissionOverrides?: {
allow?: string[];
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
};
}
/**
* Service initialization result
*/
export interface ServiceInitResult {
wasOnboarded?: boolean;
}

View file

@ -19,17 +19,20 @@ export async function startTUIChat(
ask?: string[];
exclude?: string[];
mode?: PermissionMode;
}
},
skipOnboarding?: boolean
) {
// Initialize services in the background - TUI will show loading states
initializeServices({
configPath,
rules: additionalRules,
headless: false,
toolPermissionOverrides,
}).catch((error) => {
console.error("Failed to initialize services:", error);
});
// Initialize services only if not already done (skipOnboarding means already initialized)
if (!skipOnboarding) {
initializeServices({
configPath,
rules: additionalRules,
headless: false,
toolPermissionOverrides,
}).catch((error) => {
console.error("Failed to initialize services:", error);
});
}
// Start the TUI immediately - it will handle loading states
const { unmount } = render(