# XClawLink CLI — AI Agent Skill Guide

## Metadata
- **name**: xclawlink-remote-exec
- **version**: v1.0.13
- **commit**: y1ai
- **description**: Execute commands, transfer files, manage tasks, and self-update on remote devices via XClawLink CLI. All output is JSON-structured for machine parsing.
- **triggers**: `remote execute`, `run on server`, `upload file`, `download file`, `check device`, `system info`, `scheduled task`, `update cli`, `self-update`, `config setup`, `dry run command`

---

## Architecture

```
AI Agent -> CLI (xclawlink) -> Relay -> Proxy -> Agent (remote device)
                                    |
                                 P2P tunnel (KCP) -- preferred, auto-fallback to WebSocket
```

Transport selection: P2P (KCP) always preferred. If P2P fails, falls back to WebSocket relay.

---

## Authentication

Three methods, priority order:

| Priority | Method | How |
|----------|--------|-----|
| 1 | Config file | `config.yaml` with `token` and `otp` fields |
| 2 | Environment | `CLI_TOKEN` + `CLI_OTP` (credential isolation) |
| 3 | CLI flags | `--token <TOKEN>` + `--otp <OTP>` |

---

## Global Options

| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `-d, --device-id` | string | required | CLI device identifier (format: CLI-NNNNNN) |
| `--token` | string | from config | JWT authentication token |
| `--otp` | string | from config | One-time password for device auth |
| `--tenant-id` | string | from config | Tenant identifier |
| `--output` | string | `json` | Output format: `json` (recommended), `table`, `text` |
| `-p, --persist` | bool | `false` | Route through persistent daemon process |
| `--config` | string | `./config.yaml` | Config file path |

**Credential isolation**: `CLI_TOKEN` and `CLI_OTP` environment variables override config values.

**Daemon mode** (`-p`/`--persist`): Routes all operations through a background daemon process that maintains persistent P2P tunnels and sessions. Reduces connection setup overhead for frequent operations. Daemon auto-starts if not running. Worker pool: 4 workers (configurable). Idle timeout: 30 min.

---

## Commands

### 1. `execute` -- Run command on remote device

```
xclawlink execute <DEVICE_ID> "<COMMAND>" [flags]
```

**Execution modes**:

| Flag | Type | Values | Description |
|------|------|--------|-------------|
| `--mode` | string | `once` (default) | Immediate execution |
| | | `scheduled` | One-time scheduled execution (requires `--at`) |
| | | `interval` | Recurring execution (requires `--every`, optional `--count`) |

**Scheduling flags** (for `scheduled` and `interval` modes):

| Flag | Type | Example | Description |
|------|------|---------|-------------|
| `--at` | string | `"2026-06-01 02:00:00"` | Scheduled time (format: `YYYY-MM-DD HH:MM:SS`) |
| `--every` | string | `"5m"`, `"1h"`, `"30s"`, `"1h30m"` | Interval between runs. Units: `s`(sec), `m`(min), `h`(hour). Combinable: `1h30m`, `90s` |
| `--count` | int | `10` | Max executions (0 = unlimited) |

**Shell & sandbox flags**:

| Flag | Description |
|------|-------------|
| `--shell` | Enable shell execution: `sh -c "<command>"` (allows pipes, redirects, variable expansion) |
| `--sandbox` | Network namespace isolation (**requires** `--shell`) |
| `--target` | Resource policy target: `"host:port[:protocol]"` (e.g. `"192.168.1.100:8080/tcp"`) |

**Safety flags**:

| Flag | Description |
|------|-------------|
| `--dry-run` | Preview write operations without executing. Returns what *would* happen, no side effects. |
| `--confirm <ID>` | Confirmation/approval ID to authorize a write operation. Bypasses dry-run and local hard-block. |

**Mode matrix**:

| Flags | Behavior |
|-------|----------|
| *(none)* | Direct exec on host |
| `--shell` | Shell pipeline: `sh -c "<command>"` |
| `--shell --sandbox` | Shell + network namespace isolation |
| `--shell --sandbox --target "host:port/tcp"` | Sandbox with specific network whitelist |
| `--dry-run` | Preview mode — returns planned execution without side effects |
| `--confirm <APPROVAL_ID>` | Authorize execution bypassing dry-run and destructive-command blocks |

