diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..e69de29b diff --git a/README.md b/README.md index 33c4c2c0..f1693ba8 100644 --- a/README.md +++ b/README.md @@ -2,1112 +2,255 @@ # CCS - Claude Code Switch -![CCS Logo](docs/assets/ccs-logo-medium.png) +![CCS Logo](assets/ccs-logo-medium.png) ### The universal AI profile manager for Claude Code. -Switch between multiple Claude accounts, connect **any Anthropic-compatible API**, and use OAuth providers (Gemini, Codex, Antigravity) instantly. -Stop hitting rate limits. Keep working continuously with unlimited profiles. +Run Claude, Gemini, GLM, and any Anthropic-compatible API - concurrently, without conflicts. [![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](LICENSE) -[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey?style=for-the-badge)]() +[![npm](https://img.shields.io/npm/v/@kaitranntt/ccs?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@kaitranntt/ccs) [![PoweredBy](https://img.shields.io/badge/PoweredBy-ClaudeKit-C15F3C?style=for-the-badge)](https://claudekit.cc?ref=HMNKXOHN) -[![npm](https://img.shields.io/npm/v/@kaitranntt/ccs?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@kaitranntt/ccs) -[![React](https://img.shields.io/badge/React-19-61DAFB?style=for-the-badge&logo=react)](https://react.dev/) -[![TypeScript](https://img.shields.io/badge/TypeScript-100%25-3178C6?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org/) - -**Languages**: [English](README.md) | [Tiếng Việt](docs/vi/README.md) | [日本語](docs/ja/README.md) +**[Features & Pricing](https://ccs.kaitran.ca)** | **[Documentation](https://docs.ccs.kaitran.ca)**
+## The Three Pillars + +| Capability | What It Does | Manage Via | +|------------|--------------|------------| +| **Multiple Claude Accounts** | Run work + personal Claude subs simultaneously | Dashboard | +| **OAuth Providers** | Gemini, Codex, Antigravity - zero API keys needed | Dashboard | +| **API Profiles** | GLM, Kimi, or any Anthropic-compatible API | Dashboard | + +
+ ## Quick Start -### Installation +### 1. Install -**npm Package (Recommended)** - -**macOS / Linux / Windows** ```bash npm install -g @kaitranntt/ccs ``` -**All major package managers are supported:** - -```bash -# yarn -yarn global add @kaitranntt/ccs - -# pnpm (70% less disk space) -pnpm add -g @kaitranntt/ccs - -# bun (30x faster) -bun add -g @kaitranntt/ccs -``` -
-[!] DEPRECATED: Native Shell Installers (Legacy) +Alternative package managers -
- -> [!WARNING] -> **These installers are deprecated and will be removed in a future version.** -> They now auto-redirect to npm installation. Please use npm directly. - -**macOS / Linux** ```bash -curl -fsSL ccs.kaitran.ca/install | bash +yarn global add @kaitranntt/ccs # yarn +pnpm add -g @kaitranntt/ccs # pnpm (70% less disk space) +bun add -g @kaitranntt/ccs # bun (30x faster) ``` -**Windows PowerShell** -```powershell -irm ccs.kaitran.ca/install | iex -``` - -**Note:** Scripts show deprecation warning and automatically run npm installation if Node.js is available. -
-
- -## Built-in OAuth Providers (Zero-Config) - -**New in v5.0.0**: Instant access to premium models with zero API key setup. Browser-based OAuth authentication. - -> Powered by [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) - the universal API proxy for AI models. - -| Provider | Default Model | Opus | Haiku | Example | -|:---------|:--------------|:-----|:------|:--------| -| **Gemini** | gemini-2.5-pro | gemini-2.5-pro | gemini-2.5-flash | `ccs gemini "explain code"` | -| **Codex** | gpt-5.1-codex-max | gpt-5.1-codex-max-high | gpt-5.1-codex-mini-high | `ccs codex "implement API"` | -| **Antigravity** | gemini-3-pro-preview | gemini-3-pro-preview | gemini-2.5-flash | `ccs agy "review architecture"` | - -> [!TIP] -> **These are just the built-in providers.** CCS supports **any Anthropic-compatible API** via custom profiles. See [Custom API Profiles](#custom-api-profiles-bring-your-own) below. - -**First Run**: Browser opens for authentication. Tokens cached in `~/.ccs/cliproxy/auth//`. - -**Subsequent Runs**: Instant - no re-auth needed until token expires. - -### Authentication Commands +### 2. Open Dashboard ```bash -# Interactive OAuth (default) - browser opens, complete auth -ccs gemini - -# Authenticate only (save tokens, don't start session) -ccs gemini --auth -ccs codex --auth - -# Headless mode (for SSH/servers without browser) -ccs agy --headless # Displays URL, paste in browser elsewhere - -# Logout (clear tokens) -ccs gemini --logout -``` - -### Multi-Account for OAuth Providers - -Use multiple accounts per provider (work + personal): - -```bash -# First account (default) -ccs gemini --auth - -# Add another account -ccs gemini --auth --add - -# Add with nickname for easy identification -ccs gemini --auth --add --nickname work - -# Codex provider examples -ccs codex --auth # First account for Codex -ccs codex --auth --add # Add another Codex account -ccs codex --auth --add --nickname work # Named account - -# List all accounts (any provider) -ccs gemini --accounts -ccs codex --accounts -ccs agy --accounts - -# Switch to a different account -ccs gemini --use work -ccs codex --use work -ccs agy --use work -``` - -Accounts are stored in `~/.ccs/cliproxy/accounts.json` and can be managed via web dashboard (`ccs config`). - -### OAuth vs API Key Models - -| Feature | OAuth Providers
(gemini, codex, agy) | API Key Models
(glm, kimi) | -|:--------|:----------------------------------------|:------------------------------| -| **Setup** | Browser auth on first run | Edit settings.json, add API key | -| **Token Storage** | `~/.ccs/cliproxy/auth//` | `~/.ccs/*.settings.json` | -| **Renewal** | Automatic (OAuth refresh tokens) | Manual (update key when expired) | -| **Binary** | Auto-downloads CLIProxyAPI (~15MB) | No additional binaries | -| **Port** | 8317 (configurable) | N/A | -| **Best For** | Quick testing, no key management | Production, explicit key control | - -### Troubleshooting OAuth - -**OAuth timeout (2min limit)**: -```bash -# If browser doesn't load in time: -ccs gemini --auth --headless # Get URL manually -``` - -**Port 8317 conflict**: -```bash -ccs doctor # Check port availability -# Error: "Port 8317 in use" -lsof -ti:8317 | xargs kill # Unix: kill process using port -``` - -**Binary download failures**: -```bash -ccs doctor # Shows binary status + version -# Manual download: https://github.com/router-for-me/CLIProxyAPI/releases -``` - -
- -### Configuration (Auto-created) - -**CCS automatically creates configuration during installation** (via npm postinstall script). - -**~/.ccs/config.json**: -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "glmt": "~/.ccs/glmt.settings.json", - "kimi": "~/.ccs/kimi.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -
-

Custom Claude CLI Path

- -
- -If Claude CLI is installed in a non-standard location (D drive, custom directory), set `CCS_CLAUDE_PATH`: - -```bash -export CCS_CLAUDE_PATH="/path/to/claude" # Unix -$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe" # Windows -``` - -**See also:** [Troubleshooting Guide](./docs/en/troubleshooting.md#claude-cli-in-non-standard-location) for detailed setup instructions. - -
- -
-

Windows Symlink Support (Developer Mode)

- -
- -**Windows users**: Enable Developer Mode for true symlinks (better performance, instant sync): - -1. Open **Settings** → **Privacy & Security** → **For developers** -2. Enable **Developer Mode** -3. Reinstall CCS: `npm install -g @kaitranntt/ccs` - -**Warning:** Without Developer Mode, CCS automatically falls back to copying directories (works but no instant sync across profiles). - -
- -
- -## Custom API Profiles (Bring Your Own) - -CCS isn't limited to the built-in providers. **Connect any Anthropic-compatible API** by creating custom profiles: - -```bash -# 1. Create a settings file for your API -cat > ~/.ccs/my-api.settings.json << 'EOF' -{ - "env": { - "ANTHROPIC_BASE_URL": "https://your-api.example.com/v1", - "ANTHROPIC_AUTH_TOKEN": "your-api-key", - "ANTHROPIC_MODEL": "your-model-name" - } -} -EOF - -# 2. Register it in config.json -# Add to ~/.ccs/config.json under "profiles": -# "my-api": "~/.ccs/my-api.settings.json" - -# 3. Use it! -ccs my-api "Your prompt here" -``` - -**Works with any API that implements the Anthropic messages format:** -- Self-hosted LLMs (Ollama, LM Studio, vLLM with Anthropic adapter) -- Alternative AI providers with Anthropic-compatible endpoints -- Enterprise API gateways and proxies -- Custom model deployments - -> [!TIP] -> **Already have API keys for GLM or Kimi?** CCS includes pre-configured profiles for these. Just add your API key to `~/.ccs/glm.settings.json` or `~/.ccs/kimi.settings.json`. - -
- -### Your First Switch - -> [!IMPORTANT] -> **Before using alternative models, update API keys in settings files:** -> -> - **GLM**: Edit `~/.ccs/glm.settings.json` and add your Z.AI Coding Plan API Key -> - **GLMT**: Edit `~/.ccs/glmt.settings.json` and add your Z.AI Coding Plan API Key -> - **Kimi**: Edit `~/.ccs/kimi.settings.json` and add your Kimi API key - -
- -**Parallel Workflow: Planning + Execution** - -```bash -# Terminal 1 - Planning (Claude Sonnet) -ccs "Plan a REST API with authentication and rate limiting" - -# Terminal 2 - Execution (GLM, cost-optimized) -ccs glm "Implement the user authentication endpoints from the plan" -``` - -
-Thinking Models (Kimi & GLMT) - -
- -```bash -# Kimi - Stable thinking support -ccs kimi "Design a caching strategy with trade-off analysis" - -# GLMT - Experimental (see full disclaimer below) -ccs glmt "Debug complex algorithm with reasoning steps" -``` - -**Note:** GLMT is experimental and unstable. See [GLM with Thinking (GLMT)](#glm-with-thinking-glmt) section below for full details. - -
- -
- -## The Daily Developer Pain Point - -
- -### **STOP Switching. START Orchestrating.** - -**Session limits shouldn't kill your flow state.** -
- -You're deep in implementation. Context loaded. Solution crystallizing.
-Then: 🔴 _"You've reached your usage limit."_ - -**Momentum gone. Context lost. Productivity crater.** - -## **The Solution: Parallel Workflows** - -
-❌ OLD WAY: Switch When You Hit Limits (Reactive) - -
- -```mermaid -graph LR - A[2pm: Building features
In the zone] --> B[3pm: Usage limit hit
BLOCKED] - B --> C[3:05pm: Stop work
Edit settings.json] - C --> D[3:15pm: Switch accounts
Context lost] - D --> E[3:30pm: Restart
Trying to focus] - E --> F[4pm: Finally productive
Back in flow] - - style A fill:#d4edda,stroke:#333,color:#000 - style B fill:#f8d7da,stroke:#333,color:#000 - style C fill:#fff3cd,stroke:#333,color:#000 - style D fill:#f8d7da,stroke:#333,color:#000 - style E fill:#fff3cd,stroke:#333,color:#000 - style F fill:#d4edda,stroke:#333,color:#000 -``` - -**Result:** 1 hour lost, momentum destroyed, frustration builds - -
- -
-✨ NEW WAY: Run Parallel From Start (Proactive) - RECOMMENDED - -
- -```mermaid -graph LR - A[2pm: Start work] --> B[Terminal 1: Claude Pro
Strategic planning] - A --> C[Terminal 2: GLM
Code execution] - B --> D[3pm: Still shipping
No interruptions] - C --> D - D --> E[4pm: Flow state
Productivity peak] - E --> F[5pm: Features shipped
Context maintained] - - style A fill:#e7f3ff,stroke:#333,color:#000 - style B fill:#cfe2ff,stroke:#333,color:#000 - style C fill:#cfe2ff,stroke:#333,color:#000 - style D fill:#d4edda,stroke:#333,color:#000 - style E fill:#d4edda,stroke:#333,color:#000 - style F fill:#d4edda,stroke:#333,color:#000 -``` - -**Result:** Zero downtime, continuous productivity, less frustration - -### 💰 **The Value Proposition:** -- **Setup:** Your existing Claude Pro + GLM Lite (cost-effective add-on) -- **Value:** Save 1 hour/day × 20 workdays = 20 hours/month recovered -- **ROI:** Your development time is worth more than the setup cost -- **Reality:** Shipping faster than the overhead - -
- -## Choose Your Path - -
-Budget-Focused: GLM Only - -- **Best for:** Cost-conscious development, basic code generation -- **Usage:** Just use `ccs glm` directly for cost-effective AI assistance -- **Reality:** No Claude access, but capable for many coding tasks -- **Setup:** GLM API key only, very affordable - -
- -
-✨ Recommended for Daily Development: 1 Claude Pro + 1 GLM Lite - -- **Best for:** Daily code delivery, serious development work -- **Usage:** `ccs` for planning + `ccs glm` for execution (parallel workflow) -- **Reality:** Perfect balance of capability and cost for most developers -- **Value:** Never hit session limits, continuous productivity - -
- -
-Power User: Multiple Claude Pro + GLM Pro - -- **Best for:** Heavy workloads, concurrent projects, solo dev -- **Unlocks:** Never drain session or weekly limits -- **Workflow:** 3+ terminals running specialized tasks simultaneously - -
- -
-Privacy-Focused: Work/Personal Isolation - -- **When needed:** Strict separation of work and personal AI contexts -- **Setup:** `ccs auth create work` + `ccs auth create personal` -- **Note:** Advanced feature - most users don't need this - -
- ---- - -## Why CCS Instead of Manual Switching? - -
- -**CCS isn't about "switching when you hit limits at 3pm."** - -## **It's about running in parallel from the start.** - -
- -### The Core Difference - -| **Manual Switching** | **CCS Orchestration** | -|:---|:---| -| 🔴 Hit limits → Stop work → Edit config files → Restart | ✅ Multiple terminals running different models from the start | -| 😰 Context loss and flow state interruption | 😌 Continuous productivity with preserved context | -| 📝 Sequential task handling | ⚡ Parallel workflows (planning + execution simultaneously) | -| 🛠️ Reactive problem solving when blocked | 🎯 Proactive workflow design prevents blocks | - -### What CCS Gives You - -- **Unlimited Profiles**: Built-in OAuth, API keys, or bring your own Anthropic-compatible endpoints -- **Zero Context Switching**: Keep your flow state without interruption -- **Parallel Productivity**: Strategic planning in one terminal, code execution in another -- **Instant Account Management**: One command switches, no config file editing -- **Work-Life Separation**: Isolate contexts without logging out -- **Cross-Platform Consistency**: Same smooth experience on macOS, Linux, Windows - -**Manual context switching breaks workflow. CCS orchestrates seamlessly.** - -
- -## Architecture - -CCS is a **universal profile manager** that resolves profiles in priority order: -1. **CLIProxy profiles** (gemini, codex, agy) - Built-in OAuth providers, zero config -2. **CLIProxy variants** (user-defined) - Custom model configurations for CLIProxy providers -3. **Settings-based profiles** (glm, kimi, **your-custom-api**) - Any Anthropic-compatible API -4. **Account-based profiles** (work, personal) - Isolated Claude instances -5. **Default** - Claude CLI with subscription - -> [!NOTE] -> **Extensibility is core to CCS.** While we provide built-in profiles for common providers, you can connect **any API** that speaks the Anthropic messages format. - -### Profile Types - -**CLIProxy**: gemini, codex, agy (v5.0+) -- OAuth-based authentication via [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) -- Browser auth on first run, tokens cached in `~/.ccs/cliproxy/auth//` -- Proxy runs on port 8317, auto-spawned per session -- Binary: `~/.ccs/cliproxy/bin/cli-proxy-api` (~15MB, auto-downloaded) -- Model mappings: - - **Gemini**: gemini-2.5-pro (opus), gemini-2.0-flash (sonnet), flash-lite (haiku) - - **Codex**: gpt-5.1-codex-max (opus), gpt-4o (sonnet), gpt-4o-mini (haiku) - - **Antigravity**: agy-pro (sonnet), agy-turbo (haiku) - -**CLIProxy Variants** (v5.0.2+) -- User-defined profile names that route through CLIProxy providers -- Allows multiple model configurations per provider (e.g., `flash` and `pro` for Gemini) -- Configure in `~/.ccs/config.json` under `cliproxy` section: - -```json -{ - "profiles": { ... }, - "cliproxy": { - "flash": { "provider": "gemini", "settings": "~/.ccs/gemini-flash.settings.json" }, - "pro": { "provider": "gemini", "settings": "~/.ccs/gemini-pro.settings.json" }, - "gpt": { "provider": "codex", "settings": "~/.ccs/codex-gpt.settings.json" } - } -} -``` - -Usage: `ccs flash "quick task"` or `ccs pro "complex analysis"` - -Settings file format (`~/.ccs/gemini-flash.settings.json`): - -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "http://127.0.0.1:8317/api/provider/gemini", - "ANTHROPIC_AUTH_TOKEN": "ccs-internal-managed", - "ANTHROPIC_MODEL": "gemini-2.5-flash", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "gemini-2.5-flash", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "gemini-2.5-flash", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "gemini-2.5-flash" - } -} -``` - -> [!TIP] -> Copy from `~/.ccs/gemini.settings.json` (auto-generated on first `ccs gemini` run) and modify `ANTHROPIC_MODEL` to your desired model. - -**Settings-based**: GLM, GLMT, Kimi, default -- Uses `--settings` flag pointing to config files -- GLMT: Embedded proxy for thinking mode support - -**Account-based**: work, personal, team -- Uses `CLAUDE_CONFIG_DIR` for isolated instances -- Create with `ccs auth create ` - -### Shared Data (v4.4+) - -**Shared across instances** (`~/.ccs/shared/` symlinked to `~/.claude/`): -- commands/ - Slash commands -- skills/ - Agent skills -- agents/ - Agent configs -- **settings.json** - Claude CLI settings (v4.4+) - -**Profile-specific**: -- sessions/ - Conversation history -- todolists/ - Todo lists -- logs/ - Execution logs -- **cliproxy/auth/** - OAuth tokens (CLIProxy profiles only) - -> [!NOTE] -> **v4.4 Breaking Change**: settings.json now shared across profiles. Previously each profile had isolated settings. Migration is automatic on install using ~/.claude/settings.json as the authoritative source. Backups created: `/settings.json.pre-shared-migration` - -> [!NOTE] -> **Windows**: Symlink support requires Developer Mode (v4.2 will add copy fallback) - -
- -## Web Dashboard - -CCS includes a modern React 19 dashboard for visual profile management and real-time monitoring: - -```bash -# Start the web dashboard (auto-detects available port) ccs config - -# Or specify a port -ccs config --port 3000 - -# Access at http://localhost:PORT (shown in output) +# Opens http://localhost:3000 ``` -**Dashboard Features**: -- 🎨 **Modern UI**: Built with React 19, TypeScript, and shadcn/ui -- 📊 **Real-time Updates**: WebSocket integration for live status -- ⚙️ **Profile Management**: Visual configuration of all profiles -- 🔍 **Health Monitoring**: System diagnostics and metrics -- 🌙 **Dark Mode**: Eye-friendly theme switching -- 📱 **Responsive**: Works on desktop and mobile +### 3. Configure Your Accounts -### Dashboard Screenshots +The dashboard provides visual management for all account types: -*(Add screenshots here when available)* +- **Claude Accounts**: Create isolated instances (work, personal, client) +- **OAuth Providers**: One-click auth for Gemini, Codex, Antigravity +- **API Profiles**: Configure GLM, Kimi with your keys +- **Health Monitor**: Real-time status across all profiles -## Usage Examples +**Analytics (Light/Dark Theme)** -### Basic Switching +![Analytics Light](assets/screenshots/analytics-light.png) -```bash -ccs # Claude subscription (default) -ccs glm # GLM (cost-optimized) -ccs kimi # Kimi (with thinking support) -``` +![Analytics Dark](assets/screenshots/analytics.png) -### Multi-Account Setup +**API Profiles & OAuth Providers** -```bash -# Create accounts -ccs auth create work -ccs auth create personal -``` +![API Profiles](assets/screenshots/api_profiles.png) -**Run concurrently in separate terminals:** - -```bash -# Terminal 1 - Work -ccs work "implement feature" - -# Terminal 2 - Personal (concurrent) -ccs personal "review code" -``` - -### Help & Version - -```bash -ccs --version # Show version -ccs --help # Show all commands and options -``` +![CLIProxy](assets/screenshots/cliproxy.png)
-## AI-Powered Delegation +## Built-in Providers + +| Provider | Auth Type | Command | Best For | +|----------|-----------|---------|----------| +| **Claude** | Subscription | `ccs` | Default, strategic planning | +| **Gemini** | OAuth | `ccs gemini` | Zero-config, fast iteration | +| **Codex** | OAuth | `ccs codex` | Code generation | +| **Antigravity** | OAuth | `ccs agy` | Alternative routing | +| **GLM** | API Key | `ccs glm` | Cost-optimized execution | +| **Kimi** | API Key | `ccs kimi` | Long-context, thinking mode | + +> **OAuth providers** authenticate via browser on first run. Tokens are cached in `~/.ccs/cliproxy/auth/`. > [!TIP] -> **New in v4.0**: Delegate tasks to cost-optimized models (GLM, Kimi) directly from your main Claude session. Save 81% on simple tasks with real-time visibility. - -### What is Delegation? - -CCS Delegation lets you **send tasks to alternative models** (`glm`, `kimi`) **from your main Claude session** using the `-p` flag or intelligent slash commands (`/ccs`, `/ccs:continue`). - -**Why use it?** -- **Token efficiency**: Simple tasks cost 81% less on GLM vs main Claude session -- **Context preservation**: Main session stays clean, no pollution from mechanical tasks -- **Real-time visibility**: See tool usage as tasks execute (`[Tool] Write: index.html`) -- **Multi-turn support**: Resume sessions with `:continue` for iterative work - -### Quick Examples - -**Direct CLI:** -```bash -# Delegate simple task to GLM (cost-optimized) -ccs glm -p "add tests for UserService" - -# Delegate long-context task to Kimi -ccs kimi -p "analyze all files in src/ and document architecture" - -# Continue previous session -ccs glm:continue -p "run the tests and fix any failures" -``` - -**Via Slash Commands** (inside Claude sessions): -```bash -# In your main Claude session: -/ccs "refactor auth.js to use async/await" # Auto-selects best profile -/ccs --glm "fix typo in documentation" # Forces GLM profile -/ccs --kimi "analyze entire architecture" # Forces Kimi profile -/ccs:continue "also update the README examples" # Continues last session -``` - -**Via Natural Language** (Claude auto-delegates): -```bash -# Claude detects delegation patterns and auto-executes: -"Use ccs glm to add tests for all *.service.js files" -"Delegate to kimi: analyze project structure" -``` - -### Real-Time Output - -See exactly what's happening as tasks execute: - -``` -$ ccs glm -p "/cook create a landing page" -[i] Delegating to GLM-4.6... -[Tool] Write: /home/user/project/index.html -[Tool] Write: /home/user/project/styles.css -[Tool] Write: /home/user/project/script.js -[Tool] Edit: /home/user/project/styles.css -[i] Execution completed in 45.2s - -╔══════════════════════════════════════════════════════╗ -║ Working Directory: /home/user/project ║ -║ Model: GLM-4.6 ║ -║ Duration: 45.2s ║ -║ Exit Code: 0 ║ -║ Session ID: 3a4f8c21 ║ -║ Total Cost: $0.0015 ║ -║ Turns: 3 ║ -╚══════════════════════════════════════════════════════╝ -``` - -### Advanced Features - -**Slash Command Support:** -Delegation preserves custom slash commands in prompts: -```bash -ccs glm -p "/cook create responsive landing page" -# Executes /cook command in delegated GLM session -``` - -**Signal Handling:** -Ctrl+C or Esc properly kills delegated processes (no orphans): -```bash -# Hit Ctrl+C during delegation -[!] Parent process terminating, killing delegated session... -``` - -**Time-Based Limits:** -10-minute default timeout with graceful termination (supports `:continue`): -```bash -ccs glm -p "complex task" # Auto-terminates after 10min if needed -ccs glm:continue -p "pick up where we left off" -``` - -### Cost Savings Example - -**Traditional (Main Session):** -``` -Context load: 2000 tokens -Discussion: 1500 tokens -Code gen: 4500 tokens -───────────────────────── -Total: 8000 tokens → $0.032 -``` - -**Delegation (GLM):** -``` -3x tasks via GLM: 1500 tokens → $0.0045 -───────────────────────────────────────── -Savings: $0.0275 (86% reduction) -``` - -### Documentation - -- **Workflow Diagrams**: See [docs/ccs-delegation-diagrams.md](docs/ccs-delegation-diagrams.md) for visual architecture -- **Skill Reference**: `.claude/skills/ccs-delegation/` for AI decision framework (replaces deprecated agents) -- **Agent Docs**: `.claude/agents/ccs-delegator.md` was deprecated in v4.3.2, functionality moved to ccs-delegation skill +> **Need more?** CCS supports **any Anthropic-compatible API**. Create custom profiles for self-hosted LLMs, enterprise gateways, or alternative providers. See [API Profiles documentation](https://docs.ccs.kaitran.ca/providers/api-profiles).
-## GLM with Thinking (GLMT) +## Usage -> [!CAUTION] -> ### NOT PRODUCTION READY - EXPERIMENTAL FEATURE -> -> **GLMT is experimental and requires extensive debugging**: -> - Streaming and tool support still under active development -> - May experience unexpected errors, timeouts, or incomplete responses -> - Requires frequent debugging and manual intervention -> - **Not recommended for critical workflows or production use** -> -> **Alternative for GLM Thinking**: Consider going through the **CCR hustle** with the **Transformer of Bedolla** ([ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/)) for a more stable implementation. - -> [!IMPORTANT] -> GLMT requires npm installation (`npm install -g @kaitranntt/ccs`). Not available in native shell versions (requires Node.js HTTP server). - -
- -> [!NOTE] -> ### Acknowledgments: The Foundation That Made GLMT Possible -> -> **CCS's GLMT implementation owes its existence to the groundbreaking work of [@Bedolla](https://github.com/Bedolla)**, who created [ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/) - the **first integration** to bridge [Claude Code Router (CCR)](https://github.com/musistudio/claude-code-router) with Z.AI's reasoning capabilities. -> -> **Why this matters**: Before ZaiTransformer, no one had successfully integrated Z.AI's thinking mode with Claude Code's workflow. Bedolla's work wasn't just helpful - it was **foundational**. His implementation of: -> -> - **Request/response transformation architecture** - The conceptual blueprint for how to bridge Anthropic and OpenAI formats -> - **Thinking mode control mechanisms** - The patterns for managing reasoning_content delivery -> - **Embedded proxy design** - The architecture that CCS's GLMT proxy is built upon -> -> These contributions directly inspired and enabled GLMT's design. **Without ZaiTransformer's pioneering work, GLMT wouldn't exist in its current form**. The technical patterns, transformation logic, and proxy architecture implemented in CCS are a direct evolution of the concepts Bedolla first proved viable. -> -> **Recognition**: If you benefit from GLMT's thinking capabilities, you're benefiting from Bedolla's vision and engineering. Please consider starring [ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/) to support pioneering work in the Claude Code ecosystem. - -
- -
-

GLM vs GLMT Comparison

- -
- -
- -| Feature | GLM (`ccs glm`) | GLMT (`ccs glmt`) | -|:--------|:----------------|:------------------| -| **Endpoint** | Anthropic-compatible | OpenAI-compatible | -| **Thinking** | No | Experimental (`reasoning_content`) | -| **Tool Support** | Basic | **Unstable (v3.5+)** | -| **MCP Tools** | Limited | **Buggy (v3.5+)** | -| **Streaming** | Stable | **Experimental (v3.4+)** | -| **TTFB** | <500ms | <500ms (sometimes), 2-10s+ (often) | -| **Use Case** | Reliable work | **Debugging experiments only** | - -
- -
- -
-

Tool Support (v3.5) - EXPERIMENTAL

- -
- -**GLMT attempts MCP tools and function calling:** - -- **Bidirectional Transformation**: Anthropic tools ↔ OpenAI format (unstable) -- **MCP Integration**: MCP tools sometimes execute (often output XML garbage) -- **Streaming Tool Calls**: Real-time tool calls (when not crashing) -- **Backward Compatible**: May break existing thinking support -- **Configuration Required**: Frequent manual debugging needed - -
- -
-

Streaming Support (v3.4) - OFTEN FAILS

- -
- -**GLMT attempts real-time streaming** with incremental reasoning content delivery: - -- **Default**: Streaming enabled (TTFB <500ms when it works) -- **Auto-fallback**: Frequently switches to buffered mode due to errors -- **Thinking parameter**: Claude CLI `thinking` parameter sometimes works - - May ignore `thinking.type` and `budget_tokens` - - Precedence: CLI parameter > message tags > default (when not broken) - -**Status**: Z.AI (tested, tool calls frequently break, requires constant debugging) - -
- -
-

How It Works (When It Works)

- -
- -1. CCS spawns embedded HTTP proxy on localhost (if not crashing) -2. Proxy attempts to convert Anthropic format → OpenAI format (often fails) -3. Tries to transform Anthropic tools → OpenAI function calling format (buggy) -4. Forwards to Z.AI with reasoning parameters and tools (when not timing out) -5. Attempts to convert `reasoning_content` → thinking blocks (partial or broken) -6. Attempts to convert OpenAI `tool_calls` → Anthropic `tool_use` blocks (XML garbage common) -7. Thinking and tool calls sometimes appear in Claude Code UI (when not broken) - -
- -
-

Control Tags & Keywords

- -
- -**Control Tags**: -- `` - Enable/disable reasoning blocks (default: On) -- `` - Control reasoning depth (deprecated - Z.AI only supports binary thinking) - -**Thinking Keywords** (inconsistent activation): -- `think` - Sometimes enables reasoning (low effort) -- `think hard` - Sometimes enables reasoning (medium effort) -- `think harder` - Sometimes enables reasoning (high effort) -- `ultrathink` - Attempts maximum reasoning depth (often breaks) - -
- -
-

Environment Variables

- -
- -**GLMT features** (all experimental): -- Forced English output enforcement (sometimes works) -- Random thinking mode activation (unpredictable) -- Attempted streaming with frequent fallback to buffered mode - -**General**: -- `CCS_DEBUG_LOG=1` - Enable debug file logging -- `CCS_CLAUDE_PATH=/path/to/claude` - Custom Claude CLI path - -
- -
-

API Key Setup

- -
+### Basic Commands ```bash -# Edit GLMT settings -nano ~/.ccs/glmt.settings.json +ccs # Default Claude session +ccs agy # Antigravity (OAuth) +ccs gemini # Gemini (OAuth) +ccs glm # GLM (API key) ``` -Set Z.AI API key (requires coding plan): +### Parallel Workflows -```json -{ - "env": { - "ANTHROPIC_AUTH_TOKEN": "your-z-ai-api-key" - } -} -``` +Run multiple terminals with different providers: -
- -
-

Security Limits (DoS Protection)

- -
- -**v3.4 Protection Limits**: - -| Limit | Value | Purpose | -|:------|:------|:--------| -| **SSE buffer** | 1MB max per event | Prevent buffer overflow | -| **Content buffer** | 10MB max per block | Limit thinking/text blocks | -| **Content blocks** | 100 max per message | Prevent DoS attacks | -| **Request timeout** | 120s | Both streaming and buffered | - -
- -
-

Debugging

- -
- -**Enable verbose logging**: ```bash -ccs glmt --verbose "your prompt" +# Terminal 1: Planning (Claude Pro) +ccs work "design the authentication system" + +# Terminal 2: Execution (GLM - cost optimized) +ccs glm "implement the user service from the plan" + +# Terminal 3: Review (Gemini) +ccs gemini "review the implementation for security issues" ``` -**Enable debug file logging**: +### Multi-Account Claude + +Create isolated Claude instances for work/personal separation: + ```bash -export CCS_DEBUG_LOG=1 -ccs glmt --verbose "your prompt" -# Logs: ~/.ccs/logs/ +ccs auth create work + +# Run concurrently in separate terminals +ccs work "implement feature" # Terminal 1 +ccs "review code" # Terminal 2 (personal account) ``` -**GLMT debugging**: -```bash -# Verbose logging shows streaming status and reasoning details -ccs glmt --verbose "test" -``` - -**Check reasoning content**: -```bash -cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content' -``` - -**Troubleshooting**: -- **If absent**: Z.AI API issue (verify key, account status) -- **If present**: Transformation issue (check `response-anthropic.json`) - -
-
## Maintenance ### Health Check -Run diagnostics to verify your CCS installation: - ```bash ccs doctor ``` -**Checks performed**: -- ✓ Claude CLI availability -- ✓ Configuration files (config.json, profiles) -- ✓ CCS symlinks to ~/.claude/ -- ✓ Delegation system -- ✓ File permissions +Verifies: Claude CLI, config files, symlinks, permissions. -**Output**: -``` -[?] Checking Claude CLI... [OK] -[?] Checking ~/.ccs/ directory... [OK] -[?] Checking config.json... [OK] -[?] Checking CCS symlinks... [OK] -... -Status: Installation healthy -``` - -### Updating CCS +### Update ```bash -# Update to latest stable version -ccs update - -# Force reinstall (fix corrupted installation) -ccs update --force - -# Install beta/dev channel (unstable, for testing) -ccs update --beta - -# Force reinstall from dev channel -ccs update --force --beta +ccs update # Update to latest +ccs update --force # Force reinstall +ccs update --beta # Install dev channel ``` -**Note:** `--beta` installs from the `@dev` npm tag, which contains unreleased features. Not recommended for production use. - -### Update CCS Items - -If you modify CCS items or need to re-install symlinks: +### Sync Shared Items ```bash ccs sync ``` -**What it does**: -- Re-creates selective symlinks from `~/.ccs/.claude/` to `~/.claude/` -- Backs up existing files before replacing -- Safe to run multiple times (idempotent) - -**When to use**: -- After manual modifications to ~/.claude/ -- If `ccs doctor` reports symlink issues -- After upgrading CCS to a new version +Re-creates symlinks for shared commands, skills, and settings.
-### Troubleshooting +## Configuration -#### Broken Installation +CCS auto-creates config on install. Dashboard is the recommended way to manage settings. -If CCS is corrupted or behaving unexpectedly: +**Config location**: `~/.ccs/config.yaml` + +
+Custom Claude CLI path + +If Claude CLI is installed in a non-standard location: ```bash -# Force reinstall to fix -ccs update --force +export CCS_CLAUDE_PATH="/path/to/claude" # Unix +$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe" # Windows ``` -If that doesn't work, try manual reinstall: +
-```bash -npm install -g @kaitranntt/ccs@latest --force -``` +
+Windows symlink support -#### Beta Testing Issues +Enable Developer Mode for true symlinks: -If you're on the dev channel and experiencing issues: +1. **Settings** → **Privacy & Security** → **For developers** +2. Enable **Developer Mode** +3. Reinstall: `npm install -g @kaitranntt/ccs` -```bash -# Return to stable channel -ccs update -``` +Without Developer Mode, CCS falls back to copying directories. -#### Common Issues +
-- **Update fails**: Check network connection and try `ccs update --force` -- **Beta not working**: Use `ccs update` to return to stable version -- **Direct install error**: Beta channel requires npm installation +
-For detailed troubleshooting, see [Troubleshooting Guide](./docs/en/troubleshooting.md). +## Documentation + +| Topic | Link | +|-------|------| +| Installation | [docs.ccs.kaitran.ca/getting-started/installation](https://docs.ccs.kaitran.ca/getting-started/installation) | +| Configuration | [docs.ccs.kaitran.ca/getting-started/configuration](https://docs.ccs.kaitran.ca/getting-started/configuration) | +| OAuth Providers | [docs.ccs.kaitran.ca/providers/oauth-providers](https://docs.ccs.kaitran.ca/providers/oauth-providers) | +| Multi-Account Claude | [docs.ccs.kaitran.ca/providers/claude-accounts](https://docs.ccs.kaitran.ca/providers/claude-accounts) | +| API Profiles | [docs.ccs.kaitran.ca/providers/api-profiles](https://docs.ccs.kaitran.ca/providers/api-profiles) | +| CLI Reference | [docs.ccs.kaitran.ca/reference/cli-commands](https://docs.ccs.kaitran.ca/reference/cli-commands) | +| Architecture | [docs.ccs.kaitran.ca/reference/architecture](https://docs.ccs.kaitran.ca/reference/architecture) | +| Troubleshooting | [docs.ccs.kaitran.ca/reference/troubleshooting](https://docs.ccs.kaitran.ca/reference/troubleshooting) |
## Uninstall -### npm (Recommended) - ```bash npm uninstall -g @kaitranntt/ccs ```
-Alternative Package Managers - -
+Alternative package managers ```bash -# yarn yarn global remove @kaitranntt/ccs - -# pnpm pnpm remove -g @kaitranntt/ccs - -# bun bun remove -g @kaitranntt/ccs ```
-
-Legacy Uninstallers (for native installs) -
-```bash -# macOS / Linux -curl -fsSL ccs.kaitran.ca/uninstall | bash - -# Windows PowerShell -irm ccs.kaitran.ca/uninstall | iex -``` - -
- -
- -## 🎯 Philosophy +## Philosophy - **YAGNI**: No features "just in case" -- **KISS**: Simple bash, no complexity +- **KISS**: Simple, focused implementation - **DRY**: One source of truth (config) -## 📖 Documentation +
-**Complete documentation in [docs/](./docs/)**: -- [Installation Guide](./docs/en/installation.md) -- [Configuration](./docs/en/configuration.md) -- [Usage Examples](./docs/en/usage.md) -- [System Architecture](./docs/system-architecture.md) -- [GLMT Control Mechanisms](./docs/glmt-controls.md) -- [Troubleshooting](./docs/en/troubleshooting.md) -- [Contributing](./CONTRIBUTING.md) +## Contributing -## 🤝 Contributing - -We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details. - - -## Star History - -
- -Star History Chart - -
+See [CONTRIBUTING.md](./CONTRIBUTING.md). +
## License -CCS is licensed under the [MIT License](LICENSE). +MIT License - see [LICENSE](LICENSE).
-**Made with ❤️ for developers who hit rate limits too often** +--- -[⭐ Star this repo](https://github.com/kaitranntt/ccs) | [🐛 Report issues](https://github.com/kaitranntt/ccs/issues) | [📖 Read docs](./docs/en/) +**[ccs.kaitran.ca](https://ccs.kaitran.ca)** | [Report Issues](https://github.com/kaitranntt/ccs/issues) | [Star on GitHub](https://github.com/kaitranntt/ccs)
diff --git a/VERSION b/VERSION index ad95545a..1f6ad15d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -5.17.0 +5.17.0-dev.7 diff --git a/docs/assets/ccs-logo-medium.png b/assets/ccs-logo-medium.png similarity index 100% rename from docs/assets/ccs-logo-medium.png rename to assets/ccs-logo-medium.png diff --git a/docs/assets/ccs-logo-zoomed-web.png b/assets/ccs-logo-zoomed-web.png similarity index 100% rename from docs/assets/ccs-logo-zoomed-web.png rename to assets/ccs-logo-zoomed-web.png diff --git a/assets/screenshots/analytics-light.png b/assets/screenshots/analytics-light.png new file mode 100644 index 00000000..3ab3f969 Binary files /dev/null and b/assets/screenshots/analytics-light.png differ diff --git a/assets/screenshots/analytics.png b/assets/screenshots/analytics.png new file mode 100644 index 00000000..34bd1563 Binary files /dev/null and b/assets/screenshots/analytics.png differ diff --git a/assets/screenshots/api_profiles.png b/assets/screenshots/api_profiles.png new file mode 100644 index 00000000..b6243bc1 Binary files /dev/null and b/assets/screenshots/api_profiles.png differ diff --git a/assets/screenshots/cliproxy.png b/assets/screenshots/cliproxy.png new file mode 100644 index 00000000..a292e6a0 Binary files /dev/null and b/assets/screenshots/cliproxy.png differ diff --git a/docs/ccs-delegation-diagrams.md b/docs/ccs-delegation-diagrams.md deleted file mode 100644 index 0cf8df2f..00000000 --- a/docs/ccs-delegation-diagrams.md +++ /dev/null @@ -1,492 +0,0 @@ -# CCS Delegation Workflow Diagrams - -Visual guide to understanding how CCS delegation works internally. - ---- - -## Overview Architecture - -``` -┌─────────────────────────────────────────────────────────────┐ -│ CCS Architecture │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ User Input │ -│ │ │ -│ ├─── ccs glm → Normal Profile Execution │ -│ │ │ -│ └─── ccs glm -p "task" → Delegation Flow ⚡ │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - ---- - -## Execution Flow Comparison - -### Normal Execution (Without -p) -``` -User: ccs glm - │ - ├─→ bin/ccs.js (main entry) - │ │ - │ ├─→ Profile Detection: "glm" - │ │ - │ └─→ execClaude() - │ │ - │ └─→ spawn("claude", ["--settings", "~/.ccs/glm.settings"]) - │ │ - │ └─→ Claude CLI Interactive Session - │ │ - │ └─→ Direct User Interaction -``` - -### Delegation Execution (With -p) -``` -User: ccs glm -p "add tests for UserService" - │ - ├─→ bin/ccs.js (main entry) - │ │ - │ ├─→ -p Flag Detected! 🎯 - │ │ - │ └─→ DelegationHandler.route(args) - │ │ - │ ├─→ Parse args - │ │ ├─ profile: "glm" - │ │ ├─ prompt: "add tests for UserService" - │ │ └─ options: { outputFormat: "stream-json", timeout: 600000 } - │ │ - │ ├─→ Validate profile (DelegationValidator) - │ │ - │ └─→ HeadlessExecutor.execute("glm", prompt, options) - │ │ - │ ├─→ spawn("claude", [ - │ │ "-p", prompt, - │ │ "--settings", "~/.ccs/glm.settings", - │ │ "--output-format", "stream-json", - │ │ "--permission-mode", "acceptEdits" - │ │ ]) - │ │ - │ ├─→ Parse stream-JSON output (jsonl format) - │ │ {"type":"init","session_id":"abc123"} - │ │ {"type":"assistant","message":{...}} - │ │ {"type":"result","total_cost_usd":0.0042,"num_turns":3} - │ │ - │ ├─→ SessionManager.saveSession() - │ │ └─→ ~/.ccs/delegation-sessions.json - │ │ - │ └─→ ResultFormatter.format(result) - │ │ - │ └─→ ASCII Box Output - │ ╔════════════════════════╗ - │ ║ Session: abc123 ║ - │ ║ Cost: $0.0042 ║ - │ ║ Turns: 3 ║ - │ ╚════════════════════════╝ -``` - ---- - -## Continue Command Flow - -### Multi-Turn Session Workflow -``` -┌─────────────────────────────────────────────────────────────┐ -│ Turn 1: Initial Task │ -└─────────────────────────────────────────────────────────────┘ - -User: ccs glm -p "implement user registration" - │ - └─→ HeadlessExecutor - │ - ├─→ Execute with fresh session - │ - └─→ Save session metadata: - { - "profile": "glm", - "sessionId": "session-001", - "totalCost": 0.0025, - "turns": 2, - "cwd": "/path/to/project", - "lastUpdated": "2025-11-15T18:00:00Z" - } - -┌─────────────────────────────────────────────────────────────┐ -│ Turn 2: Continue Session │ -└─────────────────────────────────────────────────────────────┘ - -User: ccs glm:continue -p "add validation tests" - │ - └─→ DelegationHandler detects ":continue" suffix - │ - ├─→ Extract base profile: "glm" - │ - ├─→ SessionManager.getLastSession("glm") - │ └─→ Returns: { sessionId: "session-001", ... } - │ - └─→ HeadlessExecutor.execute("glm", prompt, { - resumeSession: true, - sessionId: "session-001" ← Resume! - }) - │ - ├─→ spawn("claude", [ - │ "-p", "add validation tests", - │ "--resume", "session-001", ← Continue! - │ "--output-format", "stream-json", - │ "--verbose", - │ ... - │ ]) - │ - └─→ Update session metadata: - { - "sessionId": "session-001", ← Same session - "totalCost": 0.0067, ← Aggregated - "turns": 5, ← Incremented - "lastUpdated": "2025-11-15T18:05:00Z" - } - -┌─────────────────────────────────────────────────────────────┐ -│ Turn 3+: Multiple Continues │ -└─────────────────────────────────────────────────────────────┘ - -User: ccs glm:continue -p "run the tests" - │ - └─→ Same flow, cost keeps aggregating: - { - "totalCost": 0.0089, ← $0.0025 + $0.0042 + $0.0022 - "turns": 7 ← 2 + 3 + 2 - } -``` - ---- - -## Session Management Architecture - -``` -┌───────────────────────────────────────────────────────────────┐ -│ ~/.ccs/delegation-sessions.json │ -├───────────────────────────────────────────────────────────────┤ -│ { │ -│ "glm": { │ -│ "sessionId": "abc123-def456", │ -│ "totalCost": 0.0067, ← Aggregated across turns │ -│ "turns": 5, ← Total turn count │ -│ "cwd": "/home/user/project", ← Working directory │ -│ "lastUpdated": "2025-11-15T18:05:00Z", │ -│ "expiresAt": "2025-12-15T18:05:00Z" ← 30 days │ -│ }, │ -│ "kimi": { │ -│ "sessionId": "xyz789-uvw012", │ -│ "totalCost": 0.0123, │ -│ "turns": 8, │ -│ "cwd": "/home/user/other-project", │ -│ "lastUpdated": "2025-11-14T10:30:00Z", │ -│ "expiresAt": "2025-12-14T10:30:00Z" │ -│ } │ -│ } │ -└───────────────────────────────────────────────────────────────┘ - -Operations: - ├─→ saveSession(profile, metadata) → Write to file - ├─→ getLastSession(profile) → Read from file - ├─→ updateSession(profile, updates) → Merge + write - └─→ cleanupExpired() → Remove old sessions (>30 days) -``` - ---- - -## Decision Flow: When to Delegate - -``` -User Task Request - │ - ├─→ Task Analysis (ccs-delegator agent) - │ │ - │ ├─→ Read ccs-delegation skill - │ │ - │ └─→ Pattern Matching: - │ │ - │ ├─→ Match delegation patterns? - │ │ ├─ "refactor .* to use async/await" ✓ - │ │ ├─ "add tests for .*" ✓ - │ │ ├─ "fix typos in .*" ✓ - │ │ └─ ... - │ │ - │ ├─→ Match anti-patterns? - │ │ ├─ "implement .*" ✗ - │ │ ├─ "optimize .*" ✗ - │ │ └─ "design .*" ✗ - │ │ - │ └─→ Check criteria: - │ ├─ Scope: < 5 files? ✓ - │ ├─ Complexity: Mechanical? ✓ - │ ├─ Ambiguity: Zero decisions? ✓ - │ └─ Context: Patterns exist? ✓ - │ - └─→ Decision: - │ - ├─→ YES → Delegate - │ └─→ ccs glm -p "task" - │ - └─→ NO → Keep in main session - └─→ Handle directly in conversation -``` - ---- - -## Cost Tracking & Token Optimization - -### Traditional Main Session Flow -``` -User: "Add tests for UserService, AuthService, and OrderService" - │ - └─→ Claude in main session: - │ - ├─→ Loads full context (2000+ tokens) - ├─→ Discusses approach with user - ├─→ Implements UserService tests - ├─→ Shows code, waits for approval - ├─→ Implements AuthService tests - ├─→ Shows code, waits for approval - ├─→ Implements OrderService tests - └─→ Total: ~8000 tokens, $0.032 - -Main Session Cost: - Context load: 2000 tokens - Discussion: 1500 tokens - Implementation: 4500 tokens - ──────────────────────────── - Total: 8000 tokens → $0.032 -``` - -### Delegation Flow (Token Optimized) -``` -User: "Add tests for UserService, AuthService, and OrderService" - │ - └─→ ccs-delegator agent: - │ - ├─→ Analyzes: 3 similar tasks → Batch delegate - │ - ├─→ Execute 3 delegations: - │ │ - │ ├─→ ccs glm -p "add tests for UserService" - │ │ └─→ Cost: $0.0015 (500 tokens) - │ │ - │ ├─→ ccs glm -p "add tests for AuthService" - │ │ └─→ Cost: $0.0015 (500 tokens) - │ │ - │ └─→ ccs glm -p "add tests for OrderService" - │ └─→ Cost: $0.0015 (500 tokens) - │ - └─→ Total: ~1500 tokens, $0.0045 - -Delegation Cost: - Task 1 (GLM): 500 tokens → $0.0015 - Task 2 (GLM): 500 tokens → $0.0015 - Task 3 (GLM): 500 tokens → $0.0015 - ──────────────────────────────────────── - Total: 1500 tokens → $0.0045 - -Savings: $0.032 - $0.0045 = $0.0275 (86% reduction) ⚡ -``` - ---- - -## Integration Points Summary - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Integration Points │ -├─────────────────────────────────────────────────────────────┤ -│ │ -│ 1. bin/ccs.js (lines 501-507) │ -│ └─→ Detects -p flag → Routes to DelegationHandler │ -│ │ -│ 2. bin/delegation/delegation-handler.js (NEW) │ -│ └─→ Orchestrates delegation flow │ -│ │ -│ 3. bin/delegation/headless-executor.js (EXISTING) │ -│ └─→ Spawns claude -p with enhanced flags │ -│ │ -│ 4. bin/delegation/session-manager.js (EXISTING) │ -│ └─→ Persists session metadata │ -│ │ -│ 5. bin/delegation/result-formatter.js (EXISTING) │ -│ └─→ Formats ASCII box output │ -│ │ -│ 6. .claude/commands/ccs/glm.md │ -│ └─→ Executes: ccs glm -p "$ARGUMENTS" │ -│ │ -│ 7. .claude/agents/ccs-delegator.md │ -│ └─→ Proactive delegation via Task tool │ -│ │ -│ 8. .claude/skills/ccs-delegation/ │ -│ └─→ AI decision framework + technical docs │ -│ │ -└─────────────────────────────────────────────────────────────┘ -``` - ---- - -## Effectiveness Metrics - -### Feature Coverage - -``` -✅ Stream-JSON Output Parsing - └─→ Real-time jsonl format, extracts: session_id, cost, turns, errors - -✅ Real-Time Tool Visibility - └─→ Shows: [Tool] Bash: npm install, [Tool] Write: index.html - -✅ Session Management - └─→ Persists to: ~/.ccs/delegation-sessions.json - -✅ Multi-Turn Support - └─→ Resume via: ccs glm:continue -p "task" - -✅ Cost Tracking - └─→ Aggregates across turns, displays in USD - -✅ Time-Based Limits - └─→ Default: 10min timeout with graceful SIGTERM termination - -✅ Permission Mode - └─→ Default: acceptEdits (auto-approve file ops) - -✅ Signal Handling - └─→ Kills child process on Ctrl+C/Esc (no orphans) - -✅ Slash Command Preservation - └─→ Detects /cook, /plan in prompts, keeps at start - -✅ Formatted Output - └─→ ASCII box with metadata -``` - -### Performance Impact - -``` -Metric Before After Improvement -──────────────────────────────────────────────────────────── -Session overhead 2000 tok 500 tok 75% ↓ -Cost per simple task $0.008 $0.0015 81% ↓ -Time to result ~30s ~10s 67% ↓ -Context pollution High Zero 100% ↓ -Batch 3 tasks $0.024 $0.0045 81% ↓ -``` - -### User Experience Flow - -``` -BEFORE (Manual): - User: "Add tests for UserService" - Claude: "I'll add tests for UserService..." - [Generates code in main session, uses context] - Claude: "Here are the tests..." - User: "Now add tests for AuthService" - Claude: "I'll add tests for AuthService..." - [Repeats, accumulates context] - -AFTER (Delegated): - User: "Add tests for UserService, AuthService, OrderService" - Claude: "I'll delegate these similar tasks to GLM for token optimization" - [Batch delegates via ccs-delegator agent] - ccs glm -p "add tests for UserService" → $0.0015 - ccs glm -p "add tests for AuthService" → $0.0015 - ccs glm -p "add tests for OrderService" → $0.0015 - Claude: "All tests added. Total cost: $0.0045" - [Main session context stays clean] -``` - ---- - -## Architecture Benefits - -### 1. Separation of Concerns -``` -bin/ccs.js → Routing only (6 lines added) -delegation-handler.js → Orchestration logic -headless-executor.js → Execution engine -session-manager.js → State persistence -result-formatter.js → Output formatting -``` - -### 2. Progressive Disclosure -``` -SKILL.md → Entry point (56 lines) - └─→ headless-workflow.md → Technical details (155 lines) - └─→ delegation-guidelines.md → AI decision rules (100 lines) -``` - -### 3. Zero Breaking Changes -``` -ccs glm → Works as before (normal profile) -ccs glm -p "task" → NEW: Enhanced delegation -ccs glm:continue -p → NEW: Multi-turn support -``` - -### 4. Token Efficiency -``` -Main session: Full context loaded for every task -Delegation: Isolated execution, no context pollution -Savings: 81% cost reduction on simple tasks -``` - ---- - -## Future Enhancements - -### Potential Improvements -``` -1. Cost Alerts - └─→ Warn if delegation > $1.00 - -2. Session Analytics - └─→ Track delegation patterns, identify high-cost tasks - -3. Batch Optimization - └─→ Auto-detect batchable tasks: "add tests for all *.service.js" - -4. Profile Auto-Selection - └─→ Agent chooses GLM vs Kimi based on file count - -5. GLMT Integration - └─→ Complex reasoning tasks via glmt proxy + delegation -``` - ---- - -## Troubleshooting Flows - -### Common Issues - -``` -Issue: "No previous session found for glm" - │ - └─→ Cause: Using :continue without initial session - │ - └─→ Solution: Run initial task first - ccs glm -p "initial task" - ccs glm:continue -p "follow up" - -Issue: "Profile not configured for delegation" - │ - └─→ Cause: Missing ~/.ccs/glm.settings.json - │ - └─→ Solution: Run ccs doctor - ccs doctor - → Shows configuration issues - -Issue: "Missing prompt after -p flag" - │ - └─→ Cause: No argument after -p - │ - └─→ Solution: Provide prompt in quotes - ccs glm -p "task description" -``` - ---- - -**Last Updated**: 2025-11-16 -**Related**: `SKILL.md`, `headless-workflow.md`, `delegation-guidelines.md` diff --git a/docs/code-standards.md b/docs/code-standards.md deleted file mode 100644 index 509000e7..00000000 --- a/docs/code-standards.md +++ /dev/null @@ -1,1515 +0,0 @@ -# CCS Code Standards - -## Overview - -This document defines the coding standards and principles for the CCS (Claude Code Switch) project. The project uses TypeScript throughout, React 19 for the UI dashboard, Vite for fast builds, and Bun as the primary package manager. Following these standards ensures consistency, maintainability, and quality across the entire codebase. - -## Core Principles - -### Design Philosophy - -**YAGNI** (You Aren't Gonna Need It) -- Only implement features that are immediately needed -- Avoid code "just in case" scenarios -- Keep the codebase minimal and focused - -**KISS** (Keep It Simple, Stupid) -- Prefer simple solutions over complex ones -- Avoid unnecessary abstractions -- Use straightforward, readable code - -**DRY** (Don't Repeat Yourself) -- Eliminate duplicate code through consolidation -- Create reusable functions for common operations -- Maintain single sources of truth - -### Simplification Standards - -The recent codebase simplification (35% reduction from 1,315 to 855 lines) established these standards: - -1. **Consolidate duplicate logic**: Unified spawn logic in `execClaude()` function -2. **Remove security theater**: Eliminate unnecessary validation functions -3. **Simplify error handling**: Direct console.error instead of complex formatting -4. **Deduplicate platform checks**: Centralize platform-specific logic - -## TypeScript Standards - -### Code Style - -#### File Structure -```typescript -// Dependencies -import { spawn } from 'child_process'; -import path from 'path'; -import { error } from './helpers'; - -// Constants -const CCS_VERSION = require('../package.json').version; - -// Functions (grouped by responsibility) -function mainFunction(): void { - // Implementation -} - -// Main execution -function main(): void { - // Implementation -} - -// Run main -main(); -``` - -#### Function Declarations -- Use `function` declarations for named functions -- Use arrow functions only for anonymous functions or callbacks -- Group related functions together -- Place main execution logic at the bottom - -```javascript -// Good -function handleVersionCommand() { - console.log(`CCS version ${CCS_VERSION}`); - process.exit(0); -} - -// Acceptable for callbacks -fs.readFile(file, (err, data) => { - if (err) return error(err.message); - // Process data -}); -``` - -#### Variable Declarations -- Use `const` for variables that won't be reassigned -- Use `let` only when reassignment is necessary -- Declare variables as close to usage as possible -- Avoid `var` entirely - -```javascript -// Good -const configPath = getConfigPath(); -const claudeCli = detectClaudeCli(); - -// Avoid -let configPath; -configPath = getConfigPath(); -``` - -### Error Handling Standards - -#### Simple Error Reporting -```javascript -// Preferred - Simple and direct -function error(message) { - console.error(`ERROR: ${message}`); - process.exit(1); -} - -// Usage -if (!fs.existsSync(configPath)) { - error(`Config file not found: ${configPath}`); -} -``` - -#### Avoid Complex Error Formatting -```javascript -// Avoid - Complex box-drawing formatting -function showErrorBox(message) { - console.log('╔══════════════════════════════════════╗'); - console.log('║ ERROR ║'); - console.log(`║ ${message.padEnd(34)} ║`); - console.log('╚══════════════════════════════════════╝'); -} -``` - -#### Early Validation Pattern -```javascript -function getSettingsPath(profile) { - // Validate early and exit fast - const config = readConfig(); - const settingsPath = config.profiles[profile]; - - if (!settingsPath) { - error(`Profile '${profile}' not found. Available: ${Object.keys(config.profiles).join(', ')}`); - } - - return settingsPath; -} -``` - -### Process Management Standards - -#### Unified Spawn Logic -```javascript -// Consolidated spawn function - single source of truth -function execClaude(claudeCli, args) { - const child = spawn(claudeCli, args, { - stdio: 'inherit', - windowsHide: true - }); - - child.on('exit', (code, signal) => { - if (signal) process.kill(process.pid, signal); - else process.exit(code || 0); - }); - - child.on('error', () => { - showClaudeNotFoundError(); - process.exit(1); - }); -} -``` - -#### Security Best Practices -- Always use arrays with `spawn()` to prevent shell injection -- Never construct shell command strings with user input -- Validate inputs before using them in file operations - -```javascript -// Good - Safe with array arguments -spawn(claudeCli, ['--settings', settingsPath, ...args]); - -// Avoid - Unsafe string concatenation -spawn('sh', ['-c', `claude --settings ${settingsPath} ${args.join(' ')}`]); -``` - -### Module Organization Standards (Phase 02 Complete - 2025-11-27) - -#### Subsystem Directory Structure -``` -src/ -├── ccs.ts # Main entry point (593 lines, 44.6% reduction) -├── commands/ # Modular command handlers (Phase 02 NEW) -│ ├── version-command.ts # Version display functionality -│ ├── help-command.ts # Help system -│ ├── install-command.ts # Installation workflows -│ ├── doctor-command.ts # System diagnostics -│ ├── sync-command.ts # Configuration synchronization -│ └── shell-completion-command.ts # Shell completion management -├── auth/ # Auth system modules -├── delegation/ # Delegation system modules -├── glmt/ # GLMT system modules -├── management/ # Management system modules -├── utils/ # Utility modules (expanded in Phase 02) -│ ├── shell-executor.ts # Cross-platform execution (NEW) -│ └── package-manager-detector.ts # Package manager detection (NEW) -└── types/ # TypeScript type definitions -``` - -#### Module Dependencies -```javascript -// Group imports by type -// Node.js built-ins -const fs = require('fs'); -const path = require('path'); -const { spawn } = require('child_process'); - -// Local modules (relative paths from current subsystem) -const { error } = require('../utils/helpers'); -const { detectClaudeCli } = require('../utils/claude-detector'); - -// Subsystem-specific modules -const DelegationHandler = require('./delegation-handler'); -const SessionManager = require('./session-manager'); -``` - -#### Exports Pattern -```javascript -// Clear, named exports -module.exports = { - getConfigPath, - readConfig, - getSettingsPath -}; - -// Class exports (delegation, management modules) -class DelegationHandler { - constructor() { - // Implementation - } -} -module.exports = DelegationHandler; - -// Avoid exports with mixed responsibilities -module.exports = { - getConfigPath, - someUtilityFunction, - anotherUnrelatedFunction -}; -``` - -#### Subsystem Naming Conventions (v4.x) -- **handler**: Routing and orchestration (e.g., `delegation-handler.js`) -- **executor**: Execution logic (e.g., `headless-executor.js`) -- **manager**: State management (e.g., `session-manager.js`, `instance-manager.js`) -- **validator**: Validation logic (e.g., `delegation-validator.js`) -- **formatter**: Output formatting (e.g., `result-formatter.js`) -- **parser**: Parsing logic (e.g., `settings-parser.js`, `sse-parser.js`) - -## Modular Command Architecture Standards (Phase 02, 2025-11-27) - -### Overview - -Phase 02 introduced modular command architecture that separates command handling logic from the main orchestrator. This enhances maintainability, testability, and development workflow efficiency. - -### Command Handler Pattern - -**Structure Requirements**: -- Each command must be implemented in its own dedicated file in `src/commands/` -- Commands must follow consistent interface pattern for type safety -- Single responsibility principle - each module handles one command only - -**Interface Pattern**: -```typescript -interface CommandHandler { - handle(args: string[]): Promise; - requiresProfile?: boolean; - description?: string; -} - -// Example: Update command options interface -interface UpdateOptions { - force?: boolean; - beta?: boolean; -} -``` - -**Implementation Example**: -```typescript -export class VersionCommand implements CommandHandler { - async handle(args: string[]): Promise { - // Command implementation - } - - get description(): string { - return "Display version information"; - } -} -``` - -### Command Handler Standards - -#### File Organization -- **Location**: `src/commands/-command.ts` -- **Naming**: kebab-case with `-command.ts` suffix -- **Export**: Default export of command class - -#### Function Size Limits -- **Command handlers**: Maximum 200 lines (enforces focused responsibility) -- **Helper functions**: Maximum 50 lines within command modules -- **Type definitions**: Separate files for complex types (>5 interfaces) - -#### Import Patterns -```typescript -// Preferred: Specific imports -import { ConfigManager } from '../utils/config-manager.js'; -import { Logger } from '../utils/logger.js'; - -// Avoid: Wildcard imports -import * as Utils from '../utils/index.js'; -``` - -### Module Dependencies Standards - -#### Dependency Direction -``` -Main Entry Point (src/ccs.ts) - ↓ -Command Handlers (src/commands/) - ↓ -Utility Modules (src/utils/) -``` - -**Rules**: -- Command handlers may import from utils, types, and management modules -- Command handlers MUST NOT import from other command handlers -- Utility modules may import from other utilities and types -- No circular dependencies allowed - -#### Import Organization -```typescript -// 1. Node.js built-ins -import { spawn } from 'child_process'; -import { readFile } from 'fs/promises'; - -// 2. External dependencies -import ora from 'ora'; - -// 3. Internal modules (sorted alphabetically) -import { ConfigManager } from '../utils/config-manager.js'; -import { Logger } from '../utils/logger.js'; -import { Types } from '../types/index.js'; -``` - -### Error Handling in Command Modules - -#### Standardized Error Pattern -```typescript -export class CommandError extends Error { - constructor( - message: string, - public readonly code: string, - public readonly exitCode: number = 1 - ) { - super(message); - this.name = 'CommandError'; - } -} - -// Usage -try { - await this.executeCommand(); -} catch (error) { - if (error instanceof CommandError) { - console.error(`[X] ${error.message}`); - process.exit(error.exitCode); - } - throw error; -} -``` - -#### Validation Requirements -- **Input validation**: Must validate arguments before processing -- **State validation**: Check required dependencies exist -- **Permission validation**: Verify file system access where needed - -### Testing Standards for Command Modules - -#### Unit Test Structure -```typescript -import { assert } from 'chai'; -import { VersionCommand } from '../src/commands/version-command.js'; - -describe('VersionCommand', () => { - let command: VersionCommand; - - beforeEach(() => { - command = new VersionCommand(); - }); - - describe('handle()', () => { - it('should display version information', async () => { - // Test implementation - }); - }); -}); -``` - -#### Mock Requirements -- **File system**: Mock all file operations -- **External processes**: Mock spawn/exec calls -- **Configuration**: Use test fixtures for config data - -### New Utility Module Standards - -#### Shell Executor (`src/utils/shell-executor.ts`) -- **Cross-platform**: Must work on Windows, macOS, Linux -- **Process management**: Proper cleanup and signal handling -- **Error handling**: Standardized error reporting - -#### Package Manager Detector (`src/utils/package-manager-detector.ts`) -- **Detection order**: npm → yarn → pnpm → bun (priority based on availability) -- **Caching**: Cache detection results for performance -- **Fallback**: Graceful degradation when managers unavailable - -### Integration with Main Orchestrator - -#### Command Registration Pattern -```typescript -// In src/ccs.ts -import { VersionCommand } from './commands/version-command.js'; -import { HelpCommand } from './commands/help-command.js'; - -const commandHandlers = { - '--version': new VersionCommand(), - '--help': new HelpCommand(), - // ... other commands -}; -``` - -#### Routing Logic -```typescript -// Command detection and routing -for (const [flag, handler] of Object.entries(commandHandlers)) { - if (args.includes(flag)) { - await handler.handle(args); - return; - } -} -``` - -## React 19 UI Standards - -### Component Architecture - -#### Functional Components with Hooks -```typescript -import React, { useState, useEffect } from 'react'; -import { cn } from '@/lib/utils'; - -interface MyComponentProps { - title: string; - onAction?: () => void; - className?: string; -} - -export function MyComponent({ title, onAction, className }: MyComponentProps): JSX.Element { - const [isLoading, setIsLoading] = useState(false); - - useEffect(() => { - // Side effects - }, []); - - return ( -
-

{title}

- {isLoading ? ( -
Loading...
- ) : ( - - )} -
- ); -} -``` - -### UI Library Standards (shadcn/ui) - -#### Component Usage -- Use shadcn/ui components as base building blocks -- Customize with Tailwind CSS classes -- Maintain consistent design tokens -- Support dark mode out of the box - -```typescript -import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; - -export function SettingsPage(): JSX.Element { - return ( - - - Settings - - - - - - ); -} -``` - -### State Management - -#### TanStack Query for Server State -```typescript -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; -import { getProfiles, updateProfile } from '@/lib/api'; - -export function useProfiles() { - return useQuery({ - queryKey: ['profiles'], - queryFn: getProfiles, - staleTime: 5 * 60 * 1000, // 5 minutes - }); -} - -export function useUpdateProfile() { - const queryClient = useQueryClient(); - - return useMutation({ - mutationFn: updateProfile, - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['profiles'] }); - }, - }); -} -``` - -#### Local State with useState -- Use useState for simple component state -- Use useReducer for complex state logic -- Consider Zustand for global state (if needed) - -### Vite Configuration - -#### Build Settings (vite.config.ts) -```typescript -import { defineConfig } from 'vite'; -import react from '@vitejs/plugin-react'; -import path from 'path'; - -export default defineConfig({ - plugins: [react()], - resolve: { - alias: { - '@': path.resolve(__dirname, './src'), - }, - }, - build: { - outDir: 'dist', - sourcemap: true, - rollupOptions: { - output: { - manualChunks: { - vendor: ['react', 'react-dom'], - ui: ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'], - }, - }, - }, - }, - server: { - port: 3000, - proxy: { - '/api': { - target: 'http://localhost:8080', - changeOrigin: true, - }, - }, - }, -}); -``` - -### Performance Guidelines - -#### Code Splitting -- Lazy load routes with React.lazy() -- Dynamic imports for heavy components -- Use Suspense boundaries for loading states - -```typescript -import { lazy, Suspense } from 'react'; - -const SettingsPage = lazy(() => import('@/pages/settings')); - -function App() { - return ( - Loading...}> - - - ); -} -``` - -#### Optimization -- Use React.memo() for expensive components -- Implement virtual scrolling for long lists -- Optimize re-renders with useMemo() and useCallback() - -### WebSocket Integration - -#### Real-time Updates -```typescript -import { useEffect, useState } from 'react'; - -export function useWebSocket(url: string) { - const [data, setData] = useState(null); - const [isConnected, setIsConnected] = useState(false); - - useEffect(() => { - const ws = new WebSocket(url); - - ws.onopen = () => setIsConnected(true); - ws.onclose = () => setIsConnected(false); - ws.onmessage = (event) => setData(JSON.parse(event.data)); - - return () => ws.close(); - }, [url]); - - return { data, isConnected }; -} -``` - -### Testing Standards - -#### Vitest Configuration -```typescript -import { defineConfig } from 'vitest/config'; -import react from '@vitejs/plugin-react'; - -export default defineConfig({ - plugins: [react()], - test: { - environment: 'jsdom', - setupFiles: ['./src/test/setup.ts'], - }, -}); -``` - -#### Component Testing -```typescript -import { render, screen, fireEvent } from '@testing-library/react'; -import { Button } from '@/components/ui/button'; - -describe('Button', () => { - it('renders correctly', () => { - render(); - expect(screen.getByRole('button')).toBeInTheDocument(); - }); - - it('handles click events', () => { - const handleClick = vi.fn(); - render(); - - fireEvent.click(screen.getByRole('button')); - expect(handleClick).toHaveBeenCalledTimes(1); - }); -}); -``` - -### Component Interface Patterns (Phase 1) - -#### Standard Props Interface -```typescript -// Required props first, optional props last -interface ComponentProps { - // Required data - data: DataType; - // Optional boolean flags - isLoading?: boolean; - disabled?: boolean; - // Optional handlers - onAction?: () => void; - onChange?: (value: string) => void; - // Optional styling - className?: string; - // Optional children - children?: React.ReactNode; -} -``` - -#### Profile Component Pattern -```typescript -// Example from ProfileCard -interface ProfileCardProps { - profile: { - name: string; - settingsPath: string; - configured: boolean; - isActive?: boolean; - lastUsed?: string; - model?: string; - }; - onSwitch?: () => void; - onConfig?: () => void; - onTest?: () => void; -} - -// Component implementation -export function ProfileCard({ profile, onSwitch, onConfig, onTest }: ProfileCardProps) { - return ( - - -
-
-

{profile.name}

- {profile.isActive && ( - - Active - - )} -
- -
-
-
- ); -} -``` - -#### Mock Data Handling Pattern -```typescript -// Phase 1: Mock data for development -const mockProfiles = profiles.map((profile, index: number) => ({ - ...profile, - configured: profile.configured ?? false, - isActive: index === 0, // First profile is active - lastUsed: index === 0 ? '2 hours ago' : index === 1 ? '1 day ago' : undefined, - model: index === 0 ? 'claude-3.5-sonnet' : index === 1 ? 'claude-3-haiku' : undefined, -})); - -// Clearly mark mock data with TODO comments -// TODO: Replace with real data from API -const mockMetrics = [ - { - title: 'API Cost Saved', - value: '$127.50', - change: 23, - // ... - } -]; -``` - -#### Loading and Error State Pattern -```typescript -// Example from ProfileDeck -if (isLoading) { - return ( -
- {[...Array(6)].map((_, i) => ( -
- -
- ))} -
- ); -} - -if (error) { - return
Failed to load profiles: {error.message}
; -} - -if (!profiles || profiles.length === 0) { - return ( -
- No profiles configured. Create your first profile to get started. -
- ); -} -``` - -## UI System Patterns (Phase 5, v4.5.0+) - -### Central UI Module (src/utils/ui.ts) - -#### Initialization Pattern -```typescript -import { ui } from '../utils/ui'; - -// Initialize UI (call once at startup) -async function main() { - await ui.init(); - // UI functions now available -} -``` - -#### Semantic Color Usage -```typescript -// Apply semantic colors -ui.color('Success!', 'success') // Green bold -ui.color('Error!', 'error') // Red bold -ui.color('Warning!', 'warning') // Yellow -ui.color('Info', 'info') // Cyan -ui.color('Command: ccs', 'command') // Yellow italic -ui.color('/path/to/file', 'path') // Cyan underline -``` - -#### ASCII Status Indicators (NO EMOJIS) -```typescript -// Preferred: ASCII indicators only -ui.ok('Installation complete') // [OK] Installation complete -ui.fail('Build failed') // [X] Build failed -ui.warn('Deprecated feature') // [!] Deprecated feature -ui.info('Checking system') // [i] Checking system - -// NEVER use emoji (violates CLAUDE.md) -// DON'T: console.log('✓ Success') or '❌ Error' -``` - -#### Box & Table Rendering -```typescript -// Styled boxes -ui.box('Content here', { - title: 'Header', - borderColor: '#00ECFA', - padding: 1 -}); - -ui.errorBox('Error message', 'ERROR'); -ui.infoBox('Info content', 'INFO'); - -// Styled tables -ui.table([ - ['Column 1', 'Column 2'], - ['Data 1', 'Data 2'] -], { - head: ['Header 1', 'Header 2'], - style: 'unicode' -}); -``` - -#### Spinner & Progress -```typescript -// Simple spinner (falls back to plain text in non-TTY) -const spin = await ui.spinner('Processing...'); -await doWork(); -spin.succeed('Done!'); - -// Spinner with message update -const spin = await ui.spinner('Loading'); -spin.update('Still loading...'); -spin.succeed('Completed'); -``` - -#### Task Lists (Listr2 Integration - Phase 5) -```typescript -// Create task list with intelligent renderer selection -const ctx = await ui.taskList([ - { - title: 'Install dependencies', - task: async () => { - await installDeps(); - } - }, - { - title: 'Build project', - task: async () => { - await build(); - }, - skip: () => !needsBuild() ? 'Already built' : undefined - } -], { - concurrent: false // Set true for parallel execution -}); - -// Renderer selection (automatic): -// - TTY: Default renderer with subtask hierarchy -// - Non-TTY: Simple renderer (plain text) -// - CI environment: Simple renderer -// - Claude Code context: Fallback spinner-based -``` - -#### Context Detection -```typescript -// Check if running in interactive TTY -if (ui.isInteractive()) { - // Can use full spinner/box features -} - -// Check if running inside Claude Code tool -if (ui.isClaudeCodeContext()) { - // May need fallback rendering -} -``` - -### UI Compliance Rules (STRICT) - -**Mandatory**: -- ALWAYS call `await ui.init()` before using any UI functions -- ASCII status indicators ONLY: [OK], [X], [!], [i] - NO EMOJIS -- Respect NO_COLOR and FORCE_COLOR environment variables -- Use semantic colors (success, error, warning, info, dim, primary, secondary, command, path) - -**Patterns**: -- Status messages: `ui.ok()`, `ui.fail()`, `ui.warn()`, `ui.info()` -- Styled output: `ui.box()`, `ui.table()`, `ui.spinner()` -- Progress: Use `ui.taskList()` for multi-step operations (Phase 5) -- Fallback-first: Always test in non-TTY (pipe) mode - -**Testing**: -```bash -# Test in non-TTY (pipes/CI) -ccs doctor | cat # Forces plain text output -NO_COLOR=1 ccs doctor # Disables colors -``` - -## Delegation System Patterns (v4.0+, Phase 5 Enhanced) - -### Stream-JSON Parsing - -#### Tool Extraction Pattern -```javascript -// Real-time extraction of tool calls from stream-JSON output -function parseToolLine(line) { - const toolRegex = /\[Tool\]\s+(\w+)\((.*?)\)/; - const match = line.match(toolRegex); - - if (match) { - const [_, toolName, params] = match; - return { toolName, params }; - } - - return null; -} - -// Usage in stream parser -childProcess.stdout.on('data', (chunk) => { - const lines = chunk.toString().split('\n'); - for (const line of lines) { - const tool = parseToolLine(line); - if (tool) { - console.log(` ${formatToolName(tool.toolName)} ${formatParams(tool.params)}`); - } - } -}); -``` - -### Session Management Pattern - -#### Session Persistence -```javascript -// Save session for continuation -class SessionManager { - saveSession(profile, sessionId, prompt) { - const sessionData = { - profile, - sessionId, - timestamp: new Date().toISOString(), - prompt - }; - - const sessionPath = path.join(DELEGATION_SESSIONS_DIR, `${profile}-last.json`); - fs.writeFileSync(sessionPath, JSON.stringify(sessionData, null, 2)); - } - - loadSession(profile) { - const sessionPath = path.join(DELEGATION_SESSIONS_DIR, `${profile}-last.json`); - - if (!fs.existsSync(sessionPath)) { - return null; - } - - return JSON.parse(fs.readFileSync(sessionPath, 'utf8')); - } -} -``` - -### Headless Execution Pattern - -#### Spawning with Stream-JSON -```javascript -// Execute Claude CLI in headless mode with stream-JSON output -function executeHeadless(claudeCli, profile, prompt, sessionId = null) { - const args = [ - '--output-format', 'stream-json', - '--verbose', - '-p', prompt - ]; - - if (sessionId) { - args.push('--session-id', sessionId); - } - - const child = spawn(claudeCli, args, { - stdio: ['inherit', 'pipe', 'pipe'], - windowsHide: true - }); - - // Parse stdout for tools - child.stdout.on('data', (chunk) => { - parseStreamOutput(chunk.toString()); - }); - - // Handle Ctrl+C - process.on('SIGINT', () => { - child.kill('SIGTERM'); - process.exit(130); - }); - - return child; -} -``` - -### Result Formatting Pattern (Phase 5 Enhanced - Async) - -#### Async Result Formatter with UI Integration -```typescript -// result-formatter.ts - Phase 5 now fully async -import { ui } from '../utils/ui'; - -class ResultFormatter { - // Initialize UI and format result - static async format(result: ExecutionResult): Promise { - await ui.init(); // Phase 5: Initialize UI layer - - // Build styled output - let output = ''; - - // Header box with status indicator - const modelName = this.getModelDisplayName(result.profile); - const headerIcon = result.success ? '[i]' : '[X]'; - output += ui.box(`${headerIcon} Delegated to ${modelName}`, { - borderStyle: 'round', - padding: 0, - }); - output += '\n\n'; - - // Info table with styled columns - output += this.formatInfoTable(result); - - // Error details if needed - if (result.errors && result.errors.length > 0) { - output += '\n' + ui.errorBox('Execution Errors', 'ERRORS'); - } - - return output; - } - - // Phase 5: Table formatting - private static formatInfoTable(result: ExecutionResult): string { - const rows = [ - ['Working Directory', result.cwd], - ['Model', this.getModelDisplayName(result.profile)], - ['Duration', `${(result.duration / 1000).toFixed(2)}s`], - ['Exit Code', result.exitCode === 0 ? '[OK]' : '[X]'], - ]; - - if (result.totalCost) { - rows.push(['Total Cost', `$${result.totalCost.toFixed(4)}`]); - } - - return ui.table(rows, { - style: 'unicode', - wordWrap: true - }); - } -} - -// Usage in delegation-handler.ts -const formatted = await ResultFormatter.format(result); // Phase 5: Now async! -console.log(formatted); -``` - -#### Cost and Duration Extraction (Unchanged from v4.0) -```typescript -// Extract cost and duration from stream-JSON output -interface ExecutionStats { - cost: number | null; - duration: number | null; - exitCode: number; -} - -function parseExecutionStats(output: string): ExecutionStats { - const costRegex = /Cost:\s+\$(\d+\.\d+)/; - const durationRegex = /Duration:\s+(\d+)ms/; - - const costMatch = output.match(costRegex); - const durationMatch = output.match(durationRegex); - - return { - cost: costMatch ? parseFloat(costMatch[1]) : null, - duration: durationMatch ? parseInt(durationMatch[1]) : null, - exitCode: 0 - }; -} -``` - -## Symlinking Patterns (v4.1+) - -### Symlink Creation Pattern - -#### Cross-Platform Symlinking -```javascript -// Create symlink with Windows fallback -async function createSymlink(source, target) { - try { - // Try symlink first - await fs.promises.symlink(source, target, 'dir'); - return 'symlink'; - } catch (error) { - if (error.code === 'EPERM' && process.platform === 'win32') { - // Windows fallback: copy directory - await fs.promises.cp(source, target, { recursive: true }); - return 'copy'; - } - throw error; - } -} -``` - -### Symlink Validation Pattern - -#### Integrity Checking -```javascript -// Validate symlink integrity -function validateSymlink(linkPath, expectedTarget) { - try { - const stats = fs.lstatSync(linkPath); - - if (!stats.isSymbolicLink()) { - return { valid: false, reason: 'not_a_symlink' }; - } - - const actualTarget = fs.readlinkSync(linkPath); - const resolvedActual = path.resolve(path.dirname(linkPath), actualTarget); - const resolvedExpected = path.resolve(expectedTarget); - - if (resolvedActual !== resolvedExpected) { - return { valid: false, reason: 'wrong_target', actualTarget, expectedTarget }; - } - - return { valid: true }; - } catch (error) { - return { valid: false, reason: 'missing', error: error.message }; - } -} -``` - -### Sync Command Pattern - -#### Repairing Broken Symlinks -```javascript -// Repair broken symlinks -function repairSymlinks(instancePath, sharedPath) { - const symlinkDirs = ['commands', 'skills', 'agents']; - const repaired = []; - - for (const dir of symlinkDirs) { - const linkPath = path.join(instancePath, '.claude', dir); - const targetPath = path.join(sharedPath, dir); - - const validation = validateSymlink(linkPath, targetPath); - - if (!validation.valid) { - // Remove broken symlink/directory - if (fs.existsSync(linkPath)) { - fs.rmSync(linkPath, { recursive: true, force: true }); - } - - // Recreate symlink - fs.symlinkSync(targetPath, linkPath, 'dir'); - repaired.push(dir); - } - } - - return repaired; -} -``` - -## Platform Compatibility Standards - -### Cross-Platform Development - -#### Path Handling -```javascript -// Use path module for cross-platform compatibility -const configPath = path.join(os.homedir(), '.ccs', 'config.json'); - -// Avoid hardcoded separators -const configPath = os.homedir() + '/.ccs/config.json'; // Unix only -``` - -#### Platform Detection -```javascript -// Centralized platform detection -const isWindows = process.platform === 'win32'; - -if (isWindows) { - // Windows-specific logic -} else { - // Unix/macOS logic -} -``` - -#### Environment Variables -```javascript -// Support both Windows and Unix environment variable formats -function expandPath(pathStr) { - // Unix style: $HOME or ${HOME} - pathStr = pathStr.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] || ''); - - // Windows style: %USERPROFILE% - if (process.platform === 'win32') { - pathStr = pathStr.replace(/%([^%]+)%/g, (_, name) => process.env[name] || ''); - } - - return path.normalize(pathStr); -} -``` - -## Configuration Standards - -### JSON Configuration Format - -#### Configuration Schema -```json -{ - "profiles": { - "default": "~/.claude/settings.json", - "glm": "~/.ccs/glm.settings.json" - } -} -``` - -#### Settings File Format -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic", - "ANTHROPIC_AUTH_TOKEN": "your_api_key", - "ANTHROPIC_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-4.6" - } -} -``` - -### Configuration Handling Patterns - -#### Safe JSON Parsing -```javascript -function readConfig() { - try { - const configContent = fs.readFileSync(configPath, 'utf8'); - return JSON.parse(configContent); - } catch (e) { - error(`Invalid JSON in ${configPath}: ${e.message}`); - } -} -``` - -#### Validation Patterns -```javascript -function validateConfig(config) { - if (!config.profiles || typeof config.profiles !== 'object') { - error(`Config must have 'profiles' object`); - } - - // Essential validation only - avoid excessive checks - return true; -} -``` - -## Testing Standards - -### Test Organization - -#### Unit Test Structure -```javascript -const assert = require('assert'); -const { getSettingsPath } = require('../../../bin/config-manager'); - -describe('config-manager', () => { - describe('getSettingsPath', () => { - it('should return settings path for valid profile', () => { - const result = getSettingsPath('glm'); - assert(result.includes('glm.settings.json')); - }); - - it('should throw error for invalid profile', () => { - assert.throws(() => { - getSettingsPath('invalid'); - }, /Profile 'invalid' not found/); - }); - }); -}); -``` - -#### Test Data Management -```javascript -// Use fixtures for test data -const testConfig = { - profiles: { - glm: '~/.ccs/glm.settings.json', - default: '~/.claude/settings.json' - } -}; - -// Clean up after tests -afterEach(() => { - // Clean up test files -}); -``` - -### Test Coverage Requirements - -Before any PR, ensure: -- [ ] All new functions have unit tests -- [ ] Error conditions are tested -- [ ] Cross-platform behavior is verified -- [ ] Edge cases are covered -- [ ] Integration tests validate end-to-end workflows - -## Documentation Standards - -### Code Documentation - -#### Function Documentation -```javascript -/** - * Execute Claude CLI with unified spawn logic - * @param {string} claudeCli - Path to Claude CLI executable - * @param {string[]} args - Arguments to pass to Claude CLI - */ -function execClaude(claudeCli, args) { - // Implementation -} -``` - -#### Inline Comments -```javascript -// Special case: version command (check BEFORE profile detection) -if (firstArg === '--version') { - handleVersionCommand(); -} - -// Validate settings file exists before using it -if (!fs.existsSync(expandedPath)) { - error(`Settings file not found: ${expandedPath}`); -} -``` - -### README Standards - -#### Installation Instructions -- Provide multiple installation methods -- Include prerequisites clearly -- Show first usage examples -- Include troubleshooting links - -#### Usage Examples -```bash -# Basic usage -ccs # Use default profile -ccs glm # Switch to GLM profile -ccs glm "your prompt" # One-time command with GLM - -# Special commands -ccs --version # Show version -ccs --help # Show help -ccs --install # Install Claude Code integration -``` - -## Version Management Standards - -### Version Synchronization -When updating version, maintain consistency across: -1. `package.json` version field -2. `VERSION` file -3. Installer scripts (if applicable) - -### Semantic Versioning -- **Major**: Breaking changes -- **Minor**: New features (backward compatible) -- **Patch**: Bug fixes (backward compatible) - -## Security Standards - -### Input Validation -- Validate configuration file existence and format -- Check executable permissions before use -- Sanitize user inputs appropriately - -### Safe Process Execution -```javascript -// Good: Using arrays prevents shell injection -spawn(claudeCli, ['--settings', settingsPath, ...userArgs]); - -// Avoid: String concatenation can lead to injection -spawn('sh', ['-c', `claude --settings ${settingsPath} ${command}`]); -``` - -### File System Access -- Only access known configuration directories -- Use path normalization to prevent traversal -- Validate file permissions before reading - -## Performance Standards - -### Optimization Principles -- Minimize function call overhead -- Reduce I/O operations through caching -- Use efficient data structures -- Avoid unnecessary computations - -### Memory Management -- Use streams for large file operations -- Clean up resources properly -- Avoid memory leaks in long-running processes - -## Quality Assurance Standards - -### ESLint Quality Gates (Phase 01 Enhanced + Phase 02 Modular) - -**Strict TypeScript Rules** (enforced as errors): -- ✅ `@typescript-eslint/no-unused-vars`: Zero unused variables, imports, or parameters -- ✅ `@typescript-eslint/no-explicit-any`: No explicit `any` types allowed (use `unknown` or proper types) -- ✅ `@typescript-eslint/no-non-null-assertion`: No non-null assertions (`value!`) - use explicit checks - -**Quality Validation Commands**: -```bash -bun run validate # Full validation: typecheck + lint + format + test -bun run typecheck # TypeScript compilation (tsc --noEmit) -bun run lint # ESLint validation (must show 0 errors) -bun run format # Prettier formatting -bun run test # Test suite execution -``` - -**Pre-commit Requirements**: -- All ESLint rules must pass (zero errors, zero warnings) -- TypeScript compilation must succeed -- All tests must pass -- Code must be properly formatted - -**Phase 02 Additional Requirements**: -- Command modules must not exceed 200 lines (enforces single responsibility) -- No circular dependencies between command handlers -- Each command must implement the CommandHandler interface -- Utility modules must be cross-platform compatible - -### Code Review Checklist -Before submitting code, verify: -- [ ] Follows all coding standards -- [ ] Has appropriate test coverage -- [ ] Documentation is updated -- [ ] No console.log statements left in production code -- [ ] Error handling is comprehensive -- [ ] Cross-platform compatibility is maintained -- [ ] **ESLint strictness rules pass** (no unused vars, no explicit any, no non-null assertions) - -### Release Checklist -Before releasing new version: -- [ ] All tests pass on all platforms -- [ ] Documentation is updated -- [ ] Version numbers are synchronized -- [ ] Installation is tested from scratch -- [ ] Edge cases are manually verified - -## Contributing Standards - -### Development Workflow -1. Create feature branch from main -2. Implement changes following these standards -3. Add comprehensive tests -4. Update documentation -5. Submit PR with clear description - -### Pull Request Requirements -- Clear description of changes -- Test coverage for new functionality -- Documentation updates -- No breaking changes without version bump -- All CI checks passing - -## Summary - -These code standards ensure the CCS codebase remains: -- **Maintainable**: Clear modular structure with 7 subsystems, consistent naming patterns -- **Reliable**: Comprehensive error handling, testing, and validation -- **Performant**: Optimized spawn logic, stream parsing, minimal overhead -- **Secure**: Safe process execution, symlink validation, file handling -- **Compatible**: Cross-platform symlinking, Windows fallbacks, unified behavior -- **Extensible**: Clean subsystem boundaries, reusable patterns -- **Type-Safe**: Enhanced ESLint strictness enforces zero-tolerance for code quality issues -- **User-Friendly**: Semantic UI system with intelligent fallback rendering (Phase 5) - -**Phase 5 (2025-12-01) - UI & Listr2 Integration**: -- **Central UI Module**: src/utils/ui.ts with semantic colors, status indicators, boxes, tables -- **Listr2 Integration**: Task list progress with intelligent renderer selection -- **Claude Code Detection**: Automatic fallback for tool context (isClaudeCodeContext) -- **Async Formatting**: Result formatter now async with ui.init() call -- **Compliance**: ASCII-only indicators ([OK], [X], [!], [i]), NO_COLOR respect - -**v4.x Specific Standards**: -- **Delegation patterns**: Stream-JSON parsing, session management, headless execution -- **Symlinking patterns**: Cross-platform symlink creation, validation, repair -- **UI patterns**: Semantic colors, status indicators, boxes, tables, spinners, task lists -- **Subsystem organization**: Clear separation (auth, delegation, glmt, management, utils) -- **Naming conventions**: handler, executor, manager, validator, formatter, parser suffixes - -**v4.5.0 Installation Standards**: -- **Bootstrap-based installers**: Native shell wrappers delegate to Node.js via npx -- **Node.js requirement**: 14+ required (checked during install) -- **No shell dependencies**: error-codes.sh, progress-indicator.sh, prompt.sh removed -- **First-run bootstrap**: Auto-installs @kaitranntt/ccs npm package globally - -Following these standards helps maintain the quality, modularity, and extensibility of the v4.x architecture while enabling future development with AI delegation, shared data management, and comprehensive diagnostics. Phase 5 adds a professional UI layer that gracefully degrades in non-TTY environments while maintaining strict compliance with project constraints. \ No newline at end of file diff --git a/docs/codebase-summary.md b/docs/codebase-summary.md deleted file mode 100644 index ae5c957d..00000000 --- a/docs/codebase-summary.md +++ /dev/null @@ -1,307 +0,0 @@ -# CCS Codebase Summary - -## Overview - -CCS (Claude Code Switch) is a TypeScript-based CLI tool that provides instant profile switching between multiple AI models (Claude Sonnet 4.5, GLM 4.6, GLMT, and Kimi). The project features a comprehensive architecture with TypeScript source, React UI dashboard, cross-platform shell scripts, and extensive automation. Current version includes a modern React 19 dashboard with real-time WebSocket integration, Vite build system, and shadcn/ui components. - -## Repository Structure - -``` -ccs/ -├── src/ # TypeScript source code (43 files) -│ ├── ccs.ts # Main entry point (593 lines) -│ ├── commands/ # Modular command handlers (7 files) -│ ├── auth/ # Authentication system (3 files) -│ ├── cliproxy/ # CLIProxy integration (6 files) -│ ├── delegation/ # AI delegation system (6 files) -│ ├── glmt/ # GLMT thinking mode (7 files) -│ ├── management/ # System management (5 files) -│ ├── utils/ # Utilities (6 files) -│ └── types/ # TypeScript definitions (6 files) -├── ui/ # React 19 Dashboard (Vite + shadcn/ui) -│ ├── src/ -│ │ ├── App.tsx # Main React app -│ │ ├── components/ # UI components -│ │ │ ├── ui/ # shadcn/ui components -│ │ │ └── *.tsx # Custom components -│ │ ├── hooks/ # React hooks -│ │ ├── lib/ # Utilities -│ │ └── pages/ # Route pages -│ ├── public/ # Static assets -│ ├── package.json # Dependencies -│ └── vite.config.ts # Vite configuration -├── lib/ # Cross-platform scripts -│ ├── ccs # Bash bootstrap -│ └── ccs.ps1 # PowerShell bootstrap -├── scripts/ # Build and automation -│ ├── build.js # TypeScript compilation -│ ├── postinstall.js # Auto-configuration -│ └── sync-version.js # Version sync -├── tests/ # Test suites -│ ├── unit/ # Unit tests -│ ├── npm/ # Package tests -│ └── native/ # Native install tests -└── docs/ # Documentation - ├── project-overview-pdr.md - ├── code-standards.md - ├── system-architecture.md - └── project-roadmap.md -``` - -## Key Components - -### TypeScript Core (src/) - -1. **Main Entry Point** (`src/ccs.ts`) - - Command parsing and routing - - Profile detection logic - - Delegation flag handling (`-p`) - - GLMT proxy lifecycle management - -2. **Modular Commands** (`src/commands/`) - - `version-command.ts`: Version display - - `help-command.ts`: Comprehensive help system - - `install-command.ts`: Installation workflows - - `doctor-command.ts`: System diagnostics - - `sync-command.ts`: Configuration synchronization - - `shell-completion-command.ts`: Shell completion - - `update-command.ts`: Version updates with beta channel support - -3. **Authentication System** (`src/auth/`) - - Profile detection and validation - - Multi-account management - - Profile registry operations - -4. **CLIProxy Integration** (`src/cliproxy/`) - - OAuth-based provider integration - - Binary manager for cliproxy executables, including the new **version pin feature** (see Recent Changes) - - Auth handler for OAuth flows - - **Model Catalog**: Manages available models (Gemini, Codex, AGY, Qwen, Iflow) - -5. **AI Delegation** (`src/delegation/`) - - Headless Claude execution - - Stream-JSON parsing - - Real-time tool tracking - - Session persistence - -6. **GLMT System** (`src/glmt/`) - - HTTP proxy for thinking mode - - Format transformation (Anthropic ↔ OpenAI) - - Reasoning content handling - - Debug logging - -7. **Management** (`src/management/`) - - System diagnostics - - Instance management - - Shared data management - - Recovery operations - -8. **Utilities** (`src/utils/`) - - Cross-platform helpers - - Shell execution - - Package manager detection - - Update checking - -### React Dashboard (ui/) - -**Technology Stack**: -- React 19 with TypeScript -- Vite for fast development and building -- shadcn/ui component library (Radix UI + Tailwind) -- TanStack Query for server state -- Real-time WebSocket integration -- Dark mode support - -**Key Pages**: -- Dashboard: Overview, status, usage analytics, CLIProxy controls, and system health monitoring -- API Profiles: Model configuration -- CLIProxy: OAuth provider setup -- Accounts: Account management -- Health: System diagnostics -- Settings: Configuration -- Shared: Data sharing management - -**Components**: -- Modern UI with responsive design -- Real-time updates via WebSocket -- Professional theme with consistent styling -- Accessibility-compliant components - -### Cross-Platform Scripts (lib/) - -1. **Bash Bootstrap** (`lib/ccs`) - - Entrypoint for Unix/macOS - - Delegates to Node.js via npx - - Argument passthrough support - -2. **PowerShell Bootstrap** (`lib/ccs.ps1`) - - Windows PowerShell support - - Parameter splatting for arguments - - Cross-platform parity with bash - -### Build & Automation (scripts/) - -1. **Build System** - - TypeScript compilation to dist/ - - Source maps and declarations - - Linting and formatting - -2. **Post-Installation** - - Auto-configuration creation - - Directory structure setup - - Migration for version upgrades - -3. **Quality Gates** - - Type checking (strict mode) - - ESLint validation - - Test execution - - Code formatting - -## Technology Stack - -### Core Technologies -- **TypeScript 5.3+**: 100% type coverage, zero `any` types -- **Node.js 14+**: Runtime environment -- **Bun**: Package manager (10-25x faster than npm) -- **React 19**: Modern UI with concurrent features -- **Vite**: Fast build tool and dev server - -### UI Libraries -- **shadcn/ui**: Modern component library -- **Radix UI**: Accessible component primitives -- **Tailwind CSS**: Utility-first styling -- **Lucide React**: Icon library -- **React Router**: Client-side routing -- **TanStack Query**: Server state management - -### Development Tools -- **ESLint**: Code linting with strict rules -- **Prettier**: Code formatting -- **Mocha**: Test framework -- **Chai**: Assertion library -- **Semantic Release**: Automated versioning - -## Key Features - -### Profile Management -- **Settings-based profiles**: glm, glmt, kimi -- **Account-based profiles**: work, personal -- **CLIProxy providers**: OAuth-based integration -- **Instant switching**: Zero-downtime profile changes - -### AI Delegation System -- **Headless execution**: `-p` flag for delegation -- **Real-time tracking**: 13+ Claude Code tools -- **Stream-JSON parsing**: Live tool visibility -- **Session persistence**: `:continue` support -- **Cost tracking**: Usage statistics - -### GLMT Thinking Mode -- **Embedded proxy**: HTTP server for format conversion -- **Reasoning support**: GLM 4.6 with thinking blocks -- **Debug logging**: File-based logging with timestamps -- **Configuration**: Temperature, max tokens, timeouts - -### Web Dashboard -- **Real-time UI**: WebSocket for live updates -- **Modern interface**: Responsive, accessible design -- **Configuration**: Visual profile and settings management -- **Health monitoring**: System diagnostics dashboard -- **Dark mode**: Theme switching support - -### Cross-Platform Support -- **Universal**: macOS, Linux, Windows -- **Shell completion**: Bash, Zsh, Fish, PowerShell -- **Consistent behavior**: Unified across platforms -- **Windows fallbacks**: Copy when symlinks unavailable - -### Development Workflow -- **TypeScript strict**: Maximum type safety -- **Automated releases**: Semantic versioning -- **Quality gates**: Pre-commit validation -- **Comprehensive tests**: Unit, integration, native - -## Recent Changes - -### Version Pin Feature (Issue #88) -- **Description**: Users can now explicitly pin a specific version of CLIProxy using `ccs cliproxy --install `. This creates a `.version-pin` file, preventing automatic updates and ensuring stability for specific project requirements. - -### Profile Persistence Fix (Issue #82) -- **Description**: Relaxed configuration validation rules to prevent unintended data loss when handling user profiles, improving robustness and user experience. - -### UI Dashboard Capabilities -- **Description**: The web-based UI now provides comprehensive dashboard functionalities, including usage analytics, CLIProxy controls, and system health monitoring, enhancing user visibility and control. - -### Multi-Provider Support -- **Description**: The CLIProxy now supports multiple AI model providers, including Gemini, Codex, AGY, Qwen, and Iflow, offering greater flexibility and choice for users. - -### Unified Config System -- **Description**: A consolidated configuration system ensures consistent management of settings, feature flags, and secrets across the CLI and its components. - -## Architecture Patterns - -### Modular Design -- **Single responsibility**: Each module focused -- **Clear interfaces**: TypeScript contracts -- **Dependency injection**: Testable architecture -- **Error boundaries**: Graceful error handling - -### Configuration Management -- **Unified Config System**: Consolidated management of settings, feature flags, and secrets across the CLI and its components (see Recent Changes). -- **Shared data**: Symlinks for commands, skills, agents -- **Isolated state**: Profile-specific sessions, logs -- **Auto-recovery**: Self-healing configurations -- **Migration support**: Seamless upgrades - -### Performance Optimization -- **Lazy loading**: On-demand initialization -- **Stream processing**: Real-time parsing -- **Minimal overhead**: Direct CLI execution -- **Efficient builds**: Vite and Bun optimization - -## Statistics (as of v4.5.0) - -- **Total files**: 163 files -- **TypeScript files**: 43 source files -- **Lines of code**: ~8,000 lines TypeScript -- **Test coverage**: 90%+ critical paths -- **Platform support**: 3 OS (macOS, Linux, Windows) -- **Shell completions**: 4 shells supported -- **AI models**: 4+ models integrated -- **Languages**: TypeScript, React, Bash, PowerShell - -## Development Standards - -### Code Quality -- **Zero any types**: 100% type coverage -- **Strict ESLint**: All errors enforced -- **Pre-commit hooks**: Automated validation -- **Semantic releases**: Automated versioning - -### Testing Strategy -- **Unit tests**: Module isolation -- **Integration tests**: Cross-module flows -- **Platform tests**: OS-specific behavior -- **Native tests**: Shell script validation - -### Documentation -- **Living docs**: Updated with releases -- **Code examples**: Real usage patterns -- **Architecture docs**: System design -- **API references**: Complete coverage - -## Future Roadmap - -### v4.6-v4.7 (UI Enhancements) -- Sidebar redesign with modern UX -- Enhanced dashboard visualizations -- Real-time collaboration features -- Mobile-responsive improvements - -### v5.0+ (Next Generation) -- AI-powered automation -- Plugin system -- Enterprise features -- Ecosystem expansion - -This codebase demonstrates a mature, well-architected TypeScript application with modern React UI, comprehensive testing, and cross-platform support. The modular design enables easy maintenance and extension while maintaining high quality standards. \ No newline at end of file diff --git a/docs/concurrent-sessions.md b/docs/concurrent-sessions.md deleted file mode 100644 index 18b45add..00000000 --- a/docs/concurrent-sessions.md +++ /dev/null @@ -1,417 +0,0 @@ -# Concurrent Sessions (v3.0.0) - -## Overview - -CCS v3.0.0 enables running multiple Claude CLI instances simultaneously with different accounts. Each profile runs in an isolated environment with independent credentials, sessions, and state. - -**Key Feature**: Login once per profile → use anywhere, anytime. - -## How It Works - -### Instance Isolation - -CCS uses `CLAUDE_CONFIG_DIR` environment variable to create isolated Claude instances: - -```bash -# Each profile = separate directory -~/.ccs/instances/work/ # Work account instance -~/.ccs/instances/personal/ # Personal account instance -``` - -When you run `ccs work "task"`, CCS: -1. Points `CLAUDE_CONFIG_DIR` to `~/.ccs/instances/work/` -2. Claude CLI loads credentials from that directory -3. All state (sessions, todos, logs) stays isolated - -### Platform Support - -✅ **All platforms supported**: Linux, macOS, Windows -- Same approach everywhere (unified implementation) -- No platform-specific workarounds needed -- Tested and working on all three platforms - -## Quick Start - -### 1. Create Profiles - -```bash -# Create first profile (will prompt for login) -ccs auth create work -# Complete OAuth login with work account - -# Create second profile -ccs auth create personal -# Complete OAuth login with personal account -``` - -### 2. Use Profiles - -```bash -# Use work account -ccs work "review code" - -# Use personal account -ccs personal "help with project" - -# Check which account is active -ccs work /status # Shows work account email -ccs personal /status # Shows personal account email -``` - -### 3. Concurrent Sessions - -```bash -# Terminal 1 -ccs work "implement feature X" - -# Terminal 2 (simultaneously) -ccs personal "research topic Y" - -# Both run at the same time with isolated state -``` - -## Profile Management - -### List Profiles - -```bash -ccs auth list - -# Output: -# [*] work (default) -# Type: account -# Created: 2025-11-09T10:30:00.000Z -# -# [ ] personal -# Type: account -# Created: 2025-11-09T11:15:00.000Z -``` - -### Set Default - -```bash -ccs auth default work - -# Now `ccs` without profile name uses work -ccs "task" # Uses work account -``` - -### Remove Profile - -```bash -ccs auth remove personal --force -# Deletes instance and credentials -``` - -### Check Account - -```bash -# See which account a profile is logged into -ccs work /status -# Output shows: email, subscription tier, etc. - -ccs personal /status -# Different email/account info -``` - -## Instance Structure - -Each profile gets its own isolated directory: - -``` -~/.ccs/instances/work/ -├── .credentials.json # OAuth credentials (managed by Claude) -├── session-env/ # Chat history & context -├── todos/ # Task lists -├── logs/ # Execution logs -├── file-history/ # Edit tracking -├── shell-snapshots/ # Shell state -├── debug/ # Debug info -├── .anthropic/ # SDK config -├── commands/ # Custom commands -└── skills/ # Custom skills -``` - -**Key Points**: -- Credentials managed by Claude CLI (not CCS) -- Each profile requires separate OAuth login -- State never shared between profiles -- Completely isolated environments - -## Use Cases - -### 1. Work vs Personal - -```bash -# Work account for client projects -ccs work "implement auth feature" - -# Personal account for side projects -ccs personal "help with my portfolio site" -``` - -### 2. Different Subscriptions - -```bash -# Pro account for heavy tasks -ccs pro "analyze large codebase" - -# Free account for light tasks -ccs free "quick question about syntax" -``` - -### 3. Team Collaboration - -```bash -# Company account -ccs company "review team's code" - -# Client account (when working on client's Claude) -ccs client "implement their requirements" -``` - -## Architecture - -### Profile Creation Flow - -``` -1. User: ccs auth create work -2. CCS creates ~/.ccs/instances/work/ directory -3. CCS spawns Claude with CLAUDE_CONFIG_DIR=~/.ccs/instances/work/ -4. Claude detects no credentials -5. Claude prompts OAuth login -6. User completes login -7. Claude saves credentials to instance/.credentials.json -8. Done - profile ready to use -``` - -### Profile Usage Flow - -``` -1. User: ccs work "task" -2. CCS detects "work" is account profile -3. CCS ensures instance exists -4. CCS sets CLAUDE_CONFIG_DIR=~/.ccs/instances/work/ -5. CCS executes: claude [args] with env var -6. Claude loads credentials from instance -7. Task executes with work account -``` - -### Settings Profiles (Backward Compatible) - -```bash -# GLM and Kimi profiles still work (v2.x approach) -ccs glm "task" # Uses --settings flag -ccs kimi "task" # Uses --settings flag - -# These are NOT account profiles, they're API configurations -# Cannot run concurrently with each other -``` - -## Performance - -### Fast Activation - -- **First use**: ~20-35ms (create directories + copy configs) -- **Subsequent use**: ~5-10ms (just validation) -- **No encryption overhead** (50-120ms faster than v2.x) - -### Lightweight - -- **Memory**: ~3-5 KB per activation -- **Disk**: ~200-700 KB per profile -- **I/O**: 1 read + 1 write per activation - -## Limitations - -### 1. Same Profile = No Concurrent - -Running the same profile in 2 terminals causes conflicts: - -```bash -# Terminal 1 -ccs work "task1" - -# Terminal 2 (will conflict) -ccs work "task2" # Same session files, log files - -# Solution: Use different profiles -``` - -### 2. CLAUDE_CONFIG_DIR Compatibility - -- Undocumented env var (no official Anthropic support) -- Works on recent Claude CLI versions -- May not work on very old versions -- **Solution**: Keep Claude CLI updated - -### 3. Global Config Not Synced - -Commands/skills copied on profile creation, not synced later: - -```bash -# If you update ~/.claude/commands/ after creating profile: -# Option 1: Delete and recreate instance -rm -rf ~/.ccs/instances/work -ccs work "task" # Recreates with latest configs - -# Option 2: Manually copy -cp -r ~/.claude/commands/* ~/.ccs/instances/work/commands/ -``` - -### 4. No Auto-Cleanup - -Sessions/logs accumulate over time: - -```bash -# Manual cleanup if needed -du -sh ~/.ccs/instances/* # Check sizes -rm -rf ~/.ccs/instances/work/session-env/* # Clear sessions -rm -rf ~/.ccs/instances/work/logs/* # Clear logs -``` - -## Security - -### Credentials - -- Stored at `~/.ccs/instances//.credentials.json` -- Managed by Claude CLI (OAuth tokens) -- Permissions: 0600 (owner read/write only) -- Never copied between instances - -### Directories - -- Instance dirs: 0700 (owner access only) -- Isolated per profile -- No cross-contamination - -### No Encryption Needed - -- Credentials live in isolated directories -- OS-level file permissions provide security -- Simpler = less attack surface - -## Troubleshooting - -### "Profile not found" - -```bash -# Create the profile first -ccs auth create -``` - -### "Claude prompts for login" - -Normal behavior on first use - complete OAuth flow: - -```bash -ccs auth create work -# Follow OAuth prompts -``` - -### "CLAUDE_CONFIG_DIR not working" - -```bash -# Check Claude CLI version -claude --version - -# Update to latest -# (Installation varies by platform) -``` - -### Check Account Info - -```bash -# See which account is logged in -ccs work /status -# Shows: email, subscription, organization - -# If wrong account, recreate profile -ccs auth remove work --force -ccs auth create work # Login with correct account -``` - -## Migration from v2.x - -### Breaking Changes - -1. No vault - credentials in instances -2. Must login per profile (no credential copying) -3. Command changed: `auth save` → `auth create` - -### Migration Steps - -```bash -# 1. Backup old data (optional) -mv ~/.ccs/profiles.json ~/.ccs/profiles.json.v2 - -# 2. Remove old profiles -ccs auth remove work --force -ccs auth remove personal --force - -# 3. Recreate with v3.0.0 -ccs auth create work # Login with work account -ccs auth create personal # Login with personal account - -# 4. Verify -ccs auth list -ccs work /status -ccs personal /status - -# 5. Test -ccs work "hello" -ccs personal "hello" -``` - -## Advanced - -### Manual Instance Inspection - -```bash -# View instance structure -tree ~/.ccs/instances/work/ - -# Check credentials (OAuth JSON) -cat ~/.ccs/instances/work/.credentials.json - -# Check profile metadata -cat ~/.ccs/profiles.json -``` - -### Profile Metadata - -```json -{ - "version": "2.0.0", - "profiles": { - "work": { - "type": "account", - "created": "2025-11-09T10:30:00.000Z", - "last_used": "2025-11-09T15:45:00.000Z" - }, - "personal": { - "type": "account", - "created": "2025-11-09T11:15:00.000Z", - "last_used": "2025-11-09T14:30:00.000Z" - } - }, - "default": "work" -} -``` - -### Force Recreate Instance - -```bash -# Delete instance (keeps profile metadata) -rm -rf ~/.ccs/instances/work - -# Next use recreates fresh instance -ccs work "task" -# Will prompt for login again -``` - -## See Also - -- [System Architecture](./system-architecture.md) -- [Codebase Summary](./codebase-summary.md) -- [Project Overview](./project-overview-pdr.md) diff --git a/docs/en/configuration.md b/docs/en/configuration.md deleted file mode 100644 index bb02b090..00000000 --- a/docs/en/configuration.md +++ /dev/null @@ -1,172 +0,0 @@ -# CCS Configuration Guide - -## Automatic Configuration - -The installer auto-creates config and profile templates during installation. The configuration system has been simplified for better maintainability and performance while maintaining all functionality. - -**macOS / Linux**: `~/.ccs/config.json` - -**Windows**: `%USERPROFILE%\.ccs\config.json` - -### Recent Simplification Improvements - -The configuration system has been optimized with these key improvements: -- **Streamlined validation**: Removed redundant security checks while maintaining essential validation -- **Simplified error handling**: Direct error messages instead of complex formatting -- **Improved performance**: Reduced function call overhead and complexity -- **Enhanced maintainability**: Consolidated logic with single sources of truth - -## Configuration Format - -### Basic Setup - -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -### Advanced Setup (Multiple Profiles) - -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "haiku": "~/.ccs/haiku.settings.json", - "custom": "~/.ccs/custom.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -## Profile Configuration - -### GLM Profile Example - -**Location**: `~/.ccs/glm.settings.json` - -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic", - "ANTHROPIC_AUTH_TOKEN": "your_glm_api_key", - "ANTHROPIC_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-4.6" - } -} -``` - -### Claude (Default) Profile - -- Uses `~/.claude/settings.json` (your existing Claude CLI config) -- CCS never modifies this file (non-invasive approach) - -## How Configuration Works - -1. CCS reads profile name from command line (defaults to "default") -2. Looks up settings file path in `~/.ccs/config.json` -3. Executes `claude --settings [remaining-args]` - -No magic. No file modification. Pure delegation. Works identically across all platforms. - -## Environment Variables - -### CCS_CONFIG - -Override default config location: -```bash -export CCS_CONFIG=~/my-custom-config.json -ccs glm -``` - -### NO_COLOR - -Disable colored terminal output: -```bash -export NO_COLOR=1 -ccs glm -``` - -**Use Cases**: -- CI/CD pipelines -- Log files -- Terminals without color support -- Accessibility preferences - -When `NO_COLOR` is set, CCS uses plain ASCII output without ANSI color codes. - -## Platform-Specific Notes - -### Windows Configuration - -Windows uses the same file structure and approach as Linux/macOS. - -**Config format** (`~/.ccs/config.json`): -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -### macOS / Linux Configuration - -Uses settings file paths with `~` expansion: - -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -Each profile points to a Claude settings JSON file. Create settings files per [Claude CLI docs](https://docs.claude.com/en/docs/claude-code/installation). - -## Configuration Issues - -### Profile not found - -``` -Error: Profile 'foo' not found in ~/.ccs/config.json -``` - -**Fix**: Add profile to `~/.ccs/config.json`: -```json -{ - "profiles": { - "foo": "~/.ccs/foo.settings.json" - } -} -``` - -### Settings file missing - -``` -Error: Settings file not found: ~/.ccs/foo.settings.json -``` - -**Fix**: Create settings file or fix path in config. - -### Default profile missing - -``` -Error: Profile 'default' not found in ~/.ccs/config.json -``` - -**Fix**: Add "default" profile or always specify profile name: -```json -{ - "profiles": { - "default": "~/.claude/settings.json" - } -} -``` \ No newline at end of file diff --git a/docs/en/installation.md b/docs/en/installation.md deleted file mode 100644 index fe02657c..00000000 --- a/docs/en/installation.md +++ /dev/null @@ -1,240 +0,0 @@ -# CCS Installation Guide - -> [!WARNING] -> **Native shell installers (curl/irm) are deprecated.** -> Use npm installation for all platforms. Legacy installers will be removed in v5.0. - -## npm Package Installation (Recommended) - -### Cross-Platform Installation - -**macOS / Linux / Windows** -```bash -npm install -g @kaitranntt/ccs -``` - -**Compatible with all package managers:** -- `npm install -g @kaitranntt/ccs` -- `yarn global add @kaitranntt/ccs` -- `pnpm add -g @kaitranntt/ccs` -- `bun add -g @kaitranntt/ccs` - -**Benefits of npm installation:** -- ✅ Cross-platform compatibility -- ✅ Automatic PATH configuration -- ✅ Auto-creates config files via postinstall script -- ✅ Easy updates: `npm update -g @kaitranntt/ccs` -- ✅ Clean uninstall: `npm uninstall -g @kaitranntt/ccs` -- ✅ Version pinning support -- ✅ Dependency management - -**What Happens During Install:** -1. npm downloads and installs the package -2. Postinstall script automatically creates `~/.ccs/config.json` and `~/.ccs/glm.settings.json` -3. npm creates `ccs` command in your PATH - -**Note**: If you use `npm install --ignore-scripts`, config files won't be created. Run without that flag: -```bash -npm install -g @kaitranntt/ccs --force -``` - -## [!] DEPRECATED: One-Liner Installation (Legacy) - -> [!WARNING] -> **These installers are deprecated and will be removed in v5.0.** -> They now auto-redirect to npm installation. Please use npm directly. - -### macOS / Linux - -```bash -# Short URL (via CloudFlare) -curl -fsSL ccs.kaitran.ca/install | bash - -# Or direct from GitHub -curl -fsSL https://raw.githubusercontent.com/kaitranntt/ccs/main/installers/install.sh | bash -``` - -**Note:** Scripts show deprecation warning and automatically run npm installation if Node.js is available. - -### Windows PowerShell - -```powershell -# Short URL (via CloudFlare) -irm ccs.kaitran.ca/install.ps1 | iex - -# Or direct from GitHub -irm https://raw.githubusercontent.com/kaitranntt/ccs/main/installers/install.ps1 | iex -``` - -**Note:** Scripts show deprecation warning and automatically run npm installation if Node.js is available. - -## [!] DEPRECATED: Git Clone Installation (Legacy) - -> [!WARNING] -> **Git clone installation is deprecated.** Use npm installation instead. - -### macOS / Linux - -```bash -git clone https://github.com/kaitranntt/ccs.git -cd ccs -./installers/install.sh -``` - -### Windows PowerShell - -```powershell -git clone https://github.com/kaitranntt/ccs.git -cd ccs -.\installers\install.ps1 -``` - -**Note**: Scripts show deprecation warning and automatically run npm installation if Node.js is available. - -## Manual Installation - -### macOS / Linux - -```bash -# Create directory -mkdir -p ~/.local/bin - -# Download script -curl -fsSL https://raw.githubusercontent.com/kaitranntt/ccs/main/ccs -o ~/.local/bin/ccs -chmod +x ~/.local/bin/ccs - -# Add to PATH (choose your shell) -# For bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc - -# For zsh -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc -source ~/.zshrc - -# For fish -echo 'set -gx PATH $HOME/.local/bin $PATH' >> ~/.config/fish/config.fish -``` - -### Windows PowerShell - -```powershell -# Create directory -New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.ccs" - -# Download script -Invoke-WebRequest -Uri "https://raw.githubusercontent.com/kaitranntt/ccs/main/ccs.ps1" -OutFile "$env:USERPROFILE\.ccs\ccs.ps1" - -# Add to PATH (restart terminal after) -$Path = [Environment]::GetEnvironmentVariable("Path", "User") -[Environment]::SetEnvironmentVariable("Path", "$Path;$env:USERPROFILE\.ccs", "User") -``` - -## What Gets Installed - -**Executable Location**: -- macOS / Linux: `~/.local/bin/ccs` (symlink to `~/.ccs/ccs`) -- Windows: `%USERPROFILE%\.ccs\ccs.ps1` - -**Configuration Directory** (`~/.ccs/`): -```bash -~/.ccs/ -├── ccs # Main executable (symlink target) -├── config.json # Profile configuration -├── config.json.backup # Single backup (overwrites each install) -├── glm.settings.json # GLM profile -├── VERSION # Version file -├── uninstall.sh # Uninstaller -└── .claude/ # Claude Code integration - ├── commands/ccs.md # /ccs meta-command - └── skills/ # Delegation skills -``` - -## Upgrade CCS - -### macOS / Linux - -```bash -# From git clone -cd ccs && git pull && ./install.sh - -# From curl install -curl -fsSL ccs.kaitran.ca/install | bash -``` - -### Windows PowerShell - -```powershell -# From git clone -cd ccs -git pull -.\install.ps1 - -# From irm install -irm ccs.kaitran.ca/install.ps1 | iex -``` - -## Auto PATH Configuration - -The installer automatically configures your shell PATH: - -**Supported Shells**: -- bash (`.bashrc` or `.bash_profile`) -- zsh (`.zshrc`) -- fish (`.config/fish/config.fish`) - -**How It Works**: -1. Detects your current shell from `$SHELL` environment variable -2. Checks if `~/.local/bin` already in PATH -3. If not, adds appropriate export to shell profile -4. Shows reload instructions - -**Idempotent**: -- Safe to run multiple times -- Checks for existing CCS PATH entry before adding -- Won't create duplicate entries - -**Manual PATH Setup** (if auto-config fails): - -Bash/Zsh: -```bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc -source ~/.bashrc # or source ~/.zshrc -``` - -Fish: -```fish -echo 'set -gx PATH $HOME/.local/bin $PATH' >> ~/.config/fish/config.fish -``` - -## Requirements - -### macOS / Linux -- `bash` 3.2+ -- `jq` (JSON processor, optional for enhanced features) -- [Claude CLI](https://docs.claude.com/en/docs/claude-code/installation) - -### Windows -- PowerShell 5.1+ (pre-installed on Windows 10+) -- [Claude CLI](https://docs.claude.com/en/docs/claude-code/installation) - -### Installing jq (macOS / Linux, optional) - -```bash -# macOS -brew install jq - -# Ubuntu/Debian -sudo apt install jq - -# Fedora -sudo dnf install jq - -# Arch -sudo pacman -S jq -``` - -**Note**: -- jq enhances GLM profile creation but is not required -- Windows uses PowerShell's built-in JSON support - no jq needed -- Installer creates basic templates without jq \ No newline at end of file diff --git a/docs/en/troubleshooting.md b/docs/en/troubleshooting.md deleted file mode 100644 index 528ae328..00000000 --- a/docs/en/troubleshooting.md +++ /dev/null @@ -1,593 +0,0 @@ -# CCS Troubleshooting Guide - -> **Note**: CCS has been recently simplified with a 35% code reduction (1,315 → 855 lines) while maintaining all functionality. The troubleshooting steps below apply to the simplified architecture. - -## Native Installer Deprecation - -**Issue:** "Why does the curl/irm installer show a deprecation warning?" - -**Cause:** Native shell installers are deprecated in favor of npm installation. - -**Solution:** -```bash -# Uninstall legacy version (if installed via curl/irm) -ccs-uninstall # or: curl -fsSL ccs.kaitran.ca/uninstall | bash - -# Install via npm (recommended) -npm install -g @kaitranntt/ccs -``` - -**Note:** The legacy installer now auto-runs npm install if Node.js is available. - -## npm Installation Issues - -### Config File Not Found After npm Install - -**Symptom**: After `npm install -g @kaitranntt/ccs`, running `ccs --version` shows error: -``` -Config file not found: /home/user/.ccs/config.json -``` - -**Cause**: You may have installed with `--ignore-scripts` flag, which skips the postinstall script that creates config files. - -**Solution**: -```bash -# Reinstall without --ignore-scripts -npm install -g @kaitranntt/ccs --force - -# Or manually run postinstall -node $(npm root -g)/@kaitranntt/ccs/scripts/postinstall.js - -# Or use traditional installer -curl -fsSL ccs.kaitran.ca/install | bash # macOS/Linux -irm ccs.kaitran.ca/install | iex # Windows -``` - -**Verify**: -```bash -ls -la ~/.ccs/ -# Should show: config.json, glm.settings.json -``` - -### Check npm ignore-scripts Setting - -```bash -# Check if ignore-scripts is enabled -npm config get ignore-scripts - -# If true, disable it (or use --force on install) -npm config set ignore-scripts false -``` - -## Windows-Specific Issues - -### PowerShell Execution Policy - -If you see "cannot be loaded because running scripts is disabled": - -```powershell -# Check current policy -Get-ExecutionPolicy - -# Allow current user to run scripts (recommended) -Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser - -# Or run with bypass (one-time) -powershell -ExecutionPolicy Bypass -File "$env:USERPROFILE\.ccs\ccs.ps1" glm -``` - -### PATH not updated (Windows) - -If `ccs` command not found after installation: - -1. Restart your terminal -2. Or manually add to PATH: - - Open "Edit environment variables for your account" - - Add `%USERPROFILE%\.ccs` to User PATH - - Restart terminal - -### Claude CLI not found (Windows) - -```powershell -# Check Claude CLI -where.exe claude - -# If missing, install from Claude docs -``` - -## Claude CLI in Non-Standard Location - -If Claude CLI is installed on a different drive or custom location (common on Windows systems with D: drives): - -### Symptoms -``` -╔═════════════════════════════════════════════╗ -║ ERROR ║ -╚═════════════════════════════════════════════╝ - -Claude CLI not found - -Searched: - - CCS_CLAUDE_PATH: (not set) - - System PATH: not found - - Common locations: not found -``` - -### Solution: Set CCS_CLAUDE_PATH - -**Step 1: Find Claude CLI Location** - -*Windows*: -```powershell -# Search all drives -Get-ChildItem -Path C:\,D:\,E:\ -Filter claude.exe -Recurse -ErrorAction SilentlyContinue | Select-Object FullName - -# Common locations to check manually -D:\Program Files\Claude\claude.exe -D:\Tools\Claude\claude.exe -D:\Users\\AppData\Local\Claude\claude.exe -``` - -*Unix/Linux/macOS*: -```bash -# Search system -sudo find / -name claude 2>/dev/null - -# Or check specific locations -ls -la /usr/local/bin/claude -ls -la ~/.local/bin/claude -ls -la /opt/homebrew/bin/claude -``` - -**Step 2: Set Environment Variable** - -*Windows (PowerShell) - Permanent*: -```powershell -# Replace with your actual path -$ClaudePath = "D:\Program Files\Claude\claude.exe" - -# Set for current session -$env:CCS_CLAUDE_PATH = $ClaudePath - -# Set permanently for user -[Environment]::SetEnvironmentVariable("CCS_CLAUDE_PATH", $ClaudePath, "User") - -# Restart terminal to apply -``` - -*Unix (bash) - Permanent*: -```bash -# Replace with your actual path -CLAUDE_PATH="/opt/custom/location/claude" - -# Add to shell profile -echo "export CCS_CLAUDE_PATH=\"$CLAUDE_PATH\"" >> ~/.bashrc - -# Reload profile -source ~/.bashrc -``` - -*Unix (zsh) - Permanent*: -```bash -# Replace with your actual path -CLAUDE_PATH="/opt/custom/location/claude" - -# Add to shell profile -echo "export CCS_CLAUDE_PATH=\"$CLAUDE_PATH\"" >> ~/.zshrc - -# Reload profile -source ~/.zshrc -``` - -**Step 3: Verify Configuration** - -```bash -# Check environment variable is set -echo $CCS_CLAUDE_PATH # Unix -$env:CCS_CLAUDE_PATH # Windows - -# Test CCS can find Claude -ccs --version - -# Test with actual profile -ccs glm --version -``` - -### Common Issues - -**Invalid Path**: -``` -Error: File not found: D:\Program Files\Claude\claude.exe -``` - -**Fix**: Double-check path, ensure file exists: -```powershell -Test-Path "D:\Program Files\Claude\claude.exe" # Windows -ls -la "/path/to/claude" # Unix -``` - -**Directory Instead of File**: -``` -Error: Path is a directory: D:\Program Files\Claude -``` - -**Fix**: Path must point to `claude.exe` file, not directory: -```powershell -# Wrong -$env:CCS_CLAUDE_PATH = "D:\Program Files\Claude" - -# Right -$env:CCS_CLAUDE_PATH = "D:\Program Files\Claude\claude.exe" -``` - -**Not Executable**: -``` -Error: File is not executable: /path/to/claude -``` - -**Fix** (Unix only): -```bash -chmod +x /path/to/claude -``` - -### WSL-Specific Configuration - -When using Windows Claude from WSL: - -```bash -# Mount path format: /mnt/d/ for D: drive -export CCS_CLAUDE_PATH="/mnt/d/Program Files/Claude/claude.exe" - -# Add to ~/.bashrc for persistence -echo 'export CCS_CLAUDE_PATH="/mnt/d/Program Files/Claude/claude.exe"' >> ~/.bashrc -source ~/.bashrc -``` - -**Note**: Spaces in Windows paths work correctly from WSL when quoted properly. - -### Debugging Detection - -To see what CCS checked: - -```bash -# Temporarily move claude out of PATH to test -# Then run ccs - error message shows what was checked - -ccs --version -# Will show: -# - CCS_CLAUDE_PATH: (status) -# - System PATH: not found -# - Common locations: not found -``` - -### Alternative: Add to PATH Instead - -If you prefer not using CCS_CLAUDE_PATH, add Claude directory to PATH: - -*Windows (PowerShell)*: -```powershell -# Add D:\Program Files\Claude to PATH -$ClaudeDir = "D:\Program Files\Claude" -$env:Path += ";$ClaudeDir" -[Environment]::SetEnvironmentVariable("Path", $env:Path, "User") - -# Restart terminal -``` - -*Unix (bash)*: -```bash -# Add /opt/claude/bin to PATH -echo 'export PATH="/opt/claude/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc -``` - -**Note**: CCS_CLAUDE_PATH takes priority over PATH, allowing per-project overrides. - -## Installation Issues - -### BASH_SOURCE unbound variable error - -This error occurs when running the installer in some shells or environments. - -**Fixed in latest version**: The installer now handles both piped execution (`curl | bash`) and direct execution (`./install.sh`). - -**Solution**: Upgrade to the latest version: -```bash -curl -fsSL https://raw.githubusercontent.com/kaitranntt/ccs/main/installers/install.sh | bash -``` - -### Git worktree not detected - -If installing from a git worktree or submodule, older versions may fail to detect the git repository. - -**Fixed in latest version**: The installer now detects both `.git` directory (standard clone) and `.git` file (worktree/submodule). - -**Solution**: Upgrade to the latest version or use the curl installation method. - -## Configuration Issues - -### Profile not found - -``` -Error: Profile 'foo' not found in ~/.ccs/config.json -``` - -**Fix**: Add profile to `~/.ccs/config.json`: -```json -{ - "profiles": { - "foo": "~/.ccs/foo.settings.json" - } -} -``` - -### Settings file missing - -``` -Error: Settings file not found: ~/.ccs/foo.settings.json -``` - -**Fix**: Create settings file or fix path in config. - -### jq not installed - -``` -Error: jq is required but not installed -``` - -**Fix**: Install jq (see installation guide). - -**Note**: The installer creates basic templates even without jq, but enhanced features require jq. - -## PATH Configuration Issues - -### Auto PATH Configuration - -v2.2.0+ automatically configures shell PATH. If you see reload instructions after install, follow them: - -**For bash**: -```bash -source ~/.bashrc -``` - -**For zsh**: -```bash -source ~/.zshrc -``` - -**For fish**: -```fish -source ~/.config/fish/config.fish -``` - -**Or open new terminal window** (PATH auto-loaded). - -### PATH Not Configured - -If `ccs` command not found after install and reload: - -**Verify PATH entry exists**: -```bash -# For bash/zsh -grep "\.local/bin" ~/.bashrc ~/.zshrc - -# For fish -grep "\.local/bin" ~/.config/fish/config.fish -``` - -**Manual fix** (if auto-config failed): - -Bash: -```bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc -``` - -Zsh: -```bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc -source ~/.zshrc -``` - -Fish: -```fish -echo 'set -gx PATH $HOME/.local/bin $PATH' >> ~/.config/fish/config.fish -source ~/.config/fish/config.fish -``` - -### Wrong Shell Profile - -If auto-config added to wrong file: - -**Find active profile**: -```bash -echo $SHELL # Shows current shell -``` - -**Common scenarios**: -- macOS bash uses `~/.bash_profile` (not `~/.bashrc`) -- Custom shells need manual config -- Tmux/screen may use different shell - -**Solution**: Manually add PATH to correct profile file. - -### Shell Not Detected - -If installer couldn't detect shell: - -**Symptoms**: -- No PATH warning shown -- `ccs` command not found after install - -**Solution**: Manual PATH setup (see above). - -### Default profile missing - -``` -Error: Profile 'default' not found in ~/.ccs/config.json -``` - -**Fix**: Add "default" profile or always specify profile name: -```json -{ - "profiles": { - "default": "~/.claude/settings.json" - } -} -``` - -## Common Problems - -### Claude CLI not found - -**Error Message**: -``` -╔═════════════════════════════════════════════╗ -║ ERROR ║ -╚═════════════════════════════════════════════╝ - -claude command not found -``` - -**Solution**: Install Claude CLI from [official documentation](https://docs.claude.com/en/docs/claude-code/installation). - -### Permission denied - -``` -Error: Permission denied: ~/.local/bin/ccs -``` - -**Solution**: Make the script executable: -```bash -chmod +x ~/.local/bin/ccs -``` - -### Config file not found - -**Error Message**: -``` -╔═════════════════════════════════════════════╗ -║ ERROR ║ -╚═════════════════════════════════════════════╝ - -Config file not found: ~/.ccs/config.json - -Solutions: - 1. Reinstall CCS: - curl -fsSL ccs.kaitran.ca/install | bash - - 2. Or create config manually: - mkdir -p ~/.ccs - cat > ~/.ccs/config.json << 'EOF' -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -EOF -``` - -**Solution**: Re-run installer or create config manually: -```bash -mkdir -p ~/.ccs -cat > ~/.ccs/config.json << 'EOF' -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -EOF -``` - -## Getting Help - -If you encounter issues not covered here: - -1. Check the [GitHub Issues](https://github.com/kaitranntt/ccs/issues) -2. Create a new issue with: - - Your operating system - - CCS version (`ccs --version`) - - Exact error message - - Steps to reproduce - -## Debug Mode - -Enable verbose output to troubleshoot issues: - -```bash -ccs --verbose glm -``` - -This will show: -- Which config file is being read -- Which profile is being selected -- Which settings file is being used -- The exact command being executed - -## Disable Colored Output - -If color output causes issues in your terminal or logs: - -```bash -export NO_COLOR=1 -ccs glm -``` - -**Use Cases**: -- CI/CD environments -- Log file generation -- Terminals without color support -- Accessibility preferences - ---- - -## GLMT Troubleshooting - -### Thinking Blocks Not Visible - -1. **Enable debug logging**: - ```bash - export CCS_DEBUG_LOG=1 - ccs glmt --verbose "test" - ``` - -2. **Check raw response**: - ```bash - cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content' - ``` - -3. **Scenarios**: - - **reasoning_content present**: Transformation issue → check response-anthropic.json - - **reasoning_content absent**: Z.AI API issue → verify API key/account status - -### Duplicate "Enchanting" Lines - -**Symptom**: Two spinner lines during thinking - -**Cause**: Terminal rendering (not CCS issue) - -**Solutions**: -- Use native terminal (iTerm2, GNOME Terminal, Windows Terminal) -- Exit tmux/screen before running -- Accept visual glitch (functionality unaffected) - -### Proxy Startup Timeout - -**Error**: "Proxy startup timeout (5s)" - -**Solutions**: -```bash -# Try non-thinking mode -ccs glm "your prompt" - -# Check Node.js -node --version # Requires ≥14 - -# Check port availability -netstat -an | grep 127.0.0.1 - -# Verbose details -ccs glmt --verbose "test" -``` \ No newline at end of file diff --git a/docs/en/usage.md b/docs/en/usage.md deleted file mode 100644 index adef96d4..00000000 --- a/docs/en/usage.md +++ /dev/null @@ -1,365 +0,0 @@ -# CCS Usage Guide - -## Why CCS? - -**Built for developers with both Claude subscription and GLM Coding Plan.** - -### Two Real Use Cases - -#### 1. Task-Appropriate Model Selection - -**Claude Sonnet 4.5** excels at: -- Complex architectural decisions -- System design and planning -- Debugging tricky issues -- Code reviews requiring deep reasoning - -**GLM 4.6** works great for: -- Simple bug fixes -- Straightforward implementations -- Routine refactoring -- Documentation writing - -**With CCS**: Switch models based on task complexity, maximize quality while managing costs. - -```bash -ccs # Planning new feature architecture -# Got the plan? Implement with GLM: -ccs glm # Write the straightforward code -``` - -#### 2. Rate Limit Management - -If you have both Claude subscription and GLM Coding Plan, you know the pain: -- Claude hits rate limit mid-project -- You manually copy GLM config to `~/.claude/settings.json` -- 5 minutes later, need to switch back -- Repeat 10x per day - -**CCS solves this**: -- One command to switch: `ccs` (default) or `ccs glm` (fallback) -- Keep both configs saved as profiles -- Switch in <1 second -- No file editing, no copy-paste, no mistakes - -### Features - -- Instant profile switching (Claude ↔ GLM) -- Pass-through all Claude CLI args -- Smart setup: detects your current provider -- Auto-creates configs during install -- **Simplified architecture**: 35% code reduction with optimized performance -- **Unified spawn logic**: Consolidated process execution for reliability -- **Streamlined error handling**: Clear, direct error messages -- No proxies, no magic—just efficient Node.js implementation - -## Basic Usage - -### Switching Profiles - -```bash -# Works on macOS, Linux, and Windows -ccs # Use Claude subscription (default) -ccs glm # Use GLM fallback -``` - -**Windows Note**: Commands work identically in PowerShell, CMD, and Git Bash. - -### With Arguments - -All args after profile name pass directly to Claude CLI: - -```bash -ccs glm --verbose -ccs /plan "add feature" -ccs glm /code "implement feature" -``` - -### Utility Commands - -```bash -ccs --version # Show enhanced version info with installation details -ccs --help # Show CCS-specific help documentation -ccs update # Check for and install updates -ccs update --force # Force reinstall from latest (skip update checks) -ccs update --beta # Install from beta channel (npm only) -``` - -**Example `--version` Output**: -``` -CCS (Claude Code Switch) v2.4.4 - -Installation: - Location: /home/user/.local/bin/ccs -> /home/user/.ccs/ccs - Config: ~/.ccs/config.json - -Documentation: https://github.com/kaitranntt/ccs -License: MIT - -Run 'ccs --help' for usage information -``` - -**Enhanced `--help` Features**: -- CCS-specific documentation (no longer delegates to Claude CLI) -- Comprehensive usage examples and flag descriptions -- Installation and uninstallation instructions -- Platform-specific guidance -- Configuration file location and troubleshooting - -### Update Command Details - -The `ccs update` command provides flexible update management with beta channel support: - -**Standard Update**: -```bash -ccs update -``` -- Checks for updates using cached results (24-hour cache) -- Only updates if a newer version is available -- Preserves package manager preference (npm, yarn, pnpm, bun) - -**Force Reinstall**: -```bash -ccs update --force -``` -- Skips all update checks and cache validation -- Reinstalls from the target channel immediately -- Useful for: - - Troubleshooting installation issues - - Ensuring clean installation - - Switching between channels without waiting -- Automatically clears package manager cache before reinstalling - -**Beta Channel** (npm installation only): -```bash -ccs update --beta -``` -- Installs from the `@dev` npm tag instead of `@latest` -- Access to cutting-edge features and fixes before stable release -- **Shows stability warnings**: - ``` - [!] Installing from @dev channel (unstable) - [!] Not recommended for production use - [!] Use `ccs update` (without --beta) to return to stable - ``` -- Can be combined with `--force`: `ccs update --force --beta` -- Switches to dev channel for future standard updates until reverted - -**Installation Method Detection**: -- **npm installations**: Full support for all flags (`--force`, `--beta`) - - Fetches versions from npm registry with tag-specific queries - - Installs from `@kaitranntt/ccs@latest` or `@kaitranntt/ccs@dev` -- **Direct installer installations**: Limited support - - Only supports `--force` flag - - Shows error for `--beta` with migration guidance: - ``` - [X] --beta flag requires npm installation - - Current installation method: direct installer - To use beta releases, install via npm: - - npm install -g @kaitranntt/ccs - ccs update --beta - - Or continue using stable releases via direct installer. - ``` - -**Uninstall (Recommended)**: -```bash -# npm (recommended) -npm uninstall -g @kaitranntt/ccs - -# Legacy uninstallers (for native installs only) -# macOS/Linux: curl -fsSL ccs.kaitran.ca/uninstall | bash -# Windows: irm ccs.kaitran.ca/uninstall | iex -``` - -**Platform-Specific Locations**: -- macOS: `/usr/local/bin/ccs` -- Linux: `~/.local/bin/ccs` -- Windows: `%USERPROFILE%\.ccs\ccs.ps1` - -### 🚧 Features in Development - -#### .claude/ Integration - -Task delegation via `--install` / `--uninstall` flags currently under development. - -**Status**: Testing incomplete, not available in current release - -**Implementation**: Core functionality exists but disabled pending testing - -**Timeline**: No ETA - follow GitHub issues for updates - -**For Now**: Use direct profile switching (`ccs glm`) for model selection - -**Output Example**: -``` -┌─ Installing CCS Commands & Skills -│ Source: /path/to/ccs/.claude -│ Target: /home/user/.claude -│ -│ Installing commands... -│ │ [OK] Installed command: ccs.md -│ -│ Installing skills... -│ │ [OK] Installed skill: ccs-delegation -└─ - -[OK] Installation complete! - Installed: 2 items - Skipped: 0 items (already exist) - -You can now use the /ccs command in Claude CLI for task delegation. -Example: /ccs glm /plan 'add user authentication' -``` - -**Notes**: -- Output uses ASCII symbols ([OK], [i], [X]) instead of emojis -- Colored output on TTY terminals (disable with `NO_COLOR=1`) -- Existing files skipped automatically (safe to re-run) - -## Task Delegation - -**CCS includes intelligent task delegation** via the `/ccs` meta-command: - -```bash -# Delegate planning to GLM (saves Sonnet tokens) -/ccs glm /plan "add user authentication" - -# Delegate coding to GLM -/ccs glm /code "implement auth endpoints" - -# Quick questions with Haiku -/ccs haiku /ask "explain this error" -``` - -**Benefits**: -- ✅ Save tokens by delegating simple tasks to cheaper models -- ✅ Use right model for each task automatically -- ✅ Reusable commands across all projects (user-scope) -- ✅ Seamless integration with existing workflows - -## Real Workflows - -### Task-Based Model Selection - -**Scenario**: Building a new payment integration feature - -```bash -# Step 1: Architecture & Planning (needs Claude's intelligence) -ccs -/plan "Design payment integration with Stripe, handle webhooks, errors, retries" -# → Claude Sonnet 4.5 thinks deeply about edge cases, security, architecture - -# Step 2: Implementation (straightforward coding, use GLM) -ccs glm -/code "implement the payment webhook handler from the plan" -# → GLM 4.6 writes the code efficiently, saves Claude usage - -# Step 3: Code Review (needs deep analysis) -ccs -/review "check the payment handler for security issues" -# → Claude Sonnet 4.5 catches subtle vulnerabilities - -# Step 4: Bug Fixes (simple) -ccs glm -/fix "update error message formatting" -# → GLM 4.6 handles routine fixes -``` - -**Result**: Best model for each task, lower costs, better quality. - -### Rate Limit Management - -```bash -# Working on complex refactoring with Claude -ccs -/plan "refactor authentication system" - -# Claude hits rate limit mid-task -# → Error: Rate limit exceeded - -# Switch to GLM instantly -ccs glm -# Continue working without interruption - -# Rate limit resets? Switch back -ccs -``` - -## How It Works - -The simplified CCS architecture provides efficient profile switching: - -1. **Argument parsing**: Smart detection of profile vs CLI flags -2. **Configuration lookup**: Reads settings path from `~/.ccs/config.json` -3. **Claude detection**: Optimized executable discovery across platforms -4. **Unified execution**: Single `execClaude()` function spawns process with `--settings [args]` - -### Recent Optimizations - -- **Consolidated spawn logic**: Single function eliminates code duplication -- **Removed redundant validation**: Streamlined security while maintaining safety -- **Simplified error handling**: Direct console.error for clarity and performance -- **Optimized platform detection**: Centralized cross-platform logic - -No magic. No file modification. Efficient delegation. Works identically across all platforms with improved performance and maintainability. - -## API Reference - -### Update Command API - -The `ccs update` command provides comprehensive update management with the following API: - -#### Syntax -```bash -ccs update [options] -``` - -#### Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| `--force` | flag | false | Skip update checks and force reinstall | -| `--beta` | flag | false | Install from beta channel (`@dev` tag) | - -#### Return Codes - -| Code | Meaning | -|------|---------| -| 0 | Success (no update needed or update installed) | -| 1 | Error (update failed, network issues, or invalid flags) | - -#### Examples - -```bash -# Standard update check -ccs update - -# Force reinstall from latest stable -ccs update --force - -# Switch to beta channel -ccs update --beta - -# Force reinstall from beta channel -ccs update --force --beta -``` - -#### Implementation Details - -**Version Fetching**: -- npm installations: Queries `https://registry.npmjs.org/@kaitranntt/ccs/{tag}` -- Direct installations: Queries GitHub API releases endpoint -- Cache: 24-hour cache to avoid excessive API calls - -**Error Handling**: -- Network timeouts: 5-second timeout for all HTTP requests -- Missing npm tag: Graceful fallback with informative error -- Installation conflicts: Clear guidance for resolution - -**Platform Support**: -- npm: Full feature support (all flags and channels) -- yarn/pnpm/bun: Full npm compatibility -- Direct installers: Limited to `--force` flag only \ No newline at end of file diff --git a/docs/errors/README.md b/docs/errors/README.md deleted file mode 100644 index 605dc00f..00000000 --- a/docs/errors/README.md +++ /dev/null @@ -1,332 +0,0 @@ -# CCS Error Codes - -Quick reference for CCS error codes and solutions. - -## Error Categories - -- **[E100-E199](#configuration-errors)**: Configuration Errors -- **[E200-E299](#profile-management-errors)**: Profile Management Errors -- **[E300-E399](#claude-cli-errors)**: Claude CLI Detection Errors -- **[E400-E499](#network-api-errors)**: Network/API Errors -- **[E500-E599](#file-system-errors)**: File System Errors -- **[E900-E999](#internal-errors)**: Internal Errors - ---- - -## Configuration Errors - -### E101: Configuration File Missing -**Cause**: `~/.ccs/config.json` not found - -**Solutions**: -```bash -# Reinstall CCS -npm install -g @kaitranntt/ccs --force -``` - ---- - -### E102: Invalid JSON in Configuration -**Cause**: Corrupted or malformed `config.json` - -**Solutions**: -```bash -# Backup and reset -mv ~/.ccs/config.json ~/.ccs/config.json.backup -npm install -g @kaitranntt/ccs --force -``` - ---- - -### E103: Invalid Profile Configuration -**Cause**: Profile settings reference non-existent settings file - -**Solutions**: -```bash -# Check profile settings -cat ~/.ccs/config.json - -# Fix path or recreate profile -ccs auth create -``` - ---- - -## Profile Management Errors - -### E104: Profile Not Found -**Cause**: Requested profile doesn't exist - -**Solutions**: -```bash -# List available profiles -ccs auth list - -# Create new profile -ccs auth create - -# Use existing profile -ccs "your prompt" -``` - ---- - -### E105: Profile Already Exists -**Cause**: Attempting to create profile that already exists - -**Solutions**: -```bash -# Use different name -ccs auth create - -# Or overwrite existing (use with caution) -ccs auth create --force -``` - ---- - -### E106: Cannot Delete Default Profile -**Cause**: Attempting to remove currently active default profile - -**Solutions**: -```bash -# Set different default first -ccs auth default - -# Then remove old default -ccs auth remove -``` - ---- - -### E107: Invalid Profile Name -**Cause**: Profile name contains invalid characters - -**Solutions**: -```bash -# Use only: alphanumeric, dash, underscore -# Valid: work, test-env, my_profile -# Invalid: my profile, test@work, profile! -``` - ---- - -## Claude CLI Errors - -### E301: Claude CLI Not Found -**Cause**: Claude CLI not installed or not in PATH - -**Solutions**: -```bash -# Install Claude CLI -# See: https://docs.claude.com/en/docs/claude-code/installation - -# Verify installation -command -v claude # Unix -Get-Command claude # Windows - -# Custom path (if installed elsewhere) -export CCS_CLAUDE_PATH="/path/to/claude" -``` - ---- - -### E302: Claude CLI Version Incompatible -**Cause**: Claude CLI version doesn't meet minimum requirements - -**Solutions**: -```bash -# Update Claude CLI -# Follow official update guide - -# Check version -claude --version -``` - ---- - -### E303: Claude CLI Execution Failed -**Cause**: Claude CLI failed to start or crashed - -**Solutions**: -```bash -# Test Claude directly -claude --version - -# Check permissions -ls -la $(which claude) - -# Reinstall if needed -``` - ---- - -## Network/API Errors - -### E401: GLMT Proxy Timeout -**Cause**: GLMT proxy server failed to start within 30 seconds - -**Solutions**: -```bash -# Check port conflicts -lsof -i :19889 # or random port shown in error - -# Use non-proxy GLM instead -ccs glm "your prompt" - -# Enable debug mode -export CCS_DEBUG=1 -ccs glmt "test" -``` - ---- - -### E402: API Key Missing -**Cause**: Required API key not configured - -**Solutions**: -```bash -# For GLM/GLMT/Kimi -# Add to settings file or use Claude login -claude /login -``` - ---- - -### E403: API Authentication Failed -**Cause**: Invalid or expired API credentials - -**Solutions**: -```bash -# Re-authenticate -claude /login - -# Check API key validity -# Verify in Claude dashboard -``` - ---- - -### E404: API Rate Limit Exceeded -**Cause**: Too many requests to API - -**Solutions**: -```bash -# Wait and retry -sleep 60 - -# Check rate limits in API dashboard -# Consider upgrading plan -``` - ---- - -## File System Errors - -### E501: Cannot Create Directory -**Cause**: Permission denied or path issues - -**Solutions**: -```bash -# Fix ownership -sudo chown -R $USER ~/.ccs - -# Fix permissions -chmod 755 ~/.ccs - -# Retry -npm install -g @kaitranntt/ccs --force -``` - ---- - -### E502: Cannot Write File -**Cause**: Permission denied writing to CCS directories - -**Solutions**: -```bash -# Fix permissions -sudo chown -R $USER ~/.ccs ~/.claude -chmod -R 755 ~/.ccs ~/.claude - -# Check disk space -df -h ~ -``` - ---- - -### E503: Cannot Read File -**Cause**: File doesn't exist or permission denied - -**Solutions**: -```bash -# Check file exists -ls -la - -# Fix permissions -chmod 644 - -# Recreate if missing -ccs auth create -``` - ---- - -### E504: Instance Directory Not Found -**Cause**: Profile instance directory missing - -**Solutions**: -```bash -# Recreate profile -ccs auth remove -ccs auth create -``` - ---- - -## Internal Errors - -### E900: Internal Error -**Cause**: Unexpected error in CCS code - -**Solutions**: -```bash -# Report bug with debug output -export CCS_DEBUG=1 -ccs 2>&1 | tee error.log - -# Report at: https://github.com/kaitranntt/ccs/issues -``` - ---- - -### E901: Invalid State -**Cause**: CCS detected inconsistent internal state - -**Solutions**: -```bash -# Run health check -ccs doctor - -# Reset CCS data (backup first!) -mv ~/.ccs ~/.ccs.backup -npm install -g @kaitranntt/ccs --force -``` - ---- - -## Getting Help - -If you encounter an error not listed here: - -1. Enable debug mode: `export CCS_DEBUG=1` -2. Run the failing command -3. Check logs: `~/.ccs/logs/` -4. Report issue: https://github.com/kaitranntt/ccs/issues - -Include: -- Error code -- Full error message -- Debug output -- OS/platform info -- CCS version: `ccs --version` diff --git a/docs/glmt-controls.md b/docs/glmt-controls.md deleted file mode 100644 index 7254567d..00000000 --- a/docs/glmt-controls.md +++ /dev/null @@ -1,328 +0,0 @@ -# GLMT Control Mechanisms - -Technical guide for thinking controls in `ccs glmt`. - -## Problem Statement - -GLMT (GLM with Thinking) exhibited three issues: - -1. **Unbounded planning loops**: Model entered thinking loops without tool calls, wasting tokens -2. **Token waste**: Thinking enabled for simple execution tasks (e.g., "list files") -3. **Chinese output**: Responses in Chinese despite English prompts - -## Solution Overview - -Three control mechanisms: - -1. **Locale enforcer** - Force English output (automatic) -2. **Task classifier** - Detect reasoning vs execution tasks -3. **Loop detection** - Break planning loops automatically - -## Control Mechanisms - -### 1. Locale Enforcer (`bin/glmt/locale-enforcer.js`) - -**Purpose**: Prevent non-English output - -**Implementation**: -- Always injects "CRITICAL: You MUST respond in English only" into system prompts -- No configuration required - always enabled for consistency -- Handles both string and array content formats - -**Strategy**: -1. If system prompt exists: Prepend instruction -2. If no system prompt: Prepend to first user message -3. Preserve message structure (string vs array content) - -**Code**: -```javascript -class LocaleEnforcer { - constructor(options = {}) { - this.instruction = "CRITICAL: You MUST respond in English only, regardless of the input language or context. This is a strict requirement."; - } - - injectInstruction(messages) { - // Clone messages to avoid mutation - const modifiedMessages = JSON.parse(JSON.stringify(messages)); - - // Strategy 1: Inject into system prompt (preferred) - const systemIndex = modifiedMessages.findIndex(m => m.role === 'system'); - if (systemIndex >= 0) { - const systemMsg = modifiedMessages[systemIndex]; - // Prepend instruction to system message content - return modifiedMessages; - } - - // Strategy 2: Prepend to first user message - const userIndex = modifiedMessages.findIndex(m => m.role === 'user'); - if (userIndex >= 0) { - const userMsg = modifiedMessages[userIndex]; - // Prepend instruction to user message content - return modifiedMessages; - } - - return modifiedMessages; - } -} -``` - -**Files**: 85 lines - -### 2. Task Classifier (`bin/glmt/glmt-transformer.js`) - -**Purpose**: Classify tasks as reasoning vs execution for intelligent thinking activation - -**Implementation**: -- Keyword-based classification in natural language prompts -- Automatic detection without user configuration -- Supports reasoning keywords and execution keywords - -**Reasoning Keywords**: -- `think`, `analyze`, `design`, `plan`, `debug`, `optimize`, `review`, `explain` -- `think hard`, `think harder`, `ultrathink` (increasing intensity levels) - -**Execution Keywords**: -- `list`, `show`, `create`, `update`, `delete`, `run`, `execute`, `fix`, `implement` - -**Priority System**: -- `ultrathink` > `think harder` > `think hard` > `think` > default -- Higher priority keywords override lower ones -- Mixed tasks default to enabled thinking - -**Examples**: -- `"think about the architecture"` → reasoning → thinking enabled -- `"list files in directory"` → execution → thinking disabled -- `"debug authentication issue"` → reasoning → thinking enabled -- `"fix the bug"` → execution → thinking disabled -- `"ultrathink this complex problem"` → maximum reasoning → thinking enabled - -### 3. Loop Detection (`bin/glmt/delta-accumulator.js`) - -**Purpose**: Break unbounded planning loops - -**Implementation**: -- Tracks consecutive thinking blocks without tool calls -- Triggers after 3 consecutive thinking blocks (configurable) -- Injects system message to force execution mode - -**Code**: -```javascript -class DeltaAccumulator { - constructor() { - this.consecutiveThinkingBlocks = 0; - } - - trackThinkingLoop(event) { - if (event.type === 'content_block_start' && event.content_block.type === 'thinking') { - this.consecutiveThinkingBlocks++; - - if (this.consecutiveThinkingBlocks >= 3) { - // Trigger loop detection - this.injectLoopBreaker(); - } - } - - if (event.type === 'tool_call' || event.type === 'tool_result') { - // Reset counter on tool activity - this.consecutiveThinkingBlocks = 0; - } - } -} -``` - -**Loop Breaker Message**: -``` -STOP thinking and start executing. You've been planning too long without taking action. -Please provide concrete solutions or use available tools to complete the task. -``` - -**Files**: 146 lines - -## Control Tags & Keywords - -### Control Tags (Manual Control) -- `` - Enable/disable reasoning blocks (default: On) -- `` - Deprecated - Z.AI only supports binary thinking - -### Thinking Keywords (Automatic Activation) -- `think` - Enable reasoning (low effort) -- `think hard` - Enable reasoning (medium effort) -- `think harder` - Enable reasoning (high effort) -- `ultrathink` - Maximum reasoning depth (max effort) - -**Usage Examples**: -```bash -ccs glmt "think about the microservices architecture" -ccs glmt "ultrathink this complex algorithm optimization" -ccs glmt "implement the user authentication feature" -ccs glmt "debug the memory leak issue" -``` - -## Integration Flow - -```javascript -// 1. Locale enforcement (always applied) -const localeEnforcer = new LocaleEnforcer(); -const messagesWithLocale = localeEnforcer.injectInstruction(request.messages); - -// 2. Task classification (automatic) -const taskClassifier = new TaskClassifier(); // Built into transformer -const thinkingConfig = taskClassifier.classifyTask(prompt); - -// 3. Apply thinking configuration -request.thinking = thinkingConfig; - -// 4. Loop detection (during streaming) -const deltaAccumulator = new DeltaAccumulator(); -deltaAccumulator.trackThinkingLoop(event); -``` - -## Environment Variables - -### General Environment Variables - -**CCS_DEBUG=1** -- Enable debug logging (file logging to ~/.ccs/logs/ + enhanced console diagnostics) -- Shows reasoning deltas, block creation, and loop detection activity - -**CCS_CLAUDE_PATH=/path/to/claude** -- Custom Claude CLI path for non-standard installations - -## Testing - -GLMT includes comprehensive test coverage: - -```bash -# Locale enforcer tests -npm test -- tests/unit/glmt/locale-enforcer.test.js - -# GLMT transformer tests -npm test -- tests/unit/glmt/glmt-transformer.test.js - -# Integration tests -npm test -- tests/integration/glmt/ -``` - -**Test Coverage**: 35+ tests covering: -- Locale enforcement (3 scenarios) -- Task classification and thinking activation -- Loop detection and breaker injection -- Streaming transformation and delta accumulation -- Tool calling support and bidirectional transformation - -## Troubleshooting - -### Chinese Output Despite Locale Enforcement - -**Expected**: Should never happen with current implementation - -**If it occurs**: -1. Check for malformed messages in debug logs -2. Verify locale enforcer is being called in proxy flow -3. Check system message content in transformation logs - -**Debug**: -```bash -export CCS_DEBUG=1 -ccs glmt "test prompt" -# Check logs: ~/.ccs/logs/*request-openai.json -``` - -### Excessive Planning Loops - -**Symptoms**: Multiple consecutive thinking blocks without tool calls - -**Expected behavior**: Loop detector should trigger after 3 blocks - -**If loops persist**: -1. Check loop detector logs: `export CCS_DEBUG=1` -2. Verify consecutive thinking counter reset on tool calls -3. Check loop breaker message injection - -**Manual intervention**: -```bash -# Use specific execution keywords to bypass thinking -ccs glmt "implement the solution now" -ccs glmt "fix the bug immediately" -ccs glmt "execute the code" -``` - -### No Thinking Blocks on Complex Tasks - -**Symptoms**: Straight to execution without reasoning - -**Cause**: Task classifier may not recognize reasoning keywords - -**Solutions**: -1. Use explicit thinking keywords: - ```bash - ccs glmt "think about this problem" - ccs glmt "ultrathink the architecture" - ``` -2. Use control tags: - ```bash - ccs glmt " analyze this complex issue" - ``` -3. Check if task classification working in debug logs - -### Token Waste on Simple Tasks - -**Expected behavior**: Task classifier should disable thinking for execution tasks - -**If thinking still enabled**: -1. Check for mixed keywords in prompt (both reasoning and execution) -2. Use explicit execution keywords: `fix`, `implement`, `execute`, `create` -3. Verify task classification in debug logs - -## Architecture Notes - -### Z.AI API Constraints - -- **Binary thinking only**: Z.AI supports `thinking_enabled: true/false`, not effort levels -- **Reasoning content**: Delivered via `reasoning_content` field in API responses -- **Tool calling**: Full OpenAI-compatible function calling supported -- **Streaming**: Real-time delivery of reasoning content and tool calls - -### Backward Compatibility - -- **Control tags**: `` still work alongside keywords -- **Claude CLI thinking parameter**: Respects `thinking.type` and `budget_tokens` -- **Precedence**: CLI parameter > message tags > keywords > default - -### Performance - -- **TTFB**: <500ms for streaming mode -- **Auto-fallback**: Switches to buffered mode if streaming errors -- **Loop prevention**: Eliminates token waste from unbounded planning -- **Intelligent activation**: Thinking only when beneficial - -## Security Limits - -**DoS protection** (built into proxy): -- SSE buffer: 1MB max per event -- Content buffer: 10MB max per block (thinking/text) -- Content blocks: 100 max per message -- Request timeout: 120s (both streaming and buffered) - -**Loop protection**: -- Maximum 3 consecutive thinking blocks -- Automatic loop breaker injection -- Prevents unlimited token consumption - -## Migration Notes - -### From Environment Variables (v3.5+) - -The following environment variables have been **removed**: -- ~~`CCS_GLMT_FORCE_ENGLISH`~~ → Now always enabled -- ~~`CCS_GLMT_THINKING_BUDGET`~~ → Replaced by intelligent task classification -- ~~`CCS_GLMT_STREAMING`~~ → Automatic streaming with fallback - -**No action required** - GLMT automatically handles all these cases intelligently. - -### New Features (v3.5+) - -- **Thinking keywords**: Natural language control (`think`, `think hard`, etc.) -- **Loop detection**: Automatic prevention of planning loops -- **Enhanced streaming**: Better error handling and auto-fallback -- **Tool support**: Full MCP tools and function calling compatibility \ No newline at end of file diff --git a/docs/headless-workflow.md b/docs/headless-workflow.md deleted file mode 100644 index 5ce7893b..00000000 --- a/docs/headless-workflow.md +++ /dev/null @@ -1,175 +0,0 @@ -# Headless Workflow - -**Last Updated**: 2025-11-15 - -CCS delegation uses Claude Code headless mode with enhanced features for token optimization. - -## Core Concept - -CCS delegation executes tasks via alternative models using enhanced Claude Code headless mode with stream-JSON output, session management, and cost tracking. - -**Actual Command:** -```bash -ccs {profile} -p "prompt" -``` - -Internally executes: -```bash -claude -p "prompt" --settings ~/.ccs/{profile}.settings.json --output-format stream-json --permission-mode acceptEdits -``` - -**Docs:** https://code.claude.com/docs/en/headless.md - -## How It Works - -**Workflow:** -1. User: `/ccs "task"` in Claude Code session (auto-selects profile) -2. CCS detects `-p` flag and routes to HeadlessExecutor -3. HeadlessExecutor spawns: `claude -p "task" --settings ~/.ccs/[selected].settings.json --output-format stream-json --permission-mode acceptEdits` -4. Claude Code runs headless with selected profile + enhanced flags -5. Returns stream-JSON with session_id, cost, turns -6. Real-time tool use visibility in TTY -7. ResultFormatter displays formatted results with metadata - -**Enhanced Features:** -- Stream-JSON output parsing (`--output-format stream-json`) -- Real-time tool use visibility (e.g., `[Tool Use: Bash]`) -- Session persistence (`~/.ccs/delegation-sessions.json`) -- Cost tracking (displays USD cost per execution) -- Time-based limits (10 min default timeout with graceful termination) -- Multi-turn session management (resume via session_id) -- Formatted ASCII box output - -## Profile Settings - -**Location:** `~/.ccs/{profile}.settings.json` - -**Examples:** -- GLM: `~/.ccs/glm.settings.json` -- Kimi: `~/.ccs/kimi.settings.json` - -**Example content:** -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic", - "ANTHROPIC_AUTH_TOKEN": "your-glm-api-key", - "ANTHROPIC_MODEL": "glm-4.6" - } -} -``` - -## Output Format - -**Stream-JSON Mode** (automatically enabled): -Each message is a separate JSON object (jsonl format): -```json -{"type":"init","session_id":"abc123def456"} -{"type":"user","message":{"role":"user","content":"Task description"}} -{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash"}]}} -{"type":"result","subtype":"success","total_cost_usd":0.0025,"num_turns":3,"session_id":"abc123def456","result":"Task completed"} -``` - -**Real-time Progress** (TTY only): -``` -[i] Delegating to GLM-4.6... -[Tool Use: Write] -[Tool Use: Write] -[Tool Use: Bash] -[i] Execution completed in 1.5s -``` - -**Formatted Output** (displayed to user): -``` -╔══════════════════════════════════════════════════════╗ -║ Working Directory: /path/to/project ║ -║ Model: GLM-4.6 ║ -║ Duration: 1.5s ║ -║ Exit Code: 0 ║ -║ Session ID: abc123de ║ -║ Cost: $0.0025 ║ -║ Turns: 3 ║ -╚══════════════════════════════════════════════════════╝ -``` - -**Extracted Fields:** -- `session_id` - For multi-turn (--resume) -- `total_cost_usd` - Cost per execution -- `num_turns` - Turn count -- `is_error` - Error flag -- `result` - Task output - -**Exit codes:** 0 = success, non-zero = error - -## Multi-Turn Sessions - -**Start session:** -```bash -ccs glm -p "implement feature" -``` - -**Continue session:** -```bash -ccs glm:continue -p "add tests" -ccs glm:continue -p "run tests" -``` - -Via slash commands: -``` -/ccs "implement feature" # Auto-selects best profile -/ccs --glm "implement feature" # Forces GLM profile -/ccs:continue "add tests" # Continue last session -``` - -**Session Storage:** `~/.ccs/delegation-sessions.json` - -**Metadata:** -- Session ID -- Total cost (aggregated across turns) -- Turn count -- Last turn timestamp -- Working directory - -**Expiration:** ~30 days, auto-cleanup - -## Usage Patterns - -**Single execution:** -```bash -ccs glm -p "task description" -``` - -**With options:** -```bash -ccs glm -p "task" --permission-mode plan -``` - -**Continue session:** -```bash -ccs glm:continue -p "follow-up task" -``` - -All standard Claude Code headless flags are supported. See: https://code.claude.com/docs/en/headless.md - -## Error Handling - -**Common errors:** -- `Settings file not found` - Profile not configured (`ccs doctor` to diagnose) -- `Claude CLI not found` - Install Claude Code -- `Invalid API key` - Check profile settings in `~/.ccs/{profile}.settings.json` - -**Diagnostics:** -```bash -ccs doctor # Check configuration -ccs --version # Show delegation status -``` - ---- - -## Related Documentation - -**Entry Point**: `../SKILL.md` - Quick start and decision framework -**Decision Guide**: `delegation-guidelines.md` - When to delegate -**Error Recovery**: `troubleshooting.md` - Common issues - -**Official Docs**: https://code.claude.com/docs/en/headless.md diff --git a/docs/ja/README.md b/docs/ja/README.md deleted file mode 100644 index 7d114040..00000000 --- a/docs/ja/README.md +++ /dev/null @@ -1,653 +0,0 @@ -
- -# CCS - Claude Code Switch - -![CCS Logo](../../docs/assets/ccs-logo-medium.png) - -### Claude Code用ユニバーサルAIプロファイルマネージャー - -**複数のClaudeアカウント、任意のAnthropic互換API、OAuthプロバイダー(Gemini、Codex、Antigravity)を瞬時に切り替え。** -レート制限を回避し、無制限のプロファイルで継続的に作業。 - -
- -[![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](LICENSE) -[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey?style=for-the-badge)]() -[![npm](https://img.shields.io/npm/v/@kaitranntt/ccs?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@kaitranntt/ccs) -[![PoweredBy](https://img.shields.io/badge/PoweredBy-ClaudeKit-C15F3C?style=for-the-badge)](https://claudekit.cc?ref=HMNKXOHN) - -**Languages**: [English](../../README.md) · [Tiếng Việt](../vi/README.md) · [日本語](README.md) - -
- -
- -## クイックスタート - -### インストール - -**npmパッケージ(推奨)** - -**macOS / Linux / Windows** -```bash -npm install -g @kaitranntt/ccs -``` - -**主要なパッケージマネージャーすべてに対応:** - -```bash -# yarn -yarn global add @kaitranntt/ccs - -# pnpm(ディスク使用量70%削減) -pnpm add -g @kaitranntt/ccs - -# bun(30倍高速) -bun add -g @kaitranntt/ccs -``` - -
-[!] 非推奨: ネイティブシェルインストーラー(レガシー) - -
- -> [!WARNING] -> **これらのインストーラーは非推奨であり、将来のバージョンで削除されます。** -> 現在は npm インストールに自動リダイレクトされます。npm を直接使用してください。 - -**macOS / Linux** -```bash -curl -fsSL ccs.kaitran.ca/install | bash -``` - -**Windows PowerShell** -```powershell -irm ccs.kaitran.ca/install | iex -``` - -**注**: スクリプトは非推奨の警告を表示し、Node.jsが利用可能な場合は自動的にnpmインストールを実行します。 - -
- -
- -### 設定(自動作成) - -**CCSはインストール時に自動的に設定を作成します**(npm postinstallスクリプト経由)。 - -**~/.ccs/config.json**: -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "glmt": "~/.ccs/glmt.settings.json", - "kimi": "~/.ccs/kimi.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -
-

カスタムClaude CLIパス

- -
- -Claude CLIが標準以外の場所(Dドライブ、カスタムディレクトリ)にインストールされている場合は、`CCS_CLAUDE_PATH`を設定してください: - -```bash -# Unix/Linux/macOS -export CCS_CLAUDE_PATH="/path/to/claude" - -# Windows PowerShell -$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe" -``` - -**参照**: [トラブルシューティングガイド](./docs/en/troubleshooting.md#claude-cli-in-non-standard-location) 詳細な設定手順 - -
- -
-

Windowsシンボリックリンクサポート(開発者モード)

- -
- -**Windowsユーザー**: 本物のシンボリックリンクで高速な動作と即時同期を得るために開発者モードを有効にしてください: - -1. **設定** → **プライバシーとセキュリティ** → **開発者向け** を開く -2. **開発者モード** を有効にする -3. CCSを再インストール: `npm install -g @kaitranntt/ccs` - -**警告**: 開発者モードなしの場合、CCSは自動的にディレクトリコピーにフォールバック(動作しますが、プロファイル間の即時同期はありません) - -
- -
- -### 最初の切り替え - -> [!IMPORTANT] -> **代替モデルを使用する前に、設定ファイルでAPIキーを更新してください:** -> -> - **GLM**: `~/.ccs/glm.settings.json`を編集してZ.AI Coding Plan APIキーを追加 -> - **GLMT**: `~/.ccs/glmt.settings.json`を編集してZ.AI Coding Plan APIキーを追加 -> - **Kimi**: `~/.ccs/kimi.settings.json`を編集してKimi APIキーを追加 - -
- -**並列ワークフロー:計画 + 実行** - -```bash -# Terminal 1 - 計画(Claude Sonnet) -ccs "認証とレート制限付きREST APIの計画" - -# Terminal 2 - 実行(GLM、コスト最適化) -ccs glm "計画からユーザー認証エンドポイントを実装" -``` - -
-思考モデル(Kimi & GLMT) - -
- -```bash -# Kimi - 安定した思考サポート -ccs kimi "トレードオフ分析付きキャッシュ戦略の設計" - -# GLMT - 実験的(詳細は下記参照) -ccs glmt "推論ステップ付き複雑なアルゴリズムのデバッグ" -``` - -**注**: GLMTは実験的で不安定です。詳細については下記の[GLM with Thinking (GLMT)](#glm-with-thinking-glmt)セクションを参照してください。 - -
- -
- -## 開発者の日常的な課題 - -
- -### **切り替えを停止。調整を開始。** - -**セッション制限がフロー状態を殺すべきではありません。** -
- -実装に深く集中しています。コンテキストが読み込まれました。解決策が結晶化しています。
-その後: 🔴 _"使用制限に達しました。"_ - -**モチベーションが失われました。コンテキストが失われました。生産性が崩壊しました。** - -## **解決策:並列ワークフロー** - -
-❌ 古い方法: 制限に達した時に切り替える(反応的) - -### 現在のワークフロー: -- **14時:** 機能開発、ゾーン状態 -- **15時:** 🔴 使用制限に達した -- **15:05:** 作業停止、`~/.claude/settings.json`を編集 -- **15:15:** アカウント切り替え、コンテキストが失われる -- **15:30:** フロー状態に戻ろうと試みる -- **16時:** ついに生産性が回復 - -- **結果:** 1時間失われ、モチベーションが破壊され、不満が蓄積 - -
- -
-✨ 新しい方法: 最初から並列で実行(主導的) - 推奨 - -### 新しいワークフロー: -- **14時:** **ターミナル1:** `ccs "APIアーキテクチャを計画"` → 戦略的思考(Claude Pro) -- **14時:** **ターミナル2:** `ccs glm "エンドポイントを実装"` → コード実行(GLM) -- **15時:** まだ開発継続、割れなし -- **16時:** フロー状態達成、生産性急上昇 -- **17時:** 機能が完了、コンテキスト維持 - -- **結果:** ダウムタイムなし、継続的生産性、不満減少 - -### 💰 **価値提案:** -- **設定:** 既存のClaude Pro + GLM Lite(費用対効果の高い追加) -- **価値:** 1時間/日 × 20労働日 = 20時間/月を回収 -- **ROI:** 開発時間は設定コスト以上の価値がある -- **現実:** オーバーヘッドより速く出荷 - -
- -## あなたの道を選択 - -
-予算重視: GLMのみ - -- **最適:** 費用意識の高い開発、基本的なコード生成 -- **使用法:** 費用効果の高いAI支援のために`ccs glm`を直接使用 -- **現実:** Claudeアクセスなし、多くのコーディングタスクに対応可能 -- **設定:** GLM APIキーのみ、非常に手頃 - -
- -
-✨ 日々の開発に推奨: 1 Claude Pro + 1 GLM Lite - -- **最適:** 日々のコードデリバリー、真剣な開発作業 -- **使用法:** `ccs`で計画 + `ccs glm`で実行(並列ワークフロー) -- **現実:** ほとんどの開発者にとって能力と費用の完璧なバランス -- **価値:** セッション制限に達せず、継続的生産性 - -
- -
-パワーユーザー: 複数のClaude Pro + GLM Pro - -- **最適:** 重い作業量、並行プロジェクト、ソロ開発 -- **解放:** セッション・週次制限を決して枯渇させない -- **ワークフロー:** 3+以上のターミナルで専門タスクを同時実行 - -
- -
-プライバシー重視: 仕事/個人の分離 - -- **必要時:** 仕事と個人AIコンテキストの厳格な分離 -- **設定:** `ccs auth create work` + `ccs auth create personal` -- **注意:** 高度な機能 - ほとんどのユーザーには不要 - -
- ---- - -## 手動切り替えではなくCCSを使う理由は? - -
- -**CCSは「午後3時に制限に達したら切り替える」ことではありません。** - -## **それは最初から並列で実行することです。** - -
- -### コアな違い - -| **手動切り替え** | **CCSオーケストレーション** | -|:---|:---| -| 🔴 制限達成 → 作業停止 → 設定ファイル編集 → 再起動 | ✅ 最初から異なるモデルで複数ターミナルを実行 | -| 😰 コンテキストロスとフロー状態中断 | 😌 コンテキスト維持での継続的生産性 | -| 📝 逐次的タスク処理 | ⚡ 並列ワークフロー(計画 + 実行を同時に) | -| 🛠️ ブロックされた時の反応的問題解決 | 🎯 ブロックを防ぐ主導的ワークフロー設計 | - -### CCSが提供するもの - -- **ゼロコンテキスト切り替え:** 割れずにフロー状態を維持 -- **並列生産性:** 1ターミナルで戦略計画、もう1つでコード実行 -- **即座アカウント管理:** 1コマンド切り替え、設定ファイル編集不要 -- **仕事と生活の分離:** ログアウトせずにコンテキストを分離 -- **クロスプラットフォーム一貫性:** macOS、Linux、Windowsで同じスムーズな体験 - -
- -## アーキテクチャ - -### プロファイルタイプ - -**設定ベース**: GLM, GLMT, Kimi, default -- 設定ファイルを指す`--settings`フラグを使用 -- GLMT: 思考モードサポートの埋め込みプロキシ - -**アカウントベース**: work, personal, team -- 分離されたインスタンスに`CLAUDE_CONFIG_DIR`を使用 -- `ccs auth create `で作成 - -### 共有データ(v3.1) - -コマンドとスキルは`~/.ccs/shared/`からシンボリックリンク - プロファイル間の重複なし。 - -```plaintext -~/.ccs/ -├── shared/ # すべてのプロファイルで共有 -│ ├── agents/ -│ ├── commands/ -│ └── skills/ -├── instances/ # プロファイル固有のデータ -│ └── work/ -│ ├── agents@ → shared/agents/ -│ ├── commands@ → shared/commands/ -│ ├── skills@ → shared/skills/ -│ ├── settings.json # APIキー、認証情報 -│ ├── sessions/ # 会話履歴 -│ └── ... -``` - -| タイプ | ファイル | -|:-----|:------| -| **共有** | `commands/`, `skills/`, `agents/` | -| **プロファイル固有** | `settings.json`, `sessions/`, `todolists/`, `logs/` | - -> [!NOTE] -> **Windows**: シンボリックリンクが利用できない場合はディレクトリをコピー(本物のシンボリックリンクには開発者モードを有効にしてください) - -
- -## 使用例 - -### 基本的な切り替え - -```bash -ccs # Claudeサブスクリプション(デフォルト) -ccs glm # GLM(コスト最適化) -ccs kimi # Kimi(思考サポート付き) -``` - -### マルチアカウント設定 - -```bash -# アカウントを作成 -ccs auth create work -ccs auth create personal -``` - -**別々のターミナルで同時に実行:** - -```bash -# Terminal 1 - 業務用 -ccs work "機能を実装" - -# Terminal 2 - 個人用(同時) -ccs personal "コードレビュー" -``` - -### ヘルプとバージョン - -```bash -ccs --version # バージョンを表示 -ccs --help # すべてのコマンドとオプションを表示 -``` - -
- -## GLM with Thinking (GLMT) - -> [!CAUTION] -> ### 本番環境未対応 - 実験的機能 -> -> **GLMTは実験的で広範なデバッグが必要です**: -> - ストリーミングとツールサポートはまだ開発中 -> - 予期せぬエラー、タイムアウト、不完全な応答が発生する可能性 -> - 頻繁なデバッグと手動介入が必要 -> - **重要なワークフローや本番使用には推奨されません** -> -> **GLM Thinkingの代替案**: **CCR hustle**と**BedollaのTransformer**([ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/))を通じて、より安定した実装を検討してください。 - -> [!IMPORTANT] -> GLMTはnpmインストールが必要です(`npm install -g @kaitranntt/ccs`)。ネイティブシェルバージョンでは利用できません(Node.js HTTPサーバーが必要)。 - -
- -> [!NOTE] -> ### 謝辞:GLMTを可能にした基盤 -> -> **CCSのGLMT実装は、[@Bedolla](https://github.com/Bedolla)の画期的な仕事に存在を負っています**。彼は[Claude Code Router (CCR)](https://github.com/musistudio/claude-code-router)とZ.AIの推論能力をブリッジする[最初の統合](https://github.com/Bedolla/ZaiTransformer/)を作成しました。 -> -> ZaiTransformer以前、誰もZ.AIの思考モードとClaude Codeのワークフローを正常に統合できませんでした。Bedollaの仕事は単なる有用なものではなく、**基盤的**でした。彼のリクエスト/レスポンストランスフォーメーションアーキテクチャ、思考モード制御メカニズム、埋め込みプロキシ設計の実装は、GLMTの設計に直接インスピレーションを与え、可能にしました。 -> -> **ZaiTransformerの先駆的な仕事なしでは、GLMTは現在の形では存在しませんでした。** GLMTの思考能力から利益を得る場合は、Claude Codeエコシステムでの先駆的な仕事をサポートするために[ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/)にスターを付けてください。 - -
- -
-

GLM vs GLMT 比較

- -
- -
- -| 機能 | GLM (`ccs glm`) | GLMT (`ccs glmt`) | -|:--------|:----------------|:------------------| -| **エンドポイント** | Anthropic互換 | OpenAI互換 | -| **思考** | なし | 実験的(reasoning_content) | -| **ツールサポート** | 基本的 | **不安定(v3.5+)** | -| **MCPツール** | 制限あり | **バグあり(v3.5+)** | -| **ストリーミング** | 安定 | **実験的(v3.4+)** | -| **TTFB** | <500ms | <500ms(時々)、2-10秒+(頻繁) | -| **使用例** | 信頼性の高い作業 | **デバッグ実験のみ** | - -
- -
- -
- -
-

ツールサポート(v3.5) - 実験的

- -
- -**GLMTはMCPツールと関数呼び出しを試行:** - -- **双方向トランスフォーメーション**: Anthropicツール ↔ OpenAI形式(不安定) -- **MCP統合**: MCPツールが時々実行(多くの場合XMLガベージを出力) -- **ストリーミングツール呼び出し**: リアルタイムツール呼び出し(クラッシュしない場合) -- **後方互換**: 既存の思考サポートを破壊する可能性 -- **設定が必要**: 頻繁な手動デバッグが必要 - -
- -
-

ストリーミングサポート(v3.4) - しばしば失敗

- -
- -**GLMTは増分推論コンテンツ配信でリアルタイムストリーミングを試行:** - -- **デフォルト**: ストリーミング有効(動作時TTFB <500ms) -- **自動フォールバック**: エラーにより頻繁にバッファモードに切り替え -- **思考パラメータ**: Claude CLI `thinking`パラメータが時々動作 - - `thinking.type`と`budget_tokens`を無視する場合 - - 優先順位: CLIパラメータ > メッセージタグ > デフォルト(破壊されていない場合) - -**ステータス**: Z.AI(テスト済み、ツール呼び出しが頻繁に破壊、継続的なデバッグが必要) - -
- -
-

動作原理(動作時)

- -
- -1. CCSがlocalhostに埋め込みHTTPプロキシを生成(クラッシュしない場合) -2. プロキシがAnthropic形式 → OpenAI形式への変換を試行(多くの場合失敗) -3. Anthropicツール → OpenAI関数呼び出し形式への変換を試行(バグあり) -4. 推論パラメータとツールを付けてZ.AIに転送(タイムアウトしない場合) -5. `reasoning_content` → 思考ブロックへの変換を試行(部分的または破壊) -6. OpenAI `tool_calls` → Anthropic `tool_use` ブロックへの変換を試行(XMLガベージが一般的) -7. 思考とツール呼び出しが時々Claude Code UIに表示(破壊されていない場合) - -
- -
-

制御タグとキーワード

- -
- -**制御タグ**: -- `` - 推論ブロックの有効/無効(デフォルト: On) -- `` - 推論深度の制御(非推奨 - Z.AIはバイナリ思考のみサポート) - -**思考キーワード**(不安定なアクティベーション): -- `think` - 時々推論を有効化(低労力) -- `think hard` - 時々推論を有効化(中労力) -- `think harder` - 時々推論を有効化(高労力) -- `ultrathink` - 最大推論深度を試行(多くの場合破壊) - -
- -
-

環境変数

- -
- -**GLMT機能**(すべて実験的): -- 強制的な英語出力強制(時々動作) -- ランダムな思考モードアクティベーション(予測不可能) -- 頻繁なバッファモードへのフォールバック付きストリーミング試行 - -**一般**: -- `CCS_DEBUG_LOG=1` - デバッグファイルロギングを有効化 -- `CCS_CLAUDE_PATH=/path/to/claude` - カスタムClaude CLIパス - -
- -
-

APIキー設定

- -
- -```bash -# GLMT設定を編集 -nano ~/.ccs/glmt.settings.json -``` - -Z.AI APIキーを設定(コーディングプランが必要): - -```json -{ - "env": { - "ANTHROPIC_AUTH_TOKEN": "your-z-ai-api-key" - } -} -``` - -
- -
-

セキュリティ制限(DoS保護)

- -
- -**v3.4 保護制限**: - -| 制限 | 値 | 目的 | -|:------|:------|:--------| -| **SSEバッファ** | イベントあたり最大1MB | バッファオーバーフローを防止 | -| **コンテンツバッファ** | ブロックあたり最大10MB | 思考/テキストブロックを制限 | -| **コンテンツブロック** | メッセージあたり最大100 | DoS攻撃を防止 | -| **リクエストタイムアウト** | 120秒 | ストリーミングとバッファの両方 | - -
- -
-

デバッグ

- -
- -**詳細ロギングを有効化**: -```bash -ccs glmt --verbose "your prompt" -``` - -**デバッグファイルロギングを有効化**: -```bash -export CCS_DEBUG_LOG=1 -ccs glmt --verbose "your prompt" -# ログ: ~/.ccs/logs/ -``` - -**GLMTデバッグ**: -```bash -# 詳細ロギングでストリーミングステータスと推論詳細を表示 -ccs glmt --verbose "test" -``` - -**推論コンテンツを確認**: -```bash -cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content' -``` - -**トラブルシューティング**: -- **存在しない場合**: Z.AI APIの問題(キー、アカウントステータスを確認) -- **存在する場合**: トランスフォーメーションの問題(`response-anthropic.json`を確認) - -
- -
- -## アンインストール - -
-

パッケージマネージャー

- -
- -```bash -# npm -npm uninstall -g @kaitranntt/ccs - -# yarn -yarn global remove @kaitranntt/ccs - -# pnpm -pnpm remove -g @kaitranntt/ccs - -# bun -bun remove -g @kaitranntt/ccs -``` - -
- -
-

公式アンインストーラー

- -
- -```bash -# macOS / Linux -curl -fsSL ccs.kaitran.ca/uninstall | bash - -# Windows PowerShell -irm ccs.kaitran.ca/uninstall | iex -``` - -
- -
- -## 🎯 哲学 - -- **YAGNI**: 「念のため」の機能は追加しない -- **KISS**: シンプルなbash、複雑さなし -- **DRY**: 単一の情報源(設定) - -## 📖 ドキュメント - -**[docs/](./docs/)の完全なドキュメント**: -- [インストールガイド](./docs/en/installation.md) -- [設定](./docs/en/configuration.md) -- [使用例](./docs/en/usage.md) -- [システムアーキテクチャ](./docs/system-architecture.md) -- [GLMT制御メカニズム](./docs/glmt-controls.md) -- [トラブルシューティング](./docs/en/troubleshooting.md) -- [貢献](./CONTRIBUTING.md) - -## 🤝 貢献 - -貢献を歓迎します!詳細については[貢献ガイド](./CONTRIBUTING.md)をご覧ください。 - -## Star History - -
- -Star History Chart - -
- - -## ライセンス - -CCSは[MITライセンス](LICENSE)の下でライセンスされています。 - -
- -**レート制限に頻繁に遭遇する開発者のために ❤️ を込めて作成** - -[⭐ このリポジトリにスター](https://github.com/kaitranntt/ccs) | [🐛 問題を報告](https://github.com/kaitranntt/ccs/issues) | [📖 ドキュメントを読む](./docs/en/) - -
\ No newline at end of file diff --git a/docs/project-overview-pdr.md b/docs/project-overview-pdr.md deleted file mode 100644 index d52826a4..00000000 --- a/docs/project-overview-pdr.md +++ /dev/null @@ -1,497 +0,0 @@ -# CCS Project Overview and Product Development Requirements (PDR) - -## Executive Summary - -CCS (Claude Code Switch) is a TypeScript-based CLI tool that enables instant profile switching between Claude, GLM, Kimi, Gemini, Codex, and Antigravity (and any OAuth-based models) models. It features a version pin mechanism for precise model control and a unified configuration system for seamless management across all providers. The project features a modern React 19 web dashboard with real-time WebSocket integration, comprehensive TypeScript architecture, and cross-platform support. Current architecture includes: - -- **TypeScript Core**: 43 source files with 100% type coverage -- **React 19 Dashboard**: Modern UI with Vite, shadcn/ui, and real-time features -- **AI Delegation System**: Headless execution with stream-JSON output -- **Cross-Platform**: Native support for macOS, Linux, and Windows -- **163 total files**: ~8,000 lines of TypeScript code - -## Product Vision - -### Mission Statement -Provide developers with instant, zero-downtime switching between diverse AI models, ensuring precise version control, optimizing for cost, performance, and rate limit management while maintaining a seamless workflow experience. - -### Core Value Proposition -- **Instant Switching**: One command to change AI models and providers without file editing -- **Zero Downtime**: Never interrupt development workflow during model or provider switches -- **Version Pinning**: Lock to specific model versions for consistent behavior -- **Cost Optimization**: Use the right model/provider for each task automatically -- **Developer Experience**: Maintain familiar Claude CLI interface with enhanced capabilities and multi-provider support - -## Product Development Requirements (PDR) - -### Functional Requirements - -#### FR-001: Profile Management -**Requirement**: System shall support instant switching between multiple AI model profiles -- **Priority**: High -- **Acceptance Criteria**: - - Switch profiles with single command (`ccs glm`, `ccs`) - - Maintain profile state until explicitly changed - - Support unlimited profile configurations - - Automatic profile detection from command arguments - -#### FR-002: Configuration Management -**Requirement**: System shall provide automatic configuration management -- **Priority**: High -- **Acceptance Criteria**: - - Auto-create configuration during installation - - Support custom configuration paths via environment variables - - Validate configuration file format and existence - - Provide clear error messages for configuration issues - -#### FR-003: Claude CLI Integration -**Requirement**: System shall seamlessly integrate with official Claude CLI -- **Priority**: High -- **Acceptance Criteria**: - - Pass all arguments transparently to Claude CLI - - Support all Claude CLI features and flags - - Maintain identical user experience to native Claude CLI - - Auto-detect Claude CLI installation location - -#### FR-004: Cross-Platform Compatibility -**Requirement**: System shall work identically across all supported platforms -- **Priority**: High -- **Acceptance Criteria**: - - Support macOS (Intel and Apple Silicon) - - Support Linux distributions - - Support Windows (PowerShell and Git Bash) - - Consistent behavior and error handling across platforms - -#### FR-005: Special Command Support -**Requirement**: System shall support special meta-commands for management -- **Priority**: Medium -- **Acceptance Criteria**: - - `ccs --version` displays version and installation location - - `ccs --help` shows usage information - - **WIP**: `ccs --install` integrates with Claude Code commands (testing incomplete) - - **WIP**: `ccs --uninstall` removes Claude Code integration (testing incomplete) - -#### FR-006: Error Handling -**Requirement**: System shall provide clear, actionable error messages -- **Priority**: Medium -- **Acceptance Criteria**: - - Validate configuration file existence and format - - Detect Claude CLI availability and report issues - - Provide suggestions for resolving common problems - - Maintain consistent error message format - -#### FR-007: AI-Powered Delegation System -**Requirement**: System shall enable headless AI task delegation with real-time tool tracking -- **Priority**: High -- **Acceptance Criteria**: - - Execute Claude CLI in headless mode with `-p` flag - - Parse stream-JSON output for real-time tool visibility - - Track 13+ Claude Code tools (Bash, Read, Write, Edit, Glob, Grep, etc.) - - Support session continuation (`:continue` suffix) - - Display cost and duration statistics - - Handle Ctrl+C signal properly (kill child processes) - -#### FR-008: .claude/ Directory Symlinking -**Requirement**: System shall selectively symlink .claude/ directories for data sharing -- **Priority**: Medium -- **Acceptance Criteria**: - - Symlink shared data: commands/, skills/, agents/ - - Keep profile-specific data isolated: settings.json, sessions/, todolists/, logs/ - - Windows fallback to directory copying when symlinks unavailable - - Non-invasive installation (never modify ~/.claude/settings.json) - - Idempotent installation (safe to run multiple times) - -#### FR-009: Shell Completion -**Requirement**: System shall provide comprehensive shell completion across 4 shells -- **Priority**: Low -- **Acceptance Criteria**: - - Support Bash, Zsh, Fish, PowerShell - - Color-coded categories (profiles, commands, flags) - - Profile-aware completions (glm, glmt, kimi, work, personal) - - Easy installation via `--shell-completion` flag - - Show installation instructions per shell - -#### FR-010: Diagnostics and Maintenance -**Requirement**: System shall provide comprehensive health diagnostics -- **Priority**: Medium -- **Acceptance Criteria**: - - `ccs doctor`: Validate installation, profiles, symlinks, API keys - - `ccs sync`: Fix broken symlinks and directory structure - - `ccs update`: Check for newer versions with smart notifications - - Color-coded status indicators ([OK], [!], [X]) - - Actionable recommendations for issues - -#### FR-011: Web Dashboard UI -**Requirement**: System shall provide a modern web dashboard for profile and configuration management -- **Priority**: High -- **Acceptance Criteria**: - - Profile management interface with active/inactive states - - Interactive command builder with search and categorization - - Performance metrics visualization with trend indicators - - Responsive design supporting mobile, tablet, and desktop - - Real-time updates via WebSocket integration - - Dark mode support out of the box - -### Non-Functional Requirements - -#### NFR-001: Performance -**Requirement**: System shall execute with minimal overhead -- **Priority**: High -- **Acceptance Criteria**: - - Profile switching completes in < 100ms - - Startup time < 50ms for any command - - Memory footprint < 10MB during execution - - No perceptible delay compared to native Claude CLI - -#### NFR-002: Reliability -**Requirement**: System shall maintain 99.9% uptime during normal operations -- **Priority**: High -- **Acceptance Criteria**: - - Handle edge cases gracefully without crashes - - Maintain functionality across system reboots - - Recover gracefully from temporary system issues - - No memory leaks or resource exhaustion - -#### NFR-003: Security -**Requirement**: System shall follow security best practices -- **Priority**: High -- **Acceptance Criteria**: - - No shell injection vulnerabilities in process execution - - Validate file paths to prevent traversal attacks - - Use secure process spawning with argument arrays - - No storage of sensitive credentials or API keys - -#### NFR-004: Maintainability -**Requirement**: System shall be easy to maintain and extend -- **Priority**: Medium -- **Acceptance Criteria**: - - Code complexity maintained at manageable levels - - Comprehensive test coverage (>90%) - - Clear documentation and code comments - - Modular architecture supporting future enhancements - -#### NFR-005: Usability -**Requirement**: System shall provide excellent developer experience -- **Priority**: Medium -- **Acceptance Criteria**: - - Intuitive command structure matching CLI conventions - - Clear help documentation and usage examples - - Minimal learning curve for existing Claude CLI users - - Consistent behavior across all use cases - -## Technical Architecture - -### System Components - -#### Core Subsystems (v4.3.2) -1. **Main Entry Point** (`bin/ccs.js` ~800 lines): Command parsing, profile routing, delegation detection -2. **Auth System** (`bin/auth/` ~800 lines): Multi-account management (create, list, delete, switch) -3. **Delegation System** (`bin/delegation/` ~1,200 lines): AI-powered task delegation with stream-JSON -4. **GLMT System** (`bin/glmt/` ~700 lines): Thinking mode proxy and transformation -5. **Management System** (`bin/management/` ~600 lines): Config, instance, profile, shared data management -6. **Utilities** (`bin/utils/` ~1,500 lines): Symlink manager, validators, update checker, completion -7. **.claude/ Integration** (`~/.ccs/shared/`): Symlinked commands, skills, agents directories - -#### v4.0-4.3.2 Major Enhancements -- **AI Delegation** (v4.0): Headless execution with stream-JSON output, session continuation -- **Selective Symlinking** (v4.1): Share .claude/ directories (commands, skills, agents) -- **Shell Completion** (v4.1.4): 4 shells supported with color-coded categories -- **Diagnostics** (v4.2): Doctor, sync, update commands for health checks -- **Stream-JSON Parser** (v4.3): Real-time tool tracking during delegation - -### Data Flow (v4.3.2) - -**Settings-based profiles (glm, kimi, glmt)**: -```mermaid -graph LR - USER[ccs glm "task"] --> PARSE[Parse Args] - PARSE --> DETECT[ProfileDetector] - DETECT --> CONFIG[Read config.json] - CONFIG --> EXEC[execClaude with --settings] - EXEC --> CLAUDE[Claude CLI] -``` - -**Delegation execution (v4.0+)**: -```mermaid -graph LR - USER[ccs glm -p "task"] --> DELEGATE[DelegationHandler] - DELEGATE --> HEADLESS[HeadlessExecutor] - HEADLESS --> STREAM[Parse stream-JSON] - STREAM --> FORMAT[ResultFormatter] - FORMAT --> SESSION[SessionManager save] -``` - -**Account-based profiles (work, personal)**: -```mermaid -graph LR - USER[ccs work "task"] --> PARSE[Parse Args] - PARSE --> DETECT[ProfileDetector] - DETECT --> INSTANCE[InstanceManager.ensureInstance] - INSTANCE --> EXEC[execClaude with CLAUDE_CONFIG_DIR] - EXEC --> CLAUDE[Claude CLI reads from instance] -``` - -**Evolution Flow Comparison**: -- **v2.x**: Login → Encrypt → Store → Decrypt → Copy → Execute (6 steps) -- **v3.0**: Create instance → Login → Execute (3 steps, 50% reduction) -- **v4.x**: Add delegation routing → Stream-JSON parsing → Session persistence (extended capabilities) - -### Configuration Architecture (v4.3.2) - -**Settings-based Config** (`~/.ccs/config.json`): -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "glmt": "~/.ccs/glmt.settings.json", - "kimi": "~/.ccs/kimi.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -**Shared Data Architecture** (v4.1+): -``` -~/.ccs/shared/ # Symlinked to instance .claude/ directories -├── commands/ # Slash commands (shared across profiles) -├── skills/ # Agent skills (shared across profiles) -└── agents/ # Agent configs (shared across profiles) -``` - -**Account Profile Registry** (`~/.ccs/profiles.json`): -```json -{ - "version": "2.0.0", - "profiles": { - "work": { - "type": "account", - "created": "2025-11-09T10:00:00.000Z", - "last_used": "2025-11-09T15:30:00.000Z" - } - }, - "default": "work" -} -``` - -**v3.0 Schema Simplification**: -- **Removed fields**: `vault`, `subscription`, `email` (not needed for login-per-profile) -- **Kept fields**: `type`, `created`, `last_used` (essential metadata only) -- **Rationale**: Credentials live in instance directories, no vault needed - -**Instance Directory Structure** (v4.1+ with symlinking): -``` -~/.ccs/instances/work/ -├── .claude/ -│ ├── commands@ → ~/.ccs/shared/commands/ # Symlink (v4.1+) -│ ├── skills@ → ~/.ccs/shared/skills/ # Symlink (v4.1+) -│ ├── agents@ → ~/.ccs/shared/agents/ # Symlink (v4.1+) -│ ├── settings.json # Profile-specific (isolated) -│ ├── sessions/ # Profile-specific (isolated) -│ ├── todolists/ # Profile-specific (isolated) -│ └── logs/ # Profile-specific (isolated) -├── .anthropic/ # SDK config -└── .credentials.json # Login credentials (managed by Claude CLI) -``` - -- **Environment Override**: `CCS_CLAUDE_PATH` - Custom Claude CLI path -- **Auto-Creation**: Configuration generated automatically during installation - -## Implementation Standards - -### Code Quality Standards -- **YAGNI Principle**: Only implement features immediately needed -- **KISS Principle**: Maintain simplicity over complexity -- **DRY Principle**: Eliminate code duplication -- **Test Coverage**: >90% coverage for all critical paths -- **Documentation**: Clear code comments and external documentation - -### Development Workflow -1. **Feature Development**: Implement following coding standards -2. **Testing**: Comprehensive unit and integration tests -3. **Documentation**: Update relevant documentation -4. **Quality Review**: Code review against standards checklist -5. **Release**: Version management and distribution - -### Platform Support Matrix -| Platform | Version Support | Testing Coverage | -|----------|----------------|------------------| -| macOS | 10.15+ | Full | -| Linux | Ubuntu 18.04+, CentOS 7+ | Full | -| Windows | 10+ (PowerShell, Git Bash) | Full | - -## Quality Assurance - -### Testing Strategy -- **Unit Tests**: Individual module functionality -- **Integration Tests**: Cross-module interaction -- **Platform Tests**: OS-specific behavior validation -- **Edge Case Tests**: Error conditions and boundary cases -- **Performance Tests**: Resource usage and response time - -### Quality Metrics -- **Code Coverage**: >90% line coverage -- **Complexity**: Maintain cyclomatic complexity < 10 per function -- **Performance**: Startup time < 50ms, memory < 10MB -- **Reliability**: <0.1% error rate in normal operations - -## Deployment and Distribution - -### Distribution Channels -- **npm Package**: Primary distribution channel (`@kaitranntt/ccs`) -- **Direct Install**: Platform-specific install scripts -- **GitHub Releases**: Source code and binary distributions - -### Installation Methods -1. **npm Package** (Recommended): `npm install -g @kaitranntt/ccs` -2. **Direct Install**: `curl -fsSL ccs.kaitran.ca/install | bash` -3. **Windows PowerShell**: `irm ccs.kaitran.ca/install | iex` - -### Auto-Configuration Process -1. **Package Installation**: npm or direct script execution -2. **Post-install Hook**: Automatic configuration creation -3. **Path Setup**: Add to system PATH when needed -4. **Validation**: Verify Claude CLI availability -5. **Ready State**: System ready for profile switching - -## Success Metrics - -### v4.3.2 Achievement Metrics -- **Delegation System**: AI-powered task execution with stream-JSON output -- **Tool Tracking**: 13+ Claude Code tools supported -- **Session Persistence**: `:continue` support for follow-up tasks -- **Shell Completion**: 4 shells supported (Bash, Zsh, Fish, PowerShell) -- **Diagnostics**: Doctor, sync, update commands for health checks -- **Symlinking**: Selective .claude/ directory sharing (commands, skills, agents) - -### Phase 1 UI Achievement Metrics (2024-12-12) -- **Core Components**: 5 foundational UI components implemented - - ProfileCard: Individual profile display with state management - - ProfileDeck: Grid container with loading/error states - - CommandBuilder: Interactive CLI tool with search/filter - - ValueMetrics: Performance visualization with trends - - HubFooter: Navigation footer with version info -- **Responsive Design**: Mobile-first approach with Tailwind CSS -- **Component Architecture**: Modular, reusable component patterns -- **Mock Data Integration**: Development-ready with clear data flow patterns - -### Adoption Metrics -- **Download Count**: npm package downloads per month -- **Installation Success Rate**: >95% successful installations -- **User Retention**: Monthly active users -- **Platform Distribution**: Usage across supported platforms -- **Delegation Usage**: Percentage of users utilizing `-p` flag -- **API Key Configuration**: Rate of users configuring GLM/Kimi/GLMT keys - -### Performance Metrics (v4.3.2) -- **Profile Creation**: ~5-10ms (instance directory creation only) -- **Profile Activation**: ~5-10ms (no decryption overhead) -- **Delegation Startup**: <500ms (stream-JSON initialization) -- **Response Time**: Minimal overhead, direct Claude CLI execution -- **Error Rate**: <0.1% in normal operations -- **Reliability**: 99.9% uptime during normal operations - -### Quality Metrics -- **Test Coverage**: >90% for all critical paths -- **Bug Reports**: Number and severity of reported issues -- **Fix Time**: Average time to resolve reported issues -- **User Satisfaction**: Feedback and ratings - -## Risk Management - -### Technical Risks -- **Claude CLI Changes**: API changes in official CLI - - **Mitigation**: Maintain abstraction layer, monitor changes -- **Platform Compatibility**: OS-specific issues - - **Mitigation**: Comprehensive testing, CI/CD across platforms -- **Dependency Issues**: npm package or system dependency problems - - **Mitigation**: Minimal dependencies, regular testing - -### Business Risks -- **Competition**: Similar tools emerging - - **Mitigation**: Focus on simplicity and reliability -- **User Adoption**: Slow adoption rates - - **Mitigation**: Clear documentation, easy installation -- **Maintenance Burden**: Ongoing maintenance costs - - **Mitigation**: Simplified codebase, automated testing - -## Future Roadmap - -See [docs/project-roadmap.md](./project-roadmap.md) for detailed version history and future plans. - -### Completed (v4.3.2) -- ✅ **AI Delegation System** (v4.0): Headless execution with stream-JSON -- ✅ **Selective Symlinking** (v4.1): Share .claude/ directories -- ✅ **Shell Completion** (v4.1.4): 4 shells with color-coded categories -- ✅ **Diagnostics** (v4.2): Doctor, sync, update commands -- ✅ **Session Continuation** (v4.3): `:continue` support -- ✅ **Vault Removal** (v3.0): Login-per-profile model -- ✅ **Platform Parity** (v3.0): Unified macOS/Linux/Windows behavior - -### Active Development (v4.4-v4.5) -- **Delegation Improvements**: MCP tool integration, SQLite session storage -- **Performance Optimization**: Model selection based on task complexity -- **Enhanced Diagnostics**: Automated troubleshooting recommendations - -### UI Development (Phase 1 Complete - 2024-12-12) -- ✅ **Core Components**: ProfileCard, ProfileDeck, CommandBuilder, ValueMetrics, HubFooter -- ✅ **Responsive Design**: Mobile-first implementation with Tailwind CSS -- ✅ **Component Architecture**: Established patterns for future development -- **Phase 2 (Planned)**: API integration, data persistence, advanced components -- **Phase 3 (Future)**: Charts/graphs, real-time updates, enhanced interactivity - -### Future Considerations (v5.0+) -- **AI-Powered Features**: Automatic task classification, intelligent model selection -- **Enterprise Features**: Team profile sharing, usage analytics dashboard -- **Ecosystem Expansion**: Plugin system for custom models, CI/CD integration - -## Compliance and Legal - -### Licensing -- **MIT License**: Permissive open-source license -- **Third-party Dependencies**: All dependencies use compatible licenses -- **Attribution**: Proper attribution for all used components - -### Privacy -- **Data Collection**: No personal data collection or transmission -- **Local Processing**: All processing happens locally -- **Configuration Privacy**: User configurations remain private - -### Security -- **Code Review**: Regular security reviews and audits -- **Dependency Management**: Regular updates and vulnerability scanning -- **Secure Distribution**: Signed packages and secure distribution channels - -## Conclusion - -The CCS project demonstrates successful iterative evolution balancing simplification with enhanced capabilities: - -### Evolution Summary -- **v2.x**: Vault-based credential encryption (~1,700 LOC) -- **v3.0**: Vault removal, login-per-profile (~1,100 LOC, 40% reduction) -- **v4.0-4.3.2**: AI delegation, .claude/ symlinking, stream-JSON (~8,477 LOC with enhanced features) - -### v4.3.2 Architectural Benefits -1. **AI-Powered Delegation**: Headless execution with real-time tool tracking -2. **Selective Symlinking**: Shared .claude/ data (commands, skills, agents) across profiles -3. **Enhanced Diagnostics**: Doctor, sync, update commands for health checks -4. **Stream-JSON Parsing**: Real-time visibility into Claude Code tool usage -5. **Session Persistence**: Continue delegation sessions with `:continue` suffix -6. **Shell Completion**: 4 shells supported with color-coded categories -7. **Platform Parity**: Unified behavior across macOS/Linux/Windows - -### Key Strengths (v4.3.2) -- **Modular Architecture**: Clear subsystem separation (auth, delegation, glmt, management, utils) -- **Non-Invasive Installation**: Never modifies ~/.claude/settings.json -- **Idempotent Operations**: Safe to run installation/sync multiple times -- **Cross-Platform Compatibility**: Unified behavior, Windows symlink fallback -- **Developer Experience**: Familiar Claude CLI interface with AI delegation -- **Maintainability**: Modular design, clear responsibilities -- **Performance**: Minimal overhead, direct CLI execution -- **Unified Configuration**: Centralized management for all AI models and providers - -### Breaking Changes (v3.x → v4.x) -- **Zero Breaking Changes**: v4.x fully backward compatible with v3.x -- **New Features**: Delegation, symlinking, diagnostics added without breaking existing workflows -- **Migration**: No migration required from v3.x to v4.x - -The project is well-positioned for future growth with a solid architectural foundation, comprehensive AI delegation capabilities, and enhanced developer experience. The v4.x architecture provides a sustainable basis for continued enhancement while maintaining core principles of simplicity, reliability, and performance. \ No newline at end of file diff --git a/docs/project-roadmap.md b/docs/project-roadmap.md deleted file mode 100644 index 052a51ea..00000000 --- a/docs/project-roadmap.md +++ /dev/null @@ -1,862 +0,0 @@ -# CCS Project Roadmap - -## Project Overview - -CCS (Claude Code Switch) is a TypeScript-based CLI tool with a modern React 19 dashboard for instant switching between multiple AI models (Claude Sonnet 4.5, GLM 4.6, GLMT, Kimi). The project features real-time WebSocket integration, comprehensive profile management, and cross-platform support. It enables developers to maintain continuous productivity by running parallel workflows with different AI models, avoiding rate limits and context switching. - -### Core Value Proposition -- **Zero Downtime**: Instant profile switching without breaking flow state -- **Modern UI**: React 19 dashboard with real-time updates and WebSocket integration -- **Cost Optimization**: 81% cost savings through intelligent delegation to GLM/Kimi -- **Parallel Workflows**: Strategic planning with Claude + cost-effective execution with GLM -- **Cross-Platform**: Unified experience on macOS, Linux, and Windows -- **Type Safety**: 100% TypeScript coverage with zero `any` types - -## Current Status - -### Version Information -- **Current Version**: 4.5.0 (React Dashboard Integration Complete) -- **Release Status**: Production-ready with modern React UI -- **Build Status**: ✅ Working (npm run build → dist/ccs.js) -- **UI Build Status**: ✅ Working (cd ui && bun run build → dist/) -- **Test Status**: ✅ All tests passing (39/39 tests) -- **Cross-Platform**: ✅ Windows/macOS/Linux -- **Code Quality**: ✅ ESLint strictness upgrade completed -- **Code Architecture**: ✅ TypeScript-based with modular components -- **React Dashboard**: ✅ Full React 19 integration with Vite and shadcn/ui -- **Real-time Features**: ✅ WebSocket integration for live updates - -### React Dashboard Integration (v4.5.0) - -**✅ Complete Modern UI Implementation** - -CCS now features a comprehensive React 19 dashboard providing a modern web interface for profile management and system monitoring. - -**Technology Stack**: -- **React 19**: Latest version with concurrent features and hooks -- **TypeScript**: Full type safety across the entire UI codebase -- **Vite**: Fast build tool with HMR and optimized production builds -- **shadcn/ui**: Modern component library built on Radix UI primitives -- **TanStack Query**: Powerful server state management with caching -- **Tailwind CSS**: Utility-first styling for rapid development - -**Dashboard Features**: -- ✅ **Real-time Updates**: WebSocket integration for live profile status -- ✅ **Profile Management**: Visual configuration of API profiles (GLM, GLMT, Kimi) -- ✅ **CLIProxy Integration**: OAuth provider setup and management -- ✅ **Account Management**: Multi-account profile switching -- ✅ **Health Monitoring**: System diagnostics dashboard -- ✅ **Settings Panel**: Global configuration interface -- ✅ **Dark Mode**: Theme switching support -- ✅ **Responsive Design**: Mobile-friendly interface - -**Technical Implementation**: -- **163 Total Files**: Comprehensive codebase with modular architecture -- **~8,000 Lines**: Well-organized TypeScript code -- **Component Library**: Reusable UI components with consistent design -- **API Integration**: Seamless backend communication -- **Build Optimization**: Code splitting and lazy loading -- **Accessibility**: WCAG-compliant components - -### TypeScript Conversion Summary - -**✅ Conversion Completed: 100% (43 files)** - -The CCS project has been fully converted from JavaScript to TypeScript, delivering enhanced type safety, improved developer experience, and better maintainability. - -**Migration Statistics**: -- **Source Files**: 43 TypeScript files converted -- **Lines of Code**: ~8,000 lines of TypeScript code -- **Type Coverage**: 100% with zero `any` types -- **Build System**: Full TypeScript compilation pipeline -- **Type Definitions**: Comprehensive type definitions in `src/types/` - -**Converted Components**: -- ✅ **Core System** (`src/ccs.ts`) - Main entry point -- ✅ **Commands** (`src/commands/`) - Modular command handlers -- ✅ **Authentication** (`src/auth/`) - Profile management and commands -- ✅ **CLIProxy** (`src/cliproxy/`) - OAuth provider integration -- ✅ **Delegation** (`src/delegation/`) - AI-powered task delegation system -- ✅ **GLMT** (`src/glmt/`) - GLM with Thinking support -- ✅ **Management** (`src/management/`) - System diagnostics and instance management -- ✅ **Utils** (`src/utils/`) - Cross-platform utilities and helpers -- ✅ **Types** (`src/types/`) - Complete type definitions - -## Recent Achievements - -### TypeScript Conversion Benefits (v4.4.0) - -#### Type Safety & Reliability -- **Zero `any` types**: Complete type coverage across the entire codebase -- **Compile-time error detection**: Catches bugs before runtime -- **Interface contracts**: Clear API boundaries and data structures -- **Exhaustive type checking**: Eliminates entire classes of common errors - -#### Enhanced Developer Experience -- **IDE support**: Full IntelliSense autocomplete and navigation -- **Refactoring safety**: Type-safe code modifications and renames -- **Self-documenting code**: Type definitions serve as living documentation -- **Better debugging**: Clear type information in debuggers and stack traces - -#### Maintainability Improvements -- **Code navigation**: Easy "go to definition" across the entire codebase -- **Impact analysis**: Clear understanding of where types are used -- **API documentation**: Types define precise interfaces for all components -- **Future-proofing**: Easier to add new features without breaking existing code - -#### Architecture Enhancements -- **Modular type system**: Comprehensive type definitions in `src/types/` -- **Strict configuration**: TypeScript strict mode enabled for maximum safety -- **Build pipeline**: Automated compilation with source maps and declarations -- **Cross-platform consistency**: Types ensure consistent behavior across platforms - -### Phase 01: ESLint Strictness Upgrade Complete ✅ - -**Completion Date**: 2025-11-27 -**Status**: SUCCESS - All quality gates passing - -#### Enhanced Code Quality Standards - -**ESLint Rules Upgraded** (`eslint.config.mjs`): -- ✅ `@typescript-eslint/no-unused-vars`: `warn` → `error` -- ✅ `@typescript-eslint/no-explicit-any`: `warn` → `error` -- ✅ `@typescript-eslint/no-non-null-assertion`: `warn` → `error` - -#### Validation Results -- **TypeScript Compilation**: ✅ Zero type errors -- **ESLint Validation**: ✅ Zero violations (previously 3 warning rules) -- **Test Suite**: ✅ 39/39 tests passing -- **Manual Testing**: ✅ All critical commands working -- **Code Coverage**: ✅ 10,487 lines of TypeScript code analyzed - -#### Quality Improvements Achieved -1. **Type Safety Enhancement**: Zero tolerance for unused variables, explicit any types, and non-null assertions -2. **Code Quality Enforcement**: Stricter linting prevents entire categories of potential bugs -3. **Maintainability Boost**: Cleaner, more predictable codebase with enforced standards -4. **Zero Breaking Changes**: All functionality preserved, enhanced reliability only - -#### Next Phase Readiness -- **Phase 02 Status**: ✅ COMPLETED (2025-11-27) -- **Focus**: CCS monolithic split (ccs.ts 1071 lines → 593 lines, 44.6% reduction) -- **Goal**: ✅ Achieved - 7 modular command handlers created for improved maintainability -- **Results**: All validation gates pass, code review: EXCELLENT - -**Phase 03 Status**: ✅ COMPLETED (2025-12-03) -- **Focus**: Beta channel implementation with npm tag switching -- **Goal**: ✅ Achieved - Full beta channel support with stability warnings -- **Results**: All validation gates pass, comprehensive user guidance implemented - -### Phase 02: CCS Split Refactoring Complete ✅ - -**Completion Date**: 2025-11-27 -**Status**: SUCCESS - All objectives achieved - -### Phase 03: Beta Channel Implementation Complete ✅ - -**Completion Date**: 2025-12-03 -**Status**: SUCCESS - Beta channel fully implemented - -#### Beta Channel Features Delivered - -**NPM Tag Switching System**: -- ✅ Implemented `fetchVersionFromNpmTag()` function for tag-specific version queries -- ✅ Added support for `@latest` and `@dev` npm tags -- ✅ Seamless switching between stable and beta channels - -**Enhanced Update Command**: -- ✅ `--beta` flag implementation with target tag detection -- ✅ Stability warnings for beta channel installations: - - "[!] Installing from @dev channel (unstable)" - - "[!] Not recommended for production use" - - "[!] Use `ccs update` (without --beta) to return to stable" -- ✅ Combined flag support: `--force --beta` for force reinstall from beta - -**Installation Method Validation**: -- ✅ npm installations: Full beta channel support -- ✅ Direct installer installations: Clear error messages with migration guidance -- ✅ Automatic detection of installation method -- ✅ Graceful fallback to stable channel for unsupported methods - -#### Technical Implementation Details - -**Core Changes**: -- `src/utils/update-checker.ts`: Added `fetchVersionFromNpmTag()` and targetTag parameter -- `src/commands/update-command.ts`: Enhanced with beta flag parsing and validation -- `src/ccs.ts`: Updated to pass beta flag to update handler - -**User Experience Improvements**: -- Clear warnings about beta channel stability -- One-command return to stable channel -- Helpful error messages with migration instructions -- Seamless channel switching without data loss - -#### Validation Results -- **TypeScript Compilation**: ✅ Zero type errors -- **ESLint Validation**: ✅ Zero violations -- **Manual Testing**: ✅ All beta channel scenarios working -- **Error Handling**: ✅ Comprehensive error messages for edge cases -- **Documentation**: ✅ Updated across all relevant files - -#### Modular Command Architecture Implementation - -**Command Handler Modules Created:** -- ✅ `src/commands/version-command.ts` (3.0KB) - Version display functionality -- ✅ `src/commands/help-command.ts` (4.9KB) - Comprehensive help system -- ✅ `src/commands/install-command.ts` (957B) - Install/uninstall operations -- ✅ `src/commands/doctor-command.ts` (415B) - System diagnostics -- ✅ `src/commands/sync-command.ts` (1.0KB) - Configuration synchronization -- ✅ `src/commands/shell-completion-command.ts` (2.1KB) - Shell completion management - -**New Utility Modules:** -- ✅ `src/utils/shell-executor.ts` (1.5KB) - Cross-platform shell execution -- ✅ `src/utils/package-manager-detector.ts` (3.8KB) - Package manager detection - -#### Refactoring Metrics Achieved - -**File Size Reduction:** -- **src/ccs.ts**: 1,071 → 593 lines (**44.6% reduction**) -- **Main file focus**: Now contains only routing logic + profile detection + GLMT proxy -- **Maintainability**: Enhanced through modular command separation - -**Code Organization:** -- **Before**: 1 monolithic file handling all commands -- **After**: 7 focused command handlers + 2 utility modules -- **Benefits**: Easier testing, better code navigation, focused responsibilities - -#### Architecture Improvements - -**Enhanced Modularity:** -- **Command Handlers**: Each command isolated in dedicated module -- **Utility Functions**: Cross-platform shell execution and package management -- **Clean Separation**: Main file focuses on orchestration only -- **Type Safety**: All new modules maintain 100% TypeScript compliance - -**Maintainability Benefits:** -- **Single Responsibility**: Each module has focused purpose -- **Easy Testing**: Command handlers can be tested independently -- **Code Navigation**: Developers can quickly locate specific functionality -- **Future Enhancements**: New commands can be added without touching main file - -#### Validation Results -- **TypeScript Compilation**: ✅ Zero type errors -- **ESLint Validation**: ✅ Zero violations -- **Test Suite**: ✅ All tests passing -- **Functionality**: ✅ 100% feature preservation -- **Performance**: ✅ No degradation, minor improvement due to smaller main file - -#### Code Quality Assessment -- **Review Status**: EXCELLENT -- **Architecture**: Clean modular design -- **Type Safety**: Comprehensive TypeScript coverage -- **Documentation**: Well-documented interfaces and functions -- **Future-Proofing**: Scalable architecture for additional commands - -### Configuration Architecture Improvements -- **Shared Settings**: v4.4 introduces unified `settings.json` sharing across profiles -- **Plugin Support**: Enhanced shared directory structure with plugin support -- **Error Handling**: Improved error management with typed error codes -- **Shell Completion**: PowerShell compatibility improvements - -### Phase 05: Bootstrap Passthrough Verification Complete ✅ - -**Completion Date**: 2025-12-03 16:40 -**Status**: SUCCESS - Bootstrap scripts handle argument passthrough correctly - -#### Implementation Summary - -The bootstrap script verification phase confirmed that both Unix and Windows bootstrap scripts already correctly pass all command-line arguments to the Node.js implementation. No code changes were required. - -#### Technical Verification - -**Bash Bootstrap (`lib/ccs`)**: -- Line 32: `exec npx "$PACKAGE" "$@"` -- `"$@"` correctly expands to all positional parameters, preserving quotes -- Successfully passes `--force`, `--beta`, and combined flags - -**PowerShell Bootstrap (`lib/ccs.ps1`)**: -- Lines 5-8: Parameter capture with `ValueFromRemainingArguments=$true` -- Line 38: `& npx $PACKAGE @RemainingArgs` -- `@RemainingArgs` uses splatting to pass all captured arguments -- Successfully passes `--force`, `--beta`, and combined flags - -#### Key Achievements - -1. **Zero Code Changes**: Existing implementation already supports new flags -2. **Cross-Platform Consistency**: Both Unix and Windows handle arguments identically -3. **No Breaking Changes**: Existing functionality remains unaffected -4. **Security Preserved**: Arguments passed through without shell expansion risks - -#### Validation Results - -- **Argument Passthrough**: ✅ `--force` flag reaches Node.js implementation -- **Beta Support**: ✅ `--beta` flag reaches Node.js implementation -- **Combined Flags**: ✅ `--force --beta` combination works correctly -- **Existing Commands**: ✅ All existing commands continue to work -- **Error Handling**: ✅ Invalid flags properly rejected by Node.js layer - -#### Next Steps - -Ready to proceed with: -- Phase 06: Comprehensive test suite implementation -- Phase 07: Documentation updates for new features - -## Current Architecture - -### Updated Architecture Diagram - -```mermaid -%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1f2937', 'edgeLabelBackground':'#374151', 'clusterBkg':'#374151'}}}%% -graph TB - subgraph "TypeScript Source Layer (Phase 02 Modular)" - MAIN[src/ccs.ts - Main Entry - 593 lines] - CMDS[src/commands/ - Modular Commands] - AUTH[src/auth/ - Authentication] - DELEGATE[src/delegation/ - AI Delegation] - GLMT[src/glmt/ - GLM Thinking] - MGMT[src/management/ - System Mgmt] - UTILS[src/utils/ - Cross-Platform Utils] - TYPES[src/types/ - Type Definitions] - - subgraph "Command Handlers" - VER[version-command.ts] - HELP[help-command.ts] - INSTALL[install-command.ts] - DOCTOR[doctor-command.ts] - SYNC[sync-command.ts] - SHELL[shell-completion-command.ts] - end - - subgraph "New Utils" - SHELL_EXEC[shell-executor.ts] - PKG_MGR[package-manager-detector.ts] - end - end - - %% Modular connections - MAIN --> CMDS - CMDS --> VER - CMDS --> HELP - CMDS --> INSTALL - CMDS --> DOCTOR - CMDS --> SYNC - CMDS --> SHELL - UTILS --> SHELL_EXEC - UTILS --> PKG_MGR - - subgraph "Build Output Layer" - DIST[dist/ccs.js - Compiled Output] - DECL[dist/ccs.d.ts - Type Declarations] - MAP[dist/ccs.js.map - Source Maps] - end - - subgraph "Native Integration Layer" - BASH[lib/ccs - Bash Implementation] - PS[lib/ccs.ps1 - PowerShell Implementation] - SHELLS[Shell Completion Scripts] - end - - subgraph "Runtime Environment" - CLAUDE[Claude CLI] - CONFIG[Configuration Files] - SHARED[~/.ccs/shared/] - INSTANCES[Isolated Instances] - end - - MAIN --> DIST - AUTH --> DIST - DELEGATE --> DIST - GLMT --> DIST - MGMT --> DIST - UTILS --> DIST - TYPES --> DECL - - DIST --> CLAUDE - BASH --> CLAUDE - PS --> CLAUDE - SHELLS --> CLAUDE - CONFIG --> CLAUDE - SHARED --> CLAUDE - INSTANCES --> CLAUDE -``` - -### TypeScript Architecture Benefits - -#### Type System Organization -``` -src/types/ -├── cli.ts # CLI interface definitions -├── config.ts # Configuration type schemas -├── delegation.ts # Delegation system types -├── glmt.ts # GLMT-specific types -├── utils.ts # Utility function types -└── index.ts # Central type exports -``` - -#### Component Type Safety -- **Authentication**: Type-safe profile management and command execution -- **Delegation**: Structured delegation workflows with typed result handling -- **GLMT**: Type-safe transformation pipelines and proxy management -- **Management**: Typed diagnostics and instance management -- **Utils**: Cross-platform utilities with consistent interfaces - -#### Build Pipeline -- **TypeScript Compiler**: `tsc` with strict configuration and comprehensive checks -- **Declaration Generation**: Automatic `.d.ts` file generation for API documentation -- **Source Maps**: Debug-friendly mapping back to TypeScript source files -- **Incremental Builds**: Fast rebuilds with TypeScript incremental compilation - -## Development Roadmap - -### Next Development Phases - -#### Phase 1: TypeScript Foundation Stabilization (v4.4.1 - v4.4.5) -**Timeline**: Immediate - 4 weeks - -**Priorities**: -1. **Type System Refinement** - - Migrate remaining `any` types (target: zero any types) - - Add generic constraints for better type inference - - Implement branded types for enhanced type safety - - Create utility types for common patterns - -2. **Build System Enhancement** - - Add TypeScript ESLint with strict rules - - Implement pre-commit type checking - - Add automated type coverage reporting - - Enhance development build performance - -3. **Testing Infrastructure** - - Migrate tests to TypeScript - - Add type-safe test utilities - - Implement mock type definitions - - Create type-safe test data fixtures - -#### Phase 2: Advanced Delegation System (v4.5.0) -**Timeline**: 1-2 months - -**TypeScript-Driven Features**: -1. **Smart Delegation Routing** - - Type-based task classification system - - Intelligent profile selection algorithms - - Cost estimation with typed calculation models - - Performance optimization through type-aware caching - - Recently implemented significant UI improvements for analytics dashboard, enhancing data presentation. - -2. **Enhanced Session Management** - - Type-safe session persistence with serialization - - Advanced session resumption with state restoration - - Multi-turn conversation context management - - Session analytics with typed metrics - -3. **Plugin System Foundation** - - Type-safe plugin API definitions - - Plugin discovery and registration system - - Sandboxed plugin execution environment - - Community plugin marketplace infrastructure - -#### Phase 3: Enterprise Features (v4.6.0) -**Timeline**: 2-3 months - -**Enterprise-Grade TypeScript Features**: -1. **Team Profile Management** - - Type-safe role-based access control (RBAC) - - Centralized configuration management - - Audit logging with typed event structures - - Compliance reporting with structured data formats - -2. **Advanced Analytics Dashboard** - - Real-time usage metrics with typed data streams - - Cost tracking and budgeting with financial types - - Team productivity analytics with KPI types - - Performance monitoring with alert types - -3. **CI/CD Integration** - - Type-safe GitHub Actions workflows - - Automated testing with type validation - - Deployment pipelines with type checks - - Infrastructure as Code with TypeScript - -#### Phase 4: UI Enhancements - Sidebar Redesign (v4.7.0) -**Timeline**: 1-2 months (TBD) - -**Priorities**: -1. **Sidebar Redesign Implementation** - - Implement new sidebar component with modern UI/UX principles. - - Ensure responsiveness across different screen sizes. - - Integrate with existing routing and navigation logic. - - Improve accessibility features for the sidebar. - -### Technical Debt Resolution - -#### Immediate Priorities (v4.4.1) -1. **GLMT System Refactoring** - - Transform GLMT proxy with typed request/response handling - - Implement type-safe SSE parsing with error recovery - - Add typed transformation pipelines for API compatibility - - Create comprehensive GLMT test suites with type safety - -2. **Error Handling Enhancement** - - Implement typed error hierarchies with inheritance - - Create structured error reporting with localization - - Add automatic error recovery with typed retry logic - - Develop error analytics with classification systems - -3. **Performance Optimization** - - Profile and optimize hot paths with typed benchmarks - - Implement memory-efficient data structures with generics - - Add lazy loading patterns with type-safe initialization - - Create performance monitoring with typed metrics - -#### Medium-term Improvements (v4.5.0) -1. **Cross-Platform Consistency** - - Unify behavior across platforms with typed abstractions - - Implement platform-specific optimizations with type guards - - Create comprehensive cross-platform test suites - - Add platform-specific feature detection - -2. **API Evolution** - - Design backward-compatible API evolution strategies - - Implement API versioning with type migration paths - - Create deprecation warnings with upgrade guidance - - Add automated API compatibility testing - -## Future Vision (v5.0+) - -### Next-Generation Architecture - -#### AI-Powered TypeScript Development -1. **Intelligent Code Generation** - - TypeScript-aware AI code completion - - Automatic type inference from usage patterns - - Smart refactoring suggestions with type analysis - - Code quality recommendations based on type metrics - -2. **Adaptive Type System** - - Dynamic type generation based on runtime behavior - - Machine learning-assisted type predictions - - Automatic interface extraction from APIs - - Smart type narrowing with statistical analysis - -#### Enterprise TypeScript Platform -1. **Advanced Team Collaboration** - - Real-time collaborative TypeScript editing - - Shared type libraries across projects - - Automated type governance policies - - Team-wide type consistency enforcement - -2. **Comprehensive Analytics** - - Type usage analytics and optimization recommendations - - Code quality metrics with type safety scores - - Developer productivity tracking with type metrics - - Technical debt measurement with type analysis - -#### Ecosystem Integration -1. **Package Management** - - Type-safe dependency management - - Automated vulnerability scanning with type analysis - - Smart version resolution with compatibility checking - - Package quality assessment with type metrics - -2. **Tool Integration** - - TypeScript-native IDE extensions - - Enhanced debugging with type information - - Performance profiling with type insights - - Automated testing with type-driven test generation - -## Release Notes - -### Version 4.5.0 - Beta Channel Implementation Complete -**Release Date**: 2025-12-03 - -#### Major Features -- ✅ **Beta Channel Support**: Full implementation of npm tag switching between `@latest` and `@dev` -- ✅ **Enhanced Update Command**: `--beta` flag with stability warnings and validation -- ✅ **Force Reinstall Support**: `--force` flag to reinstall current version and fix corrupted installs -- ✅ **Combined Flag Support**: `--force --beta` for force reinstalling beta versions -- ✅ **Installation Method Detection**: Differential support for npm vs direct installations -- ✅ **User Safety Features**: Clear warnings and migration guidance for beta usage -- ✅ **Version Fetching Enhancement**: Tag-specific queries with `fetchVersionFromNpmTag()` -- ✅ **Comprehensive Test Suite**: 29 new tests covering update flags functionality - -#### Technical Improvements -- **NPM Integration**: Direct npm registry access for version queries -- **Version Comparison Logic**: Robust semantic version comparison with prerelease handling -- **Error Handling**: Comprehensive error messages with migration instructions -- **User Experience**: One-command channel switching without data loss -- **Backward Compatibility**: Zero breaking changes, existing workflows preserved - -### Version 4.5.1 - UI Quality Gate Fixes & Layout Improvements -**Release Date**: 2025-12-08 - -#### UI Fixes & Improvements -- ✅ **Analytics UI Enhancements**: Standardized colors, fixed truncated model names, and ensured color consistency in the analytics dashboard. -- ✅ **Auto-formatting**: 31 UI files auto-formatted for consistent styling. -- ✅ **Fast Refresh Exports**: Resolved `react-refresh/only-export-components` by extracting `buttonVariants`, `useSidebar`, and `useWebSocketContext` to separate files. -- ✅ **React Hooks Issues**: Fixed `react-hooks/purity` (`Math.random()` in `useMemo` for `sidebar.tsx`) and `react-hooks/set-state-in-effect` (`use-theme.ts`, `settings.tsx`). -- ✅ **useWebSocket Hook Restructure**: Addressed `react-hooks/immutability` errors and dependency array warnings in `use-websocket.ts`. -- ✅ **TypeScript Strict Mode**: Implemented null-check for `document.getElementById('root')` in `src/main.tsx` for strict mode compliance. -- ✅ **Duplicate Directory Removal**: Cleaned up extraneous `ui/@/` directory. -- ✅ **CLIProxy Card Padding**: Removed excessive padding from CLIProxy cards for better visual integration. -- ✅ **CLIProxy Dashboard Layout**: Improved overall layout and styling of the CLIProxy dashboard. -- ✅ **Dropdown Styling**: Refined dropdown component styling. -- ✅ **Model Usage Card**: Corrected icon display and refined donut chart styling. - -#### Technical Improvements -- **Improved UI Responsiveness**: Adjustments ensure better display across various screen sizes. -- **Enhanced User Experience**: Minor visual tweaks lead to a more polished and intuitive interface. - -#### Validation Results -- **UI Rendering**: ✅ All UI components render correctly after adjustments and fixes. -- **Functional Impact**: ✅ No regressions introduced, core functionality remains stable. -- **Code Quality**: ✅ All ESLint and TypeScript quality gates passed after fixes. - -### Version 4.5.2 - Operational Hub Redesign - Phase 1 Complete -**Release Date**: 2025-12-12 - -#### New UI Components Created -- ✅ **ProfileCard Component** (`src/components/profile-card.tsx`): Individual profile display with status indicators and action buttons -- ✅ **ProfileDeck Component** (`src/components/profile-deck.tsx`): Container for managing multiple profile cards in a grid layout -- ✅ **CommandBuilder Component** (`src/components/command-builder.tsx`): Interactive command construction interface with suggestions -- ✅ **ValueMetrics Component** (`src/components/value-metrics.tsx`): Dashboard widget for displaying efficiency metrics and cost savings -- ✅ **HubFooter Component** (`src/components/hub-footer.tsx`): Utility footer with navigation links and version information - -#### Component Features -- **Profile Management**: Visual profile switching with active/inactive states -- **Command Interface**: Interactive command builder with copy/run actions -- **Metrics Visualization**: Real-time display of cost savings and efficiency statistics -- **Responsive Design**: Mobile-friendly layout with Tailwind CSS styling -- **Accessibility**: WCAG-compliant components with proper ARIA labels - -#### Technical Implementation -- **TypeScript**: Full type safety with zero `any` types -- **React 19**: Latest React features with hooks and concurrent rendering -- **shadcn/ui**: Consistent design system with Radix UI primitives -- **Modular Architecture**: Reusable components for enhanced maintainability - -#### Code Review Notes -- Identified console.log statements for removal in Phase 2 -- Noted hardcoded version string in HubFooter requiring dynamic version -- Button handlers need implementation or disabling -- Error boundary wrappers recommended for production - -#### Validation Results -- **Component Compilation**: ✅ All components compile without errors -- **TypeScript Validation**: ✅ Zero type errors with strict mode -- **ESLint Compliance**: ✅ No violations detected -- **Manual Testing**: ✅ Components render as expected in isolation - ---- - -#### Testing Infrastructure -- **Version Comparison Tests**: 25 unit tests for all semantic version scenarios -- **Flag Parsing Tests**: 4 integration tests for update command flags -- **Edge Case Coverage**: Invalid versions, large numbers, case sensitivity -- **Downgrade Detection**: Proper warnings for beta channel downgrades -- **Test Framework**: Mocha with assert module, minimal mocking approach - -### Version 4.4.0 - TypeScript Conversion Complete -**Release Date**: 2025-11-25 - -#### Major Features -- ✅ **Complete TypeScript Conversion**: All 31 source files migrated to TypeScript -- ✅ **Zero `any` Types**: 100% type coverage with comprehensive type definitions -- ✅ **Enhanced Build Pipeline**: Automated compilation with source maps and declarations -- ✅ **Shared Settings Architecture**: Unified `settings.json` across all profiles -- ✅ **Plugin Support**: Enhanced shared directory structure -- ✅ **ESLint Strictness Upgrade**: Phase 01 completed (2025-11-27) - 3 rules upgraded to error level, 0 violations found -- ✅ **CCS Architecture Refactoring**: Phase 02 completed (2025-11-27) - 44.6% file size reduction, 9 modular components created - -#### Technical Improvements -- **Type Safety**: Compile-time error detection eliminates entire bug categories -- **Developer Experience**: Full IDE support with IntelliSense and navigation -- **Maintainability**: Self-documenting code with comprehensive type definitions -- **Cross-Platform**: Typed abstractions ensure consistent behavior - -#### Breaking Changes -- **None**: Fully backward compatible with existing configurations -- **Migration**: Seamless upgrade path with zero user impact - -#### Dependencies -- **TypeScript 5.3**: Updated to latest stable version -- **Enhanced Build Process**: Automated compilation and type checking -- **Development Tools**: Improved development tooling and debugging - -### Recent Patch Updates -- **v4.3.10**: Package manager cache clearing during updates -- **v4.3.9**: Fixed missing `commands/ccs.md` symlink in npm install -- **v4.3.8**: Resolved missing `~/.ccs/.claude/` directory creation -- **v4.3.7**: Enhanced directory creation during npm install -- **v4.3.6**: Added plugin support to shared directories -- **v4.4.0**: TypeScript conversion complete, shared settings architecture - -## Testing Strategy - -### TypeScript Testing Infrastructure -1. **Unit Testing with Type Safety** - - Mocha tests with TypeScript compilation - - Type-safe test utilities and fixtures - - Mock implementations with interface compliance - - Coverage reporting with type metrics - -2. **Integration Testing** - - Cross-platform compatibility validation - - End-to-end workflow testing with typed data - - API contract testing with type validation - - Performance testing with type-aware profiling - -3. **Type-Level Testing** - - TypeScript compiler error verification - - Type coverage measurement and reporting - - API surface validation with type checking - - Dependency graph analysis with type relationships - -## Quality Assurance - -### TypeScript Quality Metrics -- **Type Coverage**: 100% (target: maintain zero any types) -- **Compiler Strictness**: Maximum strict mode configuration -- **Interface Compliance**: All exports properly typed -- **Documentation Coverage**: Type definitions serve as documentation - -### Code Quality Standards -- **ESLint Integration**: TypeScript-specific linting rules -- **Pre-commit Hooks**: Automated type checking before commits -- **CI/CD Pipeline**: Type validation in continuous integration -- **Code Review**: Type safety as review requirement - -## Contributing to Roadmap - -### TypeScript Development Guidelines -1. **Type-First Development**: Define types before implementation -2. **Zero Any Policy**: Maintain 100% type coverage -3. **Interface Documentation**: Comprehensive JSDoc with type examples -4. **Backward Compatibility**: Evolve APIs without breaking changes - -### Feature Contribution Process -1. **Type Design**: Submit type definitions for review -2. **Implementation**: Type-safe implementation with comprehensive tests -3. **Documentation**: Update type documentation and examples -4. **Review**: Peer review focused on type safety and API design - -## Community and Ecosystem - -### TypeScript Community Engagement -- **TypeScript Best Practices**: Share learnings with TypeScript community -- **Open Source Contribution**: Contribute to TypeScript tooling ecosystem -- **Knowledge Sharing**: Document TypeScript migration experience -- **Community Support**: Help other projects with TypeScript adoption - -## Future Roadmap - -### Phase 1: UI Enhancements & Mobile Support (v4.6.0 - v4.7.0) -**Timeline**: 2-3 months - -**Priorities**: -1. **Dashboard Improvements** - - Sidebar redesign with modern UX patterns - - Enhanced data visualizations and charts - - Drag-and-drop profile reordering - - Customizable dashboard widgets - -2. **Mobile Responsiveness** - - Touch-friendly interface - - Progressive Web App (PWA) support - - Offline mode for basic functionality - - Mobile-specific shortcuts - -3. **Real-time Collaboration** - - Multi-user dashboard access - - Live profile sharing - - Collaborative delegation sessions - - Real-time activity feeds - -### Phase 2: Advanced Features (v4.8.0 - v4.9.0) -**Timeline**: 3-4 months - -**Priorities**: -1. **AI-Powered Features** - - Automatic model selection based on task type - - Intelligent delegation routing - - Cost optimization suggestions - - Performance analytics - -2. **Enterprise Features** - - Team profile management - - Usage analytics dashboard - - Role-based access control - - Audit logging - -3. **Plugin System** - - Extensible architecture for custom providers - - Community plugin marketplace - - Plugin development SDK - - Version compatibility management - -### Phase 3: Next Generation Architecture (v5.0+) -**Timeline**: 6+ months - -**Vision**: -1. **Microservices Architecture** - - Decoupled services for scalability - - Container-based deployment - - API-first design - - Cloud-native features - -2. **Advanced AI Integration** - - Multi-modal AI support (text, image, audio) - - Custom AI model training - - Advanced reasoning capabilities - - Workflow automation - -3. **Ecosystem Expansion** - - VS Code extension - - IDE integrations - - CI/CD plugins - - Developer toolchain integration - -## Technical Debt & Improvements - -### Immediate Priorities (v4.5.1) -1. **Performance Optimization** - - Bundle size reduction - - Lazy loading implementation - - Memory leak fixes - - Caching strategies - -2. **Testing Enhancement** - - E2E test suite for UI - - Visual regression testing - - Performance testing - - Accessibility testing - -3. **Documentation** - - API documentation generation - - Interactive tutorials - - Video guides - - Community resources - -### Medium-term Goals (v4.6.0) -1. **Security Hardening** - - Security audit - - Penetration testing - - Dependency vulnerability scanning - - Secure development practices - -2. **Internationalization** - - Multi-language support - - Localization infrastructure - - Cultural adaptations - - Global deployment - -3. **Analytics & Monitoring** - - Usage analytics - - Performance monitoring - - Error tracking - - User behavior insights - ---- - -**Document Status**: Living document, updated with each major release -**Last Updated**: 2025-12-12 (Operational Hub Redesign - Phase 1) -**Next Update**: v4.5.3 Operational Hub Redesign - Phase 2 Integration -**Maintainer**: CCS Development Team \ No newline at end of file diff --git a/docs/session-sharing-technical-analysis.md b/docs/session-sharing-technical-analysis.md deleted file mode 100644 index 2798f4e8..00000000 --- a/docs/session-sharing-technical-analysis.md +++ /dev/null @@ -1,239 +0,0 @@ -# Why Session Sharing Fails Across Profiles: Technical Analysis - -## Overview - -Claude CLI sessions cannot be directly shared across CCS profiles due to authentication architecture constraints. When a user starts a thread on a "work" profile and the account expires, resuming from a "personal" profile fails despite the local session file being present. - -**Core Problem**: Thread IDs stored locally, but API-side validation requires matching OAuth credentials. Session "ownership" bound to account that created it, preventing cross-account continuation. - -## Technical Architecture: How Claude CLI Sessions Work - -### Session Storage Structure - -``` -~/.claude/ -├── .credentials.json # OAuth tokens (access, refresh, expiry) -├── projects/ -│ └── / -│ └── .jsonl # Thread conversation history -├── session-env/ # Ephemeral runtime state (empty dirs) -└── todos/ # Task tracking -``` - -### Session File Format (JSONL) - -Each thread stored as newline-delimited JSON: - -```jsonl -{"type":"user","sessionId":"","message":{"role":"user","content":"..."},"uuid":"","timestamp":"..."} -{"type":"assistant","sessionId":"","message":{"role":"assistant","content":[...]},"requestId":"req_...","uuid":"","timestamp":"..."} -``` - -**Key Fields**: -- `sessionId`: Thread UUID (e.g., `58921318-0aed-4238-b6cb-d0d6222fc095`) -- `message`: User/assistant conversation turns -- `requestId`: API request ID (server-generated, scoped to original auth) -- **No embedded auth tokens**: Credentials stored separately in `.credentials.json` - -### OAuth 2.0 Authentication Model - -**Credential File** (`~/.claude/.credentials.json`): -```json -{ - "claudeAiOauth": { - "accessToken": "sk-ant-oat01-...", - "refreshToken": "sk-ant-ort01-...", - "expiresAt": 1762851849221, - "scopes": ["user:inference", "user:profile"], - "subscriptionType": "max" - } -} -``` - -**Flow**: -1. User runs `claude --resume ` -2. CLI reads `~/.claude/projects//.jsonl` -3. CLI reconstructs full conversation history -4. CLI submits request to API with OAuth token from `.credentials.json` -5. **API validates token + session ownership (inferred)** -6. API responds (session context maintained client-side only) - -### API-Side Validation - -Claude API is stateless. "Sessions" are client-side constructs: -- Thread ID alone does NOT authorize continuation -- Each request requires valid OAuth token -- Server likely validates session creator identity (undocumented but inferred from org ID headers) -- No server-side session state tied to thread IDs - -## Why Direct Sharing Fails: Core Technical Blockers - -| Component | Transferable? | Blocker | -|-----------|--------------|---------| -| Session JSONL file | ✅ Yes | None (plain text) | -| Thread ID (UUID) | ✅ Yes | None (identifier only) | -| Conversation history | ✅ Yes | None (embedded in JSONL) | -| OAuth token | ❌ No | Account-specific, expires | -| API authorization | ❌ No | Server-side session ownership validation | - -### OAuth Token Mismatch - -- Work profile session created with `work_oauth_token` -- Personal profile uses `personal_oauth_token` -- API rejects requests where token doesn't match session creator (inferred) - -### Organization ID Boundaries - -Anthropic returns `anthropic-organization-id` header in responses. Sessions may be scoped to: -- User account ID -- Organization ID (for team accounts) -- Subscription tier - -Cross-account access would violate organizational isolation. - -### Session Ownership Enforcement - -No documented API for "transferring" session ownership. Thread ID is identifier, not authorization: -- Like a file path: knowing the path doesn't grant read access -- Requires matching credentials to prove ownership -- No "share session" endpoint exists in Claude API - -### Documentation Gaps - -- No cross-account access docs in official Claude API documentation -- No session sharing/transfer APIs in CLI or Agent SDK -- Security model not explicitly documented (inferred from OAuth behavior) - -## Security Implications: Why This Is By Design - -### Risks if Session Sharing Were Possible - -| Risk | Impact | -|------|--------| -| Context Leak | Conversation history exposed to unintended accounts | -| Privilege Escalation | Lower-tier account accessing higher-tier sessions | -| Organizational Data Breach | Work conversations leaked to personal accounts | -| Audit Trail Corruption | Session actions attributed to wrong user | - -### Current Security Posture - -- **Credential Isolation**: OAuth tokens stored per-profile (CCS architecture) -- **POSIX Permissions**: `~/.claude/` readable only by user (`700` permissions) -- **No Session Encryption**: JSONL files plain text (relies on OS security) -- **Profile Separation**: CCS v3.0 login-per-profile prevents credential mixing - -### Design Intent - -Session isolation prevents: -1. **Cross-account context leakage**: Alice's work threads stay with work account -2. **Subscription boundary violations**: Free account can't "resume" Pro sessions -3. **Organizational data governance**: Company data stays within company accounts - -## Alternative Approaches: What Works Instead - -### Manual JSONL Copy (Workaround, Not Recommended) - -**Process**: -1. Copy session file: `~/.ccs/instances/work/.claude/projects//.jsonl` -2. Generate new UUID: `new_id=$(uuidgen | tr '[:upper:]' '[:lower:]')` -3. Replace `sessionId` in JSONL: `sed 's///g' file.jsonl > new.jsonl` -4. Place in personal profile: `~/.ccs/instances/personal/.claude/projects//.jsonl` -5. Resume: `ccs personal` → `claude --resume ` - -**Issues**: -- Fragile (breaks if JSONL structure changes) -- No UUID regeneration for `parentUuid`, message `uuid` fields -- Risk of malformed JSON breaking CLI -- Manual process prone to errors - -### Context Export/Import (PARTIALLY FEASIBLE, Not Implemented) - -**Concept**: -```bash -# Work profile (before expiration) -ccs export-context --session --output work-context.json - -# Personal profile (after expiration) -ccs import-context work-context.json --new-session -``` - -**Process**: -1. **Export**: Read JSONL → extract message history → strip metadata → save portable JSON -2. **Import**: Parse JSON → generate new session UUID → reconstruct JSONL with personal auth context -3. **Resume**: Use new session ID with personal OAuth token - -**Advantages**: -- ✅ Preserves conversation history -- ✅ New session = clear ownership (personal account) -- ✅ No cross-account authorization issues -- ✅ Explicit user action (no silent credential sharing) -- ✅ Audit-friendly (new session ID) - -**Status**: DEFERRED (not implemented in CCS v3.0) - -### User Experience Flow (Proposed) - -``` -$ ccs export-session 58921318-0aed-4238-b6cb-d0d6222fc095 -✓ Exported 47 messages to ~/ccs-export-58921318.json - -[Account expires] - -$ ccs personal -$ ccs import-session ~/ccs-export-58921318.json -✓ Imported as new thread: a1b2c3d4-5678-9012-3456-789012345678 -✓ Resume with: claude --resume a1b2c3d4-5678-9012-3456-789012345678 - -$ claude --resume a1b2c3d4-5678-9012-3456-789012345678 "Continue from earlier" -[Claude continues with full context under personal auth] -``` - -## Recommendations: Clear Guidance - -### REJECT: Direct Session Sharing - -**Do NOT implement**: -- Copying session files between profiles without regeneration -- Reusing thread IDs across accounts -- "Resuming" sessions created by different OAuth tokens - -**Reason**: Violates inferred security model; likely fails API-side validation. - -### DEFER: Export/Import Feature - -**Status**: Feasible but not critical for CCS v3.0. - -**Priority**: Phase 3 (post-launch). - -**Effort**: Medium (~3-5 days implementation + testing). - -**Dependencies**: -- JSONL parsing/reconstruction logic -- UUID generation for new sessions -- Profile-aware file I/O - -### Document: Manual Workaround - -**For Advanced Users** (FAQ section): - -1. Manually copy JSONL file -2. Edit `sessionId` fields (use `jq` or `sed`) -3. Regenerate UUIDs for messages (optional but safer) -4. Place in target profile's `.claude/projects/` directory -5. Resume with `claude --resume ` - -**Warning**: Unsupported; may break with Claude CLI updates. - -## Unresolved Questions - -1. **Does Claude API enforce server-side session ownership?** - Inferred from OAuth architecture; no official docs confirm. Would require API testing. - -2. **What is `~/.claude/session-env/` used for?** - Contains empty UUID directories; possibly ephemeral runtime state. Doesn't affect persistence. - -3. **Can malformed JSONL crash Claude CLI?** - Likely yes (JSON parsing errors). Manual editing risky without validation. - -4. **What happens if imported session references inaccessible resources?** - E.g., work git repo personal account can't access. Claude will continue but may request clarification. diff --git a/docs/system-architecture.md b/docs/system-architecture.md deleted file mode 100644 index 8e2a1f77..00000000 --- a/docs/system-architecture.md +++ /dev/null @@ -1,1603 +0,0 @@ -# CCS System Architecture - -## Overview - -CCS (Claude Code Switch) is a TypeScript-based CLI tool that provides instant profile switching between Claude Sonnet 4.5, GLM 4.6, GLMT (GLM with Thinking), and Kimi for Coding models. The architecture features a modern React 19 web dashboard with real-time WebSocket integration, comprehensive TypeScript core, and cross-platform shell scripts. Current version includes AI-powered delegation, CLIProxy OAuth integration, and extensive automation infrastructure. - -## Core Architecture Principles - -### Design Philosophy -- **YAGNI** (You Aren't Gonna Need It): No features "just in case" -- **KISS** (Keep It Simple): Minimal complexity, maximum reliability -- **DRY** (Don't Repeat Yourself): Single source of truth for each concern - -### Simplification Goals -- Consolidate duplicate logic into reusable functions -- Remove unnecessary validation layers ("security theater") -- Simplify error handling and messaging -- Maintain cross-platform compatibility - -## High-Level Architecture (v4.5.0) - -```mermaid -%%{init: {'theme': 'dark'}}%% -graph TB - subgraph "User Interface Layer" - CLI[Command Line Interface] - UI[React Dashboard] - FLAGS[Special Flag Handlers] - DELEGATION[Delegation Flag] - end - - subgraph "Web Dashboard (ui/)" - REACT[React 19 App] - WEBSOCKET[WebSocket Client] - VITE[Vite Dev Server] - API[API Integration] - ROUTER[React Router] - end - - subgraph "Core Processing Layer" - DETECT[Profile Detection Logic] - CONFIG[Configuration Manager] - SPAWN[Unified Spawn Executor] - DELEGATOR[Delegation Handler] - end - - subgraph "New v4.x Subsystems" - SYMLINK[Symlink Manager] - DOCTOR[Diagnostics] - COMPLETION[Shell Completion] - SESSION[Session Manager] - CLIPROXY[CLIProxy Integration] - end - - subgraph "System Integration Layer" - CLAUDE[Claude CLI Detector] - PATH[Path Resolution] - ENV[Environment Variables] - end - - subgraph "External Dependencies" - CLAUDE_EXEC[Claude CLI Executable] - SETTINGS[Claude Settings Files] - SHARED[~/.ccs/shared/] - end - - CLI --> DETECT - CLI --> DELEGATION - UI --> API - API --> DETECT - FLAGS --> SPAWN - DELEGATION --> DELEGATOR - DETECT --> CONFIG - CONFIG --> SPAWN - DELEGATOR --> SPAWN - SPAWN --> CLAUDE - CLAUDE --> PATH - CLAUDE --> ENV - SPAWN --> CLAUDE_EXEC - CONFIG --> SETTINGS - SYMLINK --> SHARED -``` - -## Component Architecture - -### 1. Main Entry Point (`src/ccs.ts` - 593 lines, Phase 02 Refactored) - -**Role**: Central orchestrator for all CCS operations (Post-Phase 02 modular architecture) - -**Key Responsibilities**: -- Argument parsing and profile detection -- **Command routing to modular handlers** (Phase 02 enhancement) -- **Flag extraction for command options** (Phase 1: update command --force and --beta flags) -- Delegation detection (`-p` / `--prompt` flag routing) -- Profile type routing (settings-based vs account-based) -- GLMT proxy lifecycle management -- Unified process execution through `execClaude()` -- Error propagation and exit code management -- Auto-recovery for missing configuration - -**Phase 02 Refactoring Achievement**: -- **Size reduction**: 1,071 → 593 lines (**44.6% reduction**) -- **Modularization**: 7 command handlers extracted to dedicated modules -- **Maintainability**: Single responsibility principle applied to all commands -- **Focus**: Now contains only core routing, profile detection, and GLMT proxy logic - -**Architecture with Delegation Support (v4.3.2)**: -```mermaid -graph TD - subgraph "Entry Point" - ARGS[Parse Arguments] - SPECIAL[Handle Special Commands] - RECOVER[Auto-recovery] - DETECT[ProfileDetector] - SETTINGS[Settings-based Profile] - GLMT{GLMT Profile?} - ACCOUNT[Account-based Profile] - PROXY[Spawn Proxy] - EXEC[Execute Claude] - end - - ARGS --> SPECIAL - SPECIAL --> RECOVER - RECOVER --> DETECT - DETECT --> SETTINGS - DETECT --> ACCOUNT - SETTINGS --> GLMT - GLMT -->|Yes| PROXY - GLMT -->|No| EXEC - PROXY --> EXEC - ACCOUNT --> EXEC -``` - -**Key Enhancements**: -- **v3.3.0**: GLMT proxy spawning with verbose flag detection, API key validation, 5s timeout -- **v3.2.0**: Dual-path execution supporting both `--settings` flag (backward compatible) and `CLAUDE_CONFIG_DIR` env var (concurrent sessions) -- **v3.1.0**: Auto-recovery manager for missing configs - -**GLMT-Specific Logic**: -```javascript -// Check if GLMT profile -if (profileInfo.name === 'glmt') { - // 1. Read API key from settings - // 2. Spawn proxy with --verbose flag (if detected in args) - // 3. Wait for PROXY_READY:port signal (5s timeout) - // 4. Spawn Claude CLI with proxy URL - // 5. Kill proxy when Claude exits - await execClaudeWithProxy(claudeCli, 'glmt', remainingArgs); -} -``` - -### React Dashboard Architecture (ui/) - -**Technology Stack**: -- React 19 with TypeScript and concurrent features -- Vite for fast development and optimized builds -- shadcn/ui component library (Radix UI + Tailwind CSS) -- TanStack Query for server state management -- Real-time WebSocket integration for live updates - -#### Dashboard Components - -**1. Main Application (`ui/src/App.tsx`)** -- React Router setup for client-side routing -- Global providers (Query, Theme, WebSocket) -- Layout structure with sidebar and main content - -**2. Pages (`ui/src/pages/`)** -- **Dashboard**: Overview with system status and metrics -- **API Profiles**: Model configuration management (GLM, GLMT, Kimi) -- **CLIProxy**: OAuth provider setup and management -- **Accounts**: Multi-account profile management -- **Health**: System diagnostics and monitoring -- **Settings**: Global configuration options -- **Shared**: Data sharing management - -**3. Components (`ui/src/components/`)** -- **UI Components (`ui/`)**: shadcn/ui base components -- **Custom Components**: Domain-specific UI elements -- **Core Components (Phase 1)**: - - `ProfileCard`: Individual profile display with active/inactive states and action buttons - - `ProfileDeck`: Grid container for profile cards with loading and error states - - `CommandBuilder`: Interactive command construction tool with search/filter capabilities - - `ValueMetrics`: Performance metrics visualization with trend indicators - - `HubFooter`: Utility footer with version info and navigation links -- **Charts**: Data visualization components -- **Forms**: Profile and configuration forms - -**4. Hooks (`ui/src/hooks/`)** -- `useWebSocket`: Real-time connection management -- `useProfiles`: Profile data fetching and caching -- `useSettings`: Settings persistence and sync -- Custom hooks for domain logic - -**5. Utils (`ui/src/lib/`)** -- API client functions -- Utility helpers -- Type definitions -- Configuration constants - -#### Real-Time Features - -**WebSocket Integration**: -```typescript -// Real-time profile updates, delegation status, system health -const wsUrl = `ws://localhost:8080/ws`; -const { data, isConnected } = useWebSocket(wsUrl); -``` - -**Live Updates**: -- Profile activation/deactivation -- Delegation progress tracking -- System health monitoring -- CLIProxy authentication status - -#### State Management - -**Server State (TanStack Query)**: -```typescript -// Cached API calls with automatic refetching -const queryClient = useQueryClient(); -const { data: profiles } = useQuery({ - queryKey: ['profiles'], - queryFn: fetchProfiles, - staleTime: 5 * 60 * 1000, // 5 minutes -}); -``` - -**Local State**: -- useState for component state -- useReducer for complex state logic -- Context for global theme preferences - -#### Build System (Vite) - -**Development**: -- Fast HMR (Hot Module Replacement) -- Vite dev server on port 3000 -- Proxy to backend API on port 8080 - -**Production**: -- Optimized bundle with code splitting -- Manual chunks for vendor libraries -- Source maps for debugging -- Assets optimization - -#### Phase 1 Component Architecture (2024-12-12) - -**Component Hierarchy**: -```mermaid -graph TD - App --> Dashboard - App --> Layout - Layout --> HubFooter - - Dashboard --> ProfileDeck - Dashboard --> CommandBuilder - Dashboard --> ValueMetrics - - ProfileDeck --> ProfileCard - - subgraph "UI Foundation" - shadcn[shadcn/ui Components] - tailwind[Tailwind CSS] - lucide[Lucide Icons] - end - - ProfileCard --> shadcn - CommandBuilder --> shadcn - ValueMetrics --> shadcn - HubFooter --> shadcn -``` - -**Component Interaction Patterns**: - -1. **Profile Management Flow**: - - `ProfileDeck` fetches profile data via `useProfiles` hook - - Transforms API response to include UI state (active, model, lastUsed) - - Renders `ProfileCard` components for each profile - - Handles loading, error, and empty states - -2. **Command Building Flow**: - - `CommandBuilder` maintains local search state - - Filters predefined command list based on user input - - Provides copy and run actions for selected commands - - Categories commands for better organization - -3. **Metrics Visualization**: - - `ValueMetrics` displays mock performance data - - Shows trend indicators with color coding - - Aggregates monthly summary statistics - - Responsive grid layout for different screen sizes - -4. **Navigation Structure**: - - `HubFooter` provides version information - - Links to internal sections (Logs, Settings) - - External link to GitHub repository - - Responsive text display based on screen size - -**Data Flow Architecture**: -```mermaid -sequenceDiagram - participant User - participant Dashboard - participant ProfileDeck - participant API as useProfiles Hook - participant ProfileCard - - User->>Dashboard: Load dashboard - Dashboard->>ProfileDeck: Request profiles - ProfileDeck->>API: fetchProfiles() - API-->>ProfileDeck: Profile data - ProfileDeck->>ProfileCard: Render with props - ProfileCard-->>User: Display profile UI -``` - -### 2. Configuration Manager (`bin/config-manager.js`) - -**Role**: Handles all configuration-related operations - -**Key Responsibilities**: -- Configuration file path resolution -- JSON parsing and validation -- Profile-to-settings-file mapping -- Error handling for configuration issues - -**Architecture Flow**: -```mermaid -graph TD - PATH[Get Config Path] --> READ[Read Config File] - READ --> PARSE[Parse JSON] - PARSE --> VALIDATE[Validate Structure] - VALIDATE --> MAP[Map Profile to Settings] - MAP --> RETURN[Return Settings Path] -``` - -**Simplified Validation**: Removed redundant validation functions while maintaining essential checks for file existence and JSON validity. - -### 3. Claude CLI Detector (`bin/claude-detector.js`) - -**Role**: Locates and validates the Claude CLI executable - -**Key Responsibilities**: -- Environment variable override support (`CCS_CLAUDE_PATH`) -- System PATH resolution -- Cross-platform executable detection -- Windows-specific executable extension handling - -**Detection Priority**: -```mermaid -graph TD - ENV[CCS_CLAUDE_PATH] --> VALID{Valid Path?} - VALID -->|Yes| USE_ENV[Use Environment Path] - VALID -->|No| PATH[System PATH Lookup] - PATH --> FOUND{Found in PATH?} - FOUND -->|Yes| USE_PATH[Use PATH Result] - FOUND -->|No| FAIL[Return null] -``` - -**Platform-Specific Logic**: -- **Unix/macOS**: Uses `which claude` command -- **Windows**: Uses `where.exe claude` with extension preference -- **Cross-platform**: Unified error handling and fallback logic - -### 4. Helpers Module (`bin/helpers.js`) - -**Role**: Provides essential utility functions - -**Key Responsibilities**: -- TTY-aware color formatting -- Path expansion with tilde and environment variables -- Simplified error reporting -- Cross-platform compatibility - -**Removed Functions** (Security Theater): -- `escapeShellArg()`: Unnecessary with spawn() arrays -- `validateProfileName()`: Redundant validation -- `isPathSafe()`: Excessive security checking - -### 5. Instance Manager (`bin/instance-manager.js`) - NEW in - -**Role**: Manages isolated Claude CLI instances per profile - -**Key Responsibilities**: -- Lazy instance initialization on first use (YAGNI principle) -- Instance directory creation (`~/.ccs/instances//`) -- Credential synchronization from vault to instance -- Instance integrity validation -- Instance lifecycle management (create, validate, delete) - -**Architecture Flow**: -```mermaid -graph TD - ACTIVATE[activateInstance] --> EXISTS{Instance exists?} - EXISTS -->|No| INIT[initializeInstance] - EXISTS -->|Yes| SYNC[syncCredentialsToInstance] - INIT --> SYNC - SYNC --> VALIDATE[validateInstance] - VALIDATE --> RETURN[Return instance path] -``` - -**Directory Structure Created**: -``` -~/.ccs/instances// -├── session-env/ # Claude session data -├── todos/ # Per-profile todo lists -├── logs/ # Execution logs -├── file-history/ # File edit history -├── shell-snapshots/ # Shell state snapshots -├── debug/ # Debug information -├── .anthropic/ # Anthropic SDK config -├── commands/ # Custom commands (copied from global) -├── skills/ # Custom skills (copied from global) -└── .credentials.json # Encrypted credentials (synced from vault) -``` - -### 6. Profile Detector (`bin/profile-detector.js`) - NEW in - -**Role**: Determines profile type for routing - -**Key Responsibilities**: -- Detect settings-based profiles (glm, kimi) - Priority 1 for backward compatibility -- Detect account-based profiles (work, personal) - Priority 2 -- Resolve default profile across both types -- Provide error messages with available profiles - -**Detection Priority**: -```mermaid -graph TD - INPUT[Profile name] --> SETTINGS{In config.json?} - SETTINGS -->|Yes| RETURN_SETTINGS[Return: type=settings] - SETTINGS -->|No| ACCOUNT{In profiles.json?} - ACCOUNT -->|Yes| RETURN_ACCOUNT[Return: type=account] - ACCOUNT -->|No| ERROR[Throw: Profile not found] -``` - -### 7. Profile Registry (`bin/profile-registry.js`) - NEW in - -**Role**: Manages account profile metadata - -**Key Responsibilities**: -- CRUD operations for account profiles in `~/.ccs/profiles.json` -- Default profile management -- Last-used timestamp tracking -- Atomic file writes for data integrity - -**Profile Metadata Schema**: -```json -{ - "version": "2.0.0", - "profiles": { - "work": { - "type": "account", - "vault": "~/.ccs/accounts/work.json.enc", - "subscription": "pro", - "email": "user@work.com", - "created": "2025-11-09T...", - "last_used": "2025-11-09T..." - } - }, - "default": "work" -} -``` -## Modular Command Architecture (Phase 02, 2025-11-27) - -### Overview - -The modular command architecture separates command handling logic from the main orchestrator, achieving significant improvements in maintainability, testability, and code organization. - -### Components - -**Command Handler Modules** (`src/commands/`): - -**1. Version Command Handler (`src/commands/version-command.ts` - 3.0KB)** -- Handles `--version` flag display -- Shows version number, build location, and platform information -- Delegates version formatting and display logic from main file - -**2. Help Command Handler (`src/commands/help-command.ts` - 4.9KB)** -- Handles `--help` flag display -- Provides comprehensive help including profile listings -- Supports delegation help with usage examples -- Dynamically generates help content based on available profiles - -**3. Install Command Handler (`src/commands/install-command.ts` - 957B)** -- Handles `--install` flag for setup instructions -- Manages installation and uninstallation workflows -- Cross-platform compatibility support - -**4. Doctor Command Handler (`src/commands/doctor-command.ts` - 415B)** -- Handles `doctor` subcommand for system diagnostics -- Validates installation, configuration, and profile status -- Provides health check functionality - -**5. Sync Command Handler (`src/commands/sync-command.ts` - 1.0KB)** -- Handles `sync` subcommand for configuration synchronization -- Repairs broken symlinks and directory structures -- Maintains shared data consistency - -**6. Shell Completion Command Handler (`src/commands/shell-completion-command.ts` - 2.1KB)** -- Handles `--shell-completion` flag and `-sc` alias -- Installs shell completion scripts for Bash, Zsh, Fish, PowerShell -- Manages shell-specific completion logic - -**7. Update Command Handler (`src/commands/update-command.ts` - 2.1KB)** -- Handles `update` subcommand for version checking and updates -- Supports both npm and direct installation methods -- Provides update notifications and installation workflows -- **Phase 1 Enhancement**: Added flag parsing for `--force` and `--beta` options (UpdateOptions interface) -- **Phase 2 Implementation**: Force reinstall logic that bypasses update checks -- **Phase 3 Enhancement**: Beta channel support with npm tag switching (latest/dev) - -#### Update Command Flow (Phase 3: Beta Channel Support) - -```mermaid -graph TD - subgraph "Update Command Handler" - START[handleUpdateCommand] --> PARSE{Parse Options} - PARSE --> |beta=true| SET_TARGET[Set targetTag=dev] - PARSE --> |beta=false| SET_TARGET_LATEST[Set targetTag=latest] - SET_TARGET --> DETECT_INSTALL[Detect Installation Method] - SET_TARGET_LATEST --> DETECT_INSTALL - - DETECT_INSTALL --> |force=true| FORCE[Force Reinstall] - DETECT_INSTALL --> |force=false| CHECK[Check for Updates] - - subgraph "Force Reinstall Path" - FORCE --> |npm| FORCE_NPM[performNpmUpdate with targetTag] - FORCE --> |direct| CHECK_BETA{beta=true?} - CHECK_BETA --> |Yes| BETA_ERROR[Show Beta Not Supported] - CHECK_BETA --> |No| FORCE_DIRECT[performDirectUpdate] - FORCE_NPM --> CLEAR_CACHE[Clear Package Cache] - CLEAR_CACHE --> INSTALL_PKG[Install Package @targetTag] - FORCE_DIRECT --> INSTALL_DIRECT[Run Direct Installer] - BETA_ERROR --> EXIT_ERROR[Exit: Error] - end - - subgraph "Standard Update Path" - CHECK --> |beta=true| CHECK_NPM{installMethod=npm?} - CHECK_NPM --> |No| BETA_ERROR - CHECK_NPM --> |Yes| FETCH_NPM[fetchVersionFromNpmTag 'dev'] - CHECK --> |beta=false| FETCH_LATEST[fetchVersionFromNpmTag 'latest' or GitHub] - - FETCH_NPM --> RESULT{Update Available?} - FETCH_LATEST --> RESULT - RESULT --> |No Update| EXIT_NO[Exit: No Update] - RESULT --> |Update Available| SHOW_BETA_WARN{beta=true?} - SHOW_BETA_WARN --> |Yes| BETA_WARNINGS[Show Beta Warnings] - SHOW_BETA_WARN --> |No| INSTALL_UPDATE[Install Update] - BETA_WARNINGS --> INSTALL_UPDATE_BETA[Install from @dev] - RESULT --> |Check Failed| EXIT_ERROR[Exit: Error] - end - - INSTALL_PKG --> SUCCESS[Exit: Success] - INSTALL_DIRECT --> SUCCESS - INSTALL_UPDATE --> SUCCESS - INSTALL_UPDATE_BETA --> SUCCESS - end -``` - -**Force Reinstall Behavior**: -- **Skip Update Check**: Bypasses version comparison and cache validation -- **Target Channel Support**: Installs from `latest` or `dev` tag based on `--beta` flag -- **Cache Clearing**: Automatically clears package manager cache before reinstalling -- **Installation Method Awareness**: - - npm installations: Supports both `--force` and `--beta` flags - - Direct installations: Only supports `--force` (shows error for `--beta`) -- **Beta Channel Warnings**: Shows stability warnings when installing from `@dev` tag - -**Beta Channel Implementation (Phase 3)**: -- **NPM Tag Switching**: Fetches versions from `@dev` tag instead of `@latest` -- **Stability Warnings**: - - Displays "[!] Installing from @dev channel (unstable)" - - Shows "[!] Not recommended for production use" - - Provides return path: "[!] Use `ccs update` (without --beta) to return to stable" -- **Installation Method Validation**: - - npm installations: Full beta channel support - - Direct installations: Error message with npm migration guidance -- **Version Fetching**: New `fetchVersionFromNpmTag()` function for tag-specific queries - -**New Utility Modules** (`src/utils/`): - -**1. Shell Executor (`src/utils/shell-executor.ts` - 1.5KB)** -- Cross-platform shell command execution utilities -- Handles process spawning, signal management, and output capture -- Provides consistent shell interface across platforms - -**2. Package Manager Detector (`src/utils/package-manager-detector.ts` - 3.8KB)** -- Detects available package managers (npm, yarn, pnpm, bun) -- Cross-platform package manager identification -- Supports installation and update workflows - -### Modular Architecture Flow - -```mermaid -graph TD - subgraph "Main Entry Point (src/ccs.ts)" - ARGS[Parse Arguments] - ROUTE[Command Router] - SPECIAL{Special Command?} - end - - subgraph "Modular Command Handlers (src/commands/)" - VERSION[version-command.ts] - HELP[help-command.ts] - INSTALL[install-command.ts] - DOCTOR[doctor-command.ts] - SYNC[sync-command.ts] - COMPLETION[shell-completion-command.ts] - UPDATE[update-command.ts] - end - - subgraph "Utility Modules (src/utils/)" - SHELL_EXEC[shell-executor.ts] - PKG_MGR[package-manager-detector.ts] - end - - ARGS --> ROUTE - ROUTE --> SPECIAL - SPECIAL -->|--version| VERSION - SPECIAL -->|--help| HELP - SPECIAL -->|--install| INSTALL - SPECIAL -->|doctor| DOCTOR - SPECIAL -->|sync| SYNC - SPECIAL -->|--shell-completion| COMPLETION - SPECIAL -->|update| UPDATE - - VERSION --> SHELL_EXEC - HELP --> SHELL_EXEC - INSTALL --> PKG_MGR -``` - -### Phase 02 Benefits Achieved - -**Maintainability Improvements:** -- **Single Responsibility**: Each command has focused, dedicated module -- **Code Navigation**: Developers can quickly locate specific command logic -- **Testing Independence**: Command handlers can be unit tested in isolation -- **Reduced Complexity**: Main file focuses on orchestration only - -**Development Workflow Enhancements:** -- **Parallel Development**: Multiple developers can work on different commands simultaneously -- **Feature Isolation**: Changes to one command don't affect others -- **Code Review Efficiency**: Smaller, focused pull requests for command modifications -- **Debugging Simplification**: Issues can be isolated to specific command modules - -**Architecture Scalability:** -- **Easy Extension**: New commands can be added without modifying main orchestrator -- **Consistent Patterns**: All command handlers follow established patterns -- **Type Safety**: Comprehensive TypeScript coverage across all modules -- **Performance**: No performance degradation, minor improvement due to smaller main file - -### Command Handler Interface Pattern - -All command handlers follow a consistent interface pattern: - -```typescript -interface CommandHandler { - handle(args: string[]): Promise; - requiresProfile?: boolean; - description?: string; -} -``` - -This standardized interface ensures: -- **Consistent API**: All commands can be called uniformly -- **Type Safety**: TypeScript ensures proper argument handling -- **Future Extension**: New commands can easily conform to the pattern -- **Testing**: Mock interfaces can be created for unit testing - -## Delegation Architecture (v4.0+) - -### Overview - -The delegation system enables headless execution of Claude CLI with real-time tool tracking. Users invoke with `-p` flag for AI-powered task delegation. - -### Components - -**1. Delegation Handler (`bin/delegation/delegation-handler.js` - ~300 lines)** -- Routes `-p` commands to appropriate profile -- Validates profile has valid API key -- Detects `:continue` suffix for session resumption -- Delegates to HeadlessExecutor for execution - -**2. Headless Executor (`bin/delegation/headless-executor.js` - ~400 lines)** -- Spawns Claude CLI with `--output-format stream-json --verbose` -- Parses stream-JSON output in real-time -- Tracks 13+ Claude Code tools (Bash, Read, Write, Edit, Glob, Grep, etc.) -- Handles Ctrl+C signal (kills child processes properly) -- Extracts cost and duration from output - -**3. Session Manager (`bin/delegation/session-manager.js` - ~200 lines)** -- Saves session IDs for continuation support -- Loads last session for `:continue` commands -- Manages session history in `~/.ccs/delegation-sessions/` - -**4. Result Formatter (`bin/delegation/result-formatter.js` - ~150 lines)** -- Formats execution results with cost, duration, exit code -- Color-codes tool names and paths -- Displays summary statistics - -**5. Settings Parser (`bin/delegation/settings-parser.js` - ~150 lines)** -- Parses profile settings to extract API keys -- Validates settings file format -- Supports both settings-based and account-based profiles - -### Delegation Execution Flow - -```mermaid -sequenceDiagram - participant User - participant Handler as DelegationHandler - participant Executor as HeadlessExecutor - participant Parser as Stream Parser - participant Session as SessionManager - participant Formatter as ResultFormatter - participant Claude as Claude CLI - - User->>Handler: ccs glm -p "add tests" - Handler->>Handler: Validate profile, check API key - Handler->>Executor: Execute with stream-JSON - Executor->>Claude: spawn --output-format stream-json --verbose - Claude->>Parser: stdout stream - Parser->>Parser: Extract [Tool] lines - Parser->>User: Display tools in real-time - Claude->>Executor: Exit with code - Executor->>Session: Save session ID - Executor->>Formatter: Format results - Formatter->>User: Display cost, duration, status -``` - -### Stream-JSON Parsing - -**Tool Tracking**: -```javascript -// Real-time extraction of tool calls from stream-JSON -const toolRegex = /\[Tool\]\s+(\w+)\((.*?)\)/; -const match = line.match(toolRegex); -if (match) { - const [_, toolName, params] = match; - console.log(` ${formatToolName(toolName)} ${formatParams(params)}`); -} -``` - -**Supported Tools** (13+): -- Bash, BashOutput, KillShell -- Read, Write, Edit, MultiEdit, NotebookEdit -- Glob, Grep -- WebFetch, WebSearch -- SlashCommand, Skill, TodoWrite - -### Session Continuation - -**Usage**: -```bash -# Initial delegation -ccs glm -p "add tests" -# Session saved to ~/.ccs/delegation-sessions/glm-last.json - -# Continue session -ccs glm:continue -p "run the tests" -# Loads session ID, continues conversation -``` - -**Session Storage** (`~/.ccs/delegation-sessions/`): -```json -{ - "profile": "glm", - "sessionId": "2a3b4c5d", - "timestamp": "2025-11-21T10:00:00.000Z", - "prompt": "add tests" -} -``` - -## .claude/ Symlinking Architecture (v4.1+) - -### Overview - -CCS selectively symlinks .claude/ directories to share data (commands, skills, agents) across profiles while keeping profile-specific data isolated (settings, sessions, logs). - -### Components - -**1. Claude Directory Installer (`bin/utils/claude-dir-installer.js` - ~300 lines)** -- Creates `~/.ccs/shared/` directory structure -- Installs shared directories: commands/, skills/, agents/ -- Non-invasive: never modifies `~/.claude/settings.json` -- Idempotent: safe to run multiple times - -**2. Claude Symlink Manager (`bin/utils/claude-symlink-manager.js` - ~400 lines)** -- Creates symlinks from instance .claude/ to `~/.ccs/shared/` -- Windows fallback: copies directories if symlinks unavailable -- Validates symlink integrity -- Repairs broken symlinks via `ccs sync` - -### Symlinking Strategy - -**Symlinked (Shared)**: -- `~/.ccs/instances/work/.claude/commands/` → `~/.ccs/shared/commands/` -- `~/.ccs/instances/work/.claude/skills/` → `~/.ccs/shared/skills/` -- `~/.ccs/instances/work/.claude/agents/` → `~/.ccs/shared/agents/` - -**Isolated (Profile-Specific)**: -- `~/.ccs/instances/work/.claude/settings.json` -- `~/.ccs/instances/work/.claude/sessions/` -- `~/.ccs/instances/work/.claude/todolists/` -- `~/.ccs/instances/work/.claude/logs/` - -### Directory Structure - -``` -~/.ccs/ -├── shared/ # Shared across all profiles (v4.1+) -│ ├── commands/ # Slash commands -│ ├── skills/ # Agent skills -│ └── agents/ # Agent configs -└── instances/ - ├── work/ - │ └── .claude/ - │ ├── commands@ → ~/.ccs/shared/commands/ # Symlink - │ ├── skills@ → ~/.ccs/shared/skills/ # Symlink - │ ├── agents@ → ~/.ccs/shared/agents/ # Symlink - │ ├── settings.json # Isolated - │ ├── sessions/ # Isolated - │ └── logs/ # Isolated - └── personal/ - └── .claude/ - ├── commands@ → ~/.ccs/shared/commands/ - ├── skills@ → ~/.ccs/shared/skills/ - ├── agents@ → ~/.ccs/shared/agents/ - ├── settings.json - ├── sessions/ - └── logs/ -``` - -### Windows Fallback - -When symlinks unavailable on Windows: -1. Copy directories instead of symlinking -2. `ccs sync` updates copies from `~/.ccs/shared/` -3. Less efficient but maintains functionality - -## Shell Completion Architecture (v4.1.4+) - -### Overview - -CCS provides comprehensive shell completion for 4 shells (Bash, Zsh, Fish, PowerShell) with color-coded categories and profile-aware completions. - -### Components - -**1. Completion Generator (`bin/utils/shell-completion.js` - ~500 lines)** -- Generates completion scripts for each shell -- Color-codes categories: profiles (blue), commands (green), flags (yellow) -- Profile-aware: reads `config.json` and `profiles.json` dynamically -- Easy installation via `ccs --shell-completion ` - -### Supported Shells - -| Shell | Completion File | Location | -|-------|----------------|----------| -| Bash | `ccs-completion.bash` | `~/.bashrc` | -| Zsh | `_ccs` | `~/.zshrc` or fpath | -| Fish | `ccs.fish` | `~/.config/fish/completions/` | -| PowerShell | `ccs-completion.ps1` | PowerShell profile | - -### Color-Coded Categories - -**Profiles** (Blue): -- glm, glmt, kimi (settings-based) -- work, personal (account-based) - -**Commands** (Green): -- auth, doctor, sync, update - -**Flags** (Yellow): -- --version, --help, --shell-completion, -p - -## Diagnostics Architecture (v4.2+) - -### Overview - -CCS provides comprehensive health diagnostics and maintenance commands. - -### Components - -**1. Doctor Command (`bin/management/doctor.js` - ~300 lines)** -- Validates installation -- Checks profiles and API keys -- Verifies symlink integrity -- Displays color-coded status ([OK], [!], [X]) - -**2. Sync Command (`bin/management/sync.js` - ~200 lines)** -- Repairs broken symlinks -- Fixes directory structure -- Updates shared data - -**3. Update Checker (`src/utils/update-checker.ts` - ~264 lines)** -- Checks for newer CCS versions -- Smart notifications (once per day) -- Displays upgrade instructions -- **Phase 3 Enhancement**: Beta channel support with tag-specific version fetching - - `fetchVersionFromNpmTag()`: Fetches from 'latest' or 'dev' npm tags - - Installation method validation for beta channel - - Target tag parameter in `checkForUpdates()` function - -## GLMT Architecture (v3.2.0+) - -### Overview - -GLMT (GLM with Thinking) uses an embedded HTTP proxy to enable thinking mode support for GLM 4.6. The proxy converts between Anthropic and OpenAI formats, injecting reasoning parameters and transforming `reasoning_content` into thinking blocks. - -### Components - -**1. GLMT Transformer (`bin/glmt-transformer.js`)** -- Converts Anthropic Messages API → OpenAI Chat Completions format -- Extracts thinking control tags: ``, `` (effort deprecated) -- Injects reasoning parameters: `reasoning: true` (binary only - Z.AI constraint) -- Transforms OpenAI `reasoning_content` → Anthropic thinking blocks -- Generates thinking signatures for Claude Code UI -- Debug logging to `~/.ccs/logs/` when `CCS_DEBUG_LOG=1` - -**Control Mechanisms** (v3.6): -- **Locale enforcer** (`bin/locale-enforcer.js`): Force English output (prevents Chinese responses) -- **Budget calculator** (`bin/budget-calculator.js`): Thinking on/off based on task type + budget -- **Task classifier** (`bin/task-classifier.js`): Classify reasoning vs execution tasks -- **Loop detection** (`bin/delta-accumulator.js`): Break unbounded planning loops (3 blocks) - -**2. GLMT Proxy (`bin/glmt-proxy.js`)** -- Embedded HTTP server on `127.0.0.1:random_port` -- Intercepts Claude CLI → Z.AI requests -- Lifecycle tied to parent process -- Buffered mode only (streaming not supported) -- Request timeout: 120s default - -### GLMT Execution Flow - -```mermaid -sequenceDiagram - participant User - participant CCS as ccs.js - participant Proxy as glmt-proxy.js - participant Transformer as glmt-transformer.js - participant ZAI as Z.AI API - participant Claude as Claude CLI - - User->>CCS: ccs glmt "solve problem" - CCS->>CCS: Read GLMT settings (API key, config) - CCS->>Proxy: Spawn proxy with --verbose flag - Proxy->>Proxy: Bind to 127.0.0.1:random_port - Proxy-->>CCS: PROXY_READY:port - CCS->>Claude: Spawn with ANTHROPIC_BASE_URL=http://127.0.0.1:port - Claude->>Proxy: POST /v1/messages (Anthropic format) - Proxy->>Transformer: transformRequest(anthropicRequest) - Transformer->>Transformer: Extract thinking control tags - Transformer->>Transformer: Inject reasoning params - Transformer-->>Proxy: OpenAI format request - Proxy->>ZAI: POST /api/coding/paas/v4/chat/completions - ZAI-->>Proxy: OpenAI response (with reasoning_content) - Proxy->>Transformer: transformResponse(openaiResponse) - Transformer->>Transformer: Convert reasoning_content → thinking blocks - Transformer-->>Proxy: Anthropic format response - Proxy-->>Claude: Return Anthropic response - Claude-->>User: Display with thinking blocks - Claude->>CCS: Exit - CCS->>Proxy: Kill (SIGTERM) -``` - -### Debug Mode Architecture - -**Verbose Logging** (`--verbose` flag): -- Console logging with timestamps -- Request/response size tracking -- Transformation validation results -- Proxy lifecycle events - -**Debug File Logging** (`CCS_DEBUG_LOG=1`): -- Writes to `~/.ccs/logs/` -- Files: `{timestamp}-request-anthropic.json`, `request-openai.json`, `response-openai.json`, `response-anthropic.json` -- Pretty-printed JSON with full request/response data -- **[!] Warning**: Contains sensitive data (API keys, prompts) - -**Debug Workflow**: -```bash -# Enable both verbose and debug logging -export CCS_DEBUG_LOG=1 -ccs glmt --verbose "test prompt" - -# Check reasoning content -cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content' - -# Verify transformation -cat ~/.ccs/logs/*response-anthropic.json | jq '.content[] | select(.type=="thinking")' -``` - -### Configuration Migration (v3.2.0 → v3.3.0) - -**Automatic Migration** (postinstall script): -```javascript -// Added fields in v3.3.0 -{ - "env": { - "ANTHROPIC_TEMPERATURE": "0.2", // New - "ANTHROPIC_MAX_TOKENS": "65536", // New - "MAX_THINKING_TOKENS": "32768", // New - "ENABLE_STREAMING": "true", // New - "ANTHROPIC_SAFE_MODE": "false", // New - "API_TIMEOUT_MS": "3000000" // New (50 minutes) - }, - "alwaysThinkingEnabled": true // New -} -``` - -**Removed/Obsolete Fields** (from v3.2.0): -- `BASH_DEFAULT_TIMEOUT_MS` - Moved to Claude CLI config -- `BASH_MAX_TIMEOUT_MS` - Moved to Claude CLI config -- `DISABLE_TELEMETRY` - No longer needed -- `ENABLE_THINKING` - Replaced by `alwaysThinkingEnabled` - -### Proxy Lifecycle Management - -**Startup**: -1. CCS spawns `node bin/glmt-proxy.js` -2. Proxy binds to `127.0.0.1:0` (random port) -3. Proxy emits `PROXY_READY:port` to stdout -4. CCS reads port, spawns Claude CLI with proxy URL -5. Timeout: 5s (configurable) - -**Cleanup**: -- Claude CLI exits → CCS kills proxy (`SIGTERM`) -- Parent process dies → Proxy auto-terminates -- Uncaught exception → Proxy logs and exits - -**Error Handling**: -- Proxy startup timeout → Show workaround (use `ccs glm`) -- Port conflict → Uses random port (unlikely) -- Upstream timeout → 120s default, configurable - -## Data Flow Architecture - -### Settings-Based Profile Execution Flow (Backward Compatible) - -```mermaid -sequenceDiagram - participant User - participant CCS as ccs.js - participant Detector as profile-detector.js - participant Config as config-manager.js - participant Claude as Claude CLI - - User->>CCS: ccs glm "command" - CCS->>CCS: Parse arguments - CCS->>Detector: detectProfileType("glm") - Detector->>Detector: Check config.json - Detector-->>CCS: {type: "settings", settingsPath: ...} - CCS->>Config: getSettingsPath("glm") - Config-->>CCS: Return settings path - CCS->>Claude: execClaude(["--settings", path, "command"]) - Claude->>User: Execute with GLM profile -``` - -### Account-Based Profile Execution Flow (Concurrent Sessions) - -```mermaid -sequenceDiagram - participant User - participant CCS as ccs.js - participant Detector as profile-detector.js - participant Instance as instance-manager.js - participant Vault as vault-manager.js - participant Registry as profile-registry.js - participant Claude as Claude CLI - - User->>CCS: ccs work "command" - CCS->>Detector: detectProfileType("work") - Detector->>Detector: Check profiles.json - Detector-->>CCS: {type: "account", name: "work"} - CCS->>Instance: activateInstance("work") - Instance->>Instance: Check if instance exists - alt Instance not exists - Instance->>Instance: initializeInstance (create dirs) - end - Instance->>Vault: decryptCredentials("work") - Vault-->>Instance: Return credentials JSON - Instance->>Instance: Write to instance/.credentials.json - Instance->>Instance: validateInstance (check integrity) - Instance-->>CCS: Return instance path - CCS->>Registry: touchProfile("work") - Registry->>Registry: Update last_used timestamp - CCS->>Claude: execClaude(["command"], {CLAUDE_CONFIG_DIR: instancePath}) - Claude->>User: Execute with work account -``` - -### Special Command Flow - -```mermaid -sequenceDiagram - participant User - participant CCS as ccs.js - - User->>CCS: ccs --version - CCS->>CCS: handleVersionCommand() - CCS->>User: Show version and install location - - User->>CCS: ccs --help - CCS->>CCS: handleHelpCommand() - CCS->>Detector: detectClaudeCli() - CCS->>User: Show Claude help - - User->>CCS: ccs --install - CCS->>CCS: handleInstallCommand() - CCS->>User: Installation message -``` - -## Configuration Architecture - -### File Structure - -``` -~/.ccs/ -├── config.json # Settings-based profile mappings (glm, glmt, kimi) -├── profiles.json # Account-based profile metadata (work, personal) -├── glm.settings.json # GLM configuration (Anthropic endpoint) -├── glmt.settings.json # GLMT configuration (v3.3.0 with thinking mode) -├── kimi.settings.json # Kimi configuration -├── config.json.backup # Single backup file -├── VERSION # Version information -├── logs/ # Debug logs (CCS_DEBUG_LOG=1) -│ ├── {timestamp}-request-anthropic.json -│ ├── {timestamp}-request-openai.json -│ ├── {timestamp}-response-openai.json -│ └── {timestamp}-response-anthropic.json -├── delegation-sessions/ # Delegation session persistence (v4.0+) -│ ├── glm-last.json -│ ├── kimi-last.json -│ └── work-last.json -├── shared/ # Shared across all profiles (v4.1+) -│ ├── commands/ # Slash commands -│ ├── skills/ # Agent skills -│ └── agents/ # Agent configs -└── instances/ # Isolated Claude instances - ├── work/ # Work account instance - │ ├── .claude/ - │ │ ├── commands@ → ~/.ccs/shared/commands/ # Symlink (v4.1+) - │ │ ├── skills@ → ~/.ccs/shared/skills/ # Symlink (v4.1+) - │ │ ├── agents@ → ~/.ccs/shared/agents/ # Symlink (v4.1+) - │ │ ├── settings.json # Profile-specific - │ │ ├── sessions/ # Profile-specific - │ │ ├── todolists/ # Profile-specific - │ │ └── logs/ # Profile-specific - │ ├── .anthropic/ - │ └── .credentials.json - └── personal/ # Personal account instance - ├── .claude/ - │ ├── commands@ → ~/.ccs/shared/commands/ - │ ├── skills@ → ~/.ccs/shared/skills/ - │ ├── agents@ → ~/.ccs/shared/agents/ - │ ├── settings.json - │ ├── sessions/ - │ └── logs/ - ├── .anthropic/ - └── .credentials.json - -src/ # TypeScript source files (Phase 02 Modular Architecture) -├── ccs.ts # Main entry point (593 lines, 44.6% reduction) -├── commands/ # Modular command handlers (Phase 02) -│ ├── version-command.ts # 3.0KB - Version display -│ ├── help-command.ts # 4.9KB - Help system -│ ├── install-command.ts # 957B - Install/uninstall -│ ├── doctor-command.ts # 415B - System diagnostics -│ ├── sync-command.ts # 1.0KB - Configuration sync -│ ├── shell-completion-command.ts # 2.1KB - Shell completion -│ └── update-command.ts # 2.1KB - Update management -├── auth/ # Authentication system -│ ├── auth-commands.ts -│ ├── profile-detector.ts -│ └── profile-registry.ts -├── delegation/ # AI delegation system -│ ├── delegation-handler.ts -│ ├── headless-executor.ts -│ ├── session-manager.ts -│ ├── result-formatter.ts -│ └── settings-parser.ts -├── glmt/ # GLMT thinking mode system -│ ├── glmt-proxy.ts -│ ├── glmt-transformer.ts -│ ├── locale-enforcer.ts -│ ├── reasoning-enforcer.ts -│ ├── sse-parser.ts -│ └── delta-accumulator.ts -├── management/ # System management -│ ├── doctor.ts -│ ├── instance-manager.ts -│ ├── shared-manager.ts -│ ├── sync.ts -│ └── recovery-manager.ts -├── utils/ # Cross-platform utilities -│ ├── claude-detector.ts -│ ├── claude-dir-installer.ts -│ ├── claude-symlink-manager.ts -│ ├── delegation-validator.ts -│ ├── shell-executor.ts # 1.5KB - Phase 02 NEW -│ ├── package-manager-detector.ts # 3.8KB - Phase 02 NEW -│ ├── shell-completion.ts -│ ├── update-checker.ts -│ ├── helpers.ts -│ └── error-manager.ts -├── types/ # TypeScript type definitions -│ ├── cli.ts -│ ├── config.ts -│ ├── delegation.ts -│ ├── glmt.ts -│ ├── utils.ts -│ └── index.ts -└── scripts/ # Build and utility scripts - -config/ -└── base-glmt.settings.json # GLMT template (v3.3.0) - -scripts/ -└── postinstall.js # Auto-configuration + migration -``` - -### Configuration Schema - -```json -{ - "profiles": { - "default": "~/.claude/settings.json", - "glm": "~/.ccs/glm.settings.json" - } -} -``` - -### Settings File Format - -**GLM Settings (Anthropic endpoint)**: -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic", - "ANTHROPIC_AUTH_TOKEN": "your_api_key", - "ANTHROPIC_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-4.6" - } -} -``` - -**GLMT Settings (v3.3.0 with thinking mode)**: -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "https://api.z.ai/api/coding/paas/v4/chat/completions", - "ANTHROPIC_AUTH_TOKEN": "your_api_key", - "ANTHROPIC_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-4.6", - "ANTHROPIC_TEMPERATURE": "0.2", - "ANTHROPIC_MAX_TOKENS": "65536", - "MAX_THINKING_TOKENS": "32768", - "ENABLE_STREAMING": "true", - "ANTHROPIC_SAFE_MODE": "false", - "API_TIMEOUT_MS": "3000000" - }, - "alwaysThinkingEnabled": true -} -``` - -**[i] Note**: All env values are strings (not booleans/numbers) for PowerShell compatibility. - -## Security Architecture - -### Inherent Security Model - -1. **No Shell Injection Risk**: Uses `spawn()` with array arguments -2. **No Arbitrary Code Execution**: No `eval()` or dynamic code generation -3. **Controlled File Access**: Only accesses known configuration locations -4. **Minimal Dependencies**: Reduces attack surface - -### Removed Security Measures - -The simplification removed several "security theater" measures that provided no real security benefit: - -- **Shell argument escaping**: Unnecessary with spawn() arrays -- **Path name validation**: Redundant with proper file system checks -- **Profile name sanitization**: Excessive validation for controlled input - -### Maintained Security Controls - -- **File existence validation**: Essential for preventing errors -- **JSON parsing safety**: Prevents malformed configuration crashes -- **Path traversal protection**: Maintained through path normalization -- **Executable validation**: Ensures found executables are actually executable - -## Platform Architecture - -### Cross-Platform Compatibility - -```mermaid -graph TD - subgraph "Platform Abstraction" - NODE[Node.js Runtime] - FS[File System API] - PROCESS[Process Management] - end - - subgraph "Platform-Specific" - UNIX[Unix/macOS Logic] - WIN[Windows Logic] - COMMON[Common Logic] - end - - NODE --> UNIX - NODE --> WIN - NODE --> COMMON -``` - -### Platform-Specific Behaviors - -**Unix/macOS**: -- Uses `which` command for executable detection -- POSIX path handling and permissions -- Standard Unix terminal TTY detection - -**Windows**: -- Uses `where.exe` for executable detection -- Windows path separator handling -- PowerShell compatibility considerations - -**Common**: -- Node.js cross-platform APIs -- Unified error handling -- Consistent configuration format - -## Performance Architecture - -### Optimization Strategies - -1. **Reduced Function Call Overhead**: Eliminated redundant validation layers -2. **Simplified Error Handling**: Direct error propagation without complex formatting -3. **Optimized Path Resolution**: Cached environment variable lookups -4. **Minimal Memory Footprint**: 35% reduction in code size - -### Performance Characteristics - -- **Startup Time**: Fast due to minimal module loading -- **Execution Time**: Direct process spawning without overhead -- **Memory Usage**: Small footprint with efficient data structures -- **I/O Operations**: Optimized configuration reading and caching - -## Testing Architecture - -### Test Organization - -``` -tests/ -├── unit/ # Module unit tests (GLMT, delegation) -├── shared/ # Shared utilities and fixtures -├── npm/ # npm package-specific tests -├── native/ # Native installation tests (bash/PowerShell) -└── integration/ # Integration tests -``` - -### Test Coverage Strategy - -- **Unit Tests**: Individual module functionality -- **Integration Tests**: Cross-module interaction -- **Platform Tests**: OS-specific behavior validation -- **Edge Case Tests**: Error conditions and unusual scenarios - -## Deployment Architecture - -### npm Package Distribution - -```mermaid -graph LR - subgraph "Development" - SRC[Source Code] - TEST[Run Tests] - BUILD[Package Files] - end - - subgraph "Distribution" - NPM[npm Registry] - DOWNLOAD[Package Download] - INSTALL[Installation Process] - end - - subgraph "Runtime" - POSTINSTALL[Post-install Script] - CONFIG[Auto-configuration] - READY[Ready to Use] - end - - SRC --> TEST - TEST --> BUILD - BUILD --> NPM - NPM --> DOWNLOAD - DOWNLOAD --> INSTALL - INSTALL --> POSTINSTALL - POSTINSTALL --> CONFIG - CONFIG --> READY -``` - -### Installation Process - -**Two installation methods available:** - -**Method 1: npm Package (Recommended)** -1. **Package Download**: User installs via npm/yarn/pnpm/bun -2. **Post-install Script** (`scripts/postinstall.js`): - - Creates `~/.ccs/` directory structure - - Creates `~/.ccs/shared/` (commands, skills, agents) - - Migrates from v3.1.1 → v3.2.0 (if needed) - - Migrates GLMT configs from v3.2.0 → v3.3.0 (adds new fields) - - Creates `config.json` (glm, glmt, kimi, default) - - Creates `glm.settings.json` (Anthropic endpoint) - - Creates `glmt.settings.json` (OpenAI endpoint + thinking mode) - - Creates `kimi.settings.json` (Kimi endpoint) - - Creates `~/.claude/settings.json` (if missing) - - Validates configuration (checks JSON syntax, file existence) - - Shows API key setup instructions -3. **Path Configuration**: npm automatically adds to PATH -4. **Ready State**: System ready for profile switching - -**Method 2: Native Installers (v4.5.0)** -1. **Requirements Check**: Validates Node.js 14+ available -2. **Bootstrap Installation**: - - Installs lightweight shell wrappers (lib/ccs, lib/ccs.ps1) - - Shell wrappers delegate to Node.js via npx on first run - - No shell dependencies (error-codes, progress-indicator, prompt removed) -3. **First Run**: Bootstrap auto-installs @kaitranntt/ccs npm package globally -4. **Completion Message**: Shows requirements section with Node.js version - -**Requirements (v4.5.0+)**: -- Node.js 14+ (checked during install, enforced by bootstrap) -- npm 5.2+ (for npx, comes with Node.js 8.2+) - -**Idempotency**: Safe to run multiple times, preserves existing configs - -**Migration Logic** (v3.3.0): -```javascript -// Auto-adds missing fields to existing GLMT configs -const envDefaults = { - ANTHROPIC_TEMPERATURE: '0.2', - ANTHROPIC_MAX_TOKENS: '65536', - MAX_THINKING_TOKENS: '32768', - ENABLE_STREAMING: 'true', - ANTHROPIC_SAFE_MODE: 'false', - API_TIMEOUT_MS: '3000000' -}; -``` - -## Concurrent Sessions Architecture () - -### CLAUDE_CONFIG_DIR Mechanism - -CCS uses the undocumented `CLAUDE_CONFIG_DIR` environment variable to isolate Claude CLI instances: - -```javascript -// Settings-based profile (backward compatible) -execClaude(claudeCli, ['--settings', settingsPath, ...args]); - -// Account-based profile (concurrent sessions) -const envVars = { CLAUDE_CONFIG_DIR: instancePath }; -execClaude(claudeCli, args, envVars); -``` - -**How it works**: -1. Claude CLI reads `CLAUDE_CONFIG_DIR` env var -2. If set, uses that directory instead of `~/.claude/` -3. All state (sessions, todos, logs) stored in instance directory -4. Each profile gets isolated state → concurrent sessions possible - -### Isolation Guarantees - -**Isolated per instance**: -- Credentials (`.credentials.json`) -- Chat sessions (`session-env/`) -- Todo lists (`todos/`) -- Execution logs (`logs/`) -- File edit history (`file-history/`) -- Shell snapshots (`shell-snapshots/`) - -**Shared across instances**: -- Claude CLI binary location -- CCS configuration (`~/.ccs/config.json`, `profiles.json`) -- Encrypted credential vaults (`~/.ccs/accounts/`) - -### Concurrent Sessions Workflow - -```mermaid -graph TD - subgraph "Terminal 1" - T1[ccs work "task1"] - I1[Instance: ~/.ccs/instances/work/] - C1[CLAUDE_CONFIG_DIR=work] - CLI1[Claude CLI Process 1] - end - - subgraph "Terminal 2" - T2[ccs personal "task2"] - I2[Instance: ~/.ccs/instances/personal/] - C2[CLAUDE_CONFIG_DIR=personal] - CLI2[Claude CLI Process 2] - end - - T1 --> I1 --> C1 --> CLI1 - T2 --> I2 --> C2 --> CLI2 -``` - -### Known Limitations () - -1. **Same Profile Concurrent Access**: Running `ccs work` in 2 terminals → file conflicts - - Not blocked in - - File locking considered for future versions - -2. **CLAUDE_CONFIG_DIR Reliability**: Undocumented env var - - May not work on all systems - - Claude CLI version dependencies unknown - - No official support from Anthropic - -3. **Disk Space**: Each instance ~200-700 KB - - Sessions accumulate over time - - No automatic cleanup in - -## Future Extensibility - -### Extension Points - -The architecture provides clean extension points: - -1. **New Profile Types**: Easy addition via ProfileDetector -2. **Additional Commands**: Straightforward command handler extension -3. **Enhanced Isolation**: File locking for same-profile concurrent access -4. **Instance Cleanup**: Automatic session/log cleanup policies -5. **Plugin System**: Clean architecture supports future plugins - -### Architectural Guarantees - -- **Backward Compatibility**: Settings-based profiles (glm, kimi) work unchanged -- **Performance**: Lazy instance initialization minimizes overhead -- **Maintainability**: Clear separation between settings-based and account-based paths -- **Reliability**: Encrypted vaults + isolated instances reduce failure coupling - -## Summary - -The CCS system architecture successfully balances simplicity with enhanced functionality: - -**Core Architecture Strengths**: -- **Modular Design**: Clear subsystem separation (auth, delegation, glmt, management, utils, commands) -- **Phase 02 Command Modularity**: 6 specialized command handlers with single responsibility principle -- **Unified spawn logic** eliminates code duplication -- **Dual-path execution** supports settings-based and account-based profiles -- **Isolated Claude instances** enable concurrent sessions via CLAUDE_CONFIG_DIR -- **Cross-platform compatibility** ensures consistent behavior everywhere -- **Clean separation of concerns** makes the codebase maintainable and extensible - -**v4.3.2 Features** (Current): -- **AI Delegation System**: Headless execution with stream-JSON output, real-time tool tracking -- **Selective Symlinking**: Share .claude/ directories (commands, skills, agents) across profiles -- **Shell Completion**: 4 shells supported (Bash, Zsh, Fish, PowerShell) with color-coded categories -- **Diagnostics**: Doctor, sync, update commands for health checks -- **Session Persistence**: `:continue` support for follow-up delegation tasks -- **13+ Claude Code Tools**: Bash, Read, Write, Edit, Glob, Grep, TodoWrite, etc. - -**v3.3.0 Features** (GLMT): -- **GLMT thinking mode**: Embedded proxy for GLM reasoning support -- **Debug logging**: File-based logging to `~/.ccs/logs/` when `CCS_DEBUG_LOG=1` -- **Verbose mode**: Console logging with `--verbose` flag -- **Configuration migration**: Auto-upgrade configs with new fields -- **Enhanced settings**: Temperature, max tokens, thinking controls, API timeout - -**Phase 02 Architecture Highlights** (2025-11-27): -1. **Modular Command Architecture**: 6 specialized command handlers with single responsibility -2. **44.6% Main File Reduction**: src/ccs.ts reduced from 1,071 to 593 lines -3. **Enhanced Maintainability**: Focused modules for version, help, install, doctor, sync, shell-completion -4. **New Utility Modules**: Cross-platform shell execution and package manager detection -5. **TypeScript Excellence**: 100% type coverage across all new modules - -**Phase 03 Architecture Highlights** (Beta Channel Implementation): -1. **Beta Channel Support**: NPM tag switching between 'latest' and 'dev' channels -2. **Enhanced Update Command**: `--beta` flag with stability warnings and validation -3. **Installation Method Awareness**: Differential support for npm vs direct installations -4. **Version Fetching Enhancement**: Tag-specific version queries with `fetchVersionFromNpmTag()` -5. **User Safety**: Clear warnings and migration guidance for beta channel usage - -**v4.3.2 Architecture Highlights**: -1. **Delegation Architecture**: Stream-JSON parsing, session management, result formatting -2. **Symlinking Architecture**: Selective sharing with Windows fallback -3. **Shell Completion**: Dynamic profile-aware completions with color-coding -4. **Diagnostics Infrastructure**: Doctor validation, sync repairs, update checking -5. **Modular Subsystems**: 8 clear subsystems including Phase 02 commands - -**Evolution Path**: -- **v2.x → v3.0**: 40% reduction through vault removal, login-per-profile model -- **v3.0 → v4.x**: Enhanced capabilities with delegation, symlinking, diagnostics (zero breaking changes) -- **v4.x → Phase 02**: Modular command architecture with 44.6% main file reduction -- **Phase 02 → Phase 03**: Beta channel implementation with npm tag switching -- **Future (v5.0+)**: AI-powered features, enterprise capabilities, ecosystem expansion - -The architecture demonstrates how thoughtful design can add sophisticated AI delegation capabilities, shared data management, and comprehensive diagnostics while maintaining simplicity, backward compatibility, and cross-platform support. \ No newline at end of file diff --git a/docs/ui-components-phase-1-summary.md b/docs/ui-components-phase-1-summary.md deleted file mode 100644 index 5337b19b..00000000 --- a/docs/ui-components-phase-1-summary.md +++ /dev/null @@ -1,210 +0,0 @@ -# UI Components Phase 1 Implementation Summary - -**Date**: 2024-12-12 -**Phase**: 1 - Core Components Implementation -**Status**: Complete - -## Overview - -Phase 1 of the CCS UI implementation has successfully delivered 5 core components that form the foundation of the modern web dashboard. These components demonstrate best practices in React development, responsive design, and component architecture. - -## Components Delivered - -### 1. ProfileCard (`/src/components/profile-card.tsx`) -A card component for displaying individual profile information with interactive elements. - -**Features**: -- Profile name and status display -- Active/inactive state visualization -- Model information and last used timestamp -- Config and Test action buttons -- Disabled state for active profile switching - -### 2. ProfileDeck (`/src/components/profile-deck.tsx`) -A grid container for managing multiple ProfileCard components with state handling. - -**Features**: -- Responsive grid layout (1-3 columns) -- Loading state with skeleton placeholders -- Error state with descriptive messages -- Empty state for unconfigured profiles -- Mock data augmentation for development - -### 3. CommandBuilder (`/src/components/command-builder.tsx`) -An interactive tool for building and discovering CCS commands. - -**Features**: -- Real-time search and filtering -- Command categorization (Config, Profile, Diagnostics, CLIProxy) -- Copy-to-clipboard functionality -- Pre-populated command library -- Interactive command selection - -### 4. ValueMetrics (`/src/components/value-metrics.tsx`) -Performance metrics visualization with trend indicators. - -**Features**: -- Four primary metric cards with trends -- Monthly summary statistics -- Color-coded trend indicators -- Icon-based categorization -- Responsive grid layout - -### 5. HubFooter (`/src/components/hub-footer.tsx`) -Utility footer component for application navigation. - -**Features**: -- Version information display -- Copyright with dynamic year -- Navigation links (Logs, Settings, GitHub) -- External link handling -- Responsive text display - -## Technical Implementation - -### Architecture -- Built with React 19 and TypeScript -- Uses shadcn/ui component library -- Styled with Tailwind CSS -- Follows functional component patterns -- Implements proper prop typing - -### Data Management -- Server state: TanStack Query (useProfiles) -- Local state: React hooks (useState, useEffect) -- Mock data for development and demonstration -- Clear separation between data and UI logic - -### Design System -- Consistent spacing and typography -- Dark mode support -- Mobile-first responsive design -- Accessible component structure -- Semantic HTML markup - -## Documentation Updates - -The following documentation files have been updated: - -1. **System Architecture** (`/docs/system-architecture.md`) - - Added component hierarchy diagrams - - Documented interaction patterns - - Included data flow architecture - -2. **Code Standards** (`/docs/code-standards.md`) - - Added component interface patterns - - Documented mock data handling - - Included loading state patterns - -3. **Project Overview PDR** (`/docs/project-overview-pdr.md`) - - Added FR-011: Web Dashboard UI requirements - - Updated success metrics - - Added UI development roadmap - -## Best Practices Demonstrated - -### Component Design -- Single responsibility principle -- Reusable and composable components -- Clear prop interfaces -- Consistent naming conventions - -### State Management -- Proper separation of concerns -- Error boundary handling -- Loading state management -- Empty state considerations - -### Accessibility -- Semantic HTML structure -- Proper ARIA labels -- Keyboard navigation support -- Screen reader compatibility - -### Performance -- Efficient re-rendering -- Proper memo usage patterns -- Optimized bundle size -- Code splitting ready - -## Next Steps - -### Phase 2 Priorities -1. **API Integration** - - Connect to real backend services - - Implement data fetching patterns - - Add error handling for network requests - -2. **Data Persistence** - - User preferences storage - - Profile state persistence - - Settings management - -3. **Advanced Components** - - Configuration forms - - Status indicators - - Data visualization charts - -4. **Testing** - - Unit tests for all components - - Integration testing - - E2E testing setup - -### Technical Debt -- Replace mock data with real API calls -- Implement proper error boundaries -- Add comprehensive test coverage -- Optimize bundle size - -## Component Usage Examples - -### Profile Management -```typescript - - {profiles.map(profile => ( - handleSwitch(profile.name)} - onConfig={() => handleConfig(profile.name)} - onTest={() => handleTest(profile.name)} - /> - ))} - -``` - -### Command Building -```typescript - executeCommand(command)} - categories={['Config', 'Profile', 'Diagnostics']} -/> -``` - -### Metrics Display -```typescript - -``` - -## Conclusion - -Phase 1 has successfully established a solid foundation for the CCS dashboard with modern React patterns, excellent developer experience, and a clear path forward for future development. The components are well-documented, tested-ready, and follow best practices for maintainability and scalability. - -The implementation demonstrates a strong understanding of: -- Component-based architecture -- Modern React patterns -- Responsive design principles -- Accessibility requirements -- Performance optimization - -These components provide an excellent starting point for Phase 2 development and will serve as reference implementations for future UI features. - ---- - -**Phase 1 Status**: ✅ Complete -**Next Review**: Phase 2 Planning (2024-12-19) -**Documentation**: Updated and current \ No newline at end of file diff --git a/docs/version-management.md b/docs/version-management.md deleted file mode 100644 index 45cd8ef2..00000000 --- a/docs/version-management.md +++ /dev/null @@ -1,172 +0,0 @@ -# Version Management - -## Overview - -CCS uses **semantic-release** for fully automated versioning and releases. Version numbers are determined automatically from conventional commit messages - no manual version bumping required. - -## Release Channels - -| Branch | npm Tag | Example | Description | -|--------|---------|---------|-------------| -| `main` | `@latest` | `5.1.0` | Stable production releases | -| `dev` | `@dev` | `5.1.0-dev.1` | Pre-release testing | - -## How Releases Work - -### Automatic Release (Default) - -1. **Write conventional commits** during development -2. **Merge PR to `main`** (or push to `dev`) -3. **CI automatically**: - - Analyzes commits to determine version bump - - Updates `CHANGELOG.md` - - Updates `VERSION`, `package.json`, installers - - Creates git tag - - Publishes to npm - - Creates GitHub release - -### Conventional Commits - -Version bump is determined by commit type: - -| Commit Type | Version Bump | Example | -|-------------|--------------|---------| -| `feat:` | MINOR | `5.0.2` → `5.1.0` | -| `fix:` | PATCH | `5.0.2` → `5.0.3` | -| `perf:` | PATCH | `5.0.2` → `5.0.3` | -| `feat!:` or `BREAKING CHANGE:` | MAJOR | `5.0.2` → `6.0.0` | -| `docs:`, `style:`, `refactor:`, `test:`, `chore:`, `ci:` | No release | - | - -### Commit Format - -``` -(): - -[optional body] - -[optional footer(s)] -``` - -**Examples:** -```bash -feat(cliproxy): add OAuth token refresh -fix(doctor): handle missing config gracefully -feat!: remove deprecated GLMT proxy -docs: update installation guide -``` - -## Workflow Examples - -### Stable Release - -```bash -# 1. Work on feature branch -git checkout -b feat/new-feature -git commit -m "feat(scope): add new feature" - -# 2. Open PR to main -gh pr create --base main - -# 3. Merge PR → CI auto-releases to npm @latest -``` - -### Dev Release - -```bash -# 1. Switch to dev branch -git checkout dev -git merge feat/experimental - -# 2. Push → CI auto-releases to npm @dev -git push origin dev -``` - -### Installing Different Channels - -```bash -# Stable (default) -npm install -g @kaitranntt/ccs - -# Dev -npm install -g @kaitranntt/ccs@dev - -# Specific version -npm install -g @kaitranntt/ccs@5.1.0-dev.1 -``` - -## Version Files - -These files are automatically synced by semantic-release: - -| File | Purpose | -|------|---------| -| `VERSION` | Shell scripts, runtime display | -| `package.json` | npm package version | -| `installers/install.sh` | Standalone bash installer | -| `installers/install.ps1` | Standalone PowerShell installer | -| `CHANGELOG.md` | Auto-generated release notes | - -## Local Commit Validation - -Commits are validated locally via husky + commitlint: - -```bash -# This will be rejected: -git commit -m "added new feature" - -# This will pass: -git commit -m "feat: add new feature" -``` - -## Emergency Manual Release - -For emergencies only (e.g., CI broken, hotfix needed): - -```bash -./scripts/bump-version.sh patch -git add -A -git commit -m "chore(release): emergency release" -git push origin main -npm publish -``` - -## Tooling - -| Tool | Purpose | -|------|---------| -| `semantic-release` | Automated versioning and publishing | -| `@semantic-release/changelog` | Auto-update CHANGELOG.md | -| `@semantic-release/git` | Commit version files back | -| `commitlint` | Validate commit message format | -| `husky` | Git hooks for local validation | - -## Configuration Files - -- `.releaserc.json` - semantic-release configuration -- `commitlint.config.cjs` - commit message rules -- `.husky/commit-msg` - commit validation hook -- `.github/workflows/release.yml` - CI release workflow - -## Troubleshooting - -### Commit rejected by commitlint - -```bash -# Check what's wrong -bunx commitlint --edit - -# Fix commit message format -git commit --amend -``` - -### No release triggered - -Check if commits include releasable types (`feat:`, `fix:`, `perf:`). Documentation-only commits (`docs:`) don't trigger releases. - -### Dev out of sync with main - -```bash -git checkout dev -git rebase main -git push --force-with-lease origin dev -``` diff --git a/docs/vi/README.md b/docs/vi/README.md deleted file mode 100644 index 7a1ad3fd..00000000 --- a/docs/vi/README.md +++ /dev/null @@ -1,653 +0,0 @@ -
- -# CCS - Claude Code Switch - -![CCS Logo](../../docs/assets/ccs-logo-medium.png) - -### Trình quản lý profile AI đa năng cho Claude Code - -**Chuyển đổi giữa nhiều tài khoản Claude, kết nối bất kỳ API tương thích Anthropic, và sử dụng OAuth providers (Gemini, Codex, Antigravity) ngay lập tức.** -Ngừng bị rate limits. Làm việc liên tục với vô số profiles. - -
- -[![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](LICENSE) -[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey?style=for-the-badge)]() -[![npm](https://img.shields.io/npm/v/@kaitranntt/ccs?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@kaitranntt/ccs) -[![PoweredBy](https://img.shields.io/badge/PoweredBy-ClaudeKit-C15F3C?style=for-the-badge)](https://claudekit.cc?ref=HMNKXOHN) - -**Languages**: [English](../../README.md) · [Tiếng Việt](README.md) · [日本語](../ja/README.md) - -
- -
- -## Bắt Đầu Nhanh - -### Cài Đặt - -**npm Package (Được khuyến nghị)** - -**macOS / Linux / Windows** -```bash -npm install -g @kaitranntt/ccs -``` - -**Tất cả các trình quản lý package chính đều được hỗ trợ:** - -```bash -# yarn -yarn global add @kaitranntt/ccs - -# pnpm (ít hơn 70% dung lượng đĩa) -pnpm add -g @kaitranntt/ccs - -# bun (nhanh hơn 30x) -bun add -g @kaitranntt/ccs -``` - -
-[!] LỖI THỜI: Trình cài đặt shell gốc (Cũ) - -
- -> [!WARNING] -> **Các trình cài đặt này đã lỗi thời và sẽ bị xóa trong phiên bản tương lai.** -> Hiện tại chúng tự động chuyển hướng đến cài đặt npm. Vui lòng sử dụng npm trực tiếp. - -**macOS / Linux** -```bash -curl -fsSL ccs.kaitran.ca/install | bash -``` - -**Windows PowerShell** -```powershell -irm ccs.kaitran.ca/install | iex -``` - -**Lưu ý**: Script hiển thị cảnh báo lỗi thời và tự động chạy cài đặt npm nếu Node.js khả dụng. - -
- -
- -### Cấu Hình (Tự Tạo) - -**CCS tự động tạo cấu hình trong quá trình cài đặt** (thông qua script postinstall của npm). - -**~/.ccs/config.json**: -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "glmt": "~/.ccs/glmt.settings.json", - "kimi": "~/.ccs/kimi.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -
-

Custom Claude CLI Path

- -
- -Nếu Claude CLI được cài đặt ở vị trí không chuẩn (ổ D, thư mục tùy chỉnh), đặt `CCS_CLAUDE_PATH`: - -```bash -# Unix/Linux/macOS -export CCS_CLAUDE_PATH="/path/to/claude" - -# Windows PowerShell -$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe" -``` - -**Xem thêm**: [Hướng dẫn Khắc phục Sự cố](./docs/en/troubleshooting.md#claude-cli-in-non-standard-location) để biết chi tiết cài đặt. - -
- -
-

Windows Symlink Support (Developer Mode)

- -
- -**Người dùng Windows**: Bật Chế độ Nhà phát triển để có symlink thực sự (hiệu suất tốt hơn, đồng bộ hóa tức thì): - -1. Mở **Settings** → **Privacy & Security** → **For developers** -2. Bật **Developer Mode** -3. Cài đặt lại CCS: `npm install -g @kaitranntt/ccs` - -**Cảnh báo**: Nếu không có Chế độ Nhà phát triển, CCS tự động chuyển sang sao chép thư mục (hoạt động nhưng không đồng bộ tức thì trên các profile). - -
- -
- -### Lần Chuyển Đổi Đầu Tiên - -> [!IMPORTANT] -> **Trước khi dùng các mô hình thay thế, cập nhật API keys trong file settings:** -> -> - **GLM**: Chỉnh sửa `~/.ccs/glm.settings.json` và thêm Z.AI Coding Plan API Key của bạn -> - **GLMT**: Chỉnh sửa `~/.ccs/glmt.settings.json` và thêm Z.AI Coding Plan API Key của bạn -> - **Kimi**: Chỉnh sửa `~/.ccs/kimi.settings.json` và thêm Kimi API key của bạn - -
- -**Parallel Workflow: Planning + Execution** - -```bash -# Terminal 1 - Planning (Claude Sonnet) -ccs "Plan a REST API with authentication and rate limiting" - -# Terminal 2 - Execution (GLM, cost-optimized) -ccs glm "Implement the user authentication endpoints from the plan" -``` - -
-Thinking Models (Kimi & GLMT) - -
- -```bash -# Kimi - Stable thinking support -ccs kimi "Design a caching strategy with trade-off analysis" - -# GLMT - Experimental (see full disclaimer below) -ccs glmt "Debug complex algorithm with reasoning steps" -``` - -**Lưu ý:** GLMT là thử nghiệm và không ổn định. Xem phần [GLM with Thinking (GLMT)](#glm-with-thinking-glmt) dưới đây để biết chi tiết. - -
- -
- -## The Daily Developer Pain Point - -
- -### **DỪNG việc chuyển đổi. BẮT ĐẦU điều phối.** - -**Giới hạn phiên không nên phá hỏng trạng thái dòng chảy của bạn.** -
- -Bạn đang sâu trong triển khai. Ngữ cảnh đã tải. Giải pháp đang kết tinh.
-Sau đó: 🔴 _"Bạn đã đạt đến giới hạn sử dụng."_ - -**Động lực mất đi. Ngữ cảnh mất. Năng suất sụp đổ.** - -## **Giải pháp: Quy trình công việc song song** - -
-❌ CÁCH CŨ: Chuyển đổi khi bạn đạt đến giới hạn (Phản ứng) - -### Quy trình làm việc hiện tại của bạn: -- **2pm:** Xây dựng tính năng, trong vùng -- **3pm:** 🔴 Đạt giới hạn sử dụng -- **3:05pm:** Dừng công việc, chỉnh sửa `~/.claude/settings.json` -- **3:15pm:** Chuyển tài khoản, mất ngữ cảnh -- **3:30pm:** Cố gắng quay lại trạng thái dòng chảy -- **4pm:** Cuối cùng cũng năng suất trở lại - -- **Kết quả:** Mất 1 giờ, động lực bị phá hủy, sự thất vọng tăng lên - -
- -
-✨ CÁCH MỚI: Chạy song song ngay từ đầu (Chủ động) - ĐƯỢC KHUYÊN NGHỊ - -### Quy trình làm việc mới của bạn: -- **2pm:** **Terminal 1:** `ccs "Lập kế hoạch kiến trúc API"` → Tư duy chiến lược (Claude Pro) -- **2pm:** **Terminal 2:** `ccs glm "Triển khai các điểm cuối API"` → Thực thi mã (GLM) -- **3pm:** Vẫn đang giao hàng, không có gián đoạn -- **4pm:** Đạt trạng thái dòng chảy, năng suất tăng vọt -- **5pm:** Tính năng đã giao hàng, ngữ cảnh được duy trì - -- **Kết quả:** Không có thời gian chết, năng suất liên tục, ít thất vọng hơn - -### 💰 **Giá trị đề xuất:** -- **Thiết lập:** Claude Pro hiện tại của bạn + GLM Lite (add-on hiệu quả về chi phí) -- **Giá trị:** Tiết kiệm 1 giờ/ngày × 20 ngày làm việc = 20 giờ/tháng được phục hồi -- **ROI:** Thời gian phát triển của bạn có giá trị hơn chi phí thiết lập -- **Thực tế:** Giao hàng nhanh hơn chi phí vận hành - -
- -## Chọn con đường của bạn - -
-Tập trung vào ngân sách: Chỉ GLM - -- **Tốt nhất cho:** Phát triển tiết kiệm chi phí, tạo mã cơ bản -- **Sử dụng:** Chỉ sử dụng `ccs glm` trực tiếp để được trợ giúp AI hiệu quả về chi phí -- **Thực tế:** Không có quyền truy cập Claude, nhưng có khả năng cho nhiều nhiệm vụ mã hóa -- **Thiết lập:** Chỉ cần API key GLM, rất phải chăng - -
- -
-✨ Được khuyên nghị cho phát triển hàng ngày: 1 Claude Pro + 1 GLM Lite - -- **Tốt nhất cho:** Giao hàng mã hàng ngày, công việc phát triển nghiêm túc -- **Sử dụng:** `ccs` để lập kế hoạch + `ccs glm` để thực thi (quy trình công việc song song) -- **Thực tế:** Cân bằng hoàn hảo giữa khả năng và chi phí cho hầu hết các nhà phát triển -- **Giá trị:** Không bao giờ đạt đến giới hạn phiên, năng suất liên tục - -
- -
-Power User: Nhiều Claude Pro + GLM Pro - -- **Tốt nhất cho:** Nhiều công việc, dự án đồng thời, solo dev -- **Mở khóa:** Không bao giờ cạn kiệt giới hạn phiên hoặc hàng tuần -- **Quy trình làm việc:** 3+ terminal chạy các nhiệm vụ chuyên biệt đồng thời - -
- -
-Tập trung vào quyền riêng tư: Cách ly Công việc/Cá nhân - -- **Khi cần:** Cách ly nghiêm ngặt ngữ cảnh AI công việc và cá nhân -- **Thiết lập:** `ccs auth create work` + `ccs auth create personal` -- **Lưu ý:** Tính năng nâng cao - hầu hết người dùng không cần điều này - -
- ---- - -## Why CCS Instead of Manual Switching? - -
- -**CCS không phải về "chuyển đổi khi bạn đạt đến giới hạn lúc 3pm."** - -## **Nó về việc chạy song song ngay từ đầu.** - -
- -### Sự khác biệt cốt lõi - -| **Chuyển đổi thủ công** | **Điều phối CCS** | -|:---|:---| -| 🔴 Đạt giới hạn → Dừng công việc → Chỉnh sửa tệp cấu hình → Khởi động lại | ✅ Nhiều terminal chạy các mô hình khác nhau ngay từ đầu | -| 😰 Mất ngữ cảnh và gián đoạn trạng thái dòng chảy | 😌 Năng suất liên tục với ngữ cảnh được bảo toàn | -| 📝 Xử lý nhiệm vụ tuần tự | ⚡ Quy trình công việc song song (lập kế hoạch + thực thi đồng thời) | -| 🛠️ Giải quyết vấn đề phản ứng khi bị chặn | 🎯 Thiết kế quy trình công việc chủ động ngăn chặn chặn | - -### CCS mang lại cho bạn - -- **Không chuyển đổi ngữ cảnh:** Duy trì trạng thái dòng chảy của bạn mà không bị gián đoạn -- **Năng suất song song:** Lập kế hoạch chiến lược trong một terminal, thực thi mã trong terminal khác -- **Quản lý tài khoản tức thì:** Một lệnh chuyển đổi, không cần chỉnh sửa tệp cấu hình -- **Cách ly công việc-cuộc sống:** Cách ly ngữ cảnh mà không cần đăng xuất -- **Tính nhất quán đa nền tảng:** Trải nghiệm mượt mà tương tự trên macOS, Linux, Windows - -
- -## Architecture - -### Profile Types - -**Settings-based**: GLM, GLMT, Kimi, default -- Uses `--settings` flag pointing to config files -- GLMT: Embedded proxy for thinking mode support - -**Account-based**: work, personal, team -- Uses `CLAUDE_CONFIG_DIR` for isolated instances -- Create with `ccs auth create ` - -### Shared Data (v3.1) - -Commands and skills symlinked from `~/.ccs/shared/` - **no duplication across profiles**. - -```plaintext -~/.ccs/ -├── shared/ # Shared across all profiles -│ ├── agents/ -│ ├── commands/ -│ └── skills/ -├── instances/ # Profile-specific data -│ └── work/ -│ ├── agents@ → shared/agents/ -│ ├── commands@ → shared/commands/ -│ ├── skills@ → shared/skills/ -│ ├── settings.json # API keys, credentials -│ ├── sessions/ # Conversation history -│ └── ... -``` - -| Type | Files | -|:-----|:------| -| **Shared** | `commands/`, `skills/`, `agents/` | -| **Profile-specific** | `settings.json`, `sessions/`, `todolists/`, `logs/` | - -> [!NOTE] -> **Windows**: Copies directories if symlinks unavailable (enable Developer Mode for true symlinks) - -
- -## Usage Examples - -### Basic Switching - -```bash -ccs # Claude subscription (default) -ccs glm # GLM (cost-optimized) -ccs kimi # Kimi (with thinking support) -``` - -### Multi-Account Setup - -```bash -# Create accounts -ccs auth create work -ccs auth create personal -``` - -**Run concurrently in separate terminals:** - -```bash -# Terminal 1 - Work -ccs work "implement feature" - -# Terminal 2 - Personal (concurrent) -ccs personal "review code" -``` - -### Help & Version - -```bash -ccs --version # Show version -ccs --help # Show all commands and options -``` - -
- -## GLM with Thinking (GLMT) - -> [!CAUTION] -> ### NOT PRODUCTION READY - EXPERIMENTAL FEATURE -> -> **GLMT is experimental and requires extensive debugging**: -> - Streaming and tool support still under active development -> - May experience unexpected errors, timeouts, or incomplete responses -> - Requires frequent debugging and manual intervention -> - **Not recommended for critical workflows or production use** -> -> **Alternative for GLM Thinking**: Consider going through the **CCR hustle** with the **Transformer of Bedolla** ([ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/)) for a more stable implementation. - -> [!IMPORTANT] -> GLMT requires npm installation (`npm install -g @kaitranntt/ccs`). Not available in native shell versions (requires Node.js HTTP server). - -
- -> [!NOTE] -> ### Acknowledgments: The Foundation That Made GLMT Possible -> -> **CCS's GLMT implementation owes its existence to the groundbreaking work of [@Bedolla](https://github.com/Bedolla)**, who created [ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/) - the **first integration** to bridge [Claude Code Router (CCR)](https://github.com/musistudio/claude-code-router) with Z.AI's reasoning capabilities. -> -> Before ZaiTransformer, no one had successfully integrated Z.AI's thinking mode with Claude Code's workflow. Bedolla's work wasn't just helpful - it was **foundational**. His implementation of request/response transformation architecture, thinking mode control mechanisms, and embedded proxy design directly inspired and enabled GLMT's design. -> -> **Without ZaiTransformer's pioneering work, GLMT wouldn't exist in its current form.** If you benefit from GLMT's thinking capabilities, please consider starring [ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/) to support pioneering work in the Claude Code ecosystem. - -
- -
-

GLM vs GLMT Comparison

- -
- -
- -| Feature | GLM (`ccs glm`) | GLMT (`ccs glmt`) | -|:--------|:----------------|:------------------| -| **Endpoint** | Anthropic-compatible | OpenAI-compatible | -| **Thinking** | No | Experimental (`reasoning_content`) | -| **Tool Support** | Basic | **Unstable (v3.5+)** | -| **MCP Tools** | Limited | **Buggy (v3.5+)** | -| **Streaming** | Stable | **Experimental (v3.4+)** | -| **TTFB** | <500ms | <500ms (sometimes), 2-10s+ (often) | -| **Use Case** | Reliable work | **Debugging experiments only** | - -
- -
- -
- -
-

Tool Support (v3.5) - EXPERIMENTAL

- -
- -**GLMT attempts MCP tools and function calling:** - -- **Bidirectional Transformation**: Anthropic tools ↔ OpenAI format (unstable) -- **MCP Integration**: MCP tools sometimes execute (often output XML garbage) -- **Streaming Tool Calls**: Real-time tool calls (when not crashing) -- **Backward Compatible**: May break existing thinking support -- **Configuration Required**: Frequent manual debugging needed - -
- -
-

Streaming Support (v3.4) - OFTEN FAILS

- -
- -**GLMT attempts real-time streaming** with incremental reasoning content delivery: - -- **Default**: Streaming enabled (TTFB <500ms when it works) -- **Auto-fallback**: Frequently switches to buffered mode due to errors -- **Thinking parameter**: Claude CLI `thinking` parameter sometimes works - - May ignore `thinking.type` and `budget_tokens` - - Precedence: CLI parameter > message tags > default (when not broken) - -**Status**: Z.AI (tested, tool calls frequently break, requires constant debugging) - -
- -
-

How It Works (When It Works)

- -
- -1. CCS spawns embedded HTTP proxy on localhost (if not crashing) -2. Proxy attempts to convert Anthropic format → OpenAI format (often fails) -3. Tries to transform Anthropic tools → OpenAI function calling format (buggy) -4. Forwards to Z.AI with reasoning parameters and tools (when not timing out) -5. Attempts to convert `reasoning_content` → thinking blocks (partial or broken) -6. Attempts to convert OpenAI `tool_calls` → Anthropic `tool_use` blocks (XML garbage common) -7. Thinking and tool calls sometimes appear in Claude Code UI (when not broken) - -
- -
-

Control Tags & Keywords

- -
- -**Control Tags**: -- `` - Enable/disable reasoning blocks (default: On) -- `` - Control reasoning depth (deprecated - Z.AI only supports binary thinking) - -**Thinking Keywords** (inconsistent activation): -- `think` - Sometimes enables reasoning (low effort) -- `think hard` - Sometimes enables reasoning (medium effort) -- `think harder` - Sometimes enables reasoning (high effort) -- `ultrathink` - Attempts maximum reasoning depth (often breaks) - -
- -
-

Environment Variables

- -
- -**GLMT features** (all experimental): -- Forced English output enforcement (sometimes works) -- Random thinking mode activation (unpredictable) -- Attempted streaming with frequent fallback to buffered mode - -**General**: -- `CCS_DEBUG_LOG=1` - Enable debug file logging -- `CCS_CLAUDE_PATH=/path/to/claude` - Custom Claude CLI path - -
- -
-

API Key Setup

- -
- -```bash -# Edit GLMT settings -nano ~/.ccs/glmt.settings.json -``` - -Set Z.AI API key (requires coding plan): - -```json -{ - "env": { - "ANTHROPIC_AUTH_TOKEN": "your-z-ai-api-key" - } -} -``` - -
- -
-

Security Limits (DoS Protection)

- -
- -**v3.4 Protection Limits**: - -| Limit | Value | Purpose | -|:------|:------|:--------| -| **SSE buffer** | 1MB max per event | Prevent buffer overflow | -| **Content buffer** | 10MB max per block | Limit thinking/text blocks | -| **Content blocks** | 100 max per message | Prevent DoS attacks | -| **Request timeout** | 120s | Both streaming and buffered | - -
- -
-

Debugging

- -
- -**Enable verbose logging**: -```bash -ccs glmt --verbose "your prompt" -``` - -**Enable debug file logging**: -```bash -export CCS_DEBUG_LOG=1 -ccs glmt --verbose "your prompt" -# Logs: ~/.ccs/logs/ -``` - -**GLMT debugging**: -```bash -# Verbose logging shows streaming status and reasoning details -ccs glmt --verbose "test" -``` - -**Check reasoning content**: -```bash -cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content' -``` - -**Troubleshooting**: -- **If absent**: Z.AI API issue (verify key, account status) -- **If present**: Transformation issue (check `response-anthropic.json`) - -
- -
- -## Uninstall - -
-

Package Managers

- -
- -```bash -# npm -npm uninstall -g @kaitranntt/ccs - -# yarn -yarn global remove @kaitranntt/ccs - -# pnpm -pnpm remove -g @kaitranntt/ccs - -# bun -bun remove -g @kaitranntt/ccs -``` - -
- -
-

Official Uninstaller

- -
- -```bash -# macOS / Linux -curl -fsSL ccs.kaitran.ca/uninstall | bash - -# Windows PowerShell -irm ccs.kaitran.ca/uninstall | iex -``` - -
- -
- -## 🎯 Philosophy - -- **YAGNI**: No features "just in case" -- **KISS**: Simple bash, no complexity -- **DRY**: One source of truth (config) - -## 📖 Documentation - -**Complete documentation in [docs/](./docs/)**: -- [Installation Guide](./docs/en/installation.md) -- [Configuration](./docs/en/configuration.md) -- [Usage Examples](./docs/en/usage.md) -- [System Architecture](./docs/system-architecture.md) -- [GLMT Control Mechanisms](./docs/glmt-controls.md) -- [Troubleshooting](./docs/en/troubleshooting.md) -- [Contributing](./CONTRIBUTING.md) - -## 🤝 Contributing - -We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details. - -## Star History - -
- -Star History Chart - -
- - -## License - -CCS is licensed under the [MIT License](LICENSE). - -
- -**Made with ❤️ for developers who hit rate limits too often** - -[⭐ Star this repo](https://github.com/kaitranntt/ccs) | [🐛 Report issues](https://github.com/kaitranntt/ccs/issues) | [📖 Read docs](./docs/en/) - -
\ No newline at end of file diff --git a/docs/vi/configuration.vi.md b/docs/vi/configuration.vi.md deleted file mode 100644 index f272bdd9..00000000 --- a/docs/vi/configuration.vi.md +++ /dev/null @@ -1,164 +0,0 @@ -# Hướng Dẫn Cấu Hình CCS - -## Cấu Hình Tự Động - -Installer tự động tạo config và mẫu profile trong quá trình cài đặt: - -**macOS / Linux**: `~/.ccs/config.json` - -**Windows**: `%USERPROFILE%\.ccs\config.json` - -## Định Dạng Cấu Hình - -### Cài Đặt Cơ Bản - -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -### Cài Đặt Nâng Cao (Nhiều Profile) - -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "haiku": "~/.ccs/haiku.settings.json", - "custom": "~/.ccs/custom.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -## Cấu Hình Profile - -### Ví Dụ Profile GLM - -**Vị trí**: `~/.ccs/glm.settings.json` - -```json -{ - "env": { - "ANTHROPIC_BASE_URL": "https://api.z.ai/api/anthropic", - "ANTHROPIC_AUTH_TOKEN": "your_glm_api_key", - "ANTHROPIC_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_OPUS_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_SONNET_MODEL": "glm-4.6", - "ANTHROPIC_DEFAULT_HAIKU_MODEL": "glm-4.6" - } -} -``` - -### Profile Claude (Mặc Định) - -- Sử dụng `~/.claude/settings.json` (config Claude CLI hiện tại của bạn) -- CCS không bao giờ sửa file này (tiếp cận không xâm phạm) - -## Cách Hoạt Động Cấu Hình - -1. CCS đọc tên profile từ dòng lệnh (mặc định là "default") -2. Tìm đường dẫn file settings trong `~/.ccs/config.json` -3. Thực thi `claude --settings [remaining-args]` - -Không có magic. Không sửa file. Chuyển giao thuần túy. Hoạt động giống nhau trên tất cả nền tảng. - -## Biến Môi Trường - -### CCS_CONFIG - -Ghi đè vị trí config mặc định: -```bash -export CCS_CONFIG=~/my-custom-config.json -ccs glm -``` - -### NO_COLOR - -Tắt output màu trên terminal: -```bash -export NO_COLOR=1 -ccs glm -``` - -**Trường Hợp Sử Dụng**: -- CI/CD pipelines -- Log files -- Terminal không hỗ trợ màu -- Tùy chọn trợ năng - -Khi `NO_COLOR` được đặt, CCS sử dụng output ASCII thuần không có mã màu ANSI. - -## Lưu Ý Tùy Theo Nền Tảng - -### Cấu Hình Windows - -Windows dùng cấu trúc file và phương pháp giống như Linux/macOS. - -**Định dạng config** (`~/.ccs/config.json`): -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -### Cấu Hình macOS / Linux - -Sử dụng đường dẫn file settings với mở rộng `~`: - -```json -{ - "profiles": { - "glm": "~/.ccs/glm.settings.json", - "default": "~/.claude/settings.json" - } -} -``` - -Mỗi profile trỏ đến một file settings JSON của Claude. Tạo file settings theo [tài liệu Claude CLI](https://docs.claude.com/en/docs/claude-code/installation). - -## Vấn Đề Cấu Hình - -### Không tìm thấy profile - -``` -Error: Profile 'foo' not found in ~/.ccs/config.json -``` - -**Fix**: Thêm profile vào `~/.ccs/config.json`: -```json -{ - "profiles": { - "foo": "~/.ccs/foo.settings.json" - } -} -``` - -### Thiếu file settings - -``` -Error: Settings file not found: ~/.ccs/foo.settings.json -``` - -**Fix**: Tạo file settings hoặc sửa đường dẫn trong config. - -### Thiếu profile mặc định - -``` -Error: Profile 'default' not found in ~/.ccs/config.json -``` - -**Fix**: Thêm profile "default" hoặc luôn chỉ định tên profile: -```json -{ - "profiles": { - "default": "~/.claude/settings.json" - } -} -``` \ No newline at end of file diff --git a/docs/vi/installation.vi.md b/docs/vi/installation.vi.md deleted file mode 100644 index 66b79e82..00000000 --- a/docs/vi/installation.vi.md +++ /dev/null @@ -1,237 +0,0 @@ -# Hướng Dẫn Cài Đặt CCS - -> [!WARNING] -> **Trình cài đặt shell gốc (curl/irm) đã lỗi thời.** -> Sử dụng cài đặt npm cho tất cả các nền tảng. Trình cài đặt cũ sẽ bị xóa trong v5.0. - -## Cài Đặt npm Package (Được khuyến nghị) - -### Cài Đặt Đa Nền Tảng - -**macOS / Linux / Windows** -```bash -npm install -g @kaitranntt/ccs -``` - -**Tương thích với tất cả các trình quản lý package:** -- `npm install -g @kaitranntt/ccs` -- `yarn global add @kaitranntt/ccs` -- `pnpm add -g @kaitranntt/ccs` -- `bun add -g @kaitranntt/ccs` - -**Lợi ích của việc cài đặt npm:** -- ✅ Tương thích đa nền tảng -- ✅ Cấu hình PATH tự động -- ✅ Tự động tạo file cấu hình qua script postinstall -- ✅ Cập nhật dễ dàng: `npm update -g @kaitranntt/ccs` -- ✅ Gỡ cài đặt sạch: `npm uninstall -g @kaitranntt/ccs` -- ✅ Hỗ trợ version pinning -- ✅ Quản lý dependencies - -**Những Gì Xảy Ra Trong Quá Trình Cài Đặt:** -1. npm tải xuống và cài đặt package -2. Script postinstall tự động tạo `~/.ccs/config.json` và `~/.ccs/glm.settings.json` -3. npm tạo lệnh `ccs` trong PATH của bạn - -**Lưu ý**: Nếu bạn dùng `npm install --ignore-scripts`, file cấu hình sẽ không được tạo. Chạy lại mà không có flag đó: -```bash -npm install -g @kaitranntt/ccs --force -``` - -## [!] LỖI THỜI: Cài Đặt Một Dòng Lệnh (Cũ) - -> [!WARNING] -> **Các trình cài đặt này đã lỗi thời và sẽ bị xóa trong v5.0.** -> Hiện tại chúng tự động chuyển hướng đến cài đặt npm. Vui lòng sử dụng npm trực tiếp. - -### macOS / Linux - -```bash -# URL ngắn (qua CloudFlare) -curl -fsSL ccs.kaitran.ca/install | bash - -# Hoặc trực tiếp từ GitHub -curl -fsSL https://raw.githubusercontent.com/kaitranntt/ccs/main/installers/install.sh | bash -``` - -**Lưu ý**: Script hiển thị cảnh báo lỗi thời và tự động chạy cài đặt npm nếu Node.js khả dụng. - -### Windows PowerShell - -```powershell -# URL ngắn (qua CloudFlare) -irm ccs.kaitran.ca/install.ps1 | iex - -# Hoặc trực tiếp từ GitHub -irm https://raw.githubusercontent.com/kaitranntt/ccs/main/installers/install.ps1 | iex -``` - -**Lưu ý**: Script hiển thị cảnh báo lỗi thời và tự động chạy cài đặt npm nếu Node.js khả dụng. - -## Cài Đặt qua Git Clone - -### macOS / Linux - -```bash -git clone https://github.com/kaitranntt/ccs.git -cd ccs -./installers/install.sh -``` - -### Windows PowerShell - -```powershell -git clone https://github.com/kaitranntt/ccs.git -cd ccs -.\installers\install.ps1 -``` - -**Lưu ý**: Hoạt động với git worktrees và submodules - installer phát hiện cả thư mục `.git` và file `.git`. - -## Cài Đặt Thủ Công - -### macOS / Linux - -```bash -# Tạo thư mục -mkdir -p ~/.local/bin - -# Tải script -curl -fsSL https://raw.githubusercontent.com/kaitranntt/ccs/main/ccs -o ~/.local/bin/ccs -chmod +x ~/.local/bin/ccs - -# Thêm vào PATH (chọn shell của bạn) -# Cho bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc - -# Cho zsh -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc -source ~/.zshrc - -# Cho fish -echo 'set -gx PATH $HOME/.local/bin $PATH' >> ~/.config/fish/config.fish -``` - -### Windows PowerShell - -```powershell -# Tạo thư mục -New-Item -ItemType Directory -Force -Path "$env:USERPROFILE\.ccs" - -# Tải script -Invoke-WebRequest -Uri "https://raw.githubusercontent.com/kaitranntt/ccs/main/ccs.ps1" -OutFile "$env:USERPROFILE\.ccs\ccs.ps1" - -# Thêm vào PATH (khởi động lại terminal sau) -$Path = [Environment]::GetEnvironmentVariable("Path", "User") -[Environment]::SetEnvironmentVariable("Path", "$Path;$env:USERPROFILE\.ccs", "User") -``` - -## Những Gì Được Cài Đặt - -**Vị Trí Tệp Thực Thi**: -- macOS / Linux: `~/.local/bin/ccs` (symlink đến `~/.ccs/ccs`) -- Windows: `%USERPROFILE%\.ccs\ccs.ps1` - -**Thư Mục Cấu Hình** (`~/.ccs/`): -```bash -~/.ccs/ -├── ccs # Tệp thực thi chính (symlink target) -├── config.json # Cấu hình profile -├── config.json.backup # Bản backup duy nhất (ghi đè mỗi lần cài) -├── glm.settings.json # Profile GLM -├── VERSION # File version -├── uninstall.sh # Trình gỡ cài đặt -└── .claude/ # Tích hợp Claude Code - ├── commands/ccs.md # meta-command /ccs - └── skills/ # Kỹ năng delegation -``` - -## Nâng Cấp CCS - -### macOS / Linux - -```bash -# Từ git clone -cd ccs && git pull && ./install.sh - -# Từ cài đặt curl -curl -fsSL ccs.kaitran.ca/install | bash -``` - -### Windows PowerShell - -```powershell -# Từ git clone -cd ccs -git pull -.\install.ps1 - -# Từ cài đặt irm -irm ccs.kaitran.ca/install.ps1 | iex -``` - -## Cấu Hình PATH Tự Động - -Installer tự động cấu hình PATH của shell: - -**Shell Được Hỗ Trợ**: -- bash (`.bashrc` hoặc `.bash_profile`) -- zsh (`.zshrc`) -- fish (`.config/fish/config.fish`) - -**Cách Hoạt Động**: -1. Phát hiện shell hiện tại từ biến môi trường `$SHELL` -2. Kiểm tra nếu `~/.local/bin` đã có trong PATH -3. Nếu chưa, thêm export phù hợp vào shell profile -4. Hiển thị hướng dẫn reload - -**Idempotent**: -- An toàn khi chạy nhiều lần -- Kiểm tra entry PATH của CCS trước khi thêm -- Không tạo entry trùng lặp - -**Thiết Lập PATH Thủ Công** (nếu auto-config thất bại): - -Bash/Zsh: -```bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # hoặc ~/.zshrc -source ~/.bashrc # hoặc source ~/.zshrc -``` - -Fish: -```fish -echo 'set -gx PATH $HOME/.local/bin $PATH' >> ~/.config/fish/config.fish -``` - -## Yêu Cầu - -### macOS / Linux -- `bash` 3.2+ -- `jq` (trình xử lý JSON, tùy chọn cho tính năng nâng cao) -- [Claude CLI](https://docs.claude.com/en/docs/claude-code/installation) - -### Windows -- PowerShell 5.1+ (đã cài sẵn trên Windows 10+) -- [Claude CLI](https://docs.claude.com/en/docs/claude-code/installation) - -### Cài đặt jq (macOS / Linux, tùy chọn) - -```bash -# macOS -brew install jq - -# Ubuntu/Debian -sudo apt install jq - -# Fedora -sudo dnf install jq - -# Arch -sudo pacman -S jq -``` - -**Lưu ý**: -- jq nâng cao quá trình tạo profile GLM nhưng không bắt buộc -- Windows dùng JSON support có sẵn của PowerShell - không cần jq -- Installer tạo template cơ bản mà không cần jq \ No newline at end of file diff --git a/docs/vi/troubleshooting.vi.md b/docs/vi/troubleshooting.vi.md deleted file mode 100644 index f738aaa7..00000000 --- a/docs/vi/troubleshooting.vi.md +++ /dev/null @@ -1,468 +0,0 @@ -# Hướng Dẫn Khắc Phục Sự Cố CCS - -## Cảnh báo lỗi thời của trình cài đặt gốc - -**Vấn đề:** "Tại sao trình cài đặt curl/irm hiển thị cảnh báo lỗi thời?" - -**Nguyên nhân:** Trình cài đặt shell gốc đã lỗi thời, ưu tiên cài đặt npm. - -**Giải pháp:** -```bash -# Gỡ cài đặt phiên bản cũ (nếu cài qua curl/irm) -ccs-uninstall # hoặc: curl -fsSL ccs.kaitran.ca/uninstall | bash - -# Cài đặt qua npm (khuyến nghị) -npm install -g @kaitranntt/ccs -``` - -**Lưu ý:** Trình cài đặt cũ hiện tự động chạy npm install nếu Node.js khả dụng. - -## Vấn Đề Riêng Của Windows - -### PowerShell Execution Policy - -Nếu bạn thấy "cannot be loaded because running scripts is disabled": - -```powershell -# Kiểm tra policy hiện tại -Get-ExecutionPolicy - -# Cho phép user hiện tại chạy scripts (khuyến nghị) -Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser - -# Hoặc chạy với bypass (một lần) -powershell -ExecutionPolicy Bypass -File "$env:USERPROFILE\.ccs\ccs.ps1" glm -``` - -### PATH chưa được cập nhật (Windows) - -Nếu lệnh `ccs` không tìm thấy sau khi cài đặt: - -1. Khởi động lại terminal của bạn -2. Hoặc thêm thủ công vào PATH: - - Mở "Edit environment variables for your account" - - Thêm `%USERPROFILE%\.ccs` vào User PATH - - Khởi động lại terminal - -### Claude CLI không tìm thấy (Windows) - -```powershell -# Kiểm tra Claude CLI -where.exe claude - -# Nếu thiếu, cài đặt từ tài liệu Claude -``` - -## Claude CLI Ở Vị Trí Không Chuẩn - -Nếu Claude CLI được cài đặt trên ổ đĩa khác hoặc vị trí tùy chỉnh (phổ biến trên Windows với ổ D:): - -### Triệu Chứng -``` -╔═════════════════════════════════════════════╗ -║ ERROR ║ -╚═════════════════════════════════════════════╝ - -Claude CLI not found - -Searched: - - CCS_CLAUDE_PATH: (not set) - - System PATH: not found - - Common locations: not found -``` - -### Giải Pháp: Đặt CCS_CLAUDE_PATH - -**Bước 1: Tìm Vị Trí Claude CLI** - -*Windows*: -```powershell -# Tìm kiếm tất cả ổ đĩa -Get-ChildItem -Path C:\,D:\,E:\ -Filter claude.exe -Recurse -ErrorAction SilentlyContinue | Select-Object FullName - -# Các vị trí phổ biến cần kiểm tra thủ công -D:\Program Files\Claude\claude.exe -D:\Tools\Claude\claude.exe -D:\Users\\AppData\Local\Claude\claude.exe -``` - -*Unix/Linux/macOS*: -```bash -# Tìm kiếm hệ thống -sudo find / -name claude 2>/dev/null - -# Hoặc kiểm tra các vị trí cụ thể -ls -la /usr/local/bin/claude -ls -la ~/.local/bin/claude -ls -la /opt/homebrew/bin/claude -``` - -**Bước 2: Đặt Biến Môi Trường** - -*Windows (PowerShell) - Vĩnh viễn*: -```powershell -# Thay bằng đường dẫn thực tế của bạn -$ClaudePath = "D:\Program Files\Claude\claude.exe" - -# Đặt cho phiên hiện tại -$env:CCS_CLAUDE_PATH = $ClaudePath - -# Đặt vĩnh viễn cho user -[Environment]::SetEnvironmentVariable("CCS_CLAUDE_PATH", $ClaudePath, "User") - -# Khởi động lại terminal để áp dụng -``` - -*Unix (bash) - Vĩnh viễn*: -```bash -# Thay bằng đường dẫn thực tế của bạn -CLAUDE_PATH="/opt/custom/location/claude" - -# Thêm vào shell profile -echo "export CCS_CLAUDE_PATH=\"$CLAUDE_PATH\"" >> ~/.bashrc - -# Reload profile -source ~/.bashrc -``` - -*Unix (zsh) - Vĩnh viễn*: -```bash -# Thay bằng đường dẫn thực tế của bạn -CLAUDE_PATH="/opt/custom/location/claude" - -# Thêm vào shell profile -echo "export CCS_CLAUDE_PATH=\"$CLAUDE_PATH\"" >> ~/.zshrc - -# Reload profile -source ~/.zshrc -``` - -**Bước 3: Xác Minh Cấu Hình** - -```bash -# Kiểm tra biến môi trường đã được đặt -echo $CCS_CLAUDE_PATH # Unix -$env:CCS_CLAUDE_PATH # Windows - -# Kiểm tra CCS có thể tìm thấy Claude -ccs --version - -# Kiểm tra với profile thực tế -ccs glm --version -``` - -### Các Vấn Đề Phổ Biến - -**Đường Dẫn Không Hợp Lệ**: -``` -Error: File not found: D:\Program Files\Claude\claude.exe -``` - -**Sửa**: Kiểm tra kỹ đường dẫn, đảm bảo file tồn tại: -```powershell -Test-Path "D:\Program Files\Claude\claude.exe" # Windows -ls -la "/path/to/claude" # Unix -``` - -**Thư Mục Thay Vì File**: -``` -Error: Path is a directory: D:\Program Files\Claude -``` - -**Sửa**: Đường dẫn phải trỏ đến file `claude.exe`, không phải thư mục: -```powershell -# Sai -$env:CCS_CLAUDE_PATH = "D:\Program Files\Claude" - -# Đúng -$env:CCS_CLAUDE_PATH = "D:\Program Files\Claude\claude.exe" -``` - -**Không Thể Thực Thi**: -``` -Error: File is not executable: /path/to/claude -``` - -**Sửa** (chỉ Unix): -```bash -chmod +x /path/to/claude -``` - -### Cấu Hình Riêng Cho WSL - -Khi sử dụng Claude trên Windows từ WSL: - -```bash -# Định dạng đường dẫn mount: /mnt/d/ cho ổ D: -export CCS_CLAUDE_PATH="/mnt/d/Program Files/Claude/claude.exe" - -# Thêm vào ~/.bashrc để lưu -echo 'export CCS_CLAUDE_PATH="/mnt/d/Program Files/Claude/claude.exe"' >> ~/.bashrc -source ~/.bashrc -``` - -**Lưu ý**: Khoảng trắng trong đường dẫn Windows hoạt động đúng từ WSL khi được quote đúng cách. - -### Debug Phát Hiện - -Để xem CCS đã kiểm tra gì: - -```bash -# Tạm thời di chuyển claude ra khỏi PATH để kiểm tra -# Sau đó chạy ccs - thông báo lỗi sẽ hiển thị những gì đã được kiểm tra - -ccs --version -# Sẽ hiển thị: -# - CCS_CLAUDE_PATH: (status) -# - System PATH: not found -# - Common locations: not found -``` - -### Phương Án Thay Thế: Thêm Vào PATH - -Nếu bạn không muốn dùng CCS_CLAUDE_PATH, thêm thư mục Claude vào PATH: - -*Windows (PowerShell)*: -```powershell -# Thêm D:\Program Files\Claude vào PATH -$ClaudeDir = "D:\Program Files\Claude" -$env:Path += ";$ClaudeDir" -[Environment]::SetEnvironmentVariable("Path", $env:Path, "User") - -# Khởi động lại terminal -``` - -*Unix (bash)*: -```bash -# Thêm /opt/claude/bin vào PATH -echo 'export PATH="/opt/claude/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc -``` - -**Lưu ý**: CCS_CLAUDE_PATH có ưu tiên cao hơn PATH, cho phép ghi đè cho từng dự án. - -## Vấn Đề Cài Đặt - -### Lỗi BASH_SOURCE unbound variable - -Lỗi này xảy ra khi chạy installer trong một số shells hoặc môi trường. - -**Đã sửa trong phiên bản mới nhất**: Installer bây giờ xử lý cả thực thi qua pipe (`curl | bash`) và thực thi trực tiếp (`./install.sh`). - -**Giải pháp**: Nâng cấp lên phiên bản mới nhất: -```bash -curl -fsSL https://raw.githubusercontent.com/kaitranntt/ccs/main/installers/install.sh | bash -``` - -### Git worktree không được phát hiện - -Nếu cài từ git worktree hoặc submodule, các phiên bản cũ có thể không phát hiện repository git. - -**Đã sửa trong phiên bản mới nhất**: Installer bây giờ phát hiện cả thư mục `.git` (clone chuẩn) và file `.git` (worktree/submodule). - -**Giải pháp**: Nâng cấp lên phiên bản mới nhất hoặc dùng phương pháp cài đặt curl. - -## Vấn Đề Cấu Hình - -### Không tìm thấy profile - -``` -Error: Profile 'foo' not found in ~/.ccs/config.json -``` - -**Fix**: Thêm profile vào `~/.ccs/config.json`: -```json -{ - "profiles": { - "foo": "~/.ccs/foo.settings.json" - } -} -``` - -### Thiếu file settings - -``` -Error: Settings file not found: ~/.ccs/foo.settings.json -``` - -**Fix**: Tạo file settings hoặc sửa đường dẫn trong config. - -### jq chưa được cài đặt - -``` -Error: jq is required but not installed -``` - -**Fix**: Cài đặt jq (xem hướng dẫn cài đặt). - -**Lưu ý**: Installer tạo các mẫu cơ bản ngay cả khi không có jq, nhưng các tính năng nâng cao cần jq. - -## Vấn Đề Cấu Hình PATH - -### Cấu Hình PATH Tự Động - -v2.2.0+ tự động cấu hình shell PATH. Nếu bạn thấy hướng dẫn reload sau khi cài, hãy làm theo: - -**Cho bash**: -```bash -source ~/.bashrc -``` - -**Cho zsh**: -```bash -source ~/.zshrc -``` - -**Cho fish**: -```fish -source ~/.config/fish/config.fish -``` - -**Hoặc mở cửa sổ terminal mới** (PATH tự động load). - -### PATH Chưa Được Cấu Hình - -Nếu lệnh `ccs` không tìm thấy sau khi cài và reload: - -**Xác minh PATH entry tồn tại**: -```bash -# Cho bash/zsh -grep "\.local/bin" ~/.bashrc ~/.zshrc - -# Cho fish -grep "\.local/bin" ~/.config/fish/config.fish -``` - -**Sửa thủ công** (nếu auto-config thất bại): - -Bash: -```bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc -source ~/.bashrc -``` - -Zsh: -```bash -echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc -source ~/.zshrc -``` - -Fish: -```fish -echo 'set -gx PATH $HOME/.local/bin $PATH' >> ~/.config/fish/config.fish -source ~/.config/fish/config.fish -``` - -### Shell Profile Sai - -Nếu auto-config thêm vào file sai: - -**Tìm profile đang active**: -```bash -echo $SHELL # Hiển thị shell hiện tại -``` - -**Tình huống phổ biến**: -- macOS bash dùng `~/.bash_profile` (không phải `~/.bashrc`) -- Shell tùy chỉnh cần config thủ công -- Tmux/screen có thể dùng shell khác - -**Giải pháp**: Thêm PATH thủ công vào file profile đúng. - -### Shell Không Được Phát Hiện - -Nếu installer không thể phát hiện shell: - -**Triệu chứng**: -- Không có cảnh báo PATH hiển thị -- Lệnh `ccs` không tìm thấy sau khi cài - -**Giải pháp**: Thiết lập PATH thủ công (xem ở trên). - -### Thiếu profile mặc định - -``` -Error: Profile 'default' not found in ~/.ccs/config.json -``` - -**Fix**: Thêm profile "default" hoặc luôn chỉ định tên profile: -```json -{ - "profiles": { - "default": "~/.claude/settings.json" - } -} -``` - -## Vấn Đề Phổ Biến - -### Claude CLI không tìm thấy - -``` -Error: claude command not found -``` - -**Giải pháp**: Cài đặt Claude CLI từ [tài liệu chính thức](https://docs.claude.com/en/docs/claude-code/installation). - -### Permission denied (Unix) - -``` -Error: Permission denied: ~/.local/bin/ccs -``` - -**Giải pháp**: Cho phép script thực thi: -```bash -chmod +x ~/.local/bin/ccs -``` - -### Không tìm thấy file config - -``` -Error: Config file not found: ~/.ccs/config.json -``` - -**Giải pháp**: Chạy lại installer hoặc tạo config thủ công: -```bash -mkdir -p ~/.ccs -echo '{"profiles":{"default":"~/.claude/settings.json"}}' > ~/.ccs/config.json -``` - -## Nhận Trợ Giúp - -Nếu bạn gặp các vấn đề không được đề cập ở đây: - -1. Kiểm tra [GitHub Issues](https://github.com/kaitranntt/ccs/issues) -2. Tạo issue mới với: - - Hệ điều hành của bạn - - Phiên bản CCS (`ccs --version`) - - Thông báo lỗi chính xác - - Các bước để tái tạo vấn đề - -## Chế Độ Debug - -Bật verbose output để khắc phục sự cố: - -```bash -ccs --verbose glm -``` - -Điều này sẽ hiển thị: -- File config nào đang được đọc -- Profile nào đang được chọn -- File settings nào đang được sử dụng -- Lệnh chính xác đang được thực thi - -## Tắt Output Có Màu - -Nếu output có màu gây vấn đề trong terminal hoặc logs của bạn: - -```bash -export NO_COLOR=1 -ccs glm -``` - -**Trường Hợp Sử Dụng**: -- Môi trường CI/CD -- Tạo log file -- Terminal không hỗ trợ màu -- Tùy chọn trợ năng \ No newline at end of file diff --git a/docs/vi/usage.vi.md b/docs/vi/usage.vi.md deleted file mode 100644 index 7f6f2495..00000000 --- a/docs/vi/usage.vi.md +++ /dev/null @@ -1,231 +0,0 @@ -# Hướng Dẫn Sử Dụng CCS - -## Tại Sao Dùng CCS? - -**Được xây dựng cho lập trình viên có cả Claude subscription và GLM Coding Plan.** - -### Hai Tình Huống Thực Tế - -#### 1. Chọn Model Phù Hợp Với Tác Vụ - -**Claude Sonnet 4.5** xuất sắc trong: -- Quyết định kiến trúc phức tạp -- Thiết kế hệ thống và lập kế hoạch -- Gỡ lỗi các vấn đề khó -- Review code cần suy luận sâu - -**GLM 4.6** hoạt động tốt cho: -- Sửa lỗi đơn giản -- Triển khai thẳng thắn -- Refactoring hàng ngày -- Viết tài liệu - -**Với CCS**: Chuyển model dựa trên độ phức tạp của tác vụ, tối đa hóa chất lượng trong khi quản lý chi phí. - -```bash -ccs # Lên kế hoạch kiến trúc tính năng mới -# Đã có kế hoạch? Triển khai với GLM: -ccs glm # Viết code đơn giản -``` - -#### 2. Quản Lý Rate Limit - -Nếu bạn có cả Claude subscription và GLM Coding Plan, bạn biết sự khó khăn: -- Claude hết rate limit giữa chừng dự án -- Bạn phải copy thủ công config GLM vào `~/.claude/settings.json` -- 5 phút sau, cần chuyển lại -- Lặp lại 10 lần mỗi ngày - -**CCS giải quyết điều này**: -- Một lệnh để chuyển: `ccs` (mặc định) hoặc `ccs glm` (fallback) -- Lưu cả hai config dạng profiles -- Chuyển trong <1 giây -- Không phải sửa file, không copy-paste, không sai sót - -### Tính Năng - -- Chuyển profile tức thì (Claude ↔ GLM) -- Chuyển tất cả args của Claude CLI -- Cài đặt thông minh: phát hiện provider hiện tại của bạn -- Tự động tạo configs khi cài đặt -- Không proxy, không magic—chỉ bash + jq - -## Sử Dụng Cơ Bản - -### Chuyển Profiles - -```bash -# Hoạt động trên macOS, Linux, và Windows -ccs # Dùng Claude subscription (mặc định) -ccs glm # Dùng GLM fallback -``` - -**Lưu ý Windows**: Lệnh hoạt động giống nhau trong PowerShell, CMD, và Git Bash. - -### Với Arguments - -Tất cả args sau tên profile được chuyển trực tiếp cho Claude CLI: - -```bash -ccs glm --verbose -ccs /plan "add feature" -ccs glm /code "implement feature" -``` - -### Lệnh Tiện Ích - -```bash -ccs --version # Hiển thị thông tin phiên bản nâng cao với chi tiết cài đặt -ccs --help # Hiển thị tài liệu trợ giúp riêng của CCS -``` - -**Ví Dụ Output `--version`**: -``` -CCS (Claude Code Switch) v2.4.4 - -Installation: - Location: /home/user/.local/bin/ccs -> /home/user/.ccs/ccs - Config: ~/.ccs/config.json - -Documentation: https://github.com/kaitranntt/ccs -License: MIT - -Run 'ccs --help' for usage information -``` - -**Tính Năng Nâng Cứa `--help`**: -- Tài liệu riêng của CCS (không còn delegate cho Claude CLI) -- Ví dụ sử dụng và mô tả flag đầy đủ -- Hướng dẫn cài đặt và gỡ bỏ -- Hướng dẫn cụ thể theo nền tảng -- Vị trí file cấu hình và khắc phục sự cố - -**Gỡ Cài Đặt Chính Thức (Khuyến Nghị)**: -```bash -# macOS/Linux -curl -fsSL ccs.kaitran.ca/uninstall | bash - -# Windows PowerShell -irm ccs.kaitran.ca/uninstall | iex -``` - -Uninstaller chính thức gỡ bỏ hoàn toàn CCS bao gồm cả cấu hình và PATH modifications. - -### Cài Đặt Commands và Skills - -### 🚧 Tính Năng Đang Phát Triển - -#### Tích hợp .claude/ - -Delegation tác vụ qua flags `--install` / `--uninstall` đang được phát triển. - -**Trạng Thái**: Testing chưa hoàn tất, không có sẵn trong release hiện tại - -**Implementation**: Chức năng cốt lõi đã có nhưng bị vô hiệu hóa pending testing - -**Timeline**: Chưa có ETA - theo dõi GitHub issues để cập nhật - -**Hiện Tại**: Sử dụng chuyển profile trực tiếp (`ccs glm`) để lựa chọn model - -**Ví Dụ Output**: -``` -┌─ Installing CCS Commands & Skills -│ Source: /path/to/ccs/.claude -│ Target: /home/user/.claude -│ -│ Installing commands... -│ │ [OK] Installed command: ccs.md -│ -│ Installing skills... -│ │ [OK] Installed skill: ccs-delegation -└─ - -[OK] Installation complete! - Installed: 2 items - Skipped: 0 items (already exist) - -You can now use the /ccs command in Claude CLI for task delegation. -Example: /ccs glm /plan 'add user authentication' -``` - -**Lưu ý**: -- Output dùng ký hiệu ASCII ([OK], [i], [X]) thay vì emoji -- Output có màu trên terminal TTY (tắt với `NO_COLOR=1`) -- File đã tồn tại tự động bỏ qua (an toàn khi chạy lại) - -## Delegation Tác Vụ - -**CCS bao gồm delegation tác vụ thông minh** qua meta-command `/ccs`: - -```bash -# Delegation lập kế hoạch cho GLM (tiết kiệm tokens Sonnet) -/ccs glm /plan "add user authentication" - -# Delegation coding cho GLM -/ccs glm /code "implement auth endpoints" - -# Câu hỏi nhanh với Haiku -/ccs haiku /ask "explain this error" -``` - -**Lợi ích**: -- ✅ Tiết kiệm tokens bằng cách delegation tác vụ đơn giản cho model rẻ hơn -- ✅ Dùng đúng model cho từng tác vụ tự động -- ✅ Lệnh có thể tái sử dụng trên tất cả dự án (user-scope) -- ✅ Tích hợp liền mạch với workflows hiện có - -## Workflow Thực Tế - -### Chọn Model Dựa Trên Tác Vụ - -**Tình huống**: Xây dựng tính năng tích hợp thanh toán mới - -```bash -# Bước 1: Kiến trúc & Lập kế hoạch (cần trí tuệ của Claude) -ccs -/plan "Design payment integration with Stripe, handle webhooks, errors, retries" -# → Claude Sonnet 4.5 suy nghĩ sâu về edge cases, bảo mật, kiến trúc - -# Bước 2: Triển khai (coding đơn giản, dùng GLM) -ccs glm -/code "implement the payment webhook handler from the plan" -# → GLM 4.6 viết code hiệu quả, tiết kiệm usage của Claude - -# Bước 3: Code Review (cần phân tích sâu) -ccs -/review "check the payment handler for security issues" -# → Claude Sonnet 4.5 phát hiện các lỗ hổng tinh vi - -# Bước 4: Sửa Lỗi (đơn giản) -ccs glm -/fix "update error message formatting" -# → GLM 4.6 xử lý các sửa lỗi hàng ngày -``` - -**Kết quả**: Model tốt nhất cho từng tác vụ, chi phí thấp hơn, chất lượng tốt hơn. - -### Quản Lý Rate Limit - -```bash -# Làm việc với refactoring phức tạp bằng Claude -ccs -/plan "refactor authentication system" - -# Claude hết rate limit giữa chừng tác vụ -# → Error: Rate limit exceeded - -# Chuyển sang GLM ngay lập tức -ccs glm -# Tiếp tục làm việc không gián đoạn - -# Rate limit reset? Chuyển lại -ccs -``` - -## Cách Hoạt Động - -1. Đọc tên profile (mặc định là "default" nếu bỏ qua) -2. Tìm đường dẫn file settings trong `~/.ccs/config.json` -3. Thực thi `claude --settings [remaining-args]` - -Không có magic. Không sửa file. Chuyển giao thuần túy. Hoạt động giống nhau trên tất cả nền tảng. \ No newline at end of file diff --git a/package.json b/package.json index 51a66bb8..c7c23092 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kaitranntt/ccs", - "version": "5.17.0", + "version": "5.17.0-dev.7", "description": "Claude Code Switch - Instant profile switching between Claude Sonnet 4.5 and GLM 4.6", "keywords": [ "cli", diff --git a/src/commands/version-command.ts b/src/commands/version-command.ts index 5c4ab2a0..f9cde90a 100644 --- a/src/commands/version-command.ts +++ b/src/commands/version-command.ts @@ -77,9 +77,7 @@ export async function handleVersionCommand(): Promise { console.log(''); } - console.log( - `${subheader('Documentation:')} ${color('https://github.com/kaitranntt/ccs', 'path')}` - ); + console.log(`${subheader('Documentation:')} ${color('https://docs.ccs.kaitran.ca', 'path')}`); console.log(`${subheader('License:')} MIT`); console.log(''); console.log(color("Run 'ccs --help' for usage information", 'command')); diff --git a/src/web-server/usage-routes.ts b/src/web-server/usage-routes.ts index c6835a90..2f255b62 100644 --- a/src/web-server/usage-routes.ts +++ b/src/web-server/usage-routes.ts @@ -640,10 +640,11 @@ function validateOffset(offset?: string): number { * Filter data by date range */ function filterByDateRange( - data: T[], + data: T[] | undefined, since?: string, until?: string ): T[] { + if (!data || !Array.isArray(data)) return []; if (!since && !until) return data; return data.filter((item) => { @@ -824,6 +825,7 @@ usageRoutes.get( * * Returns hourly usage trends for chart visualization. * Query: ?since=YYYYMMDD&until=YYYYMMDD (defaults to last 24 hours) + * Fills in gaps with zero values for hours without activity. */ usageRoutes.get( '/hourly', @@ -834,8 +836,8 @@ usageRoutes.get( const hourlyData = await getCachedHourlyData(); - // Filter by date range - const filtered = hourlyData.filter((h) => { + // Filter by date range (guard against undefined) + const filtered = (hourlyData || []).filter((h) => { // Extract date from hour format "YYYY-MM-DD HH:00" const hourDate = h.hour.slice(0, 10).replace(/-/g, ''); if (since && hourDate < since) return false; @@ -855,12 +857,12 @@ usageRoutes.get( requests: hour.modelBreakdowns.length, })); - // Sort by hour ascending for chart display - trends.sort((a, b) => a.hour.localeCompare(b.hour)); + // Fill gaps with zero values for hours without activity + const filledTrends = fillHourlyGaps(trends, since, until); res.json({ success: true, - data: trends, + data: filledTrends, }); } catch (error) { errorResponse(res, error, 'Failed to fetch hourly usage'); @@ -868,6 +870,103 @@ usageRoutes.get( } ); +/** + * Fill gaps in hourly data with zero values + * Ensures continuous timeline for chart display + */ +function fillHourlyGaps( + data: Array<{ + hour: string; + tokens: number; + inputTokens: number; + outputTokens: number; + cacheTokens: number; + cost: number; + modelsUsed: number; + requests: number; + }>, + since?: string, + until?: string +): typeof data { + // If no date range specified, return as-is + if (!since && !until) { + return data.sort((a, b) => a.hour.localeCompare(b.hour)); + } + + // Create a map of existing hours for O(1) lookup + const hourMap = new Map(data.map((d) => [d.hour, d])); + + // Determine the hour range (use UTC to match stored hour keys) + const now = new Date(); + const startDate = since + ? new Date( + Date.UTC( + parseInt(since.slice(0, 4)), + parseInt(since.slice(4, 6)) - 1, + parseInt(since.slice(6, 8)), + 0, + 0, + 0 + ) + ) + : new Date(now.getTime() - 24 * 60 * 60 * 1000); // Default: 24 hours ago + + const endDate = until + ? new Date( + Date.UTC( + parseInt(until.slice(0, 4)), + parseInt(until.slice(4, 6)) - 1, + parseInt(until.slice(6, 8)), + 23, + 59, + 59 + ) + ) + : now; + + // Cap endDate at current time to avoid filling future hours with zeros + const cappedEndDate = endDate > now ? now : endDate; + + const result: typeof data = []; + + // Iterate through each hour in the range + const current = new Date(startDate); + current.setMinutes(0, 0, 0); + + while (current <= cappedEndDate) { + // Format hour key as "YYYY-MM-DD HH:00" in UTC to match storage format + const year = current.getUTCFullYear(); + const month = String(current.getUTCMonth() + 1).padStart(2, '0'); + const day = String(current.getUTCDate()).padStart(2, '0'); + const hour = String(current.getUTCHours()).padStart(2, '0'); + const hourKey = `${year}-${month}-${day} ${hour}:00`; + + if (hourMap.has(hourKey)) { + const entry = hourMap.get(hourKey); + if (entry) { + result.push(entry); + } + } else { + // Insert zero entry for this hour + result.push({ + hour: hourKey, + tokens: 0, + inputTokens: 0, + outputTokens: 0, + cacheTokens: 0, + cost: 0, + modelsUsed: 0, + requests: 0, + }); + } + + // Move to next hour + current.setTime(current.getTime() + 60 * 60 * 1000); + } + + return result; +} + /** * GET /api/usage/models *