diff --git a/docs/code-standards.md b/docs/code-standards.md new file mode 100644 index 00000000..14059628 --- /dev/null +++ b/docs/code-standards.md @@ -0,0 +1,503 @@ +# CCS Code Standards + +Last Updated: 2025-12-19 + +Code standards, modularization patterns, and conventions for the CCS codebase. + +--- + +## Core Principles + +### YAGNI (You Aren't Gonna Need It) +- No features "just in case" +- Only implement what is currently needed +- Delete unused code rather than commenting it out + +### KISS (Keep It Simple, Stupid) +- Prefer simple solutions over clever ones +- Reduce complexity at every opportunity +- Use established patterns over custom implementations + +### DRY (Don't Repeat Yourself) +- One source of truth for configuration +- Extract common logic into shared utilities +- Use barrel exports to centralize imports + +--- + +## File Organization + +### Directory Structure Rules + +1. **Domain-based organization**: Group files by business domain, not by file type +2. **Barrel exports required**: Every directory must have an `index.ts` aggregating exports +3. **Flat within depth**: Keep nesting to 3 levels maximum +4. **Co-location**: Keep related files together (component + hooks + utils) + +### File Naming Conventions + +| Convention | Example | When to Use | +|------------|---------|-------------| +| kebab-case | `cliproxy-executor.ts` | All TypeScript/TSX files | +| kebab-case | `profile-detector.ts` | Multi-word file names | +| PascalCase | `BinaryManager` | Class exports only | +| camelCase | `detectProfile` | Function exports | + +**File names should be descriptive**: LLMs should understand the file's purpose from its name alone without reading content. + +### Correct Examples + +``` +src/cliproxy/binary-manager.ts # Binary management logic +src/commands/doctor-command.ts # Doctor CLI command handler +ui/src/components/cliproxy/provider-editor/index.tsx +``` + +### Incorrect Examples + +``` +src/utils/helper.ts # Too vague +src/cliproxy/manager.ts # Which manager? +ui/src/components/Editor.tsx # Not kebab-case +``` + +--- + +## File Size Limit: 200 Lines + +**Target**: All code files should be under 200 lines. + +**Exceptions** (with justification): +- Data files (model-pricing.ts, model-catalog.ts) +- Entry points with routing logic (ccs.ts) +- Complex transformation logic that cannot be meaningfully split + +### Why 200 Lines? + +1. **Context efficiency**: LLMs process smaller files faster +2. **Single responsibility**: Forces focused, testable modules +3. **Navigation**: Easier to scan and understand +4. **Maintainability**: Reduces merge conflicts + +### When Files Exceed 200 Lines + +If a file grows beyond 200 lines: + +1. **Identify extraction candidates**: + - Helper functions that could be utilities + - Constants and type definitions + - Subcomponents within React components + - Related logic that forms a cohesive unit + +2. **Create subdirectory structure**: + ``` + # Before + provider-editor.tsx (921 lines) + + # After + provider-editor/ + ├── index.tsx # Main component (200 lines) + ├── model-mapping-form.tsx + ├── endpoint-config.tsx + ├── auth-section.tsx + ├── hooks.ts + ├── types.ts + └── utils.ts + ``` + +3. **Preserve public API**: Main export remains the same through barrel export + +--- + +## Barrel Export Pattern + +### What is a Barrel Export? + +An `index.ts` file that aggregates and re-exports module contents: + +```typescript +// src/cliproxy/index.ts + +// Types (with explicit type keyword) +export type { PlatformInfo, BinaryInfo } from './types'; + +// Functions +export { detectPlatform } from './platform-detector'; +export { BinaryManager } from './binary-manager'; + +// From subdirectories +export * from './auth'; +export * from './services'; +``` + +### Rules for Barrel Exports + +1. **Every domain directory must have `index.ts`** +2. **Export types with `export type`** for tree-shaking +3. **Re-export subdirectories** for deep access +4. **Keep barrel exports flat** - no logic, only exports + +### Import Patterns + +```typescript +// CORRECT: Import from domain barrel +import { execClaudeWithCLIProxy, CLIProxyProvider } from '../cliproxy'; +import { Config, Settings } from '../types'; + +// INCORRECT: Import from specific file (bypasses barrel) +import { execClaudeWithCLIProxy } from '../cliproxy/cliproxy-executor'; +``` + +### Exception: Deep Imports + +Allowed when: +- Importing private utilities not exposed in barrel +- Circular dependency avoidance +- Performance-critical tree-shaking + +--- + +## Monster File Splitting Methodology + +When splitting large files (500+ lines), follow this process: + +### Step 1: Analyze Structure + +Identify logical boundaries: +- Render sections in React components +- Handler groups in route files +- Related utility functions +- Constants and types + +### Step 2: Extract Types First + +```typescript +// types.ts +export interface ProviderEditorProps { + providerId: string; + onSave: (config: ProviderConfig) => void; +} + +export interface ModelMappingValues { + model: string; + endpoint: string; +} +``` + +### Step 3: Extract Utilities + +```typescript +// utils.ts +export function validateEndpoint(url: string): boolean { ... } +export function formatModelName(name: string): string { ... } +``` + +### Step 4: Extract Hooks + +```typescript +// hooks.ts +export function useProviderConfig(providerId: string) { ... } +export function useModelValidation() { ... } +``` + +### Step 5: Extract Subcomponents + +```typescript +// model-mapping-form.tsx +export function ModelMappingForm({ values, onChange }: Props) { ... } +``` + +### Step 6: Compose in Index + +```typescript +// index.tsx +import { ModelMappingForm } from './model-mapping-form'; +import { useProviderConfig } from './hooks'; +import type { ProviderEditorProps } from './types'; + +export function ProviderEditor({ providerId, onSave }: ProviderEditorProps) { + const config = useProviderConfig(providerId); + return ( +
+ +
+ ); +} + +// Re-export types for consumers +export type { ProviderEditorProps, ModelMappingValues } from './types'; +``` + +--- + +## TypeScript Standards + +### Strict Mode Required + +All projects use TypeScript strict mode: + +```json +{ + "compilerOptions": { + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true + } +} +``` + +### Type Annotations + +```typescript +// CORRECT: Explicit return types for public functions +export function detectProfile(args: string[]): DetectedProfile { ... } + +// CORRECT: Inferred types for internal functions +const formatName = (name: string) => name.trim().toLowerCase(); + +// INCORRECT: any type +function processData(data: any) { ... } // Use unknown or proper type +``` + +### Type Exports + +```typescript +// CORRECT: Use type keyword for type-only exports +export type { Config, Settings } from './config'; + +// CORRECT: Group type exports in barrel +export type { + PlatformInfo, + BinaryInfo, + DownloadProgress, +} from './types'; +``` + +--- + +## ESLint Rules (Enforced) + +| Rule | Level | Notes | +|------|-------|-------| +| `@typescript-eslint/no-unused-vars` | error | Ignore `_` prefix | +| `@typescript-eslint/no-explicit-any` | error | Use proper types | +| `@typescript-eslint/no-non-null-assertion` | error | No `!` assertions | +| `prefer-const` | error | Immutable by default | +| `no-var` | error | Use const/let | +| `eqeqeq` | error | Strict equality | +| `react-hooks/*` | recommended | (UI only) | + +--- + +## Terminal Output Standards + +### ASCII Only + +```typescript +// CORRECT +console.log('[OK] Operation successful'); +console.log('[!] Warning message'); +console.log('[X] Error occurred'); +console.log('[i] Information'); + +// INCORRECT - NO EMOJIS +console.log('Operation successful'); // NO +console.log('Warning message'); // NO +``` + +### Color Handling + +```typescript +import { colors } from '../utils/ui'; + +// Colors are TTY-aware and respect NO_COLOR +console.log(colors.green('[OK]') + ' Operation successful'); +``` + +### Box Borders + +Use ASCII box drawing for error displays: + +``` ++=====================================+ +| [X] ERROR: Configuration failed | +| | +| Details: Unable to parse config | ++=====================================+ +``` + +--- + +## React Component Standards (UI) + +### Component Structure + +```typescript +// component-name.tsx + +// 1. Imports (grouped: react, external, internal, relative) +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { useProfiles } from '@/hooks'; +import { formatName } from './utils'; +import type { ComponentProps } from './types'; + +// 2. Types (if not in separate file) +interface Props { + id: string; + onSave: () => void; +} + +// 3. Component +export function ComponentName({ id, onSave }: Props) { + // Hooks first + const profiles = useProfiles(); + const [state, setState] = useState(null); + + // Handlers + const handleClick = () => { ... }; + + // Render + return ( ... ); +} +``` + +### Naming Conventions + +| Item | Convention | Example | +|------|------------|---------| +| Component files | kebab-case.tsx | `provider-editor.tsx` | +| Component exports | PascalCase | `ProviderEditor` | +| Hook files | use-*.ts | `use-profiles.ts` | +| Hook exports | useCamelCase | `useProfiles` | +| Utility files | kebab-case.ts | `path-utils.ts` | +| Utility exports | camelCase | `formatPath` | + +--- + +## Quality Gates + +### Pre-Commit Sequence + +```bash +# Main project +bun run format +bun run lint:fix +bun run validate + +# UI project (if changed) +cd ui +bun run format +bun run lint:fix +bun run validate +``` + +### Validate Runs + +| Project | Command | Checks | +|---------|---------|--------| +| Main | `bun run validate` | typecheck + lint + format:check + test | +| UI | `bun run validate` | typecheck + lint + format:check | + +--- + +## Conventional Commits + +All commits must follow conventional commit format: + +``` +(): +``` + +### Types + +| Type | When to Use | Version Bump | +|------|-------------|--------------| +| `feat` | New feature | MINOR | +| `fix` | Bug fix | PATCH | +| `perf` | Performance | PATCH | +| `docs` | Documentation | None | +| `style` | Formatting | None | +| `refactor` | Code restructure | None | +| `test` | Tests | None | +| `chore` | Maintenance | None | + +### Examples + +```bash +# Correct +git commit -m "feat(cliproxy): add OAuth token refresh" +git commit -m "fix(doctor): handle missing config gracefully" +git commit -m "refactor(ui): split provider-editor into modules" + +# Incorrect - REJECTED +git commit -m "added new feature" +git commit -m "Fixed bug" +``` + +--- + +## Anti-Patterns to Avoid + +### 1. God Files + +```typescript +// BAD: One file doing everything +// src/utils.ts (2000 lines with mixed concerns) + +// GOOD: Split by domain +// src/utils/ui/colors.ts +// src/utils/ui/boxes.ts +// src/utils/shell-executor.ts +// src/utils/config-manager.ts +``` + +### 2. Barrel Import Bypass + +```typescript +// BAD: Direct import bypassing barrel +import { detectPlatform } from '../cliproxy/platform-detector'; + +// GOOD: Import from domain barrel +import { detectPlatform } from '../cliproxy'; +``` + +### 3. Inline Everything + +```typescript +// BAD: Huge inline functions in components +function Component() { + const handleComplexOperation = () => { + // 100 lines of logic... + }; +} + +// GOOD: Extract to hooks or utilities +function Component() { + const { handleComplexOperation } = useComplexOperation(); +} +``` + +### 4. Type Duplication + +```typescript +// BAD: Same types defined in multiple files +// file1.ts +interface Config { ... } +// file2.ts +interface Config { ... } + +// GOOD: Single source of truth +// types/config.ts +export interface Config { ... } +``` + +--- + +## Related Documentation + +- [Codebase Summary](./codebase-summary.md) - Full directory structure +- [System Architecture](./system-architecture.md) - Architecture diagrams +- [CLAUDE.md](../CLAUDE.md) - AI-facing development guidance diff --git a/docs/codebase-summary.md b/docs/codebase-summary.md new file mode 100644 index 00000000..8f418863 --- /dev/null +++ b/docs/codebase-summary.md @@ -0,0 +1,410 @@ +# CCS Codebase Summary + +Last Updated: 2025-12-19 + +Comprehensive overview of the modularized CCS codebase structure following the Phase 5 modularization effort. + +## Repository Structure + +``` +ccs/ +├── src/ # CLI TypeScript source +├── dist/ # Compiled JavaScript (npm package) +├── lib/ # Native shell scripts (bash, PowerShell) +├── ui/ # React dashboard application +│ ├── src/ # UI source code +│ └── dist/ # Built UI bundle +├── tests/ # Test suites +├── docs/ # Documentation +└── assets/ # Static assets (logos, screenshots) +``` + +--- + +## CLI Source (`src/`) + +The main CLI is organized into domain-specific modules with barrel exports. + +### Directory Structure + +``` +src/ +├── ccs.ts # Main entry point & CLI router +├── types/ # TypeScript type definitions +│ ├── index.ts # Barrel export (aggregates all types) +│ ├── cli.ts # CLI types (ParsedArgs, ExitCode) +│ ├── config.ts # Config types (Settings, EnvVars) +│ ├── delegation.ts # Delegation types (sessions, events) +│ ├── glmt.ts # GLMT types (messages, transforms) +│ └── utils.ts # Utility types (ErrorCode, LogLevel) +│ +├── commands/ # CLI command handlers +│ ├── cliproxy-command.ts # CLIProxy subcommand handling +│ ├── doctor-command.ts # Health diagnostics +│ ├── help-command.ts # Help text generation +│ ├── install-command.ts # Install/uninstall logic +│ ├── shell-completion-command.ts +│ ├── sync-command.ts # Symlink synchronization +│ ├── update-command.ts # Self-update logic +│ └── version-command.ts # Version display +│ +├── auth/ # Authentication module +│ ├── index.ts # Barrel export +│ ├── commands/ # Auth-specific CLI commands +│ │ └── index.ts +│ ├── account-switcher.ts # Account switching logic +│ └── profile-detector.ts # Profile detection (474 lines) +│ +├── config/ # Configuration management +│ ├── index.ts # Barrel export +│ ├── unified-config-loader.ts # Central config loader (546 lines) +│ └── migration-manager.ts # Config migration logic +│ +├── cliproxy/ # CLIProxyAPI integration (heavily modularized) +│ ├── index.ts # Barrel export (137 lines, extensive) +│ ├── auth/ # OAuth handlers, token management +│ │ └── index.ts +│ ├── binary/ # Binary management +│ │ └── index.ts +│ ├── services/ # Service layer +│ │ └── index.ts +│ ├── cliproxy-executor.ts # Main executor (666 lines) +│ ├── config-generator.ts # Config file generation (531 lines) +│ ├── account-manager.ts # Account management (509 lines) +│ ├── platform-detector.ts # OS/arch detection +│ ├── binary-manager.ts # Binary download/update +│ ├── auth-handler.ts # Authentication handling +│ ├── model-catalog.ts # Provider model definitions +│ ├── model-config.ts # Model configuration +│ ├── service-manager.ts # Background service +│ ├── proxy-detector.ts # Running proxy detection +│ ├── startup-lock.ts # Race condition prevention +│ └── [more files...] +│ +├── copilot/ # GitHub Copilot integration +│ ├── index.ts # Barrel export +│ └── copilot-package-manager.ts # Package management (515 lines) +│ +├── glmt/ # GLM/GLMT integration +│ ├── index.ts # Barrel export +│ ├── pipeline/ # Processing pipeline +│ │ └── index.ts +│ ├── glmt-proxy.ts # Main proxy (675 lines) +│ └── delta-accumulator.ts # Delta processing (484 lines) +│ +├── delegation/ # Task delegation & headless execution +│ ├── index.ts # Barrel export +│ ├── executor/ # Execution engine +│ └── [delegation files...] +│ +├── errors/ # Centralized error handling +│ ├── index.ts # Barrel export +│ ├── error-handler.ts # Main error handler +│ ├── exit-codes.ts # Exit code definitions +│ └── cleanup.ts # Cleanup logic +│ +├── management/ # Doctor diagnostics +│ ├── index.ts # Barrel export +│ ├── checks/ # Diagnostic checks +│ │ └── index.ts +│ └── repair/ # Auto-repair logic +│ └── index.ts +│ +├── api/ # API utilities & services +│ ├── index.ts # Barrel export +│ └── services/ # API services +│ ├── index.ts +│ ├── profile-reader.ts +│ └── profile-writer.ts +│ +├── utils/ # Utilities (modularized into subdirs) +│ ├── index.ts # Barrel export +│ ├── ui/ # Terminal UI utilities +│ │ ├── index.ts +│ │ ├── boxes.ts # Box drawing +│ │ ├── colors.ts # Terminal colors +│ │ └── spinners.ts # Progress spinners +│ ├── websearch/ # Search tool integrations +│ │ └── index.ts +│ └── [utility files...] +│ +└── web-server/ # Express web server (heavily modularized) + ├── index.ts # Server entry & barrel export + ├── routes/ # 15+ route handlers + │ ├── index.ts + │ ├── accounts-route.ts + │ ├── auth-route.ts + │ ├── cliproxy-route.ts + │ ├── copilot-route.ts + │ ├── doctor-route.ts + │ ├── glmt-route.ts + │ ├── health-route.ts + │ ├── profiles-route.ts + │ └── [more routes...] + ├── health/ # Health check system + │ └── index.ts + ├── usage/ # Usage analytics module + │ ├── index.ts + │ ├── handlers.ts # Request handlers (633 lines) + │ ├── aggregator.ts # Data aggregation (538 lines) + │ └── data-aggregator.ts + ├── services/ # Shared services + │ └── index.ts + └── model-pricing.ts # Model cost definitions (676 lines) +``` + +### Module Categories + +| Category | Directories | Purpose | +|----------|-------------|---------| +| Core | `commands/`, `errors/` | CLI commands, error handling | +| Auth | `auth/`, `cliproxy/auth/` | Authentication across providers | +| Config | `config/`, `types/` | Configuration & type definitions | +| Providers | `cliproxy/`, `copilot/`, `glmt/` | Provider integrations | +| Services | `web-server/`, `api/` | HTTP server, API services | +| Utilities | `utils/`, `management/` | Helpers, diagnostics | + +--- + +## UI Source (`ui/src/`) + +The React dashboard organized by domain with barrel exports at every level. + +### Directory Structure + +``` +ui/src/ +├── components/ +│ ├── index.ts # Main barrel (aggregates all domains) +│ │ +│ ├── account/ # Account management +│ │ ├── index.ts # Barrel export +│ │ ├── accounts-table.tsx +│ │ ├── add-account-dialog.tsx +│ │ └── flow-viz/ # Flow visualization (split from 1,144-line file) +│ │ ├── index.tsx # Main component (200 lines) +│ │ ├── account-card.tsx +│ │ ├── account-card-stats.tsx +│ │ ├── connection-timeline.tsx +│ │ ├── flow-paths.tsx +│ │ ├── flow-viz-header.tsx +│ │ ├── provider-card.tsx +│ │ ├── hooks.ts +│ │ ├── types.ts +│ │ ├── utils.ts +│ │ ├── path-utils.ts +│ │ └── zone-utils.ts +│ │ +│ ├── analytics/ # Usage charts, stats cards +│ │ ├── index.ts +│ │ ├── cliproxy-stats-card.tsx +│ │ └── usage-trend-chart.tsx +│ │ +│ ├── cliproxy/ # CLIProxy configuration +│ │ ├── index.ts # Barrel export (30 lines) +│ │ ├── provider-editor/ # Split from 921-line file +│ │ │ ├── index.tsx # Main editor (250 lines) +│ │ │ └── [13 focused modules] +│ │ ├── config/ # YAML editor, file tree +│ │ │ ├── config-split-view.tsx +│ │ │ ├── diff-dialog.tsx +│ │ │ ├── file-tree.tsx +│ │ │ └── yaml-editor.tsx +│ │ ├── overview/ # Health lists, preferences +│ │ │ ├── credential-health-list.tsx +│ │ │ ├── model-preferences-grid.tsx +│ │ │ └── quick-stats-row.tsx +│ │ └── [7 top-level component files] +│ │ +│ ├── copilot/ # Copilot settings +│ │ ├── index.ts +│ │ └── config-form/ # Split from 846-line file +│ │ └── [13 focused modules] +│ │ +│ ├── health/ # System health gauges +│ │ └── index.ts +│ │ +│ ├── layout/ # App structure +│ │ ├── index.ts +│ │ ├── sidebar.tsx +│ │ └── footer.tsx +│ │ +│ ├── monitoring/ # Error logs, auth monitor +│ │ ├── index.ts +│ │ ├── auth-monitor.tsx # Auth monitoring (465 lines) +│ │ └── error-logs/ # Split from 617-line file +│ │ └── [6 focused modules] +│ │ +│ ├── profiles/ # Profile management +│ │ ├── index.ts +│ │ ├── profile-dialog.tsx +│ │ ├── profile-create-dialog.tsx +│ │ └── editor/ # Split from 531-line file +│ │ └── [10 focused modules] +│ │ +│ ├── setup/ # Quick setup wizard +│ │ ├── index.ts +│ │ └── wizard/ # Step-based wizard +│ │ ├── index.tsx +│ │ └── steps/ +│ │ +│ ├── shared/ # Reusable components (19 components) +│ │ ├── index.ts +│ │ ├── ccs-logo.tsx +│ │ ├── code-editor.tsx +│ │ ├── confirm-dialog.tsx +│ │ ├── provider-icon.tsx +│ │ ├── settings-dialog.tsx +│ │ ├── stat-card.tsx +│ │ └── [13 more shared components] +│ │ +│ └── ui/ # shadcn/ui primitives +│ ├── button.tsx +│ ├── card.tsx +│ ├── dialog.tsx +│ ├── sidebar.tsx # Custom sidebar (674 lines) +│ └── [UI primitives...] +│ +├── contexts/ # React Contexts +│ ├── privacy-context.tsx +│ ├── theme-context.tsx +│ └── websocket-context.tsx +│ +├── hooks/ # Custom hooks (domain-prefixed) +│ ├── use-accounts.ts +│ ├── use-cliproxy.ts +│ ├── use-health.ts +│ ├── use-profiles.ts +│ ├── use-websocket.ts +│ └── [more hooks...] +│ +├── lib/ # Utilities +│ ├── api.ts # API client +│ ├── model-catalogs.ts # Model definitions +│ └── utils.ts # Helper functions +│ +├── pages/ # Page components (lazy-loaded) +│ ├── analytics.tsx # Analytics dashboard (420 lines) +│ ├── api.tsx # API profiles page (350 lines) +│ ├── cliproxy.tsx # CLIProxy page (405 lines) +│ ├── copilot.tsx # Copilot page (295 lines) +│ ├── health.tsx # Health page (256 lines) +│ └── settings.tsx # Settings page (1,710 lines - TODO: split) +│ +└── providers/ # Context providers + └── websocket-provider.tsx +``` + +### Component Statistics + +| Domain | Components | Subdirs | Split Files | +|--------|------------|---------|-------------| +| account | 3 | flow-viz (12 files) | 1 monster split | +| analytics | 3 | - | - | +| cliproxy | 10 | provider-editor, config, overview | 1 monster split | +| copilot | 2 | config-form (13 files) | 1 monster split | +| health | 2 | - | - | +| layout | 3 | - | - | +| monitoring | 3 | error-logs (6 files) | 1 monster split | +| profiles | 4 | editor (10 files) | 1 monster split | +| setup | 2 | wizard/steps | - | +| shared | 19 | - | - | +| **Total** | **51+** | **8 subdirs** | **5 splits** | + +--- + +## Key File Metrics + +### Largest Files (Targets for Future Splitting) + +**CLI (`src/`):** + +| File | Lines | Status | +|------|-------|--------| +| model-pricing.ts | 676 | Data file - acceptable | +| glmt-proxy.ts | 675 | Complex - monitor | +| cliproxy-executor.ts | 666 | Core logic - acceptable | +| cliproxy-command.ts | 634 | Could split | +| usage/handlers.ts | 633 | Could split | +| ccs.ts | 596 | Entry point - acceptable | +| unified-config-loader.ts | 546 | Complex - acceptable | + +**UI (`ui/src/`):** + +| File | Lines | Status | +|------|-------|--------| +| pages/settings.tsx | 1,710 | **TODO: SPLIT** | +| components/ui/sidebar.tsx | 674 | shadcn - acceptable | +| monitoring/auth-monitor.tsx | 465 | Could split | +| pages/analytics.tsx | 420 | Could split | +| pages/cliproxy.tsx | 405 | Acceptable | + +--- + +## Import Patterns + +### Standard Import Path + +```typescript +// From any file in src/ +import { Config, Settings } from '../types'; +import { execClaudeWithCLIProxy } from '../cliproxy'; +import { handleError } from '../errors'; + +// From any file in ui/src/ +import { AccountsTable, ProviderIcon, StatCard } from '@/components'; +import { useAccounts, useProfiles } from '@/hooks'; +``` + +### Barrel Export Pattern + +Every domain directory has an `index.ts` that aggregates exports: + +```typescript +// ui/src/components/cliproxy/index.ts +export { CategorizedModelSelector } from './categorized-model-selector'; +export { CliproxyDialog } from './cliproxy-dialog'; +// ... + +// From subdirectories +export { ProviderEditor } from './provider-editor'; +export type { ProviderEditorProps } from './provider-editor'; +``` + +--- + +## Test Structure + +``` +tests/ +├── unit/ # Unit tests +│ ├── auth/ +│ ├── cliproxy/ +│ ├── config/ +│ └── utils/ +├── native/ # Native install tests +│ ├── linux/ +│ ├── macos/ +│ └── windows/ +└── npm/ # npm package tests +``` + +--- + +## Build Outputs + +| Output | Source | Purpose | +|--------|--------|---------| +| `dist/` | `src/` | npm package (CLI) | +| `dist/ui/` | `ui/src/` | Built React app (served by Express) | +| `lib/` | N/A | Native shell scripts | + +--- + +## Related Documentation + +- [Code Standards](./code-standards.md) - Modularization patterns, file size rules +- [System Architecture](./system-architecture.md) - High-level architecture diagrams +- [Project Roadmap](./project-roadmap.md) - Modularization phases and future work +- [WebSearch](./websearch.md) - WebSearch feature documentation +- [CLAUDE.md](../CLAUDE.md) - AI-facing development guidance diff --git a/docs/project-overview-pdr.md b/docs/project-overview-pdr.md new file mode 100644 index 00000000..09549804 --- /dev/null +++ b/docs/project-overview-pdr.md @@ -0,0 +1,225 @@ +# CCS Product Development Requirements (PDR) + +Last Updated: 2025-12-19 + +## Product Overview + +**Product Name**: CCS (Claude Code Switch) + +**Tagline**: The universal AI profile manager for Claude Code + +**Description**: CLI wrapper enabling seamless switching between multiple Claude accounts and alternative AI providers (GLM, Gemini, Codex) with a React-based dashboard for configuration management. + +--- + +## Problem Statement + +Developers using Claude Code face these challenges: + +1. **Single Account Limitation**: Cannot run multiple Claude subscriptions simultaneously +2. **Provider Lock-in**: Stuck with Anthropic's API, cannot use alternatives +3. **No Concurrent Sessions**: Cannot work on different projects with different accounts +4. **Complex Configuration**: Manual env var and config file management + +--- + +## Solution + +CCS provides: + +1. **Multi-Account Claude**: Isolated instances via `CLAUDE_CONFIG_DIR` +2. **OAuth Providers**: Zero-config Gemini, Codex, Antigravity integration +3. **API Profiles**: GLM, Kimi, any Anthropic-compatible API +4. **Visual Dashboard**: React SPA for configuration management +5. **Automatic WebSearch**: MCP fallback for third-party providers + +--- + +## Target Users + +| User Type | Use Case | Primary Features | +|-----------|----------|------------------| +| Individual Developer | Work/personal separation | Multi-account Claude | +| Agency/Contractor | Client account isolation | Profile switching | +| Cost-conscious Dev | GLM for bulk operations | API profiles | +| Enterprise | Custom LLM integration | OpenAI-compatible endpoints | + +--- + +## Functional Requirements + +### FR-001: Profile Switching +- Switch between profiles with `ccs ` command +- Support default profile when no argument provided +- Pass through all Claude CLI arguments + +### FR-002: Multi-Account Claude +- Create isolated Claude instances +- Maintain separate sessions, todolists, logs per account +- Share commands, skills, agents across accounts + +### FR-003: OAuth Provider Integration +- Support Gemini, Codex, Antigravity OAuth flows +- Browser-based authentication +- Token caching and refresh + +### FR-004: API Profile Management +- Configure custom API endpoints +- Support Anthropic-compatible APIs +- Model mapping and configuration + +### FR-005: Dashboard UI +- Visual profile management +- Real-time health monitoring +- Usage analytics + +### FR-006: Health Diagnostics +- Verify Claude CLI installation +- Check config file integrity +- Validate symlinks and permissions + +### FR-007: WebSearch Fallback +- Auto-configure MCP web search for third-party profiles +- Support Gemini CLI, Brave, Tavily providers +- Graceful fallback chain + +--- + +## Non-Functional Requirements + +### NFR-001: Performance +- CLI startup < 100ms +- Dashboard load < 2s +- Minimal memory footprint + +### NFR-002: Reliability +- Idempotent operations +- Graceful error handling +- Automatic recovery where possible + +### NFR-003: Security +- Local-only proxy binding (127.0.0.1) +- No credential exposure in logs +- Secure token storage + +### NFR-004: Cross-Platform +- Support Linux, macOS, Windows +- Bash 3.2+, PowerShell 5.1+, Node.js 14+ +- Identical behavior across platforms + +### NFR-005: Maintainability +- Files < 200 lines +- Domain-based organization +- Barrel exports for clean imports + +--- + +## Technical Requirements + +### TR-001: Runtime Dependencies +- Node.js 14+ or Bun 1.0+ +- Claude Code CLI installed +- Internet access for OAuth/API calls + +### TR-002: Optional Dependencies +- CLIProxyAPI binary (auto-managed) +- Gemini CLI for WebSearch +- Additional MCP servers + +### TR-003: Configuration +- YAML-based config (`~/.ccs/config.yaml`) +- JSON settings per profile +- Environment variable overrides + +--- + +## Architecture Constraints + +### AC-001: CLI-First Design +- All features accessible via CLI +- Dashboard is convenience layer, not required +- Scriptable and automatable + +### AC-002: Non-Invasive +- Never modify `~/.claude/settings.json` +- Use environment variables for configuration +- Reversible changes only + +### AC-003: Proxy Pattern +- Use local proxy for provider routing +- Claude CLI communicates with localhost +- Proxy handles upstream API calls + +--- + +## Success Metrics + +| Metric | Target | Current | +|--------|--------|---------| +| Startup time | < 100ms | TBD | +| Dashboard load | < 2s | TBD | +| Error rate | < 1% | TBD | +| Test coverage | > 80% | TBD | +| File size compliance | 100% < 200 lines | 85% | + +--- + +## Release Criteria + +### v1.0 Release (Current) +- [x] Multi-account Claude support +- [x] OAuth provider integration (Gemini, Codex, AGY) +- [x] API profile management +- [x] Dashboard UI +- [x] Health diagnostics +- [x] WebSearch fallback +- [x] Cross-platform support + +### v1.1 Release (Planned) +- [ ] Settings page modularization +- [ ] Enhanced analytics +- [ ] Profile templates +- [ ] Improved error messages + +### v2.0 Release (Future) +- [ ] Team collaboration features +- [ ] Cloud sync for profiles +- [ ] Plugin system +- [ ] CLI extension framework + +--- + +## Dependencies + +### External Services +- Anthropic Claude API +- Google Gemini API +- GitHub Codex API +- Z.AI GLM API + +### Third-Party Libraries +- Express.js (web server) +- React (dashboard) +- Vite (build tool) +- shadcn/ui (UI components) +- CLIProxyAPI (proxy binary) + +--- + +## Risks and Mitigations + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| Claude CLI API changes | Medium | High | Version pinning, compatibility layer | +| Provider API deprecation | Low | High | Fallback chain, multiple providers | +| OAuth token expiry | Medium | Medium | Auto-refresh, clear error messages | +| Binary compatibility | Low | Medium | Multi-platform builds, fallback | + +--- + +## Related Documentation + +- [Codebase Summary](./codebase-summary.md) - Technical structure +- [Code Standards](./code-standards.md) - Development conventions +- [System Architecture](./system-architecture.md) - Architecture diagrams +- [Project Roadmap](./project-roadmap.md) - Development phases diff --git a/docs/project-roadmap.md b/docs/project-roadmap.md new file mode 100644 index 00000000..06801f66 --- /dev/null +++ b/docs/project-roadmap.md @@ -0,0 +1,279 @@ +# CCS Project Roadmap + +Last Updated: 2025-12-19 + +Development roadmap documenting completed modularization phases and future work. + +--- + +## Completed Phases + +### Phase 1: Type System Modularization + +**Status**: COMPLETE + +Extracted TypeScript types into dedicated `types/` directory with barrel exports. + +**Changes**: +- Created `src/types/` directory structure +- Extracted types from inline definitions into dedicated files: + - `config.ts` - Config, Settings, EnvVars + - `cli.ts` - ParsedArgs, ExitCode, ClaudeCliInfo + - `delegation.ts` - Session, execution types + - `glmt.ts` - Message transformation types + - `utils.ts` - ErrorCode, LogLevel, Result +- Created `index.ts` barrel export aggregating all types + +**Impact**: +- Centralized type definitions +- Cleaner imports across codebase +- Easier type maintenance + +--- + +### Phase 2: CLI Command Extraction + +**Status**: COMPLETE + +Extracted CLI command handlers from main `ccs.ts` into dedicated `commands/` directory. + +**Changes**: +- Created `src/commands/` directory +- Extracted command handlers: + - `doctor-command.ts` - Health diagnostics + - `help-command.ts` - Help text generation + - `install-command.ts` - Install/uninstall logic + - `shell-completion-command.ts` - Shell completions + - `sync-command.ts` - Symlink synchronization + - `update-command.ts` - Self-update logic + - `version-command.ts` - Version display + - `cliproxy-command.ts` - CLIProxy subcommands (634 lines) + +**Impact**: +- Reduced `ccs.ts` from ~1200 lines to 596 lines +- Isolated command logic for easier testing +- Clear separation of concerns + +--- + +### Phase 3: CLIProxy Modularization + +**Status**: COMPLETE + +Heavily modularized the CLIProxy integration module with internal subdirectories. + +**Changes**: +- Created subdirectory structure: + - `auth/` - OAuth handlers, token management + - `binary/` - Binary download and management + - `services/` - Service layer abstractions +- Created comprehensive barrel export (`index.ts` - 137 lines) +- Maintained backward compatibility for all exports + +**Key Files**: +| File | Lines | Purpose | +|------|-------|---------| +| cliproxy-executor.ts | 666 | Main execution logic | +| config-generator.ts | 531 | Config file generation | +| account-manager.ts | 509 | Account management | +| auth-handler.ts | - | Authentication handling | +| proxy-detector.ts | - | Running proxy detection | + +--- + +### Phase 4: Utility and Error Modularization + +**Status**: COMPLETE + +Extracted utilities and error handling into focused modules. + +**Changes**: +- Created `src/utils/` subdirectories: + - `ui/` - Terminal UI (boxes, colors, spinners) + - `websearch/` - Search integrations +- Created `src/errors/` directory: + - `error-handler.ts` - Main error handling + - `exit-codes.ts` - Exit code definitions + - `cleanup.ts` - Cleanup logic +- Created `src/management/` directory: + - `checks/` - Diagnostic checks + - `repair/` - Auto-repair logic + +--- + +### Phase 5: UI Components Modularization + +**Status**: COMPLETE + +Major UI refactoring splitting monster files into focused modules. + +**Monster Files Split**: + +| Original File | Lines | Split Into | +|---------------|-------|------------| +| account-flow-viz.tsx | 1,144 | 12 modules in `flow-viz/` | +| provider-editor.tsx | 921 | 13 modules in `provider-editor/` | +| copilot-config-form.tsx | 846 | 13 modules in `config-form/` | +| error-logs.tsx | 617 | 6 modules in `error-logs/` | +| profile-editor.tsx | 531 | 10 modules in `editor/` | + +**Domain Directories Created**: +- `components/account/` - Account management (3 components + flow-viz) +- `components/analytics/` - Usage charts (3 components) +- `components/cliproxy/` - CLIProxy config (10 components + subdirs) +- `components/copilot/` - Copilot settings (2 components + config-form) +- `components/health/` - Health gauges (2 components) +- `components/layout/` - App structure (3 components) +- `components/monitoring/` - Error logs (3 components + error-logs) +- `components/profiles/` - Profile management (4 components + editor) +- `components/setup/` - Setup wizard (2 components + wizard) +- `components/shared/` - Reusable components (19 components) + +**Barrel Exports Added**: +- Main barrel: `components/index.ts` +- Domain barrels: One `index.ts` per domain directory +- Subdirectory barrels: For split component directories + +--- + +## Current Status + +### Metrics + +| Metric | Before | After | Change | +|--------|--------|-------|--------| +| Files > 500 lines | 12 | 7 | -42% | +| UI files > 200 lines | 28 | 14 | -50% | +| Barrel exports (CLI) | 5 | 24 | +380% | +| Barrel exports (UI) | 0 | 11 | New | +| Domain directories | 4 | 15 | +275% | + +### Remaining Large Files + +**CLI (Acceptable)**: +- `model-pricing.ts` (676 lines) - Data file +- `glmt-proxy.ts` (675 lines) - Complex proxy logic +- `cliproxy-executor.ts` (666 lines) - Core execution +- `ccs.ts` (596 lines) - Entry point + +**UI (Need Attention)**: +- `pages/settings.tsx` (1,710 lines) - **HIGH PRIORITY SPLIT** +- `components/ui/sidebar.tsx` (674 lines) - shadcn component +- `monitoring/auth-monitor.tsx` (465 lines) - Could split +- `pages/analytics.tsx` (420 lines) - Could split + +--- + +## Future Work + +### Priority 1: Settings Page Split + +**Target**: Split `pages/settings.tsx` (1,710 lines) + +**Proposed Structure**: +``` +pages/settings/ +├── index.tsx # Main layout +├── general-section.tsx # General settings +├── appearance-section.tsx # Theme, colors +├── providers-section.tsx # Provider config +├── websearch-section.tsx # WebSearch config +├── advanced-section.tsx # Advanced options +├── hooks.ts # Shared hooks +└── types.ts # Settings types +``` + +### Priority 2: Analytics Page Split + +**Target**: Split `pages/analytics.tsx` (420 lines) + +**Proposed Structure**: +``` +pages/analytics/ +├── index.tsx # Main layout +├── usage-overview.tsx # Usage summary +├── model-breakdown.tsx # Per-model stats +├── cost-analysis.tsx # Cost tracking +└── hooks.ts # Data hooks +``` + +### Priority 3: Auth Monitor Split + +**Target**: Split `monitoring/auth-monitor.tsx` (465 lines) + +**Proposed Structure**: +``` +monitoring/auth-monitor/ +├── index.tsx # Main component +├── provider-status.tsx # Provider cards +├── token-display.tsx # Token info +├── refresh-controls.tsx # Refresh actions +└── hooks.ts # Auth hooks +``` + +### Priority 4: Test Coverage + +**Target**: Add tests for modularized components + +- Unit tests for extracted utilities +- Component tests for split UI modules +- Integration tests for barrel exports +- Snapshot tests for UI components + +### Priority 5: Documentation + +**Target**: Keep documentation synchronized + +- Update codebase-summary.md on structural changes +- Document new patterns in code-standards.md +- Keep architecture diagrams current +- Add inline JSDoc comments + +--- + +## Development Milestones + +| Milestone | Status | Target Date | +|-----------|--------|-------------| +| Phase 1: Types | COMPLETE | - | +| Phase 2: Commands | COMPLETE | - | +| Phase 3: CLIProxy | COMPLETE | - | +| Phase 4: Utils/Errors | COMPLETE | - | +| Phase 5: UI Components | COMPLETE | - | +| Phase 6: Settings Split | PENDING | Q1 2026 | +| Phase 7: Remaining Splits | PENDING | Q1 2026 | +| Phase 8: Test Coverage | PENDING | Q2 2026 | + +--- + +## Success Criteria + +### Code Quality + +- [ ] All files under 200 lines (except documented exceptions) +- [ ] Every directory has barrel export +- [ ] No circular dependencies +- [ ] TypeScript strict mode passing + +### Maintainability + +- [ ] Clear domain boundaries +- [ ] Consistent naming conventions +- [ ] Comprehensive documentation +- [ ] Easy navigation for new developers + +### Developer Experience + +- [ ] Fast build times +- [ ] Efficient tree-shaking +- [ ] Clear import paths +- [ ] Minimal cognitive load + +--- + +## Related Documentation + +- [Codebase Summary](./codebase-summary.md) - Current structure +- [Code Standards](./code-standards.md) - Patterns and conventions +- [System Architecture](./system-architecture.md) - Architecture diagrams +- [CLAUDE.md](../CLAUDE.md) - AI development guidance diff --git a/docs/system-architecture.md b/docs/system-architecture.md new file mode 100644 index 00000000..bec06777 --- /dev/null +++ b/docs/system-architecture.md @@ -0,0 +1,581 @@ +# CCS System Architecture + +Last Updated: 2025-12-19 + +High-level architecture documentation for the CCS (Claude Code Switch) system. + +--- + +## System Overview + +CCS is a CLI wrapper that enables seamless switching between multiple Claude accounts and alternative AI providers (GLM, Gemini, Codex). It consists of two main components: + +1. **CLI Application** (`src/`) - Node.js TypeScript CLI +2. **Dashboard UI** (`ui/`) - React web application served by Express + +``` ++===========================================================================+ +| CCS System | ++===========================================================================+ +| | +| +------------------+ +-----------------+ +----------------+ | +| | User Terminal | ---> | CCS CLI | ---> | Claude Code | | +| | (ccs command) | | (src/ccs.ts) | | CLI | | +| +------------------+ +-----------------+ +----------------+ | +| | | | +| v v | +| +------------------+ +-----------------+ +----------------+ | +| | Dashboard UI | <--> | Express | ---> | Provider APIs | | +| | (React SPA) | | Web Server | | (Claude/GLM/ | | +| +------------------+ +-----------------+ | Gemini/etc) | | +| | +----------------+ | +| v | +| +-----------------+ | +| | CLIProxyAPI | | +| | (Binary) | | +| +-----------------+ | +| | ++===========================================================================+ +``` + +--- + +## Component Architecture + +### CLI Layer + +``` ++===========================================================================+ +| CLI Architecture | ++===========================================================================+ + + User Input (ccs [args]) + | + v + +-------------+ + | ccs.ts | Entry point, command routing + +-------------+ + | + +---> [Version/Help/Doctor/etc.] ---> Exit + | + v + +-------------+ + | Profile | Determines execution path + | Detection | + +-------------+ + | + +---> [Native Claude Account] ---> execClaude() + | | + +---> [CLIProxy Provider] ---> execClaudeWithCLIProxy() + | | + +---> [GLMT Profile] ---> execClaudeWithProxy() + | + v + +-------------+ + | Claude CLI | Underlying Anthropic CLI + +-------------+ +``` + +### Profile Mechanisms (Priority Order) + +``` + Profile Resolution + | + v + 1. CLIProxy Hardcoded ----+---> gemini, codex, agy + (OAuth-based) | Zero-config OAuth providers + | + 2. CLIProxy Variants -----+---> config.cliproxy section + (User-defined) | Custom provider configurations + | + 3. Settings-based --------+---> config.profiles section + (API key profiles) | GLM, GLMT, Kimi, custom + | + 4. Account-based ---------+---> profiles.json + (Claude instances) | Isolated via CLAUDE_CONFIG_DIR + | + v + Profile Config +``` + +--- + +## Module Architecture + +### CLI Modules (`src/`) + +``` ++===========================================================================+ +| CLI Module Structure | ++===========================================================================+ + + +------------------+ +------------------+ +------------------+ + | commands/ | | auth/ | | config/ | + |------------------| |------------------| |------------------| + | doctor-command | | account-switcher | | unified-config- | + | help-command | | profile-detector | | loader | + | install-command | | commands/ | | migration-manager| + | sync-command | +------------------+ +------------------+ + | update-command | + +------------------+ + | | | + +-----------------------+------------------------+ + | + v + +------------------+ +------------------+ +------------------+ + | cliproxy/ | | copilot/ | | glmt/ | + |------------------| |------------------| |------------------| + | cliproxy-executor| | copilot-package- | | glmt-proxy | + | config-generator | | manager | | delta-accumulator| + | account-manager | | [copilot logic] | | pipeline/ | + | auth/ | +------------------+ +------------------+ + | binary/ | + | services/ | + +------------------+ + | | | + +-----------------------+------------------------+ + | + v + +------------------+ +------------------+ +------------------+ + | web-server/ | | utils/ | | errors/ | + |------------------| |------------------| |------------------| + | routes/ (15+) | | ui/ (boxes, | | error-handler | + | health/ | | colors, | | exit-codes | + | usage/ | | spinners) | | cleanup | + | services/ | | websearch/ | +------------------+ + | model-pricing | | shell-executor | + +------------------+ +------------------+ + + | + v + +------------------+ +------------------+ + | types/ | | management/ | + |------------------| |------------------| + | config.ts | | checks/ | + | cli.ts | | repair/ | + | delegation.ts | | [diagnostics] | + | glmt.ts | +------------------+ + +------------------+ +``` + +### UI Modules (`ui/src/`) + +``` ++===========================================================================+ +| UI Module Structure | ++===========================================================================+ + + +------------------+ + | pages/ | Route-level components + |------------------| + | analytics.tsx | + | api.tsx | + | cliproxy.tsx | + | copilot.tsx | + | health.tsx | + | settings.tsx | + +------------------+ + | + v + +------------------+ +------------------+ +------------------+ + | components/ | | contexts/ | | hooks/ | + |------------------| |------------------| |------------------| + | account/ | | privacy-context | | use-accounts | + | analytics/ | | theme-context | | use-cliproxy | + | cliproxy/ | | websocket-context| | use-health | + | copilot/ | +------------------+ | use-profiles | + | health/ | | use-websocket | + | layout/ | +------------------+ + | monitoring/ | + | profiles/ | + | setup/ | + | shared/ | + | ui/ (shadcn) | + +------------------+ + | + v + +------------------+ +------------------+ + | lib/ | | providers/ | + |------------------| |------------------| + | api.ts | | websocket- | + | model-catalogs | | provider | + | utils.ts | +------------------+ + +------------------+ +``` + +--- + +## Data Flow Architecture + +### CLI Execution Flow + +``` ++===========================================================================+ +| CLI Execution Flow | ++===========================================================================+ + + 1. Parse Arguments + | + v + 2. Detect Profile Type + | + +---> Native Claude ---> 3a. Load Account Settings + | | + | v + | 4a. Set CLAUDE_CONFIG_DIR + | | + | v + | 5a. Spawn Claude CLI + | + +---> CLIProxy -------> 3b. Ensure Binary Installed + | | + | v + | 4b. Generate Config + | | + | v + | 5b. Start CLIProxyAPI + | | + | v + | 6b. Set Proxy Env Vars + | | + | v + | 7b. Spawn Claude CLI + | + +---> GLMT -----------> 3c. Start Embedded Proxy + | + v + 4c. Spawn Claude CLI +``` + +### Dashboard Data Flow + +``` ++===========================================================================+ +| Dashboard Data Flow | ++===========================================================================+ + + Browser (React SPA) + | + | HTTP Requests + WebSocket + v + Express Server (src/web-server/) + | + +---> /api/accounts ---> auth/account-manager + | + +---> /api/profiles ---> config/unified-config-loader + | + +---> /api/cliproxy ---> cliproxy/ + | + +---> /api/health ----> management/checks/ + | + +---> /api/usage -----> usage/aggregator + | + v + WebSocket (Real-time) + | + +---> Health status updates + +---> Auth state changes + +---> Usage analytics +``` + +--- + +## Provider Integration Architecture + +### CLIProxyAPI Flow + +``` ++===========================================================================+ +| CLIProxyAPI Integration | ++===========================================================================+ + + Claude CLI + | + | ANTHROPIC_BASE_URL = localhost:XXXX + v + +------------------+ + | CLIProxyAPI | Local proxy binary + | (binary) | + +------------------+ + | + +---> OAuth Authentication (Gemini, Codex, AGY) + | | + | v + | +------------------+ + | | OAuth Server | Browser-based auth + | +------------------+ + | + +---> Request Transformation + | | + | v + | Anthropic Format --> Provider Format + | + +---> Provider APIs + | + +---> Google (Gemini) + +---> GitHub (Codex) + +---> Antigravity + +---> OpenAI-compatible endpoints +``` + +### GLMT Proxy Flow + +``` ++===========================================================================+ +| GLMT Proxy Integration | ++===========================================================================+ + + Claude CLI + | + | ANTHROPIC_BASE_URL = localhost:XXXX + v + +------------------+ + | GLMT Proxy | Embedded Node.js proxy (src/glmt/) + | (glmt-proxy.ts)| + +------------------+ + | + v + +------------------+ + | Delta Accumulator| Stream transformation + +------------------+ + | + v + +------------------+ + | Pipeline | Request/Response transformation + +------------------+ + | + v + +------------------+ + | GLM API | Z.AI / Kimi API + +------------------+ +``` + +--- + +## Configuration Architecture + +### Config File Hierarchy + +``` ++===========================================================================+ +| Configuration Hierarchy | ++===========================================================================+ + + ~/.ccs/ + | + +---> config.yaml # Main CCS config (unified) + | + +---> profiles.json # Claude account registry + | + +---> .settings.json # Per-profile settings + | + +---> cliproxy/ + | | + | +---> config.yaml # CLIProxy configuration + | +---> auth/ # OAuth tokens + | +---> bin/ # CLIProxy binary + | + +---> shared/ # Symlinked resources + | + +---> commands/ # Claude Code commands + +---> skills/ # Custom skills + +---> agents/ # Agent configurations +``` + +### Config Loading Order + +``` + 1. Environment Variables (highest priority) + | + v + 2. CLI Arguments + | + v + 3. Profile-specific settings (~/.ccs/.settings.json) + | + v + 4. Main config (~/.ccs/config.yaml) + | + v + 5. Default values (lowest priority) +``` + +--- + +## WebSocket Architecture + +### Real-time Communication + +``` ++===========================================================================+ +| WebSocket Communication | ++===========================================================================+ + + Dashboard (React) Server (Express) + | | + |<------ Connection Established ------>| + | | + |<------ health:update ----------------| Health status + | | + |<------ auth:status ------------------| Auth changes + | | + |<------ usage:update -----------------| Usage stats + | | + |------- action:refresh -------------->| User requests + | | +``` + +--- + +## Security Architecture + +### Authentication Flow + +``` ++===========================================================================+ +| Authentication Flow | ++===========================================================================+ + + OAuth Providers (Gemini, Codex, AGY) + ----------------------------------- + + 1. User runs: ccs gemini + | + v + 2. Check token cache (~/.ccs/cliproxy/auth/) + | + +---> [Valid token] ---> Use cached token + | + +---> [No/Expired token] + | + v + 3. Open browser for OAuth + | + v + 4. Callback with auth code + | + v + 5. Exchange for access token + | + v + 6. Cache token locally + + + API Key Profiles (GLM, Kimi) + ---------------------------- + + 1. User configures API key in settings + | + v + 2. Key stored in ~/.ccs/.settings.json + | + v + 3. Key passed via ANTHROPIC_AUTH_TOKEN env var +``` + +### Security Boundaries + +``` + +------------------+ + | User Terminal | + +------------------+ + | + | Local only (no network exposure) + v + +------------------+ + | CCS CLI | + +------------------+ + | + | Localhost only (127.0.0.1) + v + +------------------+ + | CLIProxy/GLMT | Binds to localhost only + +------------------+ + | + | TLS encrypted + v + +------------------+ + | Provider APIs | External endpoints + +------------------+ +``` + +--- + +## Build and Distribution + +### Build Pipeline + +``` ++===========================================================================+ +| Build Pipeline | ++===========================================================================+ + + src/ (TypeScript) ui/src/ (React TSX) + | | + v v + TypeScript Compiler Vite Build + | | + v v + dist/ (JavaScript) dist/ui/ (Static assets) + | | + +---------------+---------------------+ + | + v + npm package (@kaitranntt/ccs) + | + v + npm registry / GitHub releases +``` + +### Package Contents + +``` + @kaitranntt/ccs + | + +---> dist/ # Compiled CLI + +---> dist/ui/ # Built dashboard + +---> lib/ # Native scripts + | +---> ccs # Bash bootstrap + | +---> ccs.ps1 # PowerShell bootstrap + +---> package.json +``` + +--- + +## Deployment Architecture + +### Local Installation + +``` + npm install -g @kaitranntt/ccs + | + v + Global node_modules + | + +---> Creates symlink: ccs --> dist/ccs.js + | + +---> First run creates: ~/.ccs/ +``` + +### Runtime Dependencies + +``` + +------------------+ +------------------+ + | Node.js 14+ | | Claude CLI | + | (required) | | (required) | + +------------------+ +------------------+ + + +------------------+ +------------------+ + | CLIProxyAPI | | Gemini CLI | + | (auto-managed) | | (optional) | + +------------------+ +------------------+ +``` + +--- + +## Related Documentation + +- [Codebase Summary](./codebase-summary.md) - Detailed directory structure +- [Code Standards](./code-standards.md) - Coding conventions +- [Project Roadmap](./project-roadmap.md) - Development phases +- [WebSearch](./websearch.md) - WebSearch feature details