# GLM CLI - AI Code Generator

AI-powered code generation with streaming output. Generate code directly from your terminal with real-time feedback.

## Installation Model

**GLM CLI is installed globally, but Claude prompts can be installed globally or locally:**

```
┌─────────────────────────────────────────────────────────┐
│  NPM Global Install (once)                              │
│  npm install -g glm-coding                              │
│  → glm command available system-wide                    │
└─────────────────────────────────────────────────────────┘
                         ↓
        ┌────────────────┴────────────────┐
        ↓                                 ↓
┌──────────────────┐            ┌─────────────────────┐
│ Global Setup     │            │ Local Setup         │
│ glm init -g      │            │ glm init            │
│                  │            │                     │
│ ~/.glm/          │            │ {project}/.glm/     │
│ ~/.claude/       │            │ {project}/.claude/  │
└──────────────────┘            └─────────────────────┘
```

## Quick Start

### 1. Install GLM CLI Globally

```bash
npm install -g glm-coding
```

This installs the `glm` command system-wide.

### 2. Choose Your Setup Style

#### Option A: Global Setup (Shared Across All Projects)

```bash
glm init -g
```

This creates:
- `~/.glm/config.json` - Your API key and settings
- `~/.glm/instructions/` - Code quality guidelines
- `~/.glm/profiles/` - Specialized agent profiles
- `~/.glm/logs/` - Usage statistics
- `~/.claude/CLAUDE.md` - Instructions for Claude Code

**Use when:** You want one configuration for all projects.

#### Option B: Local Setup (Per-Project Configuration)

```bash
cd your-project
glm init
```

This creates:
- `{project}/.glm/config.json` - Project-specific API key/settings
- `{project}/.glm/instructions/` - Project-specific quality guidelines
- `{project}/.glm/profiles/` - Project-specific profiles
- `{project}/.claude/CLAUDE.md` - Project-specific Claude instructions

**Use when:** Different projects need different API keys, profiles, or quality standards.

#### Hybrid Approach (Global + Local Override)

```bash
# Set up global defaults
glm init -g

# Override in specific projects
cd special-project
glm init
```

Local settings override global ones. Logs always go to `~/.glm/logs/`.

## Usage

### Generate Code

```bash
# Basic usage
glm -q "Create a function to validate emails"

# With profile
glm -q "React user profile component" -p frontend-design

# Save to file
glm -q "REST API client for GitHub" -o client.py -p api-integration

# Pipe input
echo "Parse JSON with error handling" | glm -o parser.py
```

### Execute Mode (NEW in v0.6.0)

Generate and immediately execute code with automatic security validation:

```bash
# Execute generated code (default: Python)
glm -x -q "Print sum of 1 to 100"
# Output: 5050

# Generate content directly (poem, data, etc.)
glm -x -q "Write a haiku about coding"
# Output: [actual haiku printed]

# Save and execute
glm -x -q "Hello world" -o hello.py
# Output: /path/to/hello.py
#         Hello, World!

# Specify language
glm -x -l node -q "console.log('Hello')"

# Security check only (dry-run)
glm --dry-run -q "System information script"

# Force execution (bypass security - not recommended)
glm -x --force -q "some dangerous code"
```

**Security Features:**
- Automatic validation before execution
- Blocks dangerous imports: os, subprocess, shutil, etc.
- Blocks dangerous operations: file deletion, system commands
- Blocks dynamic code execution functions
- Detailed violation reports with line numbers
- Blocked code saved to temp directory for inspection

### Available Profiles

| Profile | Use Case | Example |
|---------|----------|---------|
| `default` | General coding | `glm -q "utility function"` |
| `frontend-design` | UI/UX, React, components | `glm -q "navbar component" -p frontend-design` |
| `api-integration` | REST, GraphQL, OAuth | `glm -q "API client" -p api-integration` |
| `database-ops` | SQL, queries, migrations | `glm -q "user schema" -p database-ops` |
| `web-crawler` | Web scraping, parsing | `glm -q "scrape prices" -p web-crawler` |

### Options

```bash
-q, --query <prompt>      Query prompt (required if no pipe)
-o, --output <file>       Save output to file (enables token tracking)
-p, --profile <name>      Use specific profile
-l, --language <lang>     Language for execution (python, node, bash)
-m, --max-tokens <num>    Maximum tokens (default: 20000, GLM max: 20K)
-x, --exec                Execute generated code after security check
--force                   Bypass security check (not recommended)
--dry-run                 Security check only, no execution
--no-quality              Disable quality instructions
```

### Commands

```bash
glm init                  Initialize local configuration
glm init -g               Initialize global configuration
glm stats                 Show usage statistics (daily)
glm stats --monthly       Show monthly statistics
glm usage                 Alias for stats command
glm usage --monthly       Monthly statistics (alias)
glm version               Show version
glm help                  Show help
```

## Claude Code Integration

**NEW in v0.5.0:** `glm init` now automatically installs Claude Code integration!

When you run `glm init` or `glm init -g`, the installer automatically sets up:

### 1. Hook System (Auto-Trigger)
**Detect keywords in your prompts:**
```
@glm Create a REST API client → Automatically activates GLM mode
-glm Parse JSON with validation → Activates GLM mode
--glm React button component → Activates GLM mode
```

The hook injects GLM-specific instructions when keywords are detected.

### 2. Slash Command
**Explicit GLM invocation:**
```
/glm REST API client → src/api.ts
/glm fibonacci function → utils/math.py
/glm 병렬로 여러 파일 생성
```

### 3. CLAUDE.md Instructions
Automatically adds GLM usage guidelines to `~/.claude/CLAUDE.md` or `.claude/CLAUDE.md`

### What Gets Installed

```
~/.claude/
├── hooks/
│   └── glm-detector.sh          # Keyword detection hook
├── commands/
│   └── glm.md                   # /glm slash command
├── settings.json                # Hook configuration (auto-updated)
└── CLAUDE.md                    # GLM usage guidelines
```

### Manual Installation (Optional)

If you prefer manual setup, the hook script is available at:
```bash
~/.claude/hooks/glm-detector.sh
```

To verify hook installation:
```bash
# Check if hook is configured
cat ~/.claude/settings.json | grep -A 5 "UserPromptSubmit"
```

## Configuration

### Config File Structure

**Global:** `~/.glm/config.json`
**Local:** `{project}/.glm/config.json`

```json
{
  "apiKey": "your-glm-api-key",
  "apiModel": "glm-4.6",
  "apiBaseUrl": "https://api.z.ai/api/coding/paas/v4/chat/completions",
  "apiPlan": "max",
  "maxRetries": 5,
  "timeout": 120000,
  "debug": false,
  "useQuality": true,
  "verboseLog": true,
  "enableLogging": true
}
```

### Environment Variables (Fallback)

If config.json doesn't have a value, GLM checks environment variables:

```bash
export GLM_API_KEY="your-api-key"
export GLM_API_MODEL="glm-4.6"
export GLM_DEBUG="true"
```

### Configuration Priority

1. Local config: `{project}/.glm/config.json`
2. Global config: `~/.glm/config.json`
3. Environment variables: `GLM_API_KEY`, etc.
4. Default values

## Usage Limits and Plans

GLM CLI supports three API plan tiers:

| Plan | Prompts/5h | Concurrent | Use Case |
|------|-----------|------------|----------|
| **Lite** | ~120 | 5 | Light/hobby use |
| **Pro** | ~600 | 5 | Regular development |
| **Max** | ~2400 | 5 | Heavy/team use (default) |

**Note:** Each prompt ≈ 15-20 model calls internally.

### Setting Your Plan

Edit `~/.glm/config.json`:

```json
{
  "apiPlan": "pro"
}
```

Or set environment variable:

```bash
export GLM_API_PLAN="pro"
```

### Monitoring Usage

View 5-hour usage window:

```bash
glm stats
```

Output:

```
5-Hour Usage Window
────────────────────────────────────────────────────────────────────────────────
Plan: PRO
Limit: 600 prompts per 5 hours
Used:  145 prompts (24.2%)

[█████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 24.2%
```

## Claude Code Integration

When you run `glm init` (global or local), it automatically:

1. **Updates CLAUDE.md** with GLM usage guidelines
2. **Preserves existing content** (only adds/updates GLM section)

### Using in Claude Code

The CLAUDE.md section includes:
- **Complexity guidelines** (Simple < 50 lines, Medium < 200 lines, Complex > 500 lines)
- **Profile list** (default, frontend-design, api-integration, database-ops, web-crawler)
- **Usage example**

This helps Claude understand when to suggest using GLM for appropriate tasks.

## Usage Statistics

Track API usage with detailed statistics:

```bash
# View 5-hour usage + daily stats (both commands work)
glm stats
glm usage

# View monthly stats
glm stats --monthly
glm usage --monthly
```

**Statistics include:**
- **5-Hour Usage Window**: Current usage vs plan limit with progress bar
- **Historical Stats**: Daily/monthly aggregated data (in your local timezone)
- **Profile breakdown**: Top 5 profiles used
- Request counts (total, successful, failed)
- **Token usage** (prompt, completion, total) - **NEW in v0.7.0**

**Log locations:**
- Token stats: `~/.glm/usage.jsonl`
- Chat logs: `~/.glm/logs/chat-*.jsonl`

### Token Usage Tracking (NEW in v0.7.0)

**Automatic token tracking when using `-o` flag:**

```bash
# This captures token usage statistics
glm -q "create API client" -o api.py

# Check usage
glm stats
```

