> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ccs.kaitran.ca/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> CCS system architecture and design

# Architecture

CCS is designed with simplicity and reliability in mind. The architecture follows YAGNI, KISS, and DRY principles.

## Core Components

<CardGroup cols={3}>
  <Card title="Account Profiles" icon="user">
    Isolated Claude instances with separate credentials and session data
  </Card>

  <Card title="OAuth Providers" icon="key">
    CLIProxy-based providers (Gemini, Codex, Agy) with zero config
  </Card>

  <Card title="API Profiles" icon="gear">
    Settings-based profiles for GLM, KM, and custom providers
  </Card>
</CardGroup>

<Card title="Profile Resolution" icon="route">
  Smart profile detection that checks CLIProxy → Settings → Account profiles in
  order
</Card>

<Card title="Claude CLI Spawn" icon="terminal">
  Spawns Claude CLI with resolved profile settings via `--settings` flag
</Card>

## Profile Mechanisms (Priority Order)

1. **CLIProxy hardcoded**: gemini, codex, agy → OAuth-based, zero config
2. **CLIProxy variants**: `config.cliproxy` section → user-defined providers
3. **Settings-based**: `config.profiles` section → GLM, KM
4. **Account-based**: Account metadata in `config.yaml` → isolated instances via `CLAUDE_CONFIG_DIR`

## Execution Flow

<Steps>
  <Step title="Parse Arguments">
    Smart detection of profile vs CLI flags
  </Step>

  <Step title="Resolve Profile">
    Check CLIProxy → Settings → Account profiles
  </Step>

  <Step title="Configure Environment">
    Set env vars, CLAUDE\_CONFIG\_DIR if needed
  </Step>

  <Step title="Spawn Claude">
    Execute `claude --settings <path> [args]`
  </Step>
</Steps>

## Directory Structure

```
~/.ccs/
├── config.yaml           # Main configuration (v12 unified format)
├── glm.settings.json     # GLM settings file
├── km.settings.json      # Kimi for Coding settings file
│
├── instances/            # Account profile instances
│   ├── work/
│   │   ├── .credentials.json
│   │   ├── session-env/
│   │   └── ...
│   └── personal/
│
├── cliproxy/             # OAuth provider data
│   ├── auth/
│   │   ├── user@email-projectid.json      # gemini tokens
│   │   ├── codex-user@email.json          # codex tokens
│   │   └── antigravity-user_email.json    # antigravity tokens
│   ├── bin/
│   │   ├── original/    # CLIProxyAPI binary
│   │   └── plus/        # CLIProxyAPIPlus binary
│   ├── config.yaml      # CLIProxy configuration
│   ├── sessions.json    # Active session tracking
│   └── accounts.json    # Provider account registry
│
├── docker/               # Docker deployment assets (auto-generated)
│
├── shared/               # Symlinked across profiles
│   ├── commands/
│   ├── skills/
│   └── agents/
│
└── logs/                 # CCS-owned structured logs

~/.claude/
├── settings.json         # Claude Code settings
└── channels/
    ├── telegram/.env     # TELEGRAM_BOT_TOKEN
    └── discord/.env      # DISCORD_BOT_TOKEN
```

## Design Principles

### Non-Invasive

* Never modifies `~/.claude/settings.json`
* Uses `--settings` flag for delegation
* Claude CLI manages its own state

### Idempotent

* All install operations safe to run multiple times
* Profile creation handles existing directories
* No side effects on repeated runs

### Cross-Platform Parity

* Same behavior on macOS, Linux, Windows
* Node.js handles platform differences
* Unified codebase for all platforms

### Configuration Priority Resolution

CCS resolves configuration in this order (highest to lowest priority):

1. **CLI flags** - Direct command-line arguments (`--proxy-host`, `--model`, etc.)
2. **Environment variables** - Shell exports (`CCS_PROXY_HOST`, `ANTHROPIC_MODEL`, etc.)
3. **config.yaml** - User configuration file (`~/.ccs/config.yaml`)
4. **Built-in defaults** - Hardcoded fallback values

This allows flexible overrides without modifying config files.

### Automatic Token Refresh

CLIProxy-backed OAuth providers rely on upstream/runtime-managed token refresh
where supported. CCS verifies local auth material and lets CLIProxy own the
actual refresh flow. This keeps long-running conversations from failing while
avoiding provider-specific refresh logic inside CCS itself.

**How it works:**

* CLIProxy-managed providers refresh upstream when their backend supports it
* CCS checks whether local auth material is still present and usable
* users normally do not need to refresh tokens manually during healthy sessions
* unsupported providers still fall back to re-auth when refresh is not available

### Graceful Degradation

CCS implements fallback mechanisms for robust operation:

**Remote → Local Proxy Fallback:**

