Merge origin/dev into kai/feat/improve-config-home

Resolves conflicts:
- Accept dev branch structure (docs moved to external submodule)
- Keep README with extensibility messaging updates:
  - Universal profile manager tagline
  - Built-in Providers section (renamed from Supported Providers)
  - API Profiles pillar emphasizes Anthropic-compatible APIs
  - Added tip about custom provider support
This commit is contained in:
kaitranntt
2025-12-13 02:54:23 -05:00
35 changed files with 228 additions and 11913 deletions
View File
+120 -977
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1 +1 @@
5.17.0
5.17.0-dev.7

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

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
-653
View File
@@ -1,653 +0,0 @@
<div align="center">
# CCS - Claude Code Switch
![CCS Logo](../../docs/assets/ccs-logo-medium.png)
### Claude Code用ユニバーサルAIプロファイルマネージャー
**複数のClaudeアカウント、任意のAnthropic互換API、OAuthプロバイダー(Gemini、Codex、Antigravity)を瞬時に切り替え。**
レート制限を回避し、無制限のプロファイルで継続的に作業。
<br>
[![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey?style=for-the-badge)]()
[![npm](https://img.shields.io/npm/v/@kaitranntt/ccs?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@kaitranntt/ccs)
[![PoweredBy](https://img.shields.io/badge/PoweredBy-ClaudeKit-C15F3C?style=for-the-badge)](https://claudekit.cc?ref=HMNKXOHN)
**Languages**: [English](../../README.md) · [Tiếng Việt](../vi/README.md) · [日本語](README.md)
</div>
<br>
## クイックスタート
### インストール
**npmパッケージ(推奨)**
**macOS / Linux / Windows**
```bash
npm install -g @kaitranntt/ccs
```
**主要なパッケージマネージャーすべてに対応:**
```bash
# yarn
yarn global add @kaitranntt/ccs
# pnpm(ディスク使用量70%削減)
pnpm add -g @kaitranntt/ccs
# bun30倍高速)
bun add -g @kaitranntt/ccs
```
<details>
<summary><strong>[!] 非推奨: ネイティブシェルインストーラー(レガシー)</strong></summary>
<br>
> [!WARNING]
> **これらのインストーラーは非推奨であり、将来のバージョンで削除されます。**
> 現在は npm インストールに自動リダイレクトされます。npm を直接使用してください。
**macOS / Linux**
```bash
curl -fsSL ccs.kaitran.ca/install | bash
```
**Windows PowerShell**
```powershell
irm ccs.kaitran.ca/install | iex
```
**注**: スクリプトは非推奨の警告を表示し、Node.jsが利用可能な場合は自動的にnpmインストールを実行します。
</details>
<br>
### 設定(自動作成)
**CCSはインストール時に自動的に設定を作成します**(npm postinstallスクリプト経由)。
**~/.ccs/config.json**:
```json
{
"profiles": {
"glm": "~/.ccs/glm.settings.json",
"glmt": "~/.ccs/glmt.settings.json",
"kimi": "~/.ccs/kimi.settings.json",
"default": "~/.claude/settings.json"
}
}
```
<details>
<summary><h3>カスタムClaude CLIパス</h3></summary>
<br>
Claude CLIが標準以外の場所(Dドライブ、カスタムディレクトリ)にインストールされている場合は、`CCS_CLAUDE_PATH`を設定してください:
```bash
# Unix/Linux/macOS
export CCS_CLAUDE_PATH="/path/to/claude"
# Windows PowerShell
$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe"
```
**参照**: [トラブルシューティングガイド](./docs/en/troubleshooting.md#claude-cli-in-non-standard-location) 詳細な設定手順
</details>
<details>
<summary><h3>Windowsシンボリックリンクサポート(開発者モード)</h3></summary>
<br>
**Windowsユーザー**: 本物のシンボリックリンクで高速な動作と即時同期を得るために開発者モードを有効にしてください:
1. **設定****プライバシーとセキュリティ****開発者向け** を開く
2. **開発者モード** を有効にする
3. CCSを再インストール: `npm install -g @kaitranntt/ccs`
**警告**: 開発者モードなしの場合、CCSは自動的にディレクトリコピーにフォールバック(動作しますが、プロファイル間の即時同期はありません)
</details>
<br>
### 最初の切り替え
> [!IMPORTANT]
> **代替モデルを使用する前に、設定ファイルでAPIキーを更新してください:**
>
> - **GLM**: `~/.ccs/glm.settings.json`を編集してZ.AI Coding Plan APIキーを追加
> - **GLMT**: `~/.ccs/glmt.settings.json`を編集してZ.AI Coding Plan APIキーを追加
> - **Kimi**: `~/.ccs/kimi.settings.json`を編集してKimi APIキーを追加
<br>
**並列ワークフロー:計画 + 実行**
```bash
# Terminal 1 - 計画(Claude Sonnet
ccs "認証とレート制限付きREST APIの計画"
# Terminal 2 - 実行(GLM、コスト最適化)
ccs glm "計画からユーザー認証エンドポイントを実装"
```
<details>
<summary><strong>思考モデル(Kimi & GLMT</strong></summary>
<br>
```bash
# Kimi - 安定した思考サポート
ccs kimi "トレードオフ分析付きキャッシュ戦略の設計"
# GLMT - 実験的(詳細は下記参照)
ccs glmt "推論ステップ付き複雑なアルゴリズムのデバッグ"
```
**注**: GLMTは実験的で不安定です。詳細については下記の[GLM with Thinking (GLMT)](#glm-with-thinking-glmt)セクションを参照してください。
</details>
<br>
## 開発者の日常的な課題
<div align="center">
### **切り替えを停止。調整を開始。**
**セッション制限がフロー状態を殺すべきではありません。**
</div>
実装に深く集中しています。コンテキストが読み込まれました。解決策が結晶化しています。<br>
その後: 🔴 _"使用制限に達しました。"_
**モチベーションが失われました。コンテキストが失われました。生産性が崩壊しました。**
## **解決策:並列ワークフロー**
<details>
<summary><strong>❌ 古い方法:</strong> 制限に達した時に切り替える(反応的)</summary>
### 現在のワークフロー:
- **14時:** 機能開発、ゾーン状態
- **15時:** 🔴 使用制限に達した
- **15:05:** 作業停止、`~/.claude/settings.json`を編集
- **15:15:** アカウント切り替え、コンテキストが失われる
- **15:30:** フロー状態に戻ろうと試みる
- **16時:** ついに生産性が回復
- **結果:** 1時間失われ、モチベーションが破壊され、不満が蓄積
</details>
<details open>
<summary><strong>✨ 新しい方法:</strong> 最初から並列で実行(主導的) - <strong>推奨</strong></summary>
### 新しいワークフロー:
- **14時:** **ターミナル1:** `ccs "APIアーキテクチャを計画"` → 戦略的思考(Claude Pro
- **14時:** **ターミナル2:** `ccs glm "エンドポイントを実装"` → コード実行(GLM
- **15時:** まだ開発継続、割れなし
- **16時:** フロー状態達成、生産性急上昇
- **17時:** 機能が完了、コンテキスト維持
- **結果:** ダウムタイムなし、継続的生産性、不満減少
### 💰 **価値提案:**
- **設定:** 既存のClaude Pro + GLM Lite(費用対効果の高い追加)
- **価値:** 1時間/日 × 20労働日 = 20時間/月を回収
- **ROI:** 開発時間は設定コスト以上の価値がある
- **現実:** オーバーヘッドより速く出荷
</details>
## あなたの道を選択
<details>
<summary><strong>予算重視:</strong> GLMのみ</summary>
- **最適:** 費用意識の高い開発、基本的なコード生成
- **使用法:** 費用効果の高いAI支援のために`ccs glm`を直接使用
- **現実:** Claudeアクセスなし、多くのコーディングタスクに対応可能
- **設定:** GLM APIキーのみ、非常に手頃
</details>
<details open>
<summary><strong>✨ 日々の開発に推奨:</strong> 1 Claude Pro + 1 GLM Lite</summary>
- **最適:** 日々のコードデリバリー、真剣な開発作業
- **使用法:** `ccs`で計画 + `ccs glm`で実行(並列ワークフロー)
- **現実:** ほとんどの開発者にとって能力と費用の完璧なバランス
- **価値:** セッション制限に達せず、継続的生産性
</details>
<details>
<summary><strong>パワーユーザー:</strong> 複数のClaude Pro + GLM Pro</summary>
- **最適:** 重い作業量、並行プロジェクト、ソロ開発
- **解放:** セッション・週次制限を決して枯渇させない
- **ワークフロー:** 3+以上のターミナルで専門タスクを同時実行
</details>
<details>
<summary><strong>プライバシー重視:</strong> 仕事/個人の分離</summary>
- **必要時:** 仕事と個人AIコンテキストの厳格な分離
- **設定:** `ccs auth create work` + `ccs auth create personal`
- **注意:** 高度な機能 - ほとんどのユーザーには不要
</details>
---
## 手動切り替えではなくCCSを使う理由は?
<div align="center">
**CCSは「午後3時に制限に達したら切り替える」ことではありません。**
## **それは最初から並列で実行することです。**
</div>
### コアな違い
| **手動切り替え** | **CCSオーケストレーション** |
|:---|:---|
| 🔴 制限達成 → 作業停止 → 設定ファイル編集 → 再起動 | ✅ 最初から異なるモデルで複数ターミナルを実行 |
| 😰 コンテキストロスとフロー状態中断 | 😌 コンテキスト維持での継続的生産性 |
| 📝 逐次的タスク処理 | ⚡ 並列ワークフロー(計画 + 実行を同時に) |
| 🛠️ ブロックされた時の反応的問題解決 | 🎯 ブロックを防ぐ主導的ワークフロー設計 |
### CCSが提供するもの
- **ゼロコンテキスト切り替え:** 割れずにフロー状態を維持
- **並列生産性:** 1ターミナルで戦略計画、もう1つでコード実行
- **即座アカウント管理:** 1コマンド切り替え、設定ファイル編集不要
- **仕事と生活の分離:** ログアウトせずにコンテキストを分離
- **クロスプラットフォーム一貫性:** macOS、Linux、Windowsで同じスムーズな体験
<br>
## アーキテクチャ
### プロファイルタイプ
**設定ベース**: GLM, GLMT, Kimi, default
- 設定ファイルを指す`--settings`フラグを使用
- GLMT: 思考モードサポートの埋め込みプロキシ
**アカウントベース**: work, personal, team
- 分離されたインスタンスに`CLAUDE_CONFIG_DIR`を使用
- `ccs auth create <profile>`で作成
### 共有データ(v3.1
コマンドとスキルは`~/.ccs/shared/`からシンボリックリンク - プロファイル間の重複なし。
```plaintext
~/.ccs/
├── shared/ # すべてのプロファイルで共有
│ ├── agents/
│ ├── commands/
│ └── skills/
├── instances/ # プロファイル固有のデータ
│ └── work/
│ ├── agents@ → shared/agents/
│ ├── commands@ → shared/commands/
│ ├── skills@ → shared/skills/
│ ├── settings.json # APIキー、認証情報
│ ├── sessions/ # 会話履歴
│ └── ...
```
| タイプ | ファイル |
|:-----|:------|
| **共有** | `commands/`, `skills/`, `agents/` |
| **プロファイル固有** | `settings.json`, `sessions/`, `todolists/`, `logs/` |
> [!NOTE]
> **Windows**: シンボリックリンクが利用できない場合はディレクトリをコピー(本物のシンボリックリンクには開発者モードを有効にしてください)
<br>
## 使用例
### 基本的な切り替え
```bash
ccs # Claudeサブスクリプション(デフォルト)
ccs glm # GLM(コスト最適化)
ccs kimi # Kimi(思考サポート付き)
```
### マルチアカウント設定
```bash
# アカウントを作成
ccs auth create work
ccs auth create personal
```
**別々のターミナルで同時に実行:**
```bash
# Terminal 1 - 業務用
ccs work "機能を実装"
# Terminal 2 - 個人用(同時)
ccs personal "コードレビュー"
```
### ヘルプとバージョン
```bash
ccs --version # バージョンを表示
ccs --help # すべてのコマンドとオプションを表示
```
<br>
## GLM with Thinking (GLMT)
> [!CAUTION]
> ### 本番環境未対応 - 実験的機能
>
> **GLMTは実験的で広範なデバッグが必要です**
> - ストリーミングとツールサポートはまだ開発中
> - 予期せぬエラー、タイムアウト、不完全な応答が発生する可能性
> - 頻繁なデバッグと手動介入が必要
> - **重要なワークフローや本番使用には推奨されません**
>
> **GLM Thinkingの代替案**: **CCR hustle**と**BedollaのTransformer**[ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/))を通じて、より安定した実装を検討してください。
> [!IMPORTANT]
> GLMTはnpmインストールが必要です(`npm install -g @kaitranntt/ccs`)。ネイティブシェルバージョンでは利用できません(Node.js HTTPサーバーが必要)。
<br>
> [!NOTE]
> ### 謝辞:GLMTを可能にした基盤
>
> **CCSのGLMT実装は、[@Bedolla](https://github.com/Bedolla)の画期的な仕事に存在を負っています**。彼は[Claude Code Router (CCR)](https://github.com/musistudio/claude-code-router)とZ.AIの推論能力をブリッジする[最初の統合](https://github.com/Bedolla/ZaiTransformer/)を作成しました。
>
> ZaiTransformer以前、誰もZ.AIの思考モードとClaude Codeのワークフローを正常に統合できませんでした。Bedollaの仕事は単なる有用なものではなく、**基盤的**でした。彼のリクエスト/レスポンストランスフォーメーションアーキテクチャ、思考モード制御メカニズム、埋め込みプロキシ設計の実装は、GLMTの設計に直接インスピレーションを与え、可能にしました。
>
> **ZaiTransformerの先駆的な仕事なしでは、GLMTは現在の形では存在しませんでした。** GLMTの思考能力から利益を得る場合は、Claude Codeエコシステムでの先駆的な仕事をサポートするために[ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/)にスターを付けてください。
<br>
<details>
<summary><h3>GLM vs GLMT 比較</h3></summary>
<br>
<div align="center">
| 機能 | GLM (`ccs glm`) | GLMT (`ccs glmt`) |
|:--------|:----------------|:------------------|
| **エンドポイント** | Anthropic互換 | OpenAI互換 |
| **思考** | なし | 実験的(reasoning_content |
| **ツールサポート** | 基本的 | **不安定(v3.5+** |
| **MCPツール** | 制限あり | **バグあり(v3.5+** |
| **ストリーミング** | 安定 | **実験的(v3.4+** |
| **TTFB** | <500ms | <500ms(時々)、2-10秒+(頻繁) |
| **使用例** | 信頼性の高い作業 | **デバッグ実験のみ** |
</div>
</details>
<br>
<details>
<summary><h3>ツールサポート(v3.5 - 実験的</h3></summary>
<br>
**GLMTはMCPツールと関数呼び出しを試行:**
- **双方向トランスフォーメーション**: Anthropicツール ↔ OpenAI形式(不安定)
- **MCP統合**: MCPツールが時々実行(多くの場合XMLガベージを出力)
- **ストリーミングツール呼び出し**: リアルタイムツール呼び出し(クラッシュしない場合)
- **後方互換**: 既存の思考サポートを破壊する可能性
- **設定が必要**: 頻繁な手動デバッグが必要
</details>
<details>
<summary><h3>ストリーミングサポート(v3.4) - しばしば失敗</h3></summary>
<br>
**GLMTは増分推論コンテンツ配信でリアルタイムストリーミングを試行:**
- **デフォルト**: ストリーミング有効(動作時TTFB <500ms
- **自動フォールバック**: エラーにより頻繁にバッファモードに切り替え
- **思考パラメータ**: Claude CLI `thinking`パラメータが時々動作
- `thinking.type``budget_tokens`を無視する場合
- 優先順位: CLIパラメータ > メッセージタグ > デフォルト(破壊されていない場合)
**ステータス**: Z.AI(テスト済み、ツール呼び出しが頻繁に破壊、継続的なデバッグが必要)
</details>
<details>
<summary><h3>動作原理(動作時)</h3></summary>
<br>
1. CCSがlocalhostに埋め込みHTTPプロキシを生成(クラッシュしない場合)
2. プロキシがAnthropic形式 → OpenAI形式への変換を試行(多くの場合失敗)
3. Anthropicツール → OpenAI関数呼び出し形式への変換を試行(バグあり)
4. 推論パラメータとツールを付けてZ.AIに転送(タイムアウトしない場合)
5. `reasoning_content` → 思考ブロックへの変換を試行(部分的または破壊)
6. OpenAI `tool_calls` → Anthropic `tool_use` ブロックへの変換を試行(XMLガベージが一般的)
7. 思考とツール呼び出しが時々Claude Code UIに表示(破壊されていない場合)
</details>
<details>
<summary><h3>制御タグとキーワード</h3></summary>
<br>
**制御タグ**:
- `<Thinking:On|Off>` - 推論ブロックの有効/無効(デフォルト: On)
- `<Effort:Low|Medium|High>` - 推論深度の制御(非推奨 - Z.AIはバイナリ思考のみサポート)
**思考キーワード**(不安定なアクティベーション):
- `think` - 時々推論を有効化(低労力)
- `think hard` - 時々推論を有効化(中労力)
- `think harder` - 時々推論を有効化(高労力)
- `ultrathink` - 最大推論深度を試行(多くの場合破壊)
</details>
<details>
<summary><h3>環境変数</h3></summary>
<br>
**GLMT機能**(すべて実験的):
- 強制的な英語出力強制(時々動作)
- ランダムな思考モードアクティベーション(予測不可能)
- 頻繁なバッファモードへのフォールバック付きストリーミング試行
**一般**:
- `CCS_DEBUG_LOG=1` - デバッグファイルロギングを有効化
- `CCS_CLAUDE_PATH=/path/to/claude` - カスタムClaude CLIパス
</details>
<details>
<summary><h3>APIキー設定</h3></summary>
<br>
```bash
# GLMT設定を編集
nano ~/.ccs/glmt.settings.json
```
Z.AI APIキーを設定(コーディングプランが必要):
```json
{
"env": {
"ANTHROPIC_AUTH_TOKEN": "your-z-ai-api-key"
}
}
```
</details>
<details>
<summary><h3>セキュリティ制限(DoS保護)</h3></summary>
<br>
**v3.4 保護制限**:
| 制限 | 値 | 目的 |
|:------|:------|:--------|
| **SSEバッファ** | イベントあたり最大1MB | バッファオーバーフローを防止 |
| **コンテンツバッファ** | ブロックあたり最大10MB | 思考/テキストブロックを制限 |
| **コンテンツブロック** | メッセージあたり最大100 | DoS攻撃を防止 |
| **リクエストタイムアウト** | 120秒 | ストリーミングとバッファの両方 |
</details>
<details>
<summary><h3>デバッグ</h3></summary>
<br>
**詳細ロギングを有効化**:
```bash
ccs glmt --verbose "your prompt"
```
**デバッグファイルロギングを有効化**:
```bash
export CCS_DEBUG_LOG=1
ccs glmt --verbose "your prompt"
# ログ: ~/.ccs/logs/
```
**GLMTデバッグ**:
```bash
# 詳細ロギングでストリーミングステータスと推論詳細を表示
ccs glmt --verbose "test"
```
**推論コンテンツを確認**:
```bash
cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content'
```
**トラブルシューティング**:
- **存在しない場合**: Z.AI APIの問題(キー、アカウントステータスを確認)
- **存在する場合**: トランスフォーメーションの問題(`response-anthropic.json`を確認)
</details>
<br>
## アンインストール
<details>
<summary><h3>パッケージマネージャー</h3></summary>
<br>
```bash
# npm
npm uninstall -g @kaitranntt/ccs
# yarn
yarn global remove @kaitranntt/ccs
# pnpm
pnpm remove -g @kaitranntt/ccs
# bun
bun remove -g @kaitranntt/ccs
```
</details>
<details>
<summary><h3>公式アンインストーラー</h3></summary>
<br>
```bash
# macOS / Linux
curl -fsSL ccs.kaitran.ca/uninstall | bash
# Windows PowerShell
irm ccs.kaitran.ca/uninstall | iex
```
</details>
<br>
## 🎯 哲学
- **YAGNI**: 「念のため」の機能は追加しない
- **KISS**: シンプルなbash、複雑さなし
- **DRY**: 単一の情報源(設定)
## 📖 ドキュメント
**[docs/](./docs/)の完全なドキュメント**:
- [インストールガイド](./docs/en/installation.md)
- [設定](./docs/en/configuration.md)
- [使用例](./docs/en/usage.md)
- [システムアーキテクチャ](./docs/system-architecture.md)
- [GLMT制御メカニズム](./docs/glmt-controls.md)
- [トラブルシューティング](./docs/en/troubleshooting.md)
- [貢献](./CONTRIBUTING.md)
## 🤝 貢献
貢献を歓迎します!詳細については[貢献ガイド](./CONTRIBUTING.md)をご覧ください。
## Star History
<div align="center">
<img src="https://api.star-history.com/svg?repos=kaitranntt/ccs&type=timeline&logscale&legend=top-left" alt="Star History Chart" width="800">
</div>
## ライセンス
CCSは[MITライセンス](LICENSE)の下でライセンスされています。
<div align="center">
**レート制限に頻繁に遭遇する開発者のために ❤️ を込めて作成**
[⭐ このリポジトリにスター](https://github.com/kaitranntt/ccs) | [🐛 問題を報告](https://github.com/kaitranntt/ccs/issues) | [📖 ドキュメントを読む](./docs/en/)
</div>
-497
View File
@@ -1,497 +0,0 @@
# CCS Project Overview and Product Development Requirements (PDR)
## Executive Summary
CCS (Claude Code Switch) is a TypeScript-based CLI tool that enables instant profile switching between Claude, GLM, Kimi, Gemini, Codex, and Antigravity (and any OAuth-based models) models. It features a version pin mechanism for precise model control and a unified configuration system for seamless management across all providers. The project features a modern React 19 web dashboard with real-time WebSocket integration, comprehensive TypeScript architecture, and cross-platform support. Current architecture includes:
- **TypeScript Core**: 43 source files with 100% type coverage
- **React 19 Dashboard**: Modern UI with Vite, shadcn/ui, and real-time features
- **AI Delegation System**: Headless execution with stream-JSON output
- **Cross-Platform**: Native support for macOS, Linux, and Windows
- **163 total files**: ~8,000 lines of TypeScript code
## Product Vision
### Mission Statement
Provide developers with instant, zero-downtime switching between diverse AI models, ensuring precise version control, optimizing for cost, performance, and rate limit management while maintaining a seamless workflow experience.
### Core Value Proposition
- **Instant Switching**: One command to change AI models and providers without file editing
- **Zero Downtime**: Never interrupt development workflow during model or provider switches
- **Version Pinning**: Lock to specific model versions for consistent behavior
- **Cost Optimization**: Use the right model/provider for each task automatically
- **Developer Experience**: Maintain familiar Claude CLI interface with enhanced capabilities and multi-provider support
## Product Development Requirements (PDR)
### Functional Requirements
#### FR-001: Profile Management
**Requirement**: System shall support instant switching between multiple AI model profiles
- **Priority**: High
- **Acceptance Criteria**:
- Switch profiles with single command (`ccs glm`, `ccs`)
- Maintain profile state until explicitly changed
- Support unlimited profile configurations
- Automatic profile detection from command arguments
#### FR-002: Configuration Management
**Requirement**: System shall provide automatic configuration management
- **Priority**: High
- **Acceptance Criteria**:
- Auto-create configuration during installation
- Support custom configuration paths via environment variables
- Validate configuration file format and existence
- Provide clear error messages for configuration issues
#### FR-003: Claude CLI Integration
**Requirement**: System shall seamlessly integrate with official Claude CLI
- **Priority**: High
- **Acceptance Criteria**:
- Pass all arguments transparently to Claude CLI
- Support all Claude CLI features and flags
- Maintain identical user experience to native Claude CLI
- Auto-detect Claude CLI installation location
#### FR-004: Cross-Platform Compatibility
**Requirement**: System shall work identically across all supported platforms
- **Priority**: High
- **Acceptance Criteria**:
- Support macOS (Intel and Apple Silicon)
- Support Linux distributions
- Support Windows (PowerShell and Git Bash)
- Consistent behavior and error handling across platforms
#### FR-005: Special Command Support
**Requirement**: System shall support special meta-commands for management
- **Priority**: Medium
- **Acceptance Criteria**:
- `ccs --version` displays version and installation location
- `ccs --help` shows usage information
- **WIP**: `ccs --install` integrates with Claude Code commands (testing incomplete)
- **WIP**: `ccs --uninstall` removes Claude Code integration (testing incomplete)
#### FR-006: Error Handling
**Requirement**: System shall provide clear, actionable error messages
- **Priority**: Medium
- **Acceptance Criteria**:
- Validate configuration file existence and format
- Detect Claude CLI availability and report issues
- Provide suggestions for resolving common problems
- Maintain consistent error message format
#### FR-007: AI-Powered Delegation System
**Requirement**: System shall enable headless AI task delegation with real-time tool tracking
- **Priority**: High
- **Acceptance Criteria**:
- Execute Claude CLI in headless mode with `-p` flag
- Parse stream-JSON output for real-time tool visibility
- Track 13+ Claude Code tools (Bash, Read, Write, Edit, Glob, Grep, etc.)
- Support session continuation (`:continue` suffix)
- Display cost and duration statistics
- Handle Ctrl+C signal properly (kill child processes)
#### FR-008: .claude/ Directory Symlinking
**Requirement**: System shall selectively symlink .claude/ directories for data sharing
- **Priority**: Medium
- **Acceptance Criteria**:
- Symlink shared data: commands/, skills/, agents/
- Keep profile-specific data isolated: settings.json, sessions/, todolists/, logs/
- Windows fallback to directory copying when symlinks unavailable
- Non-invasive installation (never modify ~/.claude/settings.json)
- Idempotent installation (safe to run multiple times)
#### FR-009: Shell Completion
**Requirement**: System shall provide comprehensive shell completion across 4 shells
- **Priority**: Low
- **Acceptance Criteria**:
- Support Bash, Zsh, Fish, PowerShell
- Color-coded categories (profiles, commands, flags)
- Profile-aware completions (glm, glmt, kimi, work, personal)
- Easy installation via `--shell-completion` flag
- Show installation instructions per shell
#### FR-010: Diagnostics and Maintenance
**Requirement**: System shall provide comprehensive health diagnostics
- **Priority**: Medium
- **Acceptance Criteria**:
- `ccs doctor`: Validate installation, profiles, symlinks, API keys
- `ccs sync`: Fix broken symlinks and directory structure
- `ccs update`: Check for newer versions with smart notifications
- Color-coded status indicators ([OK], [!], [X])
- Actionable recommendations for issues
#### FR-011: Web Dashboard UI
**Requirement**: System shall provide a modern web dashboard for profile and configuration management
- **Priority**: High
- **Acceptance Criteria**:
- Profile management interface with active/inactive states
- Interactive command builder with search and categorization
- Performance metrics visualization with trend indicators
- Responsive design supporting mobile, tablet, and desktop
- Real-time updates via WebSocket integration
- Dark mode support out of the box
### Non-Functional Requirements
#### NFR-001: Performance
**Requirement**: System shall execute with minimal overhead
- **Priority**: High
- **Acceptance Criteria**:
- Profile switching completes in < 100ms
- Startup time < 50ms for any command
- Memory footprint < 10MB during execution
- No perceptible delay compared to native Claude CLI
#### NFR-002: Reliability
**Requirement**: System shall maintain 99.9% uptime during normal operations
- **Priority**: High
- **Acceptance Criteria**:
- Handle edge cases gracefully without crashes
- Maintain functionality across system reboots
- Recover gracefully from temporary system issues
- No memory leaks or resource exhaustion
#### NFR-003: Security
**Requirement**: System shall follow security best practices
- **Priority**: High
- **Acceptance Criteria**:
- No shell injection vulnerabilities in process execution
- Validate file paths to prevent traversal attacks
- Use secure process spawning with argument arrays
- No storage of sensitive credentials or API keys
#### NFR-004: Maintainability
**Requirement**: System shall be easy to maintain and extend
- **Priority**: Medium
- **Acceptance Criteria**:
- Code complexity maintained at manageable levels
- Comprehensive test coverage (>90%)
- Clear documentation and code comments
- Modular architecture supporting future enhancements
#### NFR-005: Usability
**Requirement**: System shall provide excellent developer experience
- **Priority**: Medium
- **Acceptance Criteria**:
- Intuitive command structure matching CLI conventions
- Clear help documentation and usage examples
- Minimal learning curve for existing Claude CLI users
- Consistent behavior across all use cases
## Technical Architecture
### System Components
#### Core Subsystems (v4.3.2)
1. **Main Entry Point** (`bin/ccs.js` ~800 lines): Command parsing, profile routing, delegation detection
2. **Auth System** (`bin/auth/` ~800 lines): Multi-account management (create, list, delete, switch)
3. **Delegation System** (`bin/delegation/` ~1,200 lines): AI-powered task delegation with stream-JSON
4. **GLMT System** (`bin/glmt/` ~700 lines): Thinking mode proxy and transformation
5. **Management System** (`bin/management/` ~600 lines): Config, instance, profile, shared data management
6. **Utilities** (`bin/utils/` ~1,500 lines): Symlink manager, validators, update checker, completion
7. **.claude/ Integration** (`~/.ccs/shared/`): Symlinked commands, skills, agents directories
#### v4.0-4.3.2 Major Enhancements
- **AI Delegation** (v4.0): Headless execution with stream-JSON output, session continuation
- **Selective Symlinking** (v4.1): Share .claude/ directories (commands, skills, agents)
- **Shell Completion** (v4.1.4): 4 shells supported with color-coded categories
- **Diagnostics** (v4.2): Doctor, sync, update commands for health checks
- **Stream-JSON Parser** (v4.3): Real-time tool tracking during delegation
### Data Flow (v4.3.2)
**Settings-based profiles (glm, kimi, glmt)**:
```mermaid
graph LR
USER[ccs glm "task"] --> PARSE[Parse Args]
PARSE --> DETECT[ProfileDetector]
DETECT --> CONFIG[Read config.json]
CONFIG --> EXEC[execClaude with --settings]
EXEC --> CLAUDE[Claude CLI]
```
**Delegation execution (v4.0+)**:
```mermaid
graph LR
USER[ccs glm -p "task"] --> DELEGATE[DelegationHandler]
DELEGATE --> HEADLESS[HeadlessExecutor]
HEADLESS --> STREAM[Parse stream-JSON]
STREAM --> FORMAT[ResultFormatter]
FORMAT --> SESSION[SessionManager save]
```
**Account-based profiles (work, personal)**:
```mermaid
graph LR
USER[ccs work "task"] --> PARSE[Parse Args]
PARSE --> DETECT[ProfileDetector]
DETECT --> INSTANCE[InstanceManager.ensureInstance]
INSTANCE --> EXEC[execClaude with CLAUDE_CONFIG_DIR]
EXEC --> CLAUDE[Claude CLI reads from instance]
```
**Evolution Flow Comparison**:
- **v2.x**: Login → Encrypt → Store → Decrypt → Copy → Execute (6 steps)
- **v3.0**: Create instance → Login → Execute (3 steps, 50% reduction)
- **v4.x**: Add delegation routing → Stream-JSON parsing → Session persistence (extended capabilities)
### Configuration Architecture (v4.3.2)
**Settings-based Config** (`~/.ccs/config.json`):
```json
{
"profiles": {
"glm": "~/.ccs/glm.settings.json",
"glmt": "~/.ccs/glmt.settings.json",
"kimi": "~/.ccs/kimi.settings.json",
"default": "~/.claude/settings.json"
}
}
```
**Shared Data Architecture** (v4.1+):
```
~/.ccs/shared/ # Symlinked to instance .claude/ directories
├── commands/ # Slash commands (shared across profiles)
├── skills/ # Agent skills (shared across profiles)
└── agents/ # Agent configs (shared across profiles)
```
**Account Profile Registry** (`~/.ccs/profiles.json`):
```json
{
"version": "2.0.0",
"profiles": {
"work": {
"type": "account",
"created": "2025-11-09T10:00:00.000Z",
"last_used": "2025-11-09T15:30:00.000Z"
}
},
"default": "work"
}
```
**v3.0 Schema Simplification**:
- **Removed fields**: `vault`, `subscription`, `email` (not needed for login-per-profile)
- **Kept fields**: `type`, `created`, `last_used` (essential metadata only)
- **Rationale**: Credentials live in instance directories, no vault needed
**Instance Directory Structure** (v4.1+ with symlinking):
```
~/.ccs/instances/work/
├── .claude/
│ ├── commands@ → ~/.ccs/shared/commands/ # Symlink (v4.1+)
│ ├── skills@ → ~/.ccs/shared/skills/ # Symlink (v4.1+)
│ ├── agents@ → ~/.ccs/shared/agents/ # Symlink (v4.1+)
│ ├── settings.json # Profile-specific (isolated)
│ ├── sessions/ # Profile-specific (isolated)
│ ├── todolists/ # Profile-specific (isolated)
│ └── logs/ # Profile-specific (isolated)
├── .anthropic/ # SDK config
└── .credentials.json # Login credentials (managed by Claude CLI)
```
- **Environment Override**: `CCS_CLAUDE_PATH` - Custom Claude CLI path
- **Auto-Creation**: Configuration generated automatically during installation
## Implementation Standards
### Code Quality Standards
- **YAGNI Principle**: Only implement features immediately needed
- **KISS Principle**: Maintain simplicity over complexity
- **DRY Principle**: Eliminate code duplication
- **Test Coverage**: >90% coverage for all critical paths
- **Documentation**: Clear code comments and external documentation
### Development Workflow
1. **Feature Development**: Implement following coding standards
2. **Testing**: Comprehensive unit and integration tests
3. **Documentation**: Update relevant documentation
4. **Quality Review**: Code review against standards checklist
5. **Release**: Version management and distribution
### Platform Support Matrix
| Platform | Version Support | Testing Coverage |
|----------|----------------|------------------|
| macOS | 10.15+ | Full |
| Linux | Ubuntu 18.04+, CentOS 7+ | Full |
| Windows | 10+ (PowerShell, Git Bash) | Full |
## Quality Assurance
### Testing Strategy
- **Unit Tests**: Individual module functionality
- **Integration Tests**: Cross-module interaction
- **Platform Tests**: OS-specific behavior validation
- **Edge Case Tests**: Error conditions and boundary cases
- **Performance Tests**: Resource usage and response time
### Quality Metrics
- **Code Coverage**: >90% line coverage
- **Complexity**: Maintain cyclomatic complexity < 10 per function
- **Performance**: Startup time < 50ms, memory < 10MB
- **Reliability**: <0.1% error rate in normal operations
## Deployment and Distribution
### Distribution Channels
- **npm Package**: Primary distribution channel (`@kaitranntt/ccs`)
- **Direct Install**: Platform-specific install scripts
- **GitHub Releases**: Source code and binary distributions
### Installation Methods
1. **npm Package** (Recommended): `npm install -g @kaitranntt/ccs`
2. **Direct Install**: `curl -fsSL ccs.kaitran.ca/install | bash`
3. **Windows PowerShell**: `irm ccs.kaitran.ca/install | iex`
### Auto-Configuration Process
1. **Package Installation**: npm or direct script execution
2. **Post-install Hook**: Automatic configuration creation
3. **Path Setup**: Add to system PATH when needed
4. **Validation**: Verify Claude CLI availability
5. **Ready State**: System ready for profile switching
## Success Metrics
### v4.3.2 Achievement Metrics
- **Delegation System**: AI-powered task execution with stream-JSON output
- **Tool Tracking**: 13+ Claude Code tools supported
- **Session Persistence**: `:continue` support for follow-up tasks
- **Shell Completion**: 4 shells supported (Bash, Zsh, Fish, PowerShell)
- **Diagnostics**: Doctor, sync, update commands for health checks
- **Symlinking**: Selective .claude/ directory sharing (commands, skills, agents)
### Phase 1 UI Achievement Metrics (2024-12-12)
- **Core Components**: 5 foundational UI components implemented
- ProfileCard: Individual profile display with state management
- ProfileDeck: Grid container with loading/error states
- CommandBuilder: Interactive CLI tool with search/filter
- ValueMetrics: Performance visualization with trends
- HubFooter: Navigation footer with version info
- **Responsive Design**: Mobile-first approach with Tailwind CSS
- **Component Architecture**: Modular, reusable component patterns
- **Mock Data Integration**: Development-ready with clear data flow patterns
### Adoption Metrics
- **Download Count**: npm package downloads per month
- **Installation Success Rate**: >95% successful installations
- **User Retention**: Monthly active users
- **Platform Distribution**: Usage across supported platforms
- **Delegation Usage**: Percentage of users utilizing `-p` flag
- **API Key Configuration**: Rate of users configuring GLM/Kimi/GLMT keys
### Performance Metrics (v4.3.2)
- **Profile Creation**: ~5-10ms (instance directory creation only)
- **Profile Activation**: ~5-10ms (no decryption overhead)
- **Delegation Startup**: <500ms (stream-JSON initialization)
- **Response Time**: Minimal overhead, direct Claude CLI execution
- **Error Rate**: <0.1% in normal operations
- **Reliability**: 99.9% uptime during normal operations
### Quality Metrics
- **Test Coverage**: >90% for all critical paths
- **Bug Reports**: Number and severity of reported issues
- **Fix Time**: Average time to resolve reported issues
- **User Satisfaction**: Feedback and ratings
## Risk Management
### Technical Risks
- **Claude CLI Changes**: API changes in official CLI
- **Mitigation**: Maintain abstraction layer, monitor changes
- **Platform Compatibility**: OS-specific issues
- **Mitigation**: Comprehensive testing, CI/CD across platforms
- **Dependency Issues**: npm package or system dependency problems
- **Mitigation**: Minimal dependencies, regular testing
### Business Risks
- **Competition**: Similar tools emerging
- **Mitigation**: Focus on simplicity and reliability
- **User Adoption**: Slow adoption rates
- **Mitigation**: Clear documentation, easy installation
- **Maintenance Burden**: Ongoing maintenance costs
- **Mitigation**: Simplified codebase, automated testing
## Future Roadmap
See [docs/project-roadmap.md](./project-roadmap.md) for detailed version history and future plans.
### Completed (v4.3.2)
- ✅ **AI Delegation System** (v4.0): Headless execution with stream-JSON
- ✅ **Selective Symlinking** (v4.1): Share .claude/ directories
- ✅ **Shell Completion** (v4.1.4): 4 shells with color-coded categories
- ✅ **Diagnostics** (v4.2): Doctor, sync, update commands
- ✅ **Session Continuation** (v4.3): `:continue` support
- ✅ **Vault Removal** (v3.0): Login-per-profile model
- ✅ **Platform Parity** (v3.0): Unified macOS/Linux/Windows behavior
### Active Development (v4.4-v4.5)
- **Delegation Improvements**: MCP tool integration, SQLite session storage
- **Performance Optimization**: Model selection based on task complexity
- **Enhanced Diagnostics**: Automated troubleshooting recommendations
### UI Development (Phase 1 Complete - 2024-12-12)
- ✅ **Core Components**: ProfileCard, ProfileDeck, CommandBuilder, ValueMetrics, HubFooter
- ✅ **Responsive Design**: Mobile-first implementation with Tailwind CSS
- ✅ **Component Architecture**: Established patterns for future development
- **Phase 2 (Planned)**: API integration, data persistence, advanced components
- **Phase 3 (Future)**: Charts/graphs, real-time updates, enhanced interactivity
### Future Considerations (v5.0+)
- **AI-Powered Features**: Automatic task classification, intelligent model selection
- **Enterprise Features**: Team profile sharing, usage analytics dashboard
- **Ecosystem Expansion**: Plugin system for custom models, CI/CD integration
## Compliance and Legal
### Licensing
- **MIT License**: Permissive open-source license
- **Third-party Dependencies**: All dependencies use compatible licenses
- **Attribution**: Proper attribution for all used components
### Privacy
- **Data Collection**: No personal data collection or transmission
- **Local Processing**: All processing happens locally
- **Configuration Privacy**: User configurations remain private
### Security
- **Code Review**: Regular security reviews and audits
- **Dependency Management**: Regular updates and vulnerability scanning
- **Secure Distribution**: Signed packages and secure distribution channels
## Conclusion
The CCS project demonstrates successful iterative evolution balancing simplification with enhanced capabilities:
### Evolution Summary
- **v2.x**: Vault-based credential encryption (~1,700 LOC)
- **v3.0**: Vault removal, login-per-profile (~1,100 LOC, 40% reduction)
- **v4.0-4.3.2**: AI delegation, .claude/ symlinking, stream-JSON (~8,477 LOC with enhanced features)
### v4.3.2 Architectural Benefits
1. **AI-Powered Delegation**: Headless execution with real-time tool tracking
2. **Selective Symlinking**: Shared .claude/ data (commands, skills, agents) across profiles
3. **Enhanced Diagnostics**: Doctor, sync, update commands for health checks
4. **Stream-JSON Parsing**: Real-time visibility into Claude Code tool usage
5. **Session Persistence**: Continue delegation sessions with `:continue` suffix
6. **Shell Completion**: 4 shells supported with color-coded categories
7. **Platform Parity**: Unified behavior across macOS/Linux/Windows
### Key Strengths (v4.3.2)
- **Modular Architecture**: Clear subsystem separation (auth, delegation, glmt, management, utils)
- **Non-Invasive Installation**: Never modifies ~/.claude/settings.json
- **Idempotent Operations**: Safe to run installation/sync multiple times
- **Cross-Platform Compatibility**: Unified behavior, Windows symlink fallback
- **Developer Experience**: Familiar Claude CLI interface with AI delegation
- **Maintainability**: Modular design, clear responsibilities
- **Performance**: Minimal overhead, direct CLI execution
- **Unified Configuration**: Centralized management for all AI models and providers
### Breaking Changes (v3.x → v4.x)
- **Zero Breaking Changes**: v4.x fully backward compatible with v3.x
- **New Features**: Delegation, symlinking, diagnostics added without breaking existing workflows
- **Migration**: No migration required from v3.x to v4.x
The project is well-positioned for future growth with a solid architectural foundation, comprehensive AI delegation capabilities, and enhanced developer experience. The v4.x architecture provides a sustainable basis for continued enhancement while maintaining core principles of simplicity, reliability, and performance.
-862
View File
@@ -1,862 +0,0 @@
# CCS Project Roadmap
## Project Overview
CCS (Claude Code Switch) is a TypeScript-based CLI tool with a modern React 19 dashboard for instant switching between multiple AI models (Claude Sonnet 4.5, GLM 4.6, GLMT, Kimi). The project features real-time WebSocket integration, comprehensive profile management, and cross-platform support. It enables developers to maintain continuous productivity by running parallel workflows with different AI models, avoiding rate limits and context switching.
### Core Value Proposition
- **Zero Downtime**: Instant profile switching without breaking flow state
- **Modern UI**: React 19 dashboard with real-time updates and WebSocket integration
- **Cost Optimization**: 81% cost savings through intelligent delegation to GLM/Kimi
- **Parallel Workflows**: Strategic planning with Claude + cost-effective execution with GLM
- **Cross-Platform**: Unified experience on macOS, Linux, and Windows
- **Type Safety**: 100% TypeScript coverage with zero `any` types
## Current Status
### Version Information
- **Current Version**: 4.5.0 (React Dashboard Integration Complete)
- **Release Status**: Production-ready with modern React UI
- **Build Status**: ✅ Working (npm run build → dist/ccs.js)
- **UI Build Status**: ✅ Working (cd ui && bun run build → dist/)
- **Test Status**: ✅ All tests passing (39/39 tests)
- **Cross-Platform**: ✅ Windows/macOS/Linux
- **Code Quality**: ✅ ESLint strictness upgrade completed
- **Code Architecture**: ✅ TypeScript-based with modular components
- **React Dashboard**: ✅ Full React 19 integration with Vite and shadcn/ui
- **Real-time Features**: ✅ WebSocket integration for live updates
### React Dashboard Integration (v4.5.0)
**✅ Complete Modern UI Implementation**
CCS now features a comprehensive React 19 dashboard providing a modern web interface for profile management and system monitoring.
**Technology Stack**:
- **React 19**: Latest version with concurrent features and hooks
- **TypeScript**: Full type safety across the entire UI codebase
- **Vite**: Fast build tool with HMR and optimized production builds
- **shadcn/ui**: Modern component library built on Radix UI primitives
- **TanStack Query**: Powerful server state management with caching
- **Tailwind CSS**: Utility-first styling for rapid development
**Dashboard Features**:
- ✅ **Real-time Updates**: WebSocket integration for live profile status
- ✅ **Profile Management**: Visual configuration of API profiles (GLM, GLMT, Kimi)
- ✅ **CLIProxy Integration**: OAuth provider setup and management
- ✅ **Account Management**: Multi-account profile switching
- ✅ **Health Monitoring**: System diagnostics dashboard
- ✅ **Settings Panel**: Global configuration interface
- ✅ **Dark Mode**: Theme switching support
- ✅ **Responsive Design**: Mobile-friendly interface
**Technical Implementation**:
- **163 Total Files**: Comprehensive codebase with modular architecture
- **~8,000 Lines**: Well-organized TypeScript code
- **Component Library**: Reusable UI components with consistent design
- **API Integration**: Seamless backend communication
- **Build Optimization**: Code splitting and lazy loading
- **Accessibility**: WCAG-compliant components
### TypeScript Conversion Summary
**✅ Conversion Completed: 100% (43 files)**
The CCS project has been fully converted from JavaScript to TypeScript, delivering enhanced type safety, improved developer experience, and better maintainability.
**Migration Statistics**:
- **Source Files**: 43 TypeScript files converted
- **Lines of Code**: ~8,000 lines of TypeScript code
- **Type Coverage**: 100% with zero `any` types
- **Build System**: Full TypeScript compilation pipeline
- **Type Definitions**: Comprehensive type definitions in `src/types/`
**Converted Components**:
- ✅ **Core System** (`src/ccs.ts`) - Main entry point
- ✅ **Commands** (`src/commands/`) - Modular command handlers
- ✅ **Authentication** (`src/auth/`) - Profile management and commands
- ✅ **CLIProxy** (`src/cliproxy/`) - OAuth provider integration
- ✅ **Delegation** (`src/delegation/`) - AI-powered task delegation system
- ✅ **GLMT** (`src/glmt/`) - GLM with Thinking support
- ✅ **Management** (`src/management/`) - System diagnostics and instance management
- ✅ **Utils** (`src/utils/`) - Cross-platform utilities and helpers
- ✅ **Types** (`src/types/`) - Complete type definitions
## Recent Achievements
### TypeScript Conversion Benefits (v4.4.0)
#### Type Safety & Reliability
- **Zero `any` types**: Complete type coverage across the entire codebase
- **Compile-time error detection**: Catches bugs before runtime
- **Interface contracts**: Clear API boundaries and data structures
- **Exhaustive type checking**: Eliminates entire classes of common errors
#### Enhanced Developer Experience
- **IDE support**: Full IntelliSense autocomplete and navigation
- **Refactoring safety**: Type-safe code modifications and renames
- **Self-documenting code**: Type definitions serve as living documentation
- **Better debugging**: Clear type information in debuggers and stack traces
#### Maintainability Improvements
- **Code navigation**: Easy "go to definition" across the entire codebase
- **Impact analysis**: Clear understanding of where types are used
- **API documentation**: Types define precise interfaces for all components
- **Future-proofing**: Easier to add new features without breaking existing code
#### Architecture Enhancements
- **Modular type system**: Comprehensive type definitions in `src/types/`
- **Strict configuration**: TypeScript strict mode enabled for maximum safety
- **Build pipeline**: Automated compilation with source maps and declarations
- **Cross-platform consistency**: Types ensure consistent behavior across platforms
### Phase 01: ESLint Strictness Upgrade Complete ✅
**Completion Date**: 2025-11-27
**Status**: SUCCESS - All quality gates passing
#### Enhanced Code Quality Standards
**ESLint Rules Upgraded** (`eslint.config.mjs`):
- ✅ `@typescript-eslint/no-unused-vars`: `warn``error`
- ✅ `@typescript-eslint/no-explicit-any`: `warn``error`
- ✅ `@typescript-eslint/no-non-null-assertion`: `warn``error`
#### Validation Results
- **TypeScript Compilation**: ✅ Zero type errors
- **ESLint Validation**: ✅ Zero violations (previously 3 warning rules)
- **Test Suite**: ✅ 39/39 tests passing
- **Manual Testing**: ✅ All critical commands working
- **Code Coverage**: ✅ 10,487 lines of TypeScript code analyzed
#### Quality Improvements Achieved
1. **Type Safety Enhancement**: Zero tolerance for unused variables, explicit any types, and non-null assertions
2. **Code Quality Enforcement**: Stricter linting prevents entire categories of potential bugs
3. **Maintainability Boost**: Cleaner, more predictable codebase with enforced standards
4. **Zero Breaking Changes**: All functionality preserved, enhanced reliability only
#### Next Phase Readiness
- **Phase 02 Status**: ✅ COMPLETED (2025-11-27)
- **Focus**: CCS monolithic split (ccs.ts 1071 lines → 593 lines, 44.6% reduction)
- **Goal**: ✅ Achieved - 7 modular command handlers created for improved maintainability
- **Results**: All validation gates pass, code review: EXCELLENT
**Phase 03 Status**: ✅ COMPLETED (2025-12-03)
- **Focus**: Beta channel implementation with npm tag switching
- **Goal**: ✅ Achieved - Full beta channel support with stability warnings
- **Results**: All validation gates pass, comprehensive user guidance implemented
### Phase 02: CCS Split Refactoring Complete ✅
**Completion Date**: 2025-11-27
**Status**: SUCCESS - All objectives achieved
### Phase 03: Beta Channel Implementation Complete ✅
**Completion Date**: 2025-12-03
**Status**: SUCCESS - Beta channel fully implemented
#### Beta Channel Features Delivered
**NPM Tag Switching System**:
- ✅ Implemented `fetchVersionFromNpmTag()` function for tag-specific version queries
- ✅ Added support for `@latest` and `@dev` npm tags
- ✅ Seamless switching between stable and beta channels
**Enhanced Update Command**:
- ✅ `--beta` flag implementation with target tag detection
- ✅ Stability warnings for beta channel installations:
- "[!] Installing from @dev channel (unstable)"
- "[!] Not recommended for production use"
- "[!] Use `ccs update` (without --beta) to return to stable"
- ✅ Combined flag support: `--force --beta` for force reinstall from beta
**Installation Method Validation**:
- ✅ npm installations: Full beta channel support
- ✅ Direct installer installations: Clear error messages with migration guidance
- ✅ Automatic detection of installation method
- ✅ Graceful fallback to stable channel for unsupported methods
#### Technical Implementation Details
**Core Changes**:
- `src/utils/update-checker.ts`: Added `fetchVersionFromNpmTag()` and targetTag parameter
- `src/commands/update-command.ts`: Enhanced with beta flag parsing and validation
- `src/ccs.ts`: Updated to pass beta flag to update handler
**User Experience Improvements**:
- Clear warnings about beta channel stability
- One-command return to stable channel
- Helpful error messages with migration instructions
- Seamless channel switching without data loss
#### Validation Results
- **TypeScript Compilation**: ✅ Zero type errors
- **ESLint Validation**: ✅ Zero violations
- **Manual Testing**: ✅ All beta channel scenarios working
- **Error Handling**: ✅ Comprehensive error messages for edge cases
- **Documentation**: ✅ Updated across all relevant files
#### Modular Command Architecture Implementation
**Command Handler Modules Created:**
- ✅ `src/commands/version-command.ts` (3.0KB) - Version display functionality
- ✅ `src/commands/help-command.ts` (4.9KB) - Comprehensive help system
- ✅ `src/commands/install-command.ts` (957B) - Install/uninstall operations
- ✅ `src/commands/doctor-command.ts` (415B) - System diagnostics
- ✅ `src/commands/sync-command.ts` (1.0KB) - Configuration synchronization
- ✅ `src/commands/shell-completion-command.ts` (2.1KB) - Shell completion management
**New Utility Modules:**
- ✅ `src/utils/shell-executor.ts` (1.5KB) - Cross-platform shell execution
- ✅ `src/utils/package-manager-detector.ts` (3.8KB) - Package manager detection
#### Refactoring Metrics Achieved
**File Size Reduction:**
- **src/ccs.ts**: 1,071 → 593 lines (**44.6% reduction**)
- **Main file focus**: Now contains only routing logic + profile detection + GLMT proxy
- **Maintainability**: Enhanced through modular command separation
**Code Organization:**
- **Before**: 1 monolithic file handling all commands
- **After**: 7 focused command handlers + 2 utility modules
- **Benefits**: Easier testing, better code navigation, focused responsibilities
#### Architecture Improvements
**Enhanced Modularity:**
- **Command Handlers**: Each command isolated in dedicated module
- **Utility Functions**: Cross-platform shell execution and package management
- **Clean Separation**: Main file focuses on orchestration only
- **Type Safety**: All new modules maintain 100% TypeScript compliance
**Maintainability Benefits:**
- **Single Responsibility**: Each module has focused purpose
- **Easy Testing**: Command handlers can be tested independently
- **Code Navigation**: Developers can quickly locate specific functionality
- **Future Enhancements**: New commands can be added without touching main file
#### Validation Results
- **TypeScript Compilation**: ✅ Zero type errors
- **ESLint Validation**: ✅ Zero violations
- **Test Suite**: ✅ All tests passing
- **Functionality**: ✅ 100% feature preservation
- **Performance**: ✅ No degradation, minor improvement due to smaller main file
#### Code Quality Assessment
- **Review Status**: EXCELLENT
- **Architecture**: Clean modular design
- **Type Safety**: Comprehensive TypeScript coverage
- **Documentation**: Well-documented interfaces and functions
- **Future-Proofing**: Scalable architecture for additional commands
### Configuration Architecture Improvements
- **Shared Settings**: v4.4 introduces unified `settings.json` sharing across profiles
- **Plugin Support**: Enhanced shared directory structure with plugin support
- **Error Handling**: Improved error management with typed error codes
- **Shell Completion**: PowerShell compatibility improvements
### Phase 05: Bootstrap Passthrough Verification Complete ✅
**Completion Date**: 2025-12-03 16:40
**Status**: SUCCESS - Bootstrap scripts handle argument passthrough correctly
#### Implementation Summary
The bootstrap script verification phase confirmed that both Unix and Windows bootstrap scripts already correctly pass all command-line arguments to the Node.js implementation. No code changes were required.
#### Technical Verification
**Bash Bootstrap (`lib/ccs`)**:
- Line 32: `exec npx "$PACKAGE" "$@"`
- `"$@"` correctly expands to all positional parameters, preserving quotes
- Successfully passes `--force`, `--beta`, and combined flags
**PowerShell Bootstrap (`lib/ccs.ps1`)**:
- Lines 5-8: Parameter capture with `ValueFromRemainingArguments=$true`
- Line 38: `& npx $PACKAGE @RemainingArgs`
- `@RemainingArgs` uses splatting to pass all captured arguments
- Successfully passes `--force`, `--beta`, and combined flags
#### Key Achievements
1. **Zero Code Changes**: Existing implementation already supports new flags
2. **Cross-Platform Consistency**: Both Unix and Windows handle arguments identically
3. **No Breaking Changes**: Existing functionality remains unaffected
4. **Security Preserved**: Arguments passed through without shell expansion risks
#### Validation Results
- **Argument Passthrough**: ✅ `--force` flag reaches Node.js implementation
- **Beta Support**: ✅ `--beta` flag reaches Node.js implementation
- **Combined Flags**: ✅ `--force --beta` combination works correctly
- **Existing Commands**: ✅ All existing commands continue to work
- **Error Handling**: ✅ Invalid flags properly rejected by Node.js layer
#### Next Steps
Ready to proceed with:
- Phase 06: Comprehensive test suite implementation
- Phase 07: Documentation updates for new features
## Current Architecture
### Updated Architecture Diagram
```mermaid
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#1f2937', 'edgeLabelBackground':'#374151', 'clusterBkg':'#374151'}}}%%
graph TB
subgraph "TypeScript Source Layer (Phase 02 Modular)"
MAIN[src/ccs.ts - Main Entry - 593 lines]
CMDS[src/commands/ - Modular Commands]
AUTH[src/auth/ - Authentication]
DELEGATE[src/delegation/ - AI Delegation]
GLMT[src/glmt/ - GLM Thinking]
MGMT[src/management/ - System Mgmt]
UTILS[src/utils/ - Cross-Platform Utils]
TYPES[src/types/ - Type Definitions]
subgraph "Command Handlers"
VER[version-command.ts]
HELP[help-command.ts]
INSTALL[install-command.ts]
DOCTOR[doctor-command.ts]
SYNC[sync-command.ts]
SHELL[shell-completion-command.ts]
end
subgraph "New Utils"
SHELL_EXEC[shell-executor.ts]
PKG_MGR[package-manager-detector.ts]
end
end
%% Modular connections
MAIN --> CMDS
CMDS --> VER
CMDS --> HELP
CMDS --> INSTALL
CMDS --> DOCTOR
CMDS --> SYNC
CMDS --> SHELL
UTILS --> SHELL_EXEC
UTILS --> PKG_MGR
subgraph "Build Output Layer"
DIST[dist/ccs.js - Compiled Output]
DECL[dist/ccs.d.ts - Type Declarations]
MAP[dist/ccs.js.map - Source Maps]
end
subgraph "Native Integration Layer"
BASH[lib/ccs - Bash Implementation]
PS[lib/ccs.ps1 - PowerShell Implementation]
SHELLS[Shell Completion Scripts]
end
subgraph "Runtime Environment"
CLAUDE[Claude CLI]
CONFIG[Configuration Files]
SHARED[~/.ccs/shared/]
INSTANCES[Isolated Instances]
end
MAIN --> DIST
AUTH --> DIST
DELEGATE --> DIST
GLMT --> DIST
MGMT --> DIST
UTILS --> DIST
TYPES --> DECL
DIST --> CLAUDE
BASH --> CLAUDE
PS --> CLAUDE
SHELLS --> CLAUDE
CONFIG --> CLAUDE
SHARED --> CLAUDE
INSTANCES --> CLAUDE
```
### TypeScript Architecture Benefits
#### Type System Organization
```
src/types/
├── cli.ts # CLI interface definitions
├── config.ts # Configuration type schemas
├── delegation.ts # Delegation system types
├── glmt.ts # GLMT-specific types
├── utils.ts # Utility function types
└── index.ts # Central type exports
```
#### Component Type Safety
- **Authentication**: Type-safe profile management and command execution
- **Delegation**: Structured delegation workflows with typed result handling
- **GLMT**: Type-safe transformation pipelines and proxy management
- **Management**: Typed diagnostics and instance management
- **Utils**: Cross-platform utilities with consistent interfaces
#### Build Pipeline
- **TypeScript Compiler**: `tsc` with strict configuration and comprehensive checks
- **Declaration Generation**: Automatic `.d.ts` file generation for API documentation
- **Source Maps**: Debug-friendly mapping back to TypeScript source files
- **Incremental Builds**: Fast rebuilds with TypeScript incremental compilation
## Development Roadmap
### Next Development Phases
#### Phase 1: TypeScript Foundation Stabilization (v4.4.1 - v4.4.5)
**Timeline**: Immediate - 4 weeks
**Priorities**:
1. **Type System Refinement**
- Migrate remaining `any` types (target: zero any types)
- Add generic constraints for better type inference
- Implement branded types for enhanced type safety
- Create utility types for common patterns
2. **Build System Enhancement**
- Add TypeScript ESLint with strict rules
- Implement pre-commit type checking
- Add automated type coverage reporting
- Enhance development build performance
3. **Testing Infrastructure**
- Migrate tests to TypeScript
- Add type-safe test utilities
- Implement mock type definitions
- Create type-safe test data fixtures
#### Phase 2: Advanced Delegation System (v4.5.0)
**Timeline**: 1-2 months
**TypeScript-Driven Features**:
1. **Smart Delegation Routing**
- Type-based task classification system
- Intelligent profile selection algorithms
- Cost estimation with typed calculation models
- Performance optimization through type-aware caching
- Recently implemented significant UI improvements for analytics dashboard, enhancing data presentation.
2. **Enhanced Session Management**
- Type-safe session persistence with serialization
- Advanced session resumption with state restoration
- Multi-turn conversation context management
- Session analytics with typed metrics
3. **Plugin System Foundation**
- Type-safe plugin API definitions
- Plugin discovery and registration system
- Sandboxed plugin execution environment
- Community plugin marketplace infrastructure
#### Phase 3: Enterprise Features (v4.6.0)
**Timeline**: 2-3 months
**Enterprise-Grade TypeScript Features**:
1. **Team Profile Management**
- Type-safe role-based access control (RBAC)
- Centralized configuration management
- Audit logging with typed event structures
- Compliance reporting with structured data formats
2. **Advanced Analytics Dashboard**
- Real-time usage metrics with typed data streams
- Cost tracking and budgeting with financial types
- Team productivity analytics with KPI types
- Performance monitoring with alert types
3. **CI/CD Integration**
- Type-safe GitHub Actions workflows
- Automated testing with type validation
- Deployment pipelines with type checks
- Infrastructure as Code with TypeScript
#### Phase 4: UI Enhancements - Sidebar Redesign (v4.7.0)
**Timeline**: 1-2 months (TBD)
**Priorities**:
1. **Sidebar Redesign Implementation**
- Implement new sidebar component with modern UI/UX principles.
- Ensure responsiveness across different screen sizes.
- Integrate with existing routing and navigation logic.
- Improve accessibility features for the sidebar.
### Technical Debt Resolution
#### Immediate Priorities (v4.4.1)
1. **GLMT System Refactoring**
- Transform GLMT proxy with typed request/response handling
- Implement type-safe SSE parsing with error recovery
- Add typed transformation pipelines for API compatibility
- Create comprehensive GLMT test suites with type safety
2. **Error Handling Enhancement**
- Implement typed error hierarchies with inheritance
- Create structured error reporting with localization
- Add automatic error recovery with typed retry logic
- Develop error analytics with classification systems
3. **Performance Optimization**
- Profile and optimize hot paths with typed benchmarks
- Implement memory-efficient data structures with generics
- Add lazy loading patterns with type-safe initialization
- Create performance monitoring with typed metrics
#### Medium-term Improvements (v4.5.0)
1. **Cross-Platform Consistency**
- Unify behavior across platforms with typed abstractions
- Implement platform-specific optimizations with type guards
- Create comprehensive cross-platform test suites
- Add platform-specific feature detection
2. **API Evolution**
- Design backward-compatible API evolution strategies
- Implement API versioning with type migration paths
- Create deprecation warnings with upgrade guidance
- Add automated API compatibility testing
## Future Vision (v5.0+)
### Next-Generation Architecture
#### AI-Powered TypeScript Development
1. **Intelligent Code Generation**
- TypeScript-aware AI code completion
- Automatic type inference from usage patterns
- Smart refactoring suggestions with type analysis
- Code quality recommendations based on type metrics
2. **Adaptive Type System**
- Dynamic type generation based on runtime behavior
- Machine learning-assisted type predictions
- Automatic interface extraction from APIs
- Smart type narrowing with statistical analysis
#### Enterprise TypeScript Platform
1. **Advanced Team Collaboration**
- Real-time collaborative TypeScript editing
- Shared type libraries across projects
- Automated type governance policies
- Team-wide type consistency enforcement
2. **Comprehensive Analytics**
- Type usage analytics and optimization recommendations
- Code quality metrics with type safety scores
- Developer productivity tracking with type metrics
- Technical debt measurement with type analysis
#### Ecosystem Integration
1. **Package Management**
- Type-safe dependency management
- Automated vulnerability scanning with type analysis
- Smart version resolution with compatibility checking
- Package quality assessment with type metrics
2. **Tool Integration**
- TypeScript-native IDE extensions
- Enhanced debugging with type information
- Performance profiling with type insights
- Automated testing with type-driven test generation
## Release Notes
### Version 4.5.0 - Beta Channel Implementation Complete
**Release Date**: 2025-12-03
#### Major Features
- ✅ **Beta Channel Support**: Full implementation of npm tag switching between `@latest` and `@dev`
- ✅ **Enhanced Update Command**: `--beta` flag with stability warnings and validation
- ✅ **Force Reinstall Support**: `--force` flag to reinstall current version and fix corrupted installs
- ✅ **Combined Flag Support**: `--force --beta` for force reinstalling beta versions
- ✅ **Installation Method Detection**: Differential support for npm vs direct installations
- ✅ **User Safety Features**: Clear warnings and migration guidance for beta usage
- ✅ **Version Fetching Enhancement**: Tag-specific queries with `fetchVersionFromNpmTag()`
- ✅ **Comprehensive Test Suite**: 29 new tests covering update flags functionality
#### Technical Improvements
- **NPM Integration**: Direct npm registry access for version queries
- **Version Comparison Logic**: Robust semantic version comparison with prerelease handling
- **Error Handling**: Comprehensive error messages with migration instructions
- **User Experience**: One-command channel switching without data loss
- **Backward Compatibility**: Zero breaking changes, existing workflows preserved
### Version 4.5.1 - UI Quality Gate Fixes & Layout Improvements
**Release Date**: 2025-12-08
#### UI Fixes & Improvements
- ✅ **Analytics UI Enhancements**: Standardized colors, fixed truncated model names, and ensured color consistency in the analytics dashboard.
- ✅ **Auto-formatting**: 31 UI files auto-formatted for consistent styling.
- ✅ **Fast Refresh Exports**: Resolved `react-refresh/only-export-components` by extracting `buttonVariants`, `useSidebar`, and `useWebSocketContext` to separate files.
- ✅ **React Hooks Issues**: Fixed `react-hooks/purity` (`Math.random()` in `useMemo` for `sidebar.tsx`) and `react-hooks/set-state-in-effect` (`use-theme.ts`, `settings.tsx`).
- ✅ **useWebSocket Hook Restructure**: Addressed `react-hooks/immutability` errors and dependency array warnings in `use-websocket.ts`.
- ✅ **TypeScript Strict Mode**: Implemented null-check for `document.getElementById('root')` in `src/main.tsx` for strict mode compliance.
- ✅ **Duplicate Directory Removal**: Cleaned up extraneous `ui/@/` directory.
- ✅ **CLIProxy Card Padding**: Removed excessive padding from CLIProxy cards for better visual integration.
- ✅ **CLIProxy Dashboard Layout**: Improved overall layout and styling of the CLIProxy dashboard.
- ✅ **Dropdown Styling**: Refined dropdown component styling.
- ✅ **Model Usage Card**: Corrected icon display and refined donut chart styling.
#### Technical Improvements
- **Improved UI Responsiveness**: Adjustments ensure better display across various screen sizes.
- **Enhanced User Experience**: Minor visual tweaks lead to a more polished and intuitive interface.
#### Validation Results
- **UI Rendering**: ✅ All UI components render correctly after adjustments and fixes.
- **Functional Impact**: ✅ No regressions introduced, core functionality remains stable.
- **Code Quality**: ✅ All ESLint and TypeScript quality gates passed after fixes.
### Version 4.5.2 - Operational Hub Redesign - Phase 1 Complete
**Release Date**: 2025-12-12
#### New UI Components Created
- ✅ **ProfileCard Component** (`src/components/profile-card.tsx`): Individual profile display with status indicators and action buttons
- ✅ **ProfileDeck Component** (`src/components/profile-deck.tsx`): Container for managing multiple profile cards in a grid layout
- ✅ **CommandBuilder Component** (`src/components/command-builder.tsx`): Interactive command construction interface with suggestions
- ✅ **ValueMetrics Component** (`src/components/value-metrics.tsx`): Dashboard widget for displaying efficiency metrics and cost savings
- ✅ **HubFooter Component** (`src/components/hub-footer.tsx`): Utility footer with navigation links and version information
#### Component Features
- **Profile Management**: Visual profile switching with active/inactive states
- **Command Interface**: Interactive command builder with copy/run actions
- **Metrics Visualization**: Real-time display of cost savings and efficiency statistics
- **Responsive Design**: Mobile-friendly layout with Tailwind CSS styling
- **Accessibility**: WCAG-compliant components with proper ARIA labels
#### Technical Implementation
- **TypeScript**: Full type safety with zero `any` types
- **React 19**: Latest React features with hooks and concurrent rendering
- **shadcn/ui**: Consistent design system with Radix UI primitives
- **Modular Architecture**: Reusable components for enhanced maintainability
#### Code Review Notes
- Identified console.log statements for removal in Phase 2
- Noted hardcoded version string in HubFooter requiring dynamic version
- Button handlers need implementation or disabling
- Error boundary wrappers recommended for production
#### Validation Results
- **Component Compilation**: ✅ All components compile without errors
- **TypeScript Validation**: ✅ Zero type errors with strict mode
- **ESLint Compliance**: ✅ No violations detected
- **Manual Testing**: ✅ Components render as expected in isolation
---
#### Testing Infrastructure
- **Version Comparison Tests**: 25 unit tests for all semantic version scenarios
- **Flag Parsing Tests**: 4 integration tests for update command flags
- **Edge Case Coverage**: Invalid versions, large numbers, case sensitivity
- **Downgrade Detection**: Proper warnings for beta channel downgrades
- **Test Framework**: Mocha with assert module, minimal mocking approach
### Version 4.4.0 - TypeScript Conversion Complete
**Release Date**: 2025-11-25
#### Major Features
- ✅ **Complete TypeScript Conversion**: All 31 source files migrated to TypeScript
- ✅ **Zero `any` Types**: 100% type coverage with comprehensive type definitions
- ✅ **Enhanced Build Pipeline**: Automated compilation with source maps and declarations
- ✅ **Shared Settings Architecture**: Unified `settings.json` across all profiles
- ✅ **Plugin Support**: Enhanced shared directory structure
- ✅ **ESLint Strictness Upgrade**: Phase 01 completed (2025-11-27) - 3 rules upgraded to error level, 0 violations found
- ✅ **CCS Architecture Refactoring**: Phase 02 completed (2025-11-27) - 44.6% file size reduction, 9 modular components created
#### Technical Improvements
- **Type Safety**: Compile-time error detection eliminates entire bug categories
- **Developer Experience**: Full IDE support with IntelliSense and navigation
- **Maintainability**: Self-documenting code with comprehensive type definitions
- **Cross-Platform**: Typed abstractions ensure consistent behavior
#### Breaking Changes
- **None**: Fully backward compatible with existing configurations
- **Migration**: Seamless upgrade path with zero user impact
#### Dependencies
- **TypeScript 5.3**: Updated to latest stable version
- **Enhanced Build Process**: Automated compilation and type checking
- **Development Tools**: Improved development tooling and debugging
### Recent Patch Updates
- **v4.3.10**: Package manager cache clearing during updates
- **v4.3.9**: Fixed missing `commands/ccs.md` symlink in npm install
- **v4.3.8**: Resolved missing `~/.ccs/.claude/` directory creation
- **v4.3.7**: Enhanced directory creation during npm install
- **v4.3.6**: Added plugin support to shared directories
- **v4.4.0**: TypeScript conversion complete, shared settings architecture
## Testing Strategy
### TypeScript Testing Infrastructure
1. **Unit Testing with Type Safety**
- Mocha tests with TypeScript compilation
- Type-safe test utilities and fixtures
- Mock implementations with interface compliance
- Coverage reporting with type metrics
2. **Integration Testing**
- Cross-platform compatibility validation
- End-to-end workflow testing with typed data
- API contract testing with type validation
- Performance testing with type-aware profiling
3. **Type-Level Testing**
- TypeScript compiler error verification
- Type coverage measurement and reporting
- API surface validation with type checking
- Dependency graph analysis with type relationships
## Quality Assurance
### TypeScript Quality Metrics
- **Type Coverage**: 100% (target: maintain zero any types)
- **Compiler Strictness**: Maximum strict mode configuration
- **Interface Compliance**: All exports properly typed
- **Documentation Coverage**: Type definitions serve as documentation
### Code Quality Standards
- **ESLint Integration**: TypeScript-specific linting rules
- **Pre-commit Hooks**: Automated type checking before commits
- **CI/CD Pipeline**: Type validation in continuous integration
- **Code Review**: Type safety as review requirement
## Contributing to Roadmap
### TypeScript Development Guidelines
1. **Type-First Development**: Define types before implementation
2. **Zero Any Policy**: Maintain 100% type coverage
3. **Interface Documentation**: Comprehensive JSDoc with type examples
4. **Backward Compatibility**: Evolve APIs without breaking changes
### Feature Contribution Process
1. **Type Design**: Submit type definitions for review
2. **Implementation**: Type-safe implementation with comprehensive tests
3. **Documentation**: Update type documentation and examples
4. **Review**: Peer review focused on type safety and API design
## Community and Ecosystem
### TypeScript Community Engagement
- **TypeScript Best Practices**: Share learnings with TypeScript community
- **Open Source Contribution**: Contribute to TypeScript tooling ecosystem
- **Knowledge Sharing**: Document TypeScript migration experience
- **Community Support**: Help other projects with TypeScript adoption
## Future Roadmap
### Phase 1: UI Enhancements & Mobile Support (v4.6.0 - v4.7.0)
**Timeline**: 2-3 months
**Priorities**:
1. **Dashboard Improvements**
- Sidebar redesign with modern UX patterns
- Enhanced data visualizations and charts
- Drag-and-drop profile reordering
- Customizable dashboard widgets
2. **Mobile Responsiveness**
- Touch-friendly interface
- Progressive Web App (PWA) support
- Offline mode for basic functionality
- Mobile-specific shortcuts
3. **Real-time Collaboration**
- Multi-user dashboard access
- Live profile sharing
- Collaborative delegation sessions
- Real-time activity feeds
### Phase 2: Advanced Features (v4.8.0 - v4.9.0)
**Timeline**: 3-4 months
**Priorities**:
1. **AI-Powered Features**
- Automatic model selection based on task type
- Intelligent delegation routing
- Cost optimization suggestions
- Performance analytics
2. **Enterprise Features**
- Team profile management
- Usage analytics dashboard
- Role-based access control
- Audit logging
3. **Plugin System**
- Extensible architecture for custom providers
- Community plugin marketplace
- Plugin development SDK
- Version compatibility management
### Phase 3: Next Generation Architecture (v5.0+)
**Timeline**: 6+ months
**Vision**:
1. **Microservices Architecture**
- Decoupled services for scalability
- Container-based deployment
- API-first design
- Cloud-native features
2. **Advanced AI Integration**
- Multi-modal AI support (text, image, audio)
- Custom AI model training
- Advanced reasoning capabilities
- Workflow automation
3. **Ecosystem Expansion**
- VS Code extension
- IDE integrations
- CI/CD plugins
- Developer toolchain integration
## Technical Debt & Improvements
### Immediate Priorities (v4.5.1)
1. **Performance Optimization**
- Bundle size reduction
- Lazy loading implementation
- Memory leak fixes
- Caching strategies
2. **Testing Enhancement**
- E2E test suite for UI
- Visual regression testing
- Performance testing
- Accessibility testing
3. **Documentation**
- API documentation generation
- Interactive tutorials
- Video guides
- Community resources
### Medium-term Goals (v4.6.0)
1. **Security Hardening**
- Security audit
- Penetration testing
- Dependency vulnerability scanning
- Secure development practices
2. **Internationalization**
- Multi-language support
- Localization infrastructure
- Cultural adaptations
- Global deployment
3. **Analytics & Monitoring**
- Usage analytics
- Performance monitoring
- Error tracking
- User behavior insights
---
**Document Status**: Living document, updated with each major release
**Last Updated**: 2025-12-12 (Operational Hub Redesign - Phase 1)
**Next Update**: v4.5.3 Operational Hub Redesign - Phase 2 Integration
**Maintainer**: CCS Development Team
-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
-210
View File
@@ -1,210 +0,0 @@
# UI Components Phase 1 Implementation Summary
**Date**: 2024-12-12
**Phase**: 1 - Core Components Implementation
**Status**: Complete
## Overview
Phase 1 of the CCS UI implementation has successfully delivered 5 core components that form the foundation of the modern web dashboard. These components demonstrate best practices in React development, responsive design, and component architecture.
## Components Delivered
### 1. ProfileCard (`/src/components/profile-card.tsx`)
A card component for displaying individual profile information with interactive elements.
**Features**:
- Profile name and status display
- Active/inactive state visualization
- Model information and last used timestamp
- Config and Test action buttons
- Disabled state for active profile switching
### 2. ProfileDeck (`/src/components/profile-deck.tsx`)
A grid container for managing multiple ProfileCard components with state handling.
**Features**:
- Responsive grid layout (1-3 columns)
- Loading state with skeleton placeholders
- Error state with descriptive messages
- Empty state for unconfigured profiles
- Mock data augmentation for development
### 3. CommandBuilder (`/src/components/command-builder.tsx`)
An interactive tool for building and discovering CCS commands.
**Features**:
- Real-time search and filtering
- Command categorization (Config, Profile, Diagnostics, CLIProxy)
- Copy-to-clipboard functionality
- Pre-populated command library
- Interactive command selection
### 4. ValueMetrics (`/src/components/value-metrics.tsx`)
Performance metrics visualization with trend indicators.
**Features**:
- Four primary metric cards with trends
- Monthly summary statistics
- Color-coded trend indicators
- Icon-based categorization
- Responsive grid layout
### 5. HubFooter (`/src/components/hub-footer.tsx`)
Utility footer component for application navigation.
**Features**:
- Version information display
- Copyright with dynamic year
- Navigation links (Logs, Settings, GitHub)
- External link handling
- Responsive text display
## Technical Implementation
### Architecture
- Built with React 19 and TypeScript
- Uses shadcn/ui component library
- Styled with Tailwind CSS
- Follows functional component patterns
- Implements proper prop typing
### Data Management
- Server state: TanStack Query (useProfiles)
- Local state: React hooks (useState, useEffect)
- Mock data for development and demonstration
- Clear separation between data and UI logic
### Design System
- Consistent spacing and typography
- Dark mode support
- Mobile-first responsive design
- Accessible component structure
- Semantic HTML markup
## Documentation Updates
The following documentation files have been updated:
1. **System Architecture** (`/docs/system-architecture.md`)
- Added component hierarchy diagrams
- Documented interaction patterns
- Included data flow architecture
2. **Code Standards** (`/docs/code-standards.md`)
- Added component interface patterns
- Documented mock data handling
- Included loading state patterns
3. **Project Overview PDR** (`/docs/project-overview-pdr.md`)
- Added FR-011: Web Dashboard UI requirements
- Updated success metrics
- Added UI development roadmap
## Best Practices Demonstrated
### Component Design
- Single responsibility principle
- Reusable and composable components
- Clear prop interfaces
- Consistent naming conventions
### State Management
- Proper separation of concerns
- Error boundary handling
- Loading state management
- Empty state considerations
### Accessibility
- Semantic HTML structure
- Proper ARIA labels
- Keyboard navigation support
- Screen reader compatibility
### Performance
- Efficient re-rendering
- Proper memo usage patterns
- Optimized bundle size
- Code splitting ready
## Next Steps
### Phase 2 Priorities
1. **API Integration**
- Connect to real backend services
- Implement data fetching patterns
- Add error handling for network requests
2. **Data Persistence**
- User preferences storage
- Profile state persistence
- Settings management
3. **Advanced Components**
- Configuration forms
- Status indicators
- Data visualization charts
4. **Testing**
- Unit tests for all components
- Integration testing
- E2E testing setup
### Technical Debt
- Replace mock data with real API calls
- Implement proper error boundaries
- Add comprehensive test coverage
- Optimize bundle size
## Component Usage Examples
### Profile Management
```typescript
<ProfileDeck>
{profiles.map(profile => (
<ProfileCard
key={profile.name}
profile={profile}
onSwitch={() => handleSwitch(profile.name)}
onConfig={() => handleConfig(profile.name)}
onTest={() => handleTest(profile.name)}
/>
))}
</ProfileDeck>
```
### Command Building
```typescript
<CommandBuilder
onCommandSelect={(command) => executeCommand(command)}
categories={['Config', 'Profile', 'Diagnostics']}
/>
```
### Metrics Display
```typescript
<ValueMetrics
metrics={performanceData}
showTrends={true}
timeRange="monthly"
/>
```
## Conclusion
Phase 1 has successfully established a solid foundation for the CCS dashboard with modern React patterns, excellent developer experience, and a clear path forward for future development. The components are well-documented, tested-ready, and follow best practices for maintainability and scalability.
The implementation demonstrates a strong understanding of:
- Component-based architecture
- Modern React patterns
- Responsive design principles
- Accessibility requirements
- Performance optimization
These components provide an excellent starting point for Phase 2 development and will serve as reference implementations for future UI features.
---
**Phase 1 Status**: ✅ Complete
**Next Review**: Phase 2 Planning (2024-12-19)
**Documentation**: Updated and current
-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
```
-653
View File
@@ -1,653 +0,0 @@
<div align="center">
# CCS - Claude Code Switch
![CCS Logo](../../docs/assets/ccs-logo-medium.png)
### Trình quản lý profile AI đa năng cho Claude Code
**Chuyển đổi giữa nhiều tài khoản Claude, kết nối bất kỳ API tương thích Anthropic, và sử dụng OAuth providers (Gemini, Codex, Antigravity) ngay lập tức.**
Ngừng bị rate limits. Làm việc liên tục với vô số profiles.
<br>
[![License](https://img.shields.io/badge/license-MIT-C15F3C?style=for-the-badge)](LICENSE)
[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey?style=for-the-badge)]()
[![npm](https://img.shields.io/npm/v/@kaitranntt/ccs?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/@kaitranntt/ccs)
[![PoweredBy](https://img.shields.io/badge/PoweredBy-ClaudeKit-C15F3C?style=for-the-badge)](https://claudekit.cc?ref=HMNKXOHN)
**Languages**: [English](../../README.md) · [Tiếng Việt](README.md) · [日本語](../ja/README.md)
</div>
<br>
## Bắt Đầu Nhanh
### Cài Đặt
**npm Package (Được khuyến nghị)**
**macOS / Linux / Windows**
```bash
npm install -g @kaitranntt/ccs
```
**Tất cả các trình quản lý package chính đều được hỗ trợ:**
```bash
# yarn
yarn global add @kaitranntt/ccs
# pnpm (ít hơn 70% dung lượng đĩa)
pnpm add -g @kaitranntt/ccs
# bun (nhanh hơn 30x)
bun add -g @kaitranntt/ccs
```
<details>
<summary><strong>[!] LỖI THỜI: Trình cài đặt shell gốc (Cũ)</strong></summary>
<br>
> [!WARNING]
> **Các trình cài đặt này đã lỗi thời và sẽ bị xóa trong phiên bản tương lai.**
> Hiện tại chúng tự động chuyển hướng đến cài đặt npm. Vui lòng sử dụng npm trực tiếp.
**macOS / Linux**
```bash
curl -fsSL ccs.kaitran.ca/install | bash
```
**Windows PowerShell**
```powershell
irm ccs.kaitran.ca/install | iex
```
**Lưu ý**: Script hiển thị cảnh báo lỗi thời và tự động chạy cài đặt npm nếu Node.js khả dụng.
</details>
<br>
### Cấu Hình (Tự Tạo)
**CCS tự động tạo cấu hình trong quá trình cài đặt** (thông qua script postinstall của npm).
**~/.ccs/config.json**:
```json
{
"profiles": {
"glm": "~/.ccs/glm.settings.json",
"glmt": "~/.ccs/glmt.settings.json",
"kimi": "~/.ccs/kimi.settings.json",
"default": "~/.claude/settings.json"
}
}
```
<details>
<summary><h3>Custom Claude CLI Path</h3></summary>
<br>
Nếu Claude CLI được cài đặt ở vị trí không chuẩn (ổ D, thư mục tùy chỉnh), đặt `CCS_CLAUDE_PATH`:
```bash
# Unix/Linux/macOS
export CCS_CLAUDE_PATH="/path/to/claude"
# Windows PowerShell
$env:CCS_CLAUDE_PATH = "D:\Tools\Claude\claude.exe"
```
**Xem thêm**: [Hướng dẫn Khắc phục Sự cố](./docs/en/troubleshooting.md#claude-cli-in-non-standard-location) để biết chi tiết cài đặt.
</details>
<details>
<summary><h3>Windows Symlink Support (Developer Mode)</h3></summary>
<br>
**Người dùng Windows**: Bật Chế độ Nhà phát triển để có symlink thực sự (hiệu suất tốt hơn, đồng bộ hóa tức thì):
1. Mở **Settings****Privacy & Security** → **For developers**
2. Bật **Developer Mode**
3. Cài đặt lại CCS: `npm install -g @kaitranntt/ccs`
**Cảnh báo**: Nếu không có Chế độ Nhà phát triển, CCS tự động chuyển sang sao chép thư mục (hoạt động nhưng không đồng bộ tức thì trên các profile).
</details>
<br>
### Lần Chuyển Đổi Đầu Tiên
> [!IMPORTANT]
> **Trước khi dùng các mô hình thay thế, cập nhật API keys trong file settings:**
>
> - **GLM**: Chỉnh sửa `~/.ccs/glm.settings.json` và thêm Z.AI Coding Plan API Key của bạn
> - **GLMT**: Chỉnh sửa `~/.ccs/glmt.settings.json` và thêm Z.AI Coding Plan API Key của bạn
> - **Kimi**: Chỉnh sửa `~/.ccs/kimi.settings.json` và thêm Kimi API key của bạn
<br>
**Parallel Workflow: Planning + Execution**
```bash
# Terminal 1 - Planning (Claude Sonnet)
ccs "Plan a REST API with authentication and rate limiting"
# Terminal 2 - Execution (GLM, cost-optimized)
ccs glm "Implement the user authentication endpoints from the plan"
```
<details>
<summary><strong>Thinking Models (Kimi & GLMT)</strong></summary>
<br>
```bash
# Kimi - Stable thinking support
ccs kimi "Design a caching strategy with trade-off analysis"
# GLMT - Experimental (see full disclaimer below)
ccs glmt "Debug complex algorithm with reasoning steps"
```
**Lưu ý:** GLMT là thử nghiệm và không ổn định. Xem phần [GLM with Thinking (GLMT)](#glm-with-thinking-glmt) dưới đây để biết chi tiết.
</details>
<br>
## The Daily Developer Pain Point
<div align="center">
### **DỪNG việc chuyển đổi. BẮT ĐẦU điều phối.**
**Giới hạn phiên không nên phá hỏng trạng thái dòng chảy của bạn.**
</div>
Bạn đang sâu trong triển khai. Ngữ cảnh đã tải. Giải pháp đang kết tinh.<br>
Sau đó: 🔴 _"Bạn đã đạt đến giới hạn sử dụng."_
**Động lực mất đi. Ngữ cảnh mất. Năng suất sụp đổ.**
## **Giải pháp: Quy trình công việc song song**
<details>
<summary><strong>❌ CÁCH CŨ:</strong> Chuyển đổi khi bạn đạt đến giới hạn (Phản ứng)</summary>
### Quy trình làm việc hiện tại của bạn:
- **2pm:** Xây dựng tính năng, trong vùng
- **3pm:** 🔴 Đạt giới hạn sử dụng
- **3:05pm:** Dừng công việc, chỉnh sửa `~/.claude/settings.json`
- **3:15pm:** Chuyển tài khoản, mất ngữ cảnh
- **3:30pm:** Cố gắng quay lại trạng thái dòng chảy
- **4pm:** Cuối cùng cũng năng suất trở lại
- **Kết quả:** Mất 1 giờ, động lực bị phá hủy, sự thất vọng tăng lên
</details>
<details open>
<summary><strong>✨ CÁCH MỚI:</strong> Chạy song song ngay từ đầu (Chủ động) - <strong>ĐƯỢC KHUYÊN NGHỊ</strong></summary>
### Quy trình làm việc mới của bạn:
- **2pm:** **Terminal 1:** `ccs "Lập kế hoạch kiến trúc API"` → Tư duy chiến lược (Claude Pro)
- **2pm:** **Terminal 2:** `ccs glm "Triển khai các điểm cuối API"` → Thực thi mã (GLM)
- **3pm:** Vẫn đang giao hàng, không có gián đoạn
- **4pm:** Đạt trạng thái dòng chảy, năng suất tăng vọt
- **5pm:** Tính năng đã giao hàng, ngữ cảnh được duy trì
- **Kết quả:** Không có thời gian chết, năng suất liên tục, ít thất vọng hơn
### 💰 **Giá trị đề xuất:**
- **Thiết lập:** Claude Pro hiện tại của bạn + GLM Lite (add-on hiệu quả về chi phí)
- **Giá trị:** Tiết kiệm 1 giờ/ngày × 20 ngày làm việc = 20 giờ/tháng được phục hồi
- **ROI:** Thời gian phát triển của bạn có giá trị hơn chi phí thiết lập
- **Thực tế:** Giao hàng nhanh hơn chi phí vận hành
</details>
## Chọn con đường của bạn
<details>
<summary><strong>Tập trung vào ngân sách:</strong> Chỉ GLM</summary>
- **Tốt nhất cho:** Phát triển tiết kiệm chi phí, tạo mã cơ bản
- **Sử dụng:** Chỉ sử dụng `ccs glm` trực tiếp để được trợ giúp AI hiệu quả về chi phí
- **Thực tế:** Không có quyền truy cập Claude, nhưng có khả năng cho nhiều nhiệm vụ mã hóa
- **Thiết lập:** Chỉ cần API key GLM, rất phải chăng
</details>
<details open>
<summary><strong>✨ Được khuyên nghị cho phát triển hàng ngày:</strong> 1 Claude Pro + 1 GLM Lite</summary>
- **Tốt nhất cho:** Giao hàng mã hàng ngày, công việc phát triển nghiêm túc
- **Sử dụng:** `ccs` để lập kế hoạch + `ccs glm` để thực thi (quy trình công việc song song)
- **Thực tế:** Cân bằng hoàn hảo giữa khả năng và chi phí cho hầu hết các nhà phát triển
- **Giá trị:** Không bao giờ đạt đến giới hạn phiên, năng suất liên tục
</details>
<details>
<summary><strong>Power User:</strong> Nhiều Claude Pro + GLM Pro</summary>
- **Tốt nhất cho:** Nhiều công việc, dự án đồng thời, solo dev
- **Mở khóa:** Không bao giờ cạn kiệt giới hạn phiên hoặc hàng tuần
- **Quy trình làm việc:** 3+ terminal chạy các nhiệm vụ chuyên biệt đồng thời
</details>
<details>
<summary><strong>Tập trung vào quyền riêng tư:</strong> Cách ly Công việc/Cá nhân</summary>
- **Khi cần:** Cách ly nghiêm ngặt ngữ cảnh AI công việc và cá nhân
- **Thiết lập:** `ccs auth create work` + `ccs auth create personal`
- **Lưu ý:** Tính năng nâng cao - hầu hết người dùng không cần điều này
</details>
---
## Why CCS Instead of Manual Switching?
<div align="center">
**CCS không phải về "chuyển đổi khi bạn đạt đến giới hạn lúc 3pm."**
## **Nó về việc chạy song song ngay từ đầu.**
</div>
### Sự khác biệt cốt lõi
| **Chuyển đổi thủ công** | **Điều phối CCS** |
|:---|:---|
| 🔴 Đạt giới hạn → Dừng công việc → Chỉnh sửa tệp cấu hình → Khởi động lại | ✅ Nhiều terminal chạy các mô hình khác nhau ngay từ đầu |
| 😰 Mất ngữ cảnh và gián đoạn trạng thái dòng chảy | 😌 Năng suất liên tục với ngữ cảnh được bảo toàn |
| 📝 Xử lý nhiệm vụ tuần tự | ⚡ Quy trình công việc song song (lập kế hoạch + thực thi đồng thời) |
| 🛠️ Giải quyết vấn đề phản ứng khi bị chặn | 🎯 Thiết kế quy trình công việc chủ động ngăn chặn chặn |
### CCS mang lại cho bạn
- **Không chuyển đổi ngữ cảnh:** Duy trì trạng thái dòng chảy của bạn mà không bị gián đoạn
- **Năng suất song song:** Lập kế hoạch chiến lược trong một terminal, thực thi mã trong terminal khác
- **Quản lý tài khoản tức thì:** Một lệnh chuyển đổi, không cần chỉnh sửa tệp cấu hình
- **Cách ly công việc-cuộc sống:** Cách ly ngữ cảnh mà không cần đăng xuất
- **Tính nhất quán đa nền tảng:** Trải nghiệm mượt mà tương tự trên macOS, Linux, Windows
<br>
## Architecture
### Profile Types
**Settings-based**: GLM, GLMT, Kimi, default
- Uses `--settings` flag pointing to config files
- GLMT: Embedded proxy for thinking mode support
**Account-based**: work, personal, team
- Uses `CLAUDE_CONFIG_DIR` for isolated instances
- Create with `ccs auth create <profile>`
### Shared Data (v3.1)
Commands and skills symlinked from `~/.ccs/shared/` - **no duplication across profiles**.
```plaintext
~/.ccs/
├── shared/ # Shared across all profiles
│ ├── agents/
│ ├── commands/
│ └── skills/
├── instances/ # Profile-specific data
│ └── work/
│ ├── agents@ → shared/agents/
│ ├── commands@ → shared/commands/
│ ├── skills@ → shared/skills/
│ ├── settings.json # API keys, credentials
│ ├── sessions/ # Conversation history
│ └── ...
```
| Type | Files |
|:-----|:------|
| **Shared** | `commands/`, `skills/`, `agents/` |
| **Profile-specific** | `settings.json`, `sessions/`, `todolists/`, `logs/` |
> [!NOTE]
> **Windows**: Copies directories if symlinks unavailable (enable Developer Mode for true symlinks)
<br>
## Usage Examples
### Basic Switching
```bash
ccs # Claude subscription (default)
ccs glm # GLM (cost-optimized)
ccs kimi # Kimi (with thinking support)
```
### Multi-Account Setup
```bash
# Create accounts
ccs auth create work
ccs auth create personal
```
**Run concurrently in separate terminals:**
```bash
# Terminal 1 - Work
ccs work "implement feature"
# Terminal 2 - Personal (concurrent)
ccs personal "review code"
```
### Help & Version
```bash
ccs --version # Show version
ccs --help # Show all commands and options
```
<br>
## GLM with Thinking (GLMT)
> [!CAUTION]
> ### NOT PRODUCTION READY - EXPERIMENTAL FEATURE
>
> **GLMT is experimental and requires extensive debugging**:
> - Streaming and tool support still under active development
> - May experience unexpected errors, timeouts, or incomplete responses
> - Requires frequent debugging and manual intervention
> - **Not recommended for critical workflows or production use**
>
> **Alternative for GLM Thinking**: Consider going through the **CCR hustle** with the **Transformer of Bedolla** ([ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/)) for a more stable implementation.
> [!IMPORTANT]
> GLMT requires npm installation (`npm install -g @kaitranntt/ccs`). Not available in native shell versions (requires Node.js HTTP server).
<br>
> [!NOTE]
> ### Acknowledgments: The Foundation That Made GLMT Possible
>
> **CCS's GLMT implementation owes its existence to the groundbreaking work of [@Bedolla](https://github.com/Bedolla)**, who created [ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/) - the **first integration** to bridge [Claude Code Router (CCR)](https://github.com/musistudio/claude-code-router) with Z.AI's reasoning capabilities.
>
> Before ZaiTransformer, no one had successfully integrated Z.AI's thinking mode with Claude Code's workflow. Bedolla's work wasn't just helpful - it was **foundational**. His implementation of request/response transformation architecture, thinking mode control mechanisms, and embedded proxy design directly inspired and enabled GLMT's design.
>
> **Without ZaiTransformer's pioneering work, GLMT wouldn't exist in its current form.** If you benefit from GLMT's thinking capabilities, please consider starring [ZaiTransformer](https://github.com/Bedolla/ZaiTransformer/) to support pioneering work in the Claude Code ecosystem.
<br>
<details>
<summary><h3>GLM vs GLMT Comparison</h3></summary>
<br>
<div align="center">
| Feature | GLM (`ccs glm`) | GLMT (`ccs glmt`) |
|:--------|:----------------|:------------------|
| **Endpoint** | Anthropic-compatible | OpenAI-compatible |
| **Thinking** | No | Experimental (`reasoning_content`) |
| **Tool Support** | Basic | **Unstable (v3.5+)** |
| **MCP Tools** | Limited | **Buggy (v3.5+)** |
| **Streaming** | Stable | **Experimental (v3.4+)** |
| **TTFB** | <500ms | <500ms (sometimes), 2-10s+ (often) |
| **Use Case** | Reliable work | **Debugging experiments only** |
</div>
</details>
<br>
<details>
<summary><h3>Tool Support (v3.5) - EXPERIMENTAL</h3></summary>
<br>
**GLMT attempts MCP tools and function calling:**
- **Bidirectional Transformation**: Anthropic tools ↔ OpenAI format (unstable)
- **MCP Integration**: MCP tools sometimes execute (often output XML garbage)
- **Streaming Tool Calls**: Real-time tool calls (when not crashing)
- **Backward Compatible**: May break existing thinking support
- **Configuration Required**: Frequent manual debugging needed
</details>
<details>
<summary><h3>Streaming Support (v3.4) - OFTEN FAILS</h3></summary>
<br>
**GLMT attempts real-time streaming** with incremental reasoning content delivery:
- **Default**: Streaming enabled (TTFB <500ms when it works)
- **Auto-fallback**: Frequently switches to buffered mode due to errors
- **Thinking parameter**: Claude CLI `thinking` parameter sometimes works
- May ignore `thinking.type` and `budget_tokens`
- Precedence: CLI parameter > message tags > default (when not broken)
**Status**: Z.AI (tested, tool calls frequently break, requires constant debugging)
</details>
<details>
<summary><h3>How It Works (When It Works)</h3></summary>
<br>
1. CCS spawns embedded HTTP proxy on localhost (if not crashing)
2. Proxy attempts to convert Anthropic format → OpenAI format (often fails)
3. Tries to transform Anthropic tools → OpenAI function calling format (buggy)
4. Forwards to Z.AI with reasoning parameters and tools (when not timing out)
5. Attempts to convert `reasoning_content` → thinking blocks (partial or broken)
6. Attempts to convert OpenAI `tool_calls` → Anthropic `tool_use` blocks (XML garbage common)
7. Thinking and tool calls sometimes appear in Claude Code UI (when not broken)
</details>
<details>
<summary><h3>Control Tags & Keywords</h3></summary>
<br>
**Control Tags**:
- `<Thinking:On|Off>` - Enable/disable reasoning blocks (default: On)
- `<Effort:Low|Medium|High>` - Control reasoning depth (deprecated - Z.AI only supports binary thinking)
**Thinking Keywords** (inconsistent activation):
- `think` - Sometimes enables reasoning (low effort)
- `think hard` - Sometimes enables reasoning (medium effort)
- `think harder` - Sometimes enables reasoning (high effort)
- `ultrathink` - Attempts maximum reasoning depth (often breaks)
</details>
<details>
<summary><h3>Environment Variables</h3></summary>
<br>
**GLMT features** (all experimental):
- Forced English output enforcement (sometimes works)
- Random thinking mode activation (unpredictable)
- Attempted streaming with frequent fallback to buffered mode
**General**:
- `CCS_DEBUG_LOG=1` - Enable debug file logging
- `CCS_CLAUDE_PATH=/path/to/claude` - Custom Claude CLI path
</details>
<details>
<summary><h3>API Key Setup</h3></summary>
<br>
```bash
# Edit GLMT settings
nano ~/.ccs/glmt.settings.json
```
Set Z.AI API key (requires coding plan):
```json
{
"env": {
"ANTHROPIC_AUTH_TOKEN": "your-z-ai-api-key"
}
}
```
</details>
<details>
<summary><h3>Security Limits (DoS Protection)</h3></summary>
<br>
**v3.4 Protection Limits**:
| Limit | Value | Purpose |
|:------|:------|:--------|
| **SSE buffer** | 1MB max per event | Prevent buffer overflow |
| **Content buffer** | 10MB max per block | Limit thinking/text blocks |
| **Content blocks** | 100 max per message | Prevent DoS attacks |
| **Request timeout** | 120s | Both streaming and buffered |
</details>
<details>
<summary><h3>Debugging</h3></summary>
<br>
**Enable verbose logging**:
```bash
ccs glmt --verbose "your prompt"
```
**Enable debug file logging**:
```bash
export CCS_DEBUG_LOG=1
ccs glmt --verbose "your prompt"
# Logs: ~/.ccs/logs/
```
**GLMT debugging**:
```bash
# Verbose logging shows streaming status and reasoning details
ccs glmt --verbose "test"
```
**Check reasoning content**:
```bash
cat ~/.ccs/logs/*response-openai.json | jq '.choices[0].message.reasoning_content'
```
**Troubleshooting**:
- **If absent**: Z.AI API issue (verify key, account status)
- **If present**: Transformation issue (check `response-anthropic.json`)
</details>
<br>
## Uninstall
<details>
<summary><h3>Package Managers</h3></summary>
<br>
```bash
# npm
npm uninstall -g @kaitranntt/ccs
# yarn
yarn global remove @kaitranntt/ccs
# pnpm
pnpm remove -g @kaitranntt/ccs
# bun
bun remove -g @kaitranntt/ccs
```
</details>
<details>
<summary><h3>Official Uninstaller</h3></summary>
<br>
```bash
# macOS / Linux
curl -fsSL ccs.kaitran.ca/uninstall | bash
# Windows PowerShell
irm ccs.kaitran.ca/uninstall | iex
```
</details>
<br>
## 🎯 Philosophy
- **YAGNI**: No features "just in case"
- **KISS**: Simple bash, no complexity
- **DRY**: One source of truth (config)
## 📖 Documentation
**Complete documentation in [docs/](./docs/)**:
- [Installation Guide](./docs/en/installation.md)
- [Configuration](./docs/en/configuration.md)
- [Usage Examples](./docs/en/usage.md)
- [System Architecture](./docs/system-architecture.md)
- [GLMT Control Mechanisms](./docs/glmt-controls.md)
- [Troubleshooting](./docs/en/troubleshooting.md)
- [Contributing](./CONTRIBUTING.md)
## 🤝 Contributing
We welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for details.
## Star History
<div align="center">
<img src="https://api.star-history.com/svg?repos=kaitranntt/ccs&type=timeline&logscale&legend=top-left" alt="Star History Chart" width="800">
</div>
## License
CCS is licensed under the [MIT License](LICENSE).
<div align="center">
**Made with ❤️ for developers who hit rate limits too often**
[⭐ Star this repo](https://github.com/kaitranntt/ccs) | [🐛 Report issues](https://github.com/kaitranntt/ccs/issues) | [📖 Read docs](./docs/en/)
</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.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@kaitranntt/ccs",
"version": "5.17.0",
"version": "5.17.0-dev.7",
"description": "Claude Code Switch - Instant profile switching between Claude Sonnet 4.5 and GLM 4.6",
"keywords": [
"cli",
+1 -3
View File
@@ -77,9 +77,7 @@ export async function handleVersionCommand(): Promise<void> {
console.log('');
}
console.log(
`${subheader('Documentation:')} ${color('https://github.com/kaitranntt/ccs', 'path')}`
);
console.log(`${subheader('Documentation:')} ${color('https://docs.ccs.kaitran.ca', 'path')}`);
console.log(`${subheader('License:')} MIT`);
console.log('');
console.log(color("Run 'ccs --help' for usage information", 'command'));
+105 -6
View File
@@ -640,10 +640,11 @@ function validateOffset(offset?: string): number {
* Filter data by date range
*/
function filterByDateRange<T extends { date?: string; month?: string; lastActivity?: string }>(
data: T[],
data: T[] | undefined,
since?: string,
until?: string
): T[] {
if (!data || !Array.isArray(data)) return [];
if (!since && !until) return data;
return data.filter((item) => {
@@ -824,6 +825,7 @@ usageRoutes.get(
*
* Returns hourly usage trends for chart visualization.
* Query: ?since=YYYYMMDD&until=YYYYMMDD (defaults to last 24 hours)
* Fills in gaps with zero values for hours without activity.
*/
usageRoutes.get(
'/hourly',
@@ -834,8 +836,8 @@ usageRoutes.get(
const hourlyData = await getCachedHourlyData();
// Filter by date range
const filtered = hourlyData.filter((h) => {
// Filter by date range (guard against undefined)
const filtered = (hourlyData || []).filter((h) => {
// Extract date from hour format "YYYY-MM-DD HH:00"
const hourDate = h.hour.slice(0, 10).replace(/-/g, '');
if (since && hourDate < since) return false;
@@ -855,12 +857,12 @@ usageRoutes.get(
requests: hour.modelBreakdowns.length,
}));
// Sort by hour ascending for chart display
trends.sort((a, b) => a.hour.localeCompare(b.hour));
// Fill gaps with zero values for hours without activity
const filledTrends = fillHourlyGaps(trends, since, until);
res.json({
success: true,
data: trends,
data: filledTrends,
});
} catch (error) {
errorResponse(res, error, 'Failed to fetch hourly usage');
@@ -868,6 +870,103 @@ usageRoutes.get(
}
);
/**
* Fill gaps in hourly data with zero values
* Ensures continuous timeline for chart display
*/
function fillHourlyGaps(
data: Array<{
hour: string;
tokens: number;
inputTokens: number;
outputTokens: number;
cacheTokens: number;
cost: number;
modelsUsed: number;
requests: number;
}>,
since?: string,
until?: string
): typeof data {
// If no date range specified, return as-is
if (!since && !until) {
return data.sort((a, b) => a.hour.localeCompare(b.hour));
}
// Create a map of existing hours for O(1) lookup
const hourMap = new Map(data.map((d) => [d.hour, d]));
// Determine the hour range (use UTC to match stored hour keys)
const now = new Date();
const startDate = since
? new Date(
Date.UTC(
parseInt(since.slice(0, 4)),
parseInt(since.slice(4, 6)) - 1,
parseInt(since.slice(6, 8)),
0,
0,
0
)
)
: new Date(now.getTime() - 24 * 60 * 60 * 1000); // Default: 24 hours ago
const endDate = until
? new Date(
Date.UTC(
parseInt(until.slice(0, 4)),
parseInt(until.slice(4, 6)) - 1,
parseInt(until.slice(6, 8)),
23,
59,
59
)
)
: now;
// Cap endDate at current time to avoid filling future hours with zeros
const cappedEndDate = endDate > now ? now : endDate;
const result: typeof data = [];
// Iterate through each hour in the range
const current = new Date(startDate);
current.setMinutes(0, 0, 0);
while (current <= cappedEndDate) {
// Format hour key as "YYYY-MM-DD HH:00" in UTC to match storage format
const year = current.getUTCFullYear();
const month = String(current.getUTCMonth() + 1).padStart(2, '0');
const day = String(current.getUTCDate()).padStart(2, '0');
const hour = String(current.getUTCHours()).padStart(2, '0');
const hourKey = `${year}-${month}-${day} ${hour}:00`;
if (hourMap.has(hourKey)) {
const entry = hourMap.get(hourKey);
if (entry) {
result.push(entry);
}
} else {
// Insert zero entry for this hour
result.push({
hour: hourKey,
tokens: 0,
inputTokens: 0,
outputTokens: 0,
cacheTokens: 0,
cost: 0,
modelsUsed: 0,
requests: 0,
});
}
// Move to next hour
current.setTime(current.getTime() + 60 * 60 * 1000);
}
return result;
}
/**
* GET /api/usage/models
*