Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ import { createNotificationsRoutes } from './routes/notifications/index.js';
import { getNotificationService } from './services/notification-service.js';
import { createEventHistoryRoutes } from './routes/event-history/index.js';
import { getEventHistoryService } from './services/event-history-service.js';
import { initGlobalSettingsAccessor } from './lib/global-settings-accessor.js';

// Load environment variables
dotenv.config();
Expand Down Expand Up @@ -227,6 +228,7 @@ const events: EventEmitter = createEventEmitter();
// Create services
// Note: settingsService is created first so it can be injected into other services
const settingsService = new SettingsService(DATA_DIR);
initGlobalSettingsAccessor(settingsService);
const agentService = new AgentService(DATA_DIR, events, settingsService);
const featureLoader = new FeatureLoader();
const autoModeService = new AutoModeService(events, settingsService);
Expand Down
162 changes: 162 additions & 0 deletions apps/server/src/lib/ccr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/**
* Claude Code Router (CCR) Utilities
*
* Provides functions to detect CCR installation, check server status,
* and read configuration for integration with Claude Agent SDK.
*/

import { exec } from 'node:child_process';
import { readFileSync, existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import type { CCRStatus, CCRConfig } from '@automaker/types';
import { createLogger } from '@automaker/utils';

const execAsync = promisify(exec);
const logger = createLogger('CCR');

/** Default CCR configuration directory */
const CCR_CONFIG_DIR = join(homedir(), '.claude-code-router');
const CCR_CONFIG_FILE = join(CCR_CONFIG_DIR, 'config.json');

// Cache for CCR status to avoid spamming the process list
let statusCache: { status: CCRStatus; timestamp: number } | null = null;
const STATUS_CACHE_TTL = 2000; // 2 seconds

/**
* Strips ANSI escape codes from a string
*/
function stripAnsi(str: string): string {
const ansiRegex = new RegExp(
'[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]',
'g'
);
return str.replace(ansiRegex, '');
}

/**
* Get the CCR configuration from disk
*/
export function getCCRConfig(): CCRConfig | null {
try {
if (!existsSync(CCR_CONFIG_FILE)) {
return null;
}
const content = readFileSync(CCR_CONFIG_FILE, 'utf-8');
return JSON.parse(content) as CCRConfig;
} catch (error) {
logger.debug('Failed to read CCR config:', error);
return null;
}
}

/**
* Check if CCR CLI is installed (async)
*/
export async function isCCRInstalled(): Promise<boolean> {
try {
// Use 'where' on Windows, 'which' on Unix
const cmd = process.platform === 'win32' ? 'where ccr' : 'which ccr';
await execAsync(cmd);
return true;
} catch {
return false;
}
}

/**
* Get CCR server status (async with caching)
*/
export async function getCCRStatus(): Promise<CCRStatus> {
// Check cache first
const now = Date.now();
if (statusCache && now - statusCache.timestamp < STATUS_CACHE_TTL) {
return statusCache.status;
}

const installed = await isCCRInstalled();
if (!installed) {
const status = { installed: false, running: false };
statusCache = { status, timestamp: now };
return status;
}

// Get config once to reuse
const config = getCCRConfig();
const port = config?.PORT ?? 3456;
const rawHost = config?.HOST || '127.0.0.1';
// If host is 0.0.0.0, use 127.0.0.1 for client connection
const host = rawHost === '0.0.0.0' ? '127.0.0.1' : rawHost;

try {
// Run 'ccr status' to check if server is running
const { stdout } = await execAsync('ccr status', {
timeout: 5000,
encoding: 'utf-8',
});

// Parse the output to determine status
const cleanStdout = stripAnsi(stdout);
// Use regex to avoid matching "not running"
// Look for word "running" not preceded by "not" (case insensitive)
const isRunning = /\b(?<!not\s)running\b/i.test(cleanStdout);

let status: CCRStatus;
if (isRunning) {
status = {
installed: true,
running: true,
port,
apiEndpoint: `http://${host}:${port}`,
};
} else {
status = { installed: true, running: false, port };
}

statusCache = { status, timestamp: now };
return status;
} catch (error) {
// CCR might not be running or command failed
const status: CCRStatus = {
installed: true,
running: false,
port,
error: error instanceof Error ? error.message : 'Unknown error',
};
statusCache = { status, timestamp: now };
return status;
}
}

/**
* Helper to generate environment variables from a valid CCR status and config.
* Avoids re-checking status if the caller already has it.
*/
export function getCCREnvFromStatus(
status: CCRStatus,
config?: CCRConfig | null
): Record<string, string | undefined> | null {
if (!status.installed || !status.running) {
return null;
}

const effectiveConfig = config ?? getCCRConfig();
const port = status.port ?? effectiveConfig?.PORT ?? 3456;
const rawHost = effectiveConfig?.HOST || '127.0.0.1';
// If host is 0.0.0.0, use 127.0.0.1 for client connection
const host = rawHost === '0.0.0.0' ? '127.0.0.1' : rawHost;
const apiKey = effectiveConfig?.APIKEY || 'ccr-default-key';
const timeoutMs = effectiveConfig?.API_TIMEOUT_MS ?? 600000;

return {
ANTHROPIC_AUTH_TOKEN: apiKey,
ANTHROPIC_BASE_URL: `http://${host}:${port}`,
NO_PROXY: '127.0.0.1',
DISABLE_TELEMETRY: 'true',
DISABLE_COST_WARNINGS: 'true',
API_TIMEOUT_MS: String(timeoutMs),
// Unset Bedrock to prevent conflicts
CLAUDE_CODE_USE_BEDROCK: undefined,
};
}
81 changes: 81 additions & 0 deletions apps/server/src/lib/global-settings-accessor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Global Settings Accessor
*
* Provides a centralized way to access global settings from anywhere in the codebase
* without needing to pass SettingsService through every function call.
*
* This is particularly useful for:
* - Provider-level code that needs global settings (like CCR routing)
* - Middleware that needs to check settings
* - Utility functions that need global configuration
*
* Usage:
* 1. Initialize at server startup: initGlobalSettingsAccessor(settingsService)
* 2. Access anywhere: const settings = await getGlobalSettingsFromAccessor()
*
* Design decisions:
* - Uses a module-level singleton pattern for simplicity
* - Returns null if not initialized (graceful degradation)
* - Async to support potential caching/optimization in the future
*/

import type { GlobalSettings } from '@automaker/types';

/**
* Minimal interface for settings access
* This allows decoupling from the full SettingsService
*/
interface GlobalSettingsProvider {
getGlobalSettings(): Promise<GlobalSettings | null>;
}

/**
* Module-level singleton for settings access
*/
let settingsProvider: GlobalSettingsProvider | null = null;

/**
* Initialize the global settings accessor
*
* Should be called once at server startup with the SettingsService instance.
*
* @param provider - The SettingsService or compatible provider
*/
export function initGlobalSettingsAccessor(provider: GlobalSettingsProvider): void {
settingsProvider = provider;
}

/**
* Get global settings from the accessor
*
* Returns null if the accessor hasn't been initialized.
* Callers should handle the null case gracefully.
*
* @returns Promise resolving to GlobalSettings or null
*/
export async function getGlobalSettingsFromAccessor(): Promise<GlobalSettings | null> {
if (!settingsProvider) {
return null;
}
return settingsProvider.getGlobalSettings();
}

/**
* Check if CCR is enabled in global settings
*
* Convenience function for the common CCR check pattern.
* Returns false if settings are not available.
*
* @returns Promise resolving to boolean
*/
export async function isCCREnabled(): Promise<boolean> {
const settings = await getGlobalSettingsFromAccessor();
return settings?.ccrEnabled ?? false;
}

/**
* Reset the accessor (useful for testing)
*/
export function resetGlobalSettingsAccessor(): void {
settingsProvider = null;
}
60 changes: 51 additions & 9 deletions apps/server/src/providers/claude-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import { query, type Options } from '@anthropic-ai/claude-agent-sdk';
import { BaseProvider } from './base-provider.js';
import { classifyError, getUserFriendlyErrorMessage, createLogger } from '@automaker/utils';
import { getCCREnvFromStatus, getCCRStatus } from '../lib/ccr.js';
import { isCCREnabled } from '../lib/global-settings-accessor.js';

const logger = createLogger('ClaudeProvider');
import {
Expand Down Expand Up @@ -70,22 +72,61 @@ function isClaudeCompatibleProvider(config: ProviderConfig): config is ClaudeCom

/**
* Build environment for the SDK with only explicitly allowed variables.
* When CCR is enabled, uses CCR's configuration for routing.
* When a provider/profile is provided, uses its configuration (clean switch - don't inherit from process.env).
* When no provider is provided, uses direct Anthropic API settings from process.env.
*
* Supports both:
* - ClaudeCompatibleProvider (new system with models[] array)
* - ClaudeApiProfile (legacy system with modelMappings)
* Priority order:
* 1. CCR enabled - routes through Claude Code Router proxy
* 2. ClaudeCompatibleProvider (new system with models[] array)
* 3. ClaudeApiProfile (legacy system with modelMappings)
* 4. Direct Anthropic API
*
* @param providerConfig - Optional provider configuration for alternative endpoint
* @param credentials - Optional credentials object for resolving 'credentials' apiKeySource
* @param ccrEnabledOverride - Explicit CCR setting (if undefined, auto-resolves from global settings)
*/
function buildEnv(
async function buildEnv(
providerConfig?: ProviderConfig,
credentials?: Credentials
): Record<string, string | undefined> {
credentials?: Credentials,
ccrEnabledOverride?: boolean
): Promise<Record<string, string | undefined>> {
const env: Record<string, string | undefined> = {};

// Auto-resolve CCR setting if not explicitly provided
// This allows providers to work without callers needing to pass ccrEnabled
const ccrEnabled = ccrEnabledOverride ?? (await isCCREnabled());

// Priority 1: CCR enabled - use Claude Code Router for API routing
if (ccrEnabled) {
const status = await getCCRStatus();
if (status.installed && status.running) {
const ccrEnv = getCCREnvFromStatus(status);
if (ccrEnv) {
logger.debug('[buildEnv] Using Claude Code Router (CCR) for API routing', {
baseUrl: ccrEnv.ANTHROPIC_BASE_URL,
});
// Apply CCR environment variables
Object.assign(env, ccrEnv);
// Always add system vars from process.env
for (const key of SYSTEM_ENV_VARS) {
if (process.env[key]) {
env[key] = process.env[key];
}
}
return env;
}
} else {
logger.warn('[buildEnv] CCR enabled but not available', {
installed: status.installed,
running: status.running,
error: status.error,
});
// Fall through to other methods if CCR is not available
}
}

// Priority 2/3: Provider configuration
if (providerConfig) {
// Use provider configuration (clean switch - don't inherit non-system vars from process.env)
logger.debug('[buildEnv] Using provider configuration:', {
Expand Down Expand Up @@ -213,6 +254,7 @@ export class ClaudeProvider extends BaseProvider {
claudeApiProfile,
claudeCompatibleProvider,
credentials,
ccrEnabled,
} = options;

// Determine which provider config to use
Expand All @@ -229,9 +271,8 @@ export class ClaudeProvider extends BaseProvider {
maxTurns,
cwd,
// Pass only explicitly allowed environment variables to SDK
// When a provider is active, uses provider settings (clean switch)
// When no provider, uses direct Anthropic API (from process.env or CLI OAuth)
env: buildEnv(providerConfig, credentials),
// Priority: CCR (if enabled) > provider config > direct Anthropic API
env: await buildEnv(providerConfig, credentials, ccrEnabled),
// Pass through allowedTools if provided by caller (decided by sdk-options.ts)
...(allowedTools && { allowedTools }),
// AUTONOMOUS MODE: Always bypass permissions for fully autonomous operation
Expand Down Expand Up @@ -284,6 +325,7 @@ export class ClaudeProvider extends BaseProvider {
hasApiKey: !!envForSdk?.['ANTHROPIC_API_KEY'],
hasAuthToken: !!envForSdk?.['ANTHROPIC_AUTH_TOKEN'],
providerName: providerConfig?.name || '(direct Anthropic)',
ccrEnabled: !!ccrEnabled,
maxTurns: sdkOptions.maxTurns,
maxThinkingTokens: sdkOptions.maxThinkingTokens,
});
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/routes/settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { createUpdateProjectHandler } from './routes/update-project.js';
import { createMigrateHandler } from './routes/migrate.js';
import { createStatusHandler } from './routes/status.js';
import { createDiscoverAgentsHandler } from './routes/discover-agents.js';
import { createGetCCRStatusHandler } from './routes/get-ccr-status.js';

/**
* Create settings router with all endpoints
Expand Down Expand Up @@ -77,5 +78,8 @@ export function createSettingsRoutes(settingsService: SettingsService): Router {
// Filesystem agents discovery (read-only)
router.post('/agents/discover', createDiscoverAgentsHandler());

// CCR (Claude Code Router) status
router.get('/ccr/status', createGetCCRStatusHandler());

return router;
}
Loading