* Attempts remote CLIProxy connection first
* On failure, automatically falls back to local proxy
* Configurable via `CCS_PROXY_FALLBACK_ENABLED` or `--remote-only` flag
* Health checks run with configurable timeout

**Network Resilience:**

* Handles connection timeouts gracefully
* Auto-retry on transient failures
* Clear error messages when fallback exhausted

## Technology Stack

| Component | Technology           |
| --------- | -------------------- |
| CLI       | Node.js (ES modules) |
| Build     | Bun + TypeScript     |
| Dashboard | React + Vite         |
| Package   | npm                  |

## Advanced Architecture Patterns

### Unified Config Pattern

CCS v6+ uses a single `config.yaml` file for all configuration instead of scattered JSON files. This simplifies management and enables atomic updates.

**Benefits:**

* Single source of truth for all settings
* Easier backup and version control
* Atomic configuration updates
* Reduced file I/O operations

**Migration:** Run `ccs migrate` to convert legacy config files to unified format.

### Session Reference Counting

CLIProxy tracks active sessions using reference counting to prevent premature shutdown:

* Each active Claude session increments counter
* Session end decrements counter
* Proxy only stops when counter reaches zero
* Prevents disruption of concurrent sessions

**Session Files:**

* `~/.ccs/cliproxy/sessions.json` - Global session tracking
* `~/.ccs/cliproxy/sessions-{port}.json` - Variant-specific sessions

### Version Mismatch Detection

CCS automatically detects CLIProxy binary version mismatches and handles them gracefully:

**Detection:**

* Compares expected version in config vs installed binary
* Checks on every proxy startup
* Validates on health check failures

**Auto-Restart:**

* Stops outdated proxy instance
* Downloads latest compatible version
* Restarts proxy with new binary
* Preserves session state

**User Impact:**

* Transparent to user (no interruption)
* Logged for debugging (`~/.ccs/logs/`)
* Optional notification in dashboard

## Docker Deployment Architecture

`ccs docker up` bundles CCS and CLIProxy into a Docker stack for team or server deployments.

```
Local Machine                    Remote Server
┌─────────────────┐              ┌────────────────────────────┐
│                 │  SSH deploy  │ Docker Stack               │
│  ccs docker up  │─────────────▶│                            │
│  --host <ssh>   │              │  ┌──────────┐  ┌────────┐  │
│                 │              │  │   CCS    │  │Superv. │  │
└─────────────────┘              │  │ (daemon) │  │ (proc) │  │
                                 │  └────┬─────┘  └────────┘  │
                                 │       │                      │
                                 │  ┌────▼─────────────┐       │
                                 │  │  CLIProxyAPI     │       │
                                 │  │  (port 8317)     │       │
                                 │  └────┬─────────────┘       │
                                 └───────┼────────────────────-┘
                                         │
                                         ▼
                                 ┌─────────────────┐
                                 │  AI Providers   │
                                 │  (Gemini, etc.) │
                                 └─────────────────┘
```

**Commands:**

| Command                            | Description                                   |
| ---------------------------------- | --------------------------------------------- |
| `ccs docker up`                    | Build + start stack locally                   |
| `ccs docker up --host <ssh>`       | Deploy to remote server                       |
| `ccs docker down`                  | Stop and remove stack                         |
| `ccs docker status`                | Show compose + supervisor status              |
| `ccs docker logs [--follow]`       | Tail combined logs                            |
| `ccs docker update [--host]`       | Update binaries in running container          |
| `ccs docker config`                | Show bundled paths + defaults                 |
| `ccs docker show-key [--full]`     | Show the active Docker CLIProxy API key       |
| `ccs docker finalize-key-rotation` | End the temporary legacy API key grace window |

***

## Multi-Target Runtime Routing

The `--target` flag (or argv0 aliases like `ccsd`, `ccsx`) routes profile execution to alternative CLI runtimes.

```
ccs glm --target droid / ccsx codex
       │
       ▼
Profile resolution (same as normal)
       │
       ▼
Target selection
  ├── target=claude  →  exec: claude --settings <path>
  ├── target=droid   →  exec: @factory/cli --settings <path>
  │                           │
  │                           ▼
  │                      CCS_DROID_PATH or PATH lookup
  └── target=codex   →  exec: codex -c <transient overrides>
                              │
                              ▼
                         CCS_CODEX_API_KEY injected via env
                         (no file writes to ~/.codex/config.toml)
```

**Priority order for target:**

1. `--target` CLI flag (highest)
2. argv0 match (`ccsd` -> droid, `ccsx`/`ccs-codex` -> codex)
3. Profile `target` config key (`claude`, `droid`, or `codex`)
4. Default: `claude`

***

## Performance

| Operation                | Time      |
| ------------------------ | --------- |
| Profile switch           | \< 10ms   |
| First account activation | \~20-35ms |
| Subsequent activation    | \~5-10ms  |
| Dashboard startup        | \~300ms   |
