-
Notifications
You must be signed in to change notification settings - Fork 563
feat(claude): add Claude Code Router (CCR) integration #750
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (isRunning) { | ||
| status = { | ||
| installed: true, | ||
| running: true, | ||
| port, | ||
| apiEndpoint: `http://${host}:${port}`, | ||
| }; | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } 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; | ||
| } | ||
wcpaxx marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| /** | ||
| * 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, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.