# Guild CLI Design

Command-line interface for Guild.ai - manage authentication, runtime environments, and AI agents.

---

## What Exists Today

The CLI currently provides these core capabilities:

### Authentication

OAuth device flow with secure token storage:

```bash
guild auth login   # Browser-based OAuth device flow
guild auth logout  # Clear credentials
guild auth status  # Check authentication state
```

- OAuth device flow (browser verification, like pairing a TV remote)
- System keyring storage (Keychain on macOS, libsecret on Linux, Credential Manager on Windows)
- Bearer tokens (no plaintext credentials)
- Credentials never touch the filesystem

### Environment Management

Create and manage runtime environments:

```bash
guild env test                  # Test server connectivity
guild env create                # Create environment
guild env list                  # List all environments
guild env destroy <env-id>      # Destroy environment
guild env cleanup               # Remove failed environments
guild env exec <env-id> <cmd>   # Execute command in environment
guild env go                    # Create environment and connect interactively
```

### Agent Management

Manage agents via the GuildCore API with git-backed versioning:

```bash
guild agent init --name my-agent --template LLM   # Initialize a new agent
guild agent clone owner/agent-name                 # Clone an existing agent
guild agent list                                   # List all agents
guild agent search "analytics"                     # Search published agents
guild agent get [identifier]                       # Get agent details
guild agent versions [identifier]                  # List all versions
guild agent code [identifier]                      # Fetch latest published code
```

**Version Control** (git-backed):

```bash
guild agent save --message "Initial version"              # Save as draft
guild agent save --message "v1.0" --wait --publish        # Save + validate + publish
guild agent pull                                           # Pull remote changes
```

**How it works:**

- Each agent stores code in a git repository (managed by GuildCore)
- `save` commits and pushes code, creating a new version
- Versions can be DRAFT or PUBLISHED
- `code` fetches the latest version's files
- Every version has a git commit SHA for traceability

All agent commands interact with the GuildCore backend API. The CLI is a remote client, similar to the web UI.

### Chat

Interactive chat with streaming:

```bash
guild chat                    # Interactive chat session
guild chat "your message"     # One-shot message
guild agent test              # Test agent interactively
guild agent chat "Hello"      # Send single message to agent
```

### Diagnostics

```bash
guild doctor    # Check CLI setup and diagnose issues
guild version   # Show CLI version info
guild --version # Show version number
```

---

## Design Principles

### Secure Authentication

- OAuth device flow instead of API keys
- System keyring storage (never filesystem)
- Per-user authentication (no shared credentials)

### JSON Output

All commands output JSON for both human and programmatic use:

```bash
# Read by humans
guild env create

# Parse in scripts
ENV_ID=$(guild env create | jq -r .environment_id)
guild env exec $ENV_ID -- python script.py
```

### Simple Interface

No YAML files. No terraform. No kubectl. Just simple commands.

---

## Architecture

```
┌──────────────────────────────────────────┐
│              Guild CLI                   │
│  ┌────────────────────────────────────┐  │
│  │  Commander.js (CLI framework)      │  │
│  │  TypeScript (type-safe dev)        │  │
│  │  Axios (HTTP client)               │  │
│  │  @napi-rs/keyring (token storage)  │  │
│  └────────────┬───────────────────────┘  │
└───────────────┼──────────────────────────┘
                │
                │ HTTPS
                ▼
┌───────────────────────────────────────────┐
│            GuildCore API                  │
│  - Authentication (OAuth)                 │
│  - Environment management                 │
│  - Agent CRUD + versioning (git-backed)   │
│  - Session management                     │
└────────────┬──────────────────────────────┘
             │
             │
             ▼
┌────────────────────────┐
│  Runtime Service       │
│  - Agent execution     │
│  - WebSocket streaming │
│  - Session registries  │
└────────────────────────┘
```

The CLI is a thin client that communicates with the GuildCore API (default: `https://app.guild.ai/api`).

---

## Authentication Flow

```
Developer -> CLI: guild auth login
CLI -> GuildCore: POST /oauth/device-flow/initiate
GuildCore -> CLI: {code, auth_url}
CLI -> Developer: Display URL and code
Developer: Opens browser, verifies code
CLI -> GuildCore: GET /oauth/device-flow/poll/{code} (polling)
GuildCore -> CLI: {access_token}
CLI -> Keyring: Store token
CLI -> Developer: Authenticated
```

Token is stored in system keyring and automatically included in subsequent API calls.

---

## Environment Management Flow

```
Developer -> CLI: guild env create
CLI -> Keyring: Get auth token
CLI -> GuildCore: PUT /env {base_image: "guildcode/guild-runtime:latest"}
GuildCore -> CLI: {environment_id, status, name}
CLI -> Developer: Environment created
```

Environments are Docker containers managed by GuildCore. The CLI provides a simple interface to create, list, execute commands in, and destroy environments.

---

## Integration with Developer Tools

The CLI integrates with AI coding assistants like Claude Code, Cursor, and others. Run `guild setup` to install Claude Code skills into your project, or `guild setup --codex` to install Codex skills.

The CLI also exposes a [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server via `guild mcp`. This gives coding assistants direct access to Guild's API — searching agents, managing workspaces, reading contexts, and starting sessions — without leaving the editor. `guild setup` configures it by default; use `--no-mcp` to skip.

**Typical Workflow:**

1. Initialize agent: `guild agent init --name my-agent --template LLM`
2. Write agent code locally in your editor
3. Test interactively: `guild agent test --ephemeral`
4. Save as draft: `guild agent save --message "WIP"`
5. Iterate on code and save new drafts
6. Publish stable version: `guild agent save --message "v1.0" --wait --publish`
7. Clone on another machine: `guild agent clone owner/my-agent`