> **⚠️ Approval-flow warning**: High-risk commands may trigger proxy-side approval. The CLI will **block up to 180 seconds** waiting for an approver to confirm. If no approval arrives, the command returns `exit_code: -1` with `"approval rejected"` or `"approval expired"`. AI agents should set appropriate timeouts and handle this gracefully — do NOT retry indefinitely.

**Response** (JSON):
```json
{
  "device_id": "AGT-000016",
  "command": "whoami",
  "exit_code": 0,
  "stdout": "root\n",
  "stderr": "",
  "error": null,
  "duration": "1.2s",
  "idempotent": false
}
```

**Exit codes**:
- `0` = success
- `1-255` = command failed (command's own exit code)
- `-1` = execution error (agent unreachable, timeout, rejected by policy, etc.)

**Examples**:
```bash
# Basic command
xclawlink execute AGT-000016 "whoami"

# Dry-run preview (no execution)
xclawlink execute AGT-000016 "rm -rf /tmp/old_logs" --dry-run

# Confirm after approval
xclawlink execute AGT-000016 "rm -rf /tmp/old_logs" --confirm "APPROVAL-abc123"

# Shell pipeline
xclawlink execute AGT-000016 "ps -ef | grep nginx > /tmp/nginx.lst" --shell

# Network-restricted sandbox
xclawlink execute AGT-000016 "ping -c 1 1.1.1.1" --shell --sandbox
xclawlink execute AGT-000016 "curl http://192.168.1.100:8080/api" --shell --sandbox --target "192.168.1.100:8080/tcp"

# One-time scheduled
xclawlink execute AGT-000016 "date" --mode scheduled --at "2026-06-01 02:00:00"

# Recurring interval
xclawlink execute AGT-000016 "free -m" --mode interval --every "5m" --count 10
xclawlink execute AGT-000016 "df -h" --mode interval --every "1h"
```

### 2. `devices` -- List online devices

```
xclawlink devices
```

**Response**:
```json
{
  "devices": [
    {"device_id": "AGT-000016", "hostname": "web-01", "os": "linux", "arch": "amd64", "status": "online"}
  ],
  "idempotent": true
}
```

### 3. `info` -- System information

```
xclawlink info <DEVICE_ID>
```

**Response**:
```json
{
  "system_info": {
    "device_id": "AGT-000016",
    "cpu_usage": 12.5,
    "memory_usage": 45.2,
    "disk_usage": 67.8,
    "uptime": "12 days, 3:15"
  }
}
```

### 4. `upload` -- Upload file to remote device

```
xclawlink upload <DEVICE_ID> <LOCAL_FILE> <REMOTE_PATH> [--progress <N|bar|0>] [--confirm <ID>]
```

**Progress flag** (`--progress`):

| Value | Behavior |
|-------|----------|
| `"bar"` | Graphical ANSI progress bar |
| `N` (int) | JSON milestone every N% (e.g. `5` = every 5%) |
| `"0"` / `"off"` / `"false"` | Disable progress output |
| *(default)* | `5` (JSON milestones every 5%) |

**`--confirm`**: Approval ID to authorize the upload (bypasses dry-run / destructive operation checks).

**JSON progress format**:
```json
{"event":"progress","file":"upload.dat","op":"upload","pct":50,"transferred":524288,"total":1048576,"speed_bps":5242880,"elapsed_ms":100}
```

**Response**:
```json
{
  "device_id": "AGT-000016",
  "operation": "upload",
  "file_path": "/tmp/upload.dat",
  "file_size": 1048576,
  "duration": "4.2s",
  "exit_code": 0
}
```

### 5. `download` -- Download file from remote device

```
xclawlink download <DEVICE_ID> <REMOTE_FILE> <LOCAL_PATH> [--progress <N|bar|0>] [--confirm <ID>]
```

Same `--progress` flag and response format as upload. `--confirm` works identically to upload.

### 6. `schedules` -- Manage scheduled tasks

```
xclawlink schedules list <DEVICE_ID>
xclawlink schedules status [<DEVICE_ID>] [<TASK_ID>] [flags]
xclawlink schedules cancel <DEVICE_ID> <TASK_ID>
```

**`schedules status` modes**:

| Mode | Flag | Behavior |
|------|------|----------|
| Default | *(none)* | Single query, formatted output, exit |
| Stream | `--stream` | JSON line per poll, exits on `completed`/`failed`/`cancelled` |
| Follow | `--follow` | Overwrite progress bar per poll, exits on `completed`/`failed` |
| Watch | `--watch` `-w` | Keep polling after completion (for interval tasks). Exits when `current_runs >= max_runs` or `cancelled`/`expired` |

**`schedules status` flags**:

| Flag | Type | Default | Description |
|------|------|---------|-------------|
| `--stream` | bool | `false` | Stream JSON lines per poll (pipe-friendly) |
| `--follow` | bool | `false` | Interactive progress bar with stdout preview |
| `--watch` `-w` | bool | `false` | Keep watching after completion (for interval tasks) |
| `--device` | string | `""` | Device ID to query all tasks for |
| `--poll-interval` | string | `5s` | Poll interval (min 500ms, e.g. `2s`, `500ms`) |
| `--max-polls` | int | `0` | Max polls (0=unlimited, capped 1000) |

**Dispatch**:

| Flags | Stops on |
|-------|----------|
| `--stream` | `completed`, `failed`, `cancelled`, `expired` |
| `--stream --watch` | `cancelled`, `expired`, `current_runs >= max_runs` |
| `--follow` | Same as `--stream` |
| `--follow --watch` | Same as `--stream --watch` |

Safeguards: max 1000 polls, 30 min timeout, 3 connection retries.

**`schedules list` response**:
```json
{
  "data": [
    {
      "id": "schedule_cmd_1783264669184976000",
      "device_id": "AGT-000006",
      "command": "date >> /tmp/time.log; tail -1 /tmp/time.log",
      "exec_mode": "interval",
      "interval": "5s",
      "max_runs": 10,
      "current_runs": 3,
      "status": "active",
      "last_run_time": "2026-07-05T23:15:20+08:00",
      "next_run_time": "2026-07-05T23:15:25+08:00"
    }
  ]
}
```

**`schedules status` (default) response**:
```json
{
  "command": "date >> /tmp/time.log; tail -1 /tmp/time.log",
  "device_id": "",
  "exit_code": 0,
  "progress": 100,
  "started_at": "2026-07-05T23:15:20.44743131+08:00",
  "status": "completed",
  "stderr": "",
  "stdout": "Sun Jul  5 23:15:20 CST 2026",
  "task_id": "schedule_cmd_1783264669184976000",
  "updated_at": "2026-07-05T23:15:20.447432365+08:00",
  "current_runs": 3,
  "max_runs": 10
}
```

**`--stream` output** (newline-delimited JSON, one object per poll):
```json
{"status":"running","task_id":"schedule_cmd_1783264669184976000","progress":0,"stdout":""}
{"status":"completed","task_id":"schedule_cmd_1783264669184976000","exit_code":0,"progress":100,"stdout":"Sun Jul  5 23:15:20 CST 2026","current_runs":3,"max_runs":10}
{"status":"running","task_id":"schedule_cmd_1783264669184976000","progress":0,"stdout":""}
{"status":"completed","task_id":"schedule_cmd_1783264669184976000","exit_code":0,"progress":100,"stdout":"Sun Jul  5 23:15:25 CST 2026","current_runs":4,"max_runs":10}
```

**`--follow` output** (single overwriting line, changes each poll):
```
Task schedule_cmd_1783264669184976000 | Status: running | [░░░░░░░░░░░░░░░░░░░░] 0%
Task schedule_cmd_1783264669184976000 | Status: completed | [████████████████████] 100% | Sun Jul  5 23:15:20 CST 2026
```

**Interval fields** (in status response):
| Field | Description |
|-------|-------------|
| `current_runs` | Executions completed so far |
| `max_runs` | Total runs (from `--count`), 0=unlimited |
| `status` | `completed` = last run done (more may follow), `running` = executing now |

**Examples**:
```bash
# List all scheduled tasks for a device
xclawlink schedules list AGT-000006

# Query specific task status (single query, formatted output)
xclawlink schedules status AGT-000006 schedule_cmd_1783264669184976000

# Stream JSON lines until completion (auto-exit on completed/failed)
xclawlink schedules status AGT-000006 schedule_cmd_1783264669184976000 --stream --poll-interval 2s

# Follow with live progress bar (auto-exit on completion)
xclawlink schedules status AGT-000006 schedule_cmd_1783264669184976000 --follow --poll-interval 5s

# Watch interval task across all runs (auto-exit when current_runs >= max_runs)
xclawlink schedules status AGT-000006 schedule_cmd_1783264669184976000 --follow -w --poll-interval 2s

# Stream + pipe to jq for status filtering
xclawlink schedules status AGT-000006 schedule_cmd_1783264669184976000 --stream -w --poll-interval 2s | jq .status

# Query all tasks for a device via flag
xclawlink schedules status --device AGT-000006

# Cancel a scheduled task
xclawlink schedules cancel AGT-000006 schedule_cmd_1783264669184976000
```

### 7. `version` -- Version info

```
xclawlink version
```

**Response**:
```json
{"version": "v1.0.13", "commit": "y1ai", "build": "release"}
```

### 8. `update` -- Self-update the CLI binary

```
xclawlink update [flags]
```

| Flag | Type | Description |
|------|------|-------------|
| `--check` | bool | Only check for updates, do not install |
| `-y, --yes` | bool | Skip confirmation prompt, install automatically |

Fetches version info from `https://www.xclawlink.com/version.json`, compares against current version. Downloads the appropriate package (tar.gz for Linux, zip for Windows) and replaces the current binary atomically.

> **Note**: Skipped in debug builds (`Version == "dev"`). The update checks the `cli` section of `version.json`, matching by `GOOS_GOARCH` key (e.g. `linux_amd64`, `windows_amd64`).

**Examples**:
```bash
# Check for updates
xclawlink update --check
# Output: "Update available: v1.0.12 -> v1.0.13" or "Already up to date (v1.0.13)"

# Auto-install update
xclawlink update -y
```

### 9. `config-start` -- Interactive configuration setup

```
xclawlink config-start [flags]
```

Interactive terminal UI for first-time setup. Also supports non-interactive mode via flags:

| Flag | Type | Description |
|------|------|-------------|
| `--device` | string | CLI device ID (format: CLI-NNNNNN) |
| `--otp` | string | One-time password (8-32 alphanumeric chars) |
| `--tenant` | string | Tenant identifier |
| `--token` | string | JWT authentication token |
| `--token-file` | string | Read token from file |
| `--skip` | bool | Validate only — check config without writing |

Writes validated config to `config.yaml`. When any of `--device`/`--tenant`/`--token` are supplied, runs non-interactively (skips TUI). OTP must match `^[a-zA-Z0-9]{8,32}$`.

**Examples**:
```bash
# Interactive setup
xclawlink config-start

# Non-interactive setup
xclawlink config-start --device CLI-000001 --tenant tenant-abc --token eyJ... --otp abc12345

# Validate without writing
xclawlink config-start --skip --device CLI-000001 --tenant tenant-abc --token eyJ...
```

### 10. `daemon` -- Background daemon management

```
xclawlink daemon start      # Fork daemon in background
xclawlink daemon stop       # Stop daemon via IPC
xclawlink daemon status     # Check daemon status (uptime, session, P2P)
xclawlink daemon run        # Foreground run (used internally by daemon start)
```

**Daemon status response**:
```json
{
  "uptime": "2h 15m",
  "session_valid": true,
  "p2p_connected": true,
  "active_ops": 0
}
```

Use `-p`/`--persist` with any command to route through the daemon instead of starting it manually:
```bash
xclawlink execute AGT-000016 "uptime" -p
```

---

## Error Handling

### Process-Level Exit Codes

The CLI process itself exits with one of three codes, distinct from the JSON `exit_code` field:

| Exit Code | Constant | Meaning |
|-----------|----------|---------|
| `0` | `ExitSuccess` | Operation succeeded (JSON `exit_code` is the remote command's own code) |
| `1` | `ExitRejected` | Business rejection: auth failed, permission denied, OTP invalid, command hard-blocked, approval expired |
| `2` | `ExitError` | System error: network timeout, connection lost, daemon unavailable |

### JSON `exit_code` Semantics

| Value | Meaning |
|-------|---------|
| `0` | Remote command succeeded |
| `1-255` | Remote command failed (command's own exit code) |
| `-1` | Execution error: agent unreachable, timeout, rejected by policy, hard-blocked, approval expired |

### Error Patterns

When `error` field is non-null or `exit_code` is `-1`, check and handle:

| Error Pattern | Cause | Action |
|---------------|-------|--------|
| `command blocked: destructive operation` | CLI-local hard-block (no network roundtrip) | Use `--dry-run` to preview, `--confirm` with approval to proceed |
| `approval rejected` / `approval expired` | Proxy-side approval not granted within 180s | Wait for portal approver, then retry with approval ID |
| `path not in allowed directories` | Agent directory restriction | Use `/tmp/` or `/var/tmp/` (check proxy mode-config for allowed dirs) |
| `command not in allowed list` | Proxy command whitelist | Contact admin to whitelist command |
| `OTP validation failed` | OTP expired or invalid | Rotate OTP in Portal |
| `Network is unreachable` | Sandbox isolation | Add `--target <host:port/proto>` |
| `connection timeout` | Agent offline | Retry later or check `xclawlink devices` |
| `permission denied` | Insufficient privileges | Use `sudo` or check permissions |
| `resource policy: IP not in allowed subnets` | Network policy violation | Adjust `--target` or policy |
| `resource policy: port not in allowed ports` | Port policy violation | Adjust `--target` or policy |
| `resource policy: protocol not allowed` | Protocol policy violation | Adjust `--target` or policy |

### CLI-Local Hard Block

Destructive commands are blocked **client-side** before any network traffic. Blocked commands include: `shutdown`, `reboot`, `mkfs`, `fdisk`, `dd of=/dev/*`, `rm -rf /`, `chmod 777 /`, `chown /`, `systemctl poweroff|halt|reboot`. Returns `exit_code: -1` with `"command blocked"` error in JSON. To bypass, you must supply a valid `--confirm <APPROVAL_ID>` obtained through the Portal approval flow.

---

## Directory Restrictions

Agent only allows operations in `/tmp` and `/var/tmp` by default. Admin can configure per-device directory whitelists in the Proxy management page under Resource Policies.

---

## Python Wrapper

```python
import subprocess, json

def xclawlink_execute(device: str, command: str, *, shell: bool = False,
                       sandbox: bool = False, target: str = None,
                       mode: str = "once", at: str = None,
                       every: str = None, count: int = 0,
                       dry_run: bool = False, confirm: str = None) -> dict:
    """Execute command on remote device via XClawLink CLI."""
    args = ["xclawlink", "execute", device, command, "--output", "json"]
    if shell: args.append("--shell")
    if sandbox: args.append("--sandbox")
    if target: args.extend(["--target", target])
    if mode != "once": args.extend(["--mode", mode])
    if at: args.extend(["--at", at])
    if every: args.extend(["--every", every])
    if count: args.extend(["--count", str(count)])
    if dry_run: args.append("--dry-run")
    if confirm: args.extend(["--confirm", confirm])

    result = subprocess.run(args, capture_output=True, text=True, timeout=30)
    data = json.loads(result.stdout)

    if data.get("error"):
        raise RuntimeError(f"XClawLink error: {data['error']}")
    if data["exit_code"] == -1:
        raise RuntimeError(f"Execution failed")
    if data["exit_code"] != 0:
        raise RuntimeError(f"Exit {data['exit_code']}: {data['stderr']}")

    return data


def xclawlink_devices() -> list[dict]:
    """List online devices."""
    result = subprocess.run(
        ["xclawlink", "devices", "--output", "json"],
        capture_output=True, text=True
    )
    return json.loads(result.stdout)["devices"]


def xclawlink_upload(device: str, local: str, remote: str,
                      progress: str = "0", confirm: str = None) -> dict:
    """Upload file to remote device."""
    args = ["xclawlink", "upload", device, local, remote,
            "--output", "json", "--progress", progress]
    if confirm: args.extend(["--confirm", confirm])
    result = subprocess.run(args, capture_output=True, text=True)
    return json.loads(result.stdout)


def xclawlink_download(device: str, remote: str, local: str,
                        progress: str = "0", confirm: str = None) -> dict:
    """Download file from remote device."""
    args = ["xclawlink", "download", device, remote, local,
            "--output", "json", "--progress", progress]
    if confirm: args.extend(["--confirm", confirm])
    result = subprocess.run(args, capture_output=True, text=True)
    return json.loads(result.stdout)


def xclawlink_info(device: str) -> dict:
    """Get system information from remote device."""
    result = subprocess.run(
        ["xclawlink", "info", device, "--output", "json"],
        capture_output=True, text=True
    )
    return json.loads(result.stdout)


def xclawlink_schedules_list(device: str) -> list[dict]:
    """List scheduled tasks for a device."""
    result = subprocess.run(
        ["xclawlink", "schedules", "list", device, "--output", "json"],
        capture_output=True, text=True
    )
    return json.loads(result.stdout).get("tasks", [])


def xclawlink_schedules_cancel(device: str, task_id: str) -> str:
    """Cancel a scheduled task."""
    result = subprocess.run(
        ["xclawlink", "schedules", "cancel", device, task_id, "--output", "json"],
        capture_output=True, text=True
    )
    return result.stdout.strip()


def xclawlink_update(check_only: bool = False, auto_yes: bool = False) -> dict:
    """Check for or install CLI updates."""
    args = ["xclawlink", "update"]
    if check_only: args.append("--check")
    if auto_yes: args.append("-y")
    result = subprocess.run(args, capture_output=True, text=True)
    return {"stdout": result.stdout.strip()}


def xclawlink_config_start(*, device: str = None, otp: str = None,
                            tenant: str = None, token: str = None,
                            skip: bool = False) -> dict:
    """Interactive or non-interactive config setup."""
    args = ["xclawlink", "config-start"]
    if device: args.extend(["--device", device])
    if otp: args.extend(["--otp", otp])
    if tenant: args.extend(["--tenant", tenant])
    if token: args.extend(["--token", token])
    if skip: args.append("--skip")
    result = subprocess.run(args, capture_output=True, text=True)
    return {"stdout": result.stdout.strip()}
```

---

## Quick Start

```bash
# 1. Initial setup (interactive)
xclawlink config-start

# 2. Check available devices
xclawlink devices

# 3. Get system info
xclawlink info AGT-000016

# 4. Execute a command
xclawlink execute AGT-000016 "systemctl status nginx"

# 5. Dry-run a destructive command (preview, no execution)
xclawlink execute AGT-000016 "rm -rf /tmp/old_logs" --dry-run

# 6. Execute with approval confirmation
xclawlink execute AGT-000016 "rm -rf /tmp/old_logs" --confirm "APPROVAL-abc123"

# 7. Execute in sandbox with network target
xclawlink execute AGT-000016 "curl http://192.168.1.100:8080/api" --shell --sandbox --target "192.168.1.100:8080/tcp"

# 8. Upload a file (with graphical progress bar)
xclawlink upload AGT-000016 ./config.json /tmp/config.json --progress bar

# 9. Download a log
xclawlink download AGT-000016 /var/log/nginx/access.log ./access.log

# 10. Schedule a recurring task
xclawlink execute AGT-000016 "df -h" --mode interval --every "1h"

# 11. Stream task status (auto-exit on completion)
xclawlink schedules status AGT-000016 <TASK_ID> --stream --poll-interval 2s

# 12. Watch interval task with live progress bar
xclawlink schedules status AGT-000016 <TASK_ID> --follow -w --poll-interval 2s

# 13. Cancel a task
xclawlink schedules cancel AGT-000016 <TASK_ID>

# 14. Daemon mode for persistent connections
xclawlink daemon start
xclawlink execute AGT-000016 "uptime" -p

# 15. Check for CLI updates
xclawlink update --check

# 16. Self-update CLI
xclawlink update -y
```
