docs: migrate to Mintlify docs submodule

- Add kaitranntt/ccs-docs as git submodule under docs/
- Update README links to point to docs.ccs.kaitran.ca
- Remove old local docs (migrated to Mintlify MDX format)

Phase 3 of README restructure complete.
This commit is contained in:
kaitranntt
2025-12-13 00:49:21 -05:00
parent 80676cb4fa
commit 8d46317cf6
31 changed files with 13 additions and 9666 deletions
+3
View File
@@ -0,0 +1,3 @@
[submodule "docs"]
path = docs
url = git@github.com:kaitranntt/ccs-docs.git
+9 -9
View File
@@ -11,7 +11,7 @@ Run Claude, Gemini, GLM, and more - concurrently, without conflicts.
[![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)
**[Features & Pricing](https://ccs.kaitran.ca)** | **[Documentation](./docs/en/)** | [Tiếng Việt](docs/vi/README.md) | [日本語](docs/ja/README.md)
**[Features & Pricing](https://ccs.kaitran.ca)** | **[Documentation](https://docs.ccs.kaitran.ca)**
</div>
@@ -196,14 +196,14 @@ Without Developer Mode, CCS falls back to copying directories.
| Topic | Link |
|-------|------|
| Installation | [docs/en/installation.md](./docs/en/installation.md) |
| Configuration | [docs/en/configuration.md](./docs/en/configuration.md) |
| OAuth Providers | [docs/en/oauth.md](./docs/en/oauth.md) |
| Multi-Account Claude | [docs/en/multi-account.md](./docs/en/multi-account.md) |
| Delegation | [docs/en/delegation.md](./docs/en/delegation.md) |
| GLMT (Experimental) | [docs/en/glmt.md](./docs/en/glmt.md) |
| Architecture | [docs/system-architecture.md](./docs/system-architecture.md) |
| Troubleshooting | [docs/en/troubleshooting.md](./docs/en/troubleshooting.md) |
| 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) |
<br>
Submodule
+1
Submodule docs added at f894f253d3
Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

-492
View File
@@ -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`
File diff suppressed because it is too large Load Diff
-307
View File
@@ -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 <version>`. 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.
-417
View File
@@ -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/<profile>/.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 <profile-name>
```
### "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)
-172
View File
@@ -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 <file> [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"
}
}
```
-240
View File
@@ -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
-593
View File
@@ -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\<Username>\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"
```
-365
View File
@@ -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 <path> [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
-332
View File
@@ -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>
```
---
## 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 <name>
# Use existing profile
ccs <profile> "your prompt"
```
---
### E105: Profile Already Exists
**Cause**: Attempting to create profile that already exists
**Solutions**:
```bash
# Use different name
ccs auth create <different-name>
# Or overwrite existing (use with caution)
ccs auth create <name> --force
```
---
### E106: Cannot Delete Default Profile
**Cause**: Attempting to remove currently active default profile
**Solutions**:
```bash
# Set different default first
ccs auth default <other-profile>
# Then remove old default
ccs auth remove <old-profile>
```
---
### 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 <file-path-from-error>
# Fix permissions
chmod 644 <file-path>
# Recreate if missing
ccs auth create <profile>
```
---
### E504: Instance Directory Not Found
**Cause**: Profile instance directory missing
**Solutions**:
```bash
# Recreate profile
ccs auth remove <profile>
ccs auth create <profile>
```
---
## Internal Errors
### E900: Internal Error
**Cause**: Unexpected error in CCS code
**Solutions**:
```bash
# Report bug with debug output
export CCS_DEBUG=1
ccs <your-command> 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`
-328
View File
@@ -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)
- `<Thinking:On|Off>` - Enable/disable reasoning blocks (default: On)
- `<Effort:Low|Medium|High>` - 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 "<Thinking:On> 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**: `<Thinking:On|Off>` 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
-175
View File
@@ -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
-253
View File
@@ -1,253 +0,0 @@
<div align="center">
# CCS - Claude Code Switch
![CCS Logo](../assets/ccs-logo-medium.png)
### 1つのダッシュボードで複数のAIアカウントを管理。
Claude、Gemini、GLM、その他を同時に実行 - 競合なしで。
[![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](../../LICENSE)
[![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)
**[機能 & 料金](https://ccs.kaitran.ca)** | **[ドキュメント](../en/)** | [English](../../README.md) | [Tiếng Việt](../vi/README.md)
</div>
<br>
## 3つの柱
| 機能 | 説明 | 管理方法 |
|------|------|----------|
| **複数Claudeアカウント** | 仕事用 + 個人用のClaudeを同時実行 | ダッシュボード |
| **OAuthプロバイダー** | Gemini、Codex、Antigravity - APIキー不要 | ダッシュボード |
| **APIプロファイル** | 自分のAPIキーでGLM、Kimiを利用 | ダッシュボード |
<br>
## クイックスタート
### 1. インストール
```bash
npm install -g @kaitranntt/ccs
```
<details>
<summary>他のパッケージマネージャー</summary>
```bash
yarn global add @kaitranntt/ccs # yarn
pnpm add -g @kaitranntt/ccs # pnpm (70%ディスク節約)
bun add -g @kaitranntt/ccs # bun (30倍高速)
```
</details>
### 2. ダッシュボードを開く
```bash
ccs config
# http://localhost:3000 を開きます
```
### 3. アカウントを設定
ダッシュボードはすべてのアカウントタイプをビジュアルに管理できます:
- **Claudeアカウント**: 分離されたインスタンスを作成(仕事、個人、クライアント)
- **OAuthプロバイダー**: Gemini、Codex、Antigravityのワンクリック認証
- **APIプロファイル**: 自分のキーでGLM、Kimiを設定
- **ヘルスモニター**: すべてのプロファイルのリアルタイムステータス
**アナリティクス (ライト/ダークテーマ)**
![Analytics Light](../assets/screenshots/analytics-light.png)
![Analytics Dark](../assets/screenshots/analytics.png)
**APIプロファイル & OAuthプロバイダー**
![API Profiles](../assets/screenshots/api_profiles.png)
![CLIProxy](../assets/screenshots/cliproxy.png)
<br>
## サポートされているプロバイダー
| プロバイダー | 認証タイプ | コマンド | 最適な用途 |
|--------------|------------|----------|------------|
| **Claude** | サブスクリプション | `ccs` | デフォルト、戦略的計画 |
| **Gemini** | OAuth | `ccs gemini` | ゼロ設定、高速イテレーション |
| **Codex** | OAuth | `ccs codex` | コード生成 |
| **Antigravity** | OAuth | `ccs agy` | 代替ルーティング |
| **GLM** | APIキー | `ccs glm` | コスト最適化 |
| **Kimi** | APIキー | `ccs kimi` | ロングコンテキスト、思考モード |
> **OAuthプロバイダー**は初回実行時にブラウザで認証します。トークンは `~/.ccs/cliproxy/auth/` にキャッシュされます。
<br>
## 使用方法
### 基本コマンド
```bash
ccs # デフォルトのClaudeセッション
ccs agy # Antigravity (OAuth)
ccs gemini # Gemini (OAuth)
ccs glm # GLM (APIキー)
```
### 並列ワークフロー
異なるプロバイダーで複数のターミナルを実行:
```bash
# ターミナル1: 計画 (Claude Pro)
ccs work "認証システムを設計"
# ターミナル2: 実行 (GLM - コスト最適化)
ccs glm "計画に基づいてユーザーサービスを実装"
# ターミナル3: レビュー (Gemini)
ccs gemini "セキュリティ問題について実装をレビュー"
```
### マルチアカウントClaude
仕事/個人用に分離されたClaudeインスタンスを作成:
```bash
ccs auth create work
# 別々のターミナルで同時実行
ccs work "機能を実装" # ターミナル1
ccs "コードをレビュー" # ターミナル2 (個人アカウント)
```
<br>
## メンテナンス
### ヘルスチェック
```bash
ccs doctor
```
検証: Claude CLI、設定ファイル、シンボリックリンク、パーミッション。
### アップデート
```bash
ccs update # 最新版にアップデート
ccs update --force # 強制再インストール
ccs update --beta # devチャンネルをインストール
```
### 共有アイテムの同期
```bash
ccs sync
```
共有コマンド、スキル、設定のシンボリックリンクを再作成します。
<br>
## 設定
CCSはインストール時に自動的に設定を作成します。ダッシュボードが設定管理の推奨方法です。
**設定の場所**: `~/.ccs/config.yaml`
<details>
<summary>カスタムClaude CLIパス</summary>
Claude CLIが標準以外の場所にインストールされている場合:
```bash
export CCS_CLAUDE_PATH="/path/to/claude" # Unix
$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe" # Windows
```
</details>
<details>
<summary>Windowsシンボリックリンクサポート</summary>
真のシンボリックリンクには開発者モードを有効にしてください:
1. **設定****プライバシーとセキュリティ****開発者向け**
2. **開発者モード**を有効化
3. 再インストール: `npm install -g @kaitranntt/ccs`
開発者モードがない場合、CCSはディレクトリコピーにフォールバックします。
</details>
<br>
## ドキュメント
| トピック | リンク |
|----------|--------|
| インストール | [docs/en/installation.md](../en/installation.md) |
| 設定 | [docs/en/configuration.md](../en/configuration.md) |
| OAuthプロバイダー | [docs/en/oauth.md](../en/oauth.md) |
| マルチアカウントClaude | [docs/en/multi-account.md](../en/multi-account.md) |
| デリゲーション | [docs/en/delegation.md](../en/delegation.md) |
| GLMT (実験的) | [docs/en/glmt.md](../en/glmt.md) |
| アーキテクチャ | [docs/system-architecture.md](../system-architecture.md) |
| トラブルシューティング | [docs/en/troubleshooting.md](../en/troubleshooting.md) |
<br>
## アンインストール
```bash
npm uninstall -g @kaitranntt/ccs
```
<details>
<summary>他のパッケージマネージャー</summary>
```bash
yarn global remove @kaitranntt/ccs
pnpm remove -g @kaitranntt/ccs
bun remove -g @kaitranntt/ccs
```
</details>
<br>
## 哲学
- **YAGNI**: 「念のため」の機能なし
- **KISS**: シンプルで焦点を絞った実装
- **DRY**: 単一の信頼できる情報源(設定)
<br>
## コントリビューション
[CONTRIBUTING.md](../../CONTRIBUTING.md)をご覧ください。
<br>
## ライセンス
MITライセンス - [LICENSE](../../LICENSE)をご覧ください。
<div align="center">
---
**[ccs.kaitran.ca](https://ccs.kaitran.ca)** | [問題を報告](https://github.com/kaitranntt/ccs/issues) | [GitHubでスター](https://github.com/kaitranntt/ccs)
</div>
-468
View File
@@ -1,468 +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
### 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)
### 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
### 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.
-827
View File
@@ -1,827 +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.
---
#### 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-09 (Analytics UI Enhancements)
**Next Update**: v4.6.0 UI Enhancements Planning
**Maintainer**: CCS Development Team
-239
View File
@@ -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/
│ └── <project-hash>/
│ └── <sessionId>.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":"<uuid>","message":{"role":"user","content":"..."},"uuid":"<msg-id>","timestamp":"..."}
{"type":"assistant","sessionId":"<uuid>","message":{"role":"assistant","content":[...]},"requestId":"req_...","uuid":"<msg-id>","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 <sessionId>`
2. CLI reads `~/.claude/projects/<project>/<sessionId>.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/<project>/<sessionId>.jsonl`
2. Generate new UUID: `new_id=$(uuidgen | tr '[:upper:]' '[:lower:]')`
3. Replace `sessionId` in JSONL: `sed 's/<old_id>/<new_id>/g' file.jsonl > new.jsonl`
4. Place in personal profile: `~/.ccs/instances/personal/.claude/projects/<project>/<new_id>.jsonl`
5. Resume: `ccs personal``claude --resume <new_id>`
**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 <id> --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 <new_id>`
**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.
File diff suppressed because it is too large Load Diff
-172
View File
@@ -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
```
<type>(<scope>): <description>
[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
```
-253
View File
@@ -1,253 +0,0 @@
<div align="center">
# CCS - Claude Code Switch
![CCS Logo](../assets/ccs-logo-medium.png)
### Quản lý nhiều tài khoản AI từ một dashboard.
Chạy Claude, Gemini, GLM, và nhiều hơn nữa - đồng thời, không xung đột.
[![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](../../LICENSE)
[![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)
**[Tính năng & Bảng giá](https://ccs.kaitran.ca)** | **[Tài liệu](../en/)** | [English](../../README.md) | [日本語](../ja/README.md)
</div>
<br>
## Ba Trụ Cột
| Khả năng | Chức năng | Quản lý qua |
|----------|-----------|-------------|
| **Nhiều Tài khoản Claude** | Chạy Claude công việc + cá nhân đồng thời | Dashboard |
| **Nhà cung cấp OAuth** | Gemini, Codex, Antigravity - không cần API key | Dashboard |
| **Hồ sơ API** | GLM, Kimi với API key của bạn | Dashboard |
<br>
## Bắt Đầu Nhanh
### 1. Cài Đặt
```bash
npm install -g @kaitranntt/ccs
```
<details>
<summary>Trình quản lý package khác</summary>
```bash
yarn global add @kaitranntt/ccs # yarn
pnpm add -g @kaitranntt/ccs # pnpm (tiết kiệm 70% dung lượng)
bun add -g @kaitranntt/ccs # bun (nhanh hơn 30x)
```
</details>
### 2. Mở Dashboard
```bash
ccs config
# Mở http://localhost:3000
```
### 3. Cấu Hình Tài Khoản
Dashboard cung cấp giao diện quản lý trực quan cho tất cả loại tài khoản:
- **Tài khoản Claude**: Tạo các instance riêng biệt (công việc, cá nhân, khách hàng)
- **Nhà cung cấp OAuth**: Xác thực một cú nhấp cho Gemini, Codex, Antigravity
- **Hồ sơ API**: Cấu hình GLM, Kimi với key của bạn
- **Giám sát Sức khỏe**: Trạng thái thời gian thực cho tất cả profile
**Analytics (Giao diện Sáng/Tối)**
![Analytics Light](../assets/screenshots/analytics-light.png)
![Analytics Dark](../assets/screenshots/analytics.png)
**API Profiles & Nhà cung cấp OAuth**
![API Profiles](../assets/screenshots/api_profiles.png)
![CLIProxy](../assets/screenshots/cliproxy.png)
<br>
## Nhà Cung Cấp Được Hỗ Trợ
| Nhà cung cấp | Loại xác thực | Lệnh | Phù hợp nhất cho |
|--------------|---------------|------|------------------|
| **Claude** | Subscription | `ccs` | Mặc định, lập kế hoạch chiến lược |
| **Gemini** | OAuth | `ccs gemini` | Zero-config, lặp nhanh |
| **Codex** | OAuth | `ccs codex` | Tạo code |
| **Antigravity** | OAuth | `ccs agy` | Routing thay thế |
| **GLM** | API Key | `ccs glm` | Tối ưu chi phí |
| **Kimi** | API Key | `ccs kimi` | Long-context, thinking mode |
> **Nhà cung cấp OAuth** xác thực qua trình duyệt khi chạy lần đầu. Token được lưu cache tại `~/.ccs/cliproxy/auth/`.
<br>
## Sử Dụng
### Lệnh Cơ Bản
```bash
ccs # Session Claude mặc định
ccs agy # Antigravity (OAuth)
ccs gemini # Gemini (OAuth)
ccs glm # GLM (API key)
```
### Luồng Công Việc Song Song
Chạy nhiều terminal với các provider khác nhau:
```bash
# Terminal 1: Lập kế hoạch (Claude Pro)
ccs work "thiết kế hệ thống xác thực"
# Terminal 2: Thực thi (GLM - tối ưu chi phí)
ccs glm "triển khai user service theo kế hoạch"
# Terminal 3: Review (Gemini)
ccs gemini "review implementation về các lỗ hổng bảo mật"
```
### Multi-Account Claude
Tạo các instance Claude riêng biệt cho công việc/cá nhân:
```bash
ccs auth create work
# Chạy đồng thời trong các terminal riêng
ccs work "implement feature" # Terminal 1
ccs "review code" # Terminal 2 (tài khoản cá nhân)
```
<br>
## Bảo Trì
### Kiểm Tra Sức Khỏe
```bash
ccs doctor
```
Xác minh: Claude CLI, file cấu hình, symlinks, permissions.
### Cập Nhật
```bash
ccs update # Cập nhật lên bản mới nhất
ccs update --force # Cài đặt lại bắt buộc
ccs update --beta # Cài đặt kênh dev
```
### Đồng Bộ Shared Items
```bash
ccs sync
```
Tạo lại symlinks cho commands, skills, và settings được chia sẻ.
<br>
## Cấu Hình
CCS tự động tạo config khi cài đặt. Dashboard là cách được khuyến nghị để quản lý settings.
**Vị trí config**: `~/.ccs/config.yaml`
<details>
<summary>Custom Claude CLI path</summary>
Nếu Claude CLI được cài đặt ở vị trí không chuẩn:
```bash
export CCS_CLAUDE_PATH="/path/to/claude" # Unix
$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe" # Windows
```
</details>
<details>
<summary>Hỗ trợ symlink Windows</summary>
Bật Developer Mode để có symlinks thực sự:
1. **Settings****Privacy & Security** → **For developers**
2. Bật **Developer Mode**
3. Cài đặt lại: `npm install -g @kaitranntt/ccs`
Không có Developer Mode, CCS sẽ fallback sang copy thư mục.
</details>
<br>
## Tài Liệu
| Chủ đề | Liên kết |
|--------|----------|
| Cài đặt | [docs/en/installation.md](../en/installation.md) |
| Cấu hình | [docs/en/configuration.md](../en/configuration.md) |
| Nhà cung cấp OAuth | [docs/en/oauth.md](../en/oauth.md) |
| Multi-Account Claude | [docs/en/multi-account.md](../en/multi-account.md) |
| Delegation | [docs/en/delegation.md](../en/delegation.md) |
| GLMT (Thử nghiệm) | [docs/en/glmt.md](../en/glmt.md) |
| Kiến trúc | [docs/system-architecture.md](../system-architecture.md) |
| Xử lý sự cố | [docs/en/troubleshooting.md](../en/troubleshooting.md) |
<br>
## Gỡ Cài Đặt
```bash
npm uninstall -g @kaitranntt/ccs
```
<details>
<summary>Trình quản lý package khác</summary>
```bash
yarn global remove @kaitranntt/ccs
pnpm remove -g @kaitranntt/ccs
bun remove -g @kaitranntt/ccs
```
</details>
<br>
## Triết Lý
- **YAGNI**: Không có tính năng "phòng hờ"
- **KISS**: Triển khai đơn giản, tập trung
- **DRY**: Một nguồn sự thật (config)
<br>
## Đóng Góp
Xem [CONTRIBUTING.md](../../CONTRIBUTING.md).
<br>
## Giấy Phép
MIT License - xem [LICENSE](../../LICENSE).
<div align="center">
---
**[ccs.kaitran.ca](https://ccs.kaitran.ca)** | [Báo cáo lỗi](https://github.com/kaitranntt/ccs/issues) | [Star trên GitHub](https://github.com/kaitranntt/ccs)
</div>
-164
View File
@@ -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 <file> [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"
}
}
```
-237
View File
@@ -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``~/.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
-468
View File
@@ -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\<Username>\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
-231
View File
@@ -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 <path> [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.