# CLI Reference

The `veil` command controls the server and provides utilities for managing agents and credentials.

---

## Installation

```bash
# From the VeilCli repo directory:
npm link                   # system-wide (requires npm prefix write access)
# or
ln -sf "$(pwd)/cli/index.js" ~/.local/bin/veil
chmod +x cli/index.js
```

Verify:
```bash
veil --version
# VeilCLI v0.1.0
```

---

## Commands

### `veil start`

Start the REST API server in the current (or specified) directory.

```bash
veil start [--port <n>] [--folder <path>] [--secret <token>] [--ably]
```

| Flag | Default | Description |
|------|---------|-------------|
| `--port` | `5050` (or from settings.json) | Port to listen on |
| `--folder` | current directory | Workspace directory (must contain `.veil/`) |
| `--secret` | none | Require `X-Veil-Secret: <token>` on all API requests |
| `--ably` | false | Enable Ably remote access |

**What happens on start:**
1. Loads settings from all layers (global → project → local → CLI flags)
2. Starts the Express HTTP server
3. Writes `.veil/runtime.pid`

The process stays in the foreground. Use SIGINT (Ctrl+C) or `veil stop` to shut down gracefully.

**Examples:**
```bash
veil start
veil start --port 5051 --folder ~/projects/my-bot
veil start --secret supersecret123
```

---

### `veil stop`

Send SIGTERM to the running server. The server will clean up and exit gracefully.

```bash
veil stop
```

Reads `.veil/runtime.pid` to find the process. Must be run from the same workspace directory as `veil start`.

---

### `veil status`

Check whether the server is running.

```bash
veil status
```

Reads `.veil/runtime.pid` and checks if the process exists.

Output examples:
```
✓ Server is running (PID: 12345)
! PID file exists but process 12345 is not running (stale PID file)
! No running server (no PID file found)
```

---

### `veil agents`

Manage agents in the current workspace.

#### `veil agents list`

List all agents:
```bash
veil agents list
# or
veil agents
```

Output (table):
```
Agents (3)
name         description                    model                    source
hello        A simple conversational agent  moonshotai/kimi-k2.6     project
assistant    General-purpose agent          moonshotai/kimi-k2.6     project
coder        Code analysis agent            moonshotai/kimi-k2.6     project
```

#### `veil agents inspect <name>`

Show full details for a single agent including modes and the first 500 chars of `AGENT.md`:

```bash
veil agents inspect assistant
```

#### `veil agents create`

Interactive agent creation wizard. Currently shows instructions to create manually.

---

### `veil login`

Save an API key to `auth.json`.

```bash
veil login --key <api-key> [--global]
```

| Flag | Description |
|------|-------------|
| `--key` | API key to save (required) |
| `--global` | Save to `~/.veil/auth.json` instead of `.veil/auth.json` |

After login, manually edit `auth.json` to set the `model` field.

**Examples:**
```bash
veil login --key sk-or-v1-...          # project-level
veil login --key sk-or-v1-... --global # global (shared across workspaces)
```

---

### `veil import`

Import agents from other formats (Claude Code, raw JSON). Not yet fully implemented — shows the source path for manual processing.

```bash
veil import --type <type> --source <path>
```

---

## Local Instance Commands

These commands talk to the Veil server **already running in the current project** over its local HTTP API — they do not start anything. They locate the instance from `.veil/runtime.pid` and resolve its port automatically:

- The port is `settings.json`'s `port` (default `5050`).
- If the project is managed by Veil Desktop, the `cliPort` value in `.veil-desktop/ports.json` takes precedence over the settings port (Desktop assigns a per-project port).

Run them from the same workspace directory as `veil start`. If no instance is running (missing or stale PID file), they exit with an error.

### `veil send`

Fire-and-forget a message to the running instance. The command dispatches the message and **returns immediately** — the agent turn keeps processing server-side with no client attached.

```bash
veil send "<message>" (--session <id> | --agent <name>)
```

| Flag | Description |
|------|-------------|
| `--session` | Deliver to an existing session. The agent is taken from the session row. |
| `--agent` | Start a **new** session with this agent and deliver the message. |

Provide exactly one of `--session` or `--agent`. Under the hood this POSTs to `/agents/:name/chat` with `fireAndForget: true`, then prints the resolved session id. Follow progress with `veil state --session <id>`.

```bash
veil send "Summarise today's commits" --agent assistant
veil send "and now open a PR" --session sess_4f3a1b9c2d8e7f01
```

### `veil sessions`

List the sessions of the running instance in this project.

```bash
veil sessions [--agent <name>]
```

| Flag | Description |
|------|-------------|
| `--agent` | Only show sessions for this agent. |

Each row shows a running/idle/closed flag, the session id, agent name, optional instance label, and last-activity timestamp. Running sessions are detected via `GET /sessions/streaming`.

### `veil state`

Show a single session's state: status, context/token usage, cost, message count, and the last few messages.

```bash
veil state --session <id>
```

Status shows `RUNNING` when a chat loop is active on the session, otherwise the stored status (`active`, `suspended`, or `closed`).

### `veil suspend` / `veil resume`

Park or reactivate a session.

```bash
veil suspend --session <id>
veil resume  --session <id>
```

- **`suspend`** cancels any running turn on the session, then rejects new messages and skips scheduled wake-ups until resumed. Queued inter-agent messages stay pending. Prints whether a running turn was cancelled.
- **`resume`** reactivates the session (status back to `active`) and drains any inter-agent messages that queued up while it was parked.

These map to `POST /sessions/:id/suspend` and `POST /sessions/:id/resume`.

---

## Global Flags

| Flag | Description |
|------|-------------|
| `--help`, `-h` | Show usage |
| `--version` | Show VeilCLI version |

---

## Interactive TUI Client

The `connect.js` client in `VeilCli_TESTS/cli-app/` is a separate interactive tool for exploring and testing a running server.

### Usage

```bash
# Open interactive menu (arrow keys or number keys)
node connect.js

# Jump straight to a chat REPL
node connect.js chat <agent>

# One-shot chat (print and exit)
node connect.js chat <agent> "Your message here"

# Print tables and exit
node connect.js status
node connect.js agents
node connect.js sessions

# Custom server URL
node connect.js --url http://localhost:5051 chat simple
```

### Interactive menu

When run with no arguments, shows a full-screen menu:

```
┌──────────────────────────────────────────┐
│  VeilCLI Connect  http://localhost:5051│
├──────────────────────────────────────────┤
│  Main Menu  http://localhost:5051        │
├──────────────────────────────────────────┤
│                                          │
│  ❯ 1. 💬  Chat         Interactive …    │
│    2. 🤖  Agents       List available …  │
│    3. 📋  Sessions     Recent chat …     │
│    4. ℹ️   Status       Server info       │
│    5. ✕   Quit                           │
│                                          │
├──────────────────────────────────────────┤
│  [↑↓ / number] move  [Enter] select  …  │
└──────────────────────────────────────────┘
```

**Navigation**: arrow keys or type the number, Enter to select, q to go back.

### Chat REPL commands

Inside the chat interface:

| Command | Action |
|---------|--------|
| `/new` | Start a new session (clear history) |
| `/clear` | Clear the display |
| `/session` | Show current session ID |
| `/back` or Ctrl+C | Return to menu |

### Environment variables

| Variable | Description |
|----------|-------------|
| `VEIL_URL` | Server URL (default: `http://localhost:5051`) |
| `VEIL_SECRET` | Auth secret header value |