**Output example:**
```
Date          Requests  Success  Failed  Total Tokens    Prompt  Completion
────────────────────────────────────────────────────────────────────────────────
2024-12-10          10        10       0         45,231    32,148      13,083
```

**How it works:**
- **Interactive mode** (`glm -q "prompt"`): Streaming output, no token tracking
- **File output mode** (`glm -q "prompt" -o file.py`): Non-streaming, **captures token usage**
- No configuration needed - automatically optimizes for each use case

### Controlling Output Length (NEW in v0.7.0)

**Use `--max-tokens` to control output size and costs:**

```bash
# Limit to 1000 tokens (good for simple functions)
glm -q "simple validation function" -o validator.py -m 1000

# Use full capacity for complex files (default: 20000)
glm -q "comprehensive REST API" -o api.py -m 20000

# Default is 20K, so no flag needed for complex tasks
glm -q "large application" -o app.py
```

**Benefits:**
- **Cost control**: Limit tokens for simple tasks
- **No truncation**: Default 20K handles complex files (increased from 4K)
- **Flexible**: Override per-request based on complexity

## Project Structure

```
{user-home}/
├── .glm/                    # Global config (if using glm init -g)
│   ├── config.json
│   ├── usage.jsonl          # Token usage statistics (centralized)
│   ├── logs/
│   │   ├── chat-2025-12-01T10-30-45-123Z.jsonl
│   │   ├── chat-2025-12-01T11-15-22-456Z.jsonl
│   │   └── ...              # Per-run chat logs (detailed)
│   ├── instructions/
│   │   └── quality.txt
│   └── profiles/
│       ├── default/
│       ├── frontend-design/
│       ├── api-integration/
│       ├── database-ops/
│       └── web-crawler/
└── .claude/
    └── CLAUDE.md            # GLM section added here

{project}/
├── .glm/                    # Local config (if using glm init)
│   ├── config.json
│   ├── instructions/
│   └── profiles/
└── .claude/
    └── CLAUDE.md
```

## Development

### Prerequisites
- Node.js 18+
- npm

### Setup

```bash
git clone https://github.com/your-org/glm-coding.git
cd glm-coding
npm install
```

### Building

```bash
npm run build          # Build CLI
npm run dev            # Watch mode
npm run typecheck      # Type check without build
npm run clean          # Clean build output
```

### Testing Locally

```bash
# Link package globally
npm link

# Test in a directory
cd /tmp/test
glm init
glm -q "hello world function"

# Unlink when done
npm unlink -g glm-coding
```

### Repository Structure

```
glm-coding/
├── src/
│   └── cli/              # CLI source code
│       ├── cli.ts        # Entry point & router
│       ├── commands/     # Command implementations
│       │   ├── generate.ts   # Code generation
│       │   ├── init.ts       # Installation
│       │   ├── stats.ts      # Statistics
│       │   ├── help.ts       # Help
│       │   └── version.ts    # Version
│       └── core/         # Core modules
│           ├── glmClient.ts     # API client
│           ├── config.ts        # Config loader
│           ├── instructions.ts  # Quality loader
│           ├── profiles.ts      # Profile loader
│           ├── usageLogger.ts   # Usage logging
│           └── ...
├── templates/            # Installed to ~/.glm/ or {project}/.glm/
│   ├── instructions/
│   │   └── quality.txt
│   └── profiles/
│       ├── default/
│       ├── frontend-design/
│       ├── api-integration/
│       ├── database-ops/
│       └── web-crawler/
├── dist/                 # Build output (gitignored)
├── package.json
├── tsconfig.json
└── tsconfig.cli.json
```

### Making Changes

1. Edit `src/cli/` files
2. Run `npm run build`
3. Test with `npm link`
4. Commit and push

### Publishing

```bash
npm version patch  # or minor, major
npm publish
```

## Migration from MCP Server

If you're migrating from the old MCP server version:

```bash
# Old MCP installation will be detected
glm init -g

# Remove old MCP server manually
rm -rf ~/.claude/mcp-servers/glm-coding
# Remove "glm-coding" from ~/.claude/mcp.json
```

## Examples

### Simple Function

```bash
glm -q "Python function to calculate fibonacci"
```

### React Component

```bash
glm -q "React card component with image, title, description" \
  -p frontend-design \
  -o components/Card.tsx
```

### API Client

```bash
glm -q "REST client for GitHub API with auth, pagination, error handling" \
  -p api-integration \
  -o github_client.py
```

### Database Schema

```bash
glm -q "PostgreSQL schema for e-commerce with users, products, orders" \
  -p database-ops \
  -o schema.sql
```

## License

MIT

## Support

For issues and questions, visit [GitHub Issues](https://github.com/your-org/glm-coding/issues).
