# Agent Light Remote Installation (for AI Agents)

The local device connection in this guide supports macOS / Linux. Hook examples
are provided for Claude Code, Codex CLI and Comate; preserve existing settings
when merging. Comate requires Python 3 on the remote machine.

This guide is for remote development environments where the Agent runs on a remote server (via VSCode Remote SSH, JetBrains Gateway, etc.) and the Agent Light hardware is connected to the local machine.

## Step 1: Setup remote send script

Run on the remote server:

mkdir -p ~/.agent-light
cat > ~/.agent-light/send.sh << 'SCRIPT'
#!/bin/bash
STATE=${1:-I}

# 计算 session 槽位：slot 为 0-92 数字编号（便于日志阅读），再映射到可打印字符发送
# 字符映射：'!'(33)~'~'(126)，跳过 '*'(42) → 93 个槽，降低多会话碰撞
if [ -n "$AGENT_LIGHT_SID" ]; then
    SID=$AGENT_LIGHT_SID
    SLOT=$AGENT_LIGHT_SID
else
    SLOT=$(( PPID % 93 ))
    code=$(( 33 + SLOT ))
    [ "$code" -ge 42 ] && code=$(( code + 1 ))
    SID=$(printf "\\$(printf '%03o' "$code")")
fi

# 日志记录（方便调试）：slot 为数字编号，sid 为实际发送字符
LOG_FILE="/tmp/agent_light.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null)
echo "[$TIMESTAMP] slot=$SLOT sid=$SID state=$STATE" >> "$LOG_FILE"

# 追加事件到队列（每行一帧），避免同一轮询窗口内多个事件互相覆盖丢失
EVENTS=/tmp/agent_light_events
if [ "$STATE" = "C" ]; then
    printf '*C\n' >> "$EVENTS"
else
    printf '%s%s\n' "$SID" "$STATE" >> "$EVENTS"
fi

# 上限保护：本地长时间未消费时只保留最近 100 行，避免队列膨胀
if [ "$(wc -l < "$EVENTS" 2>/dev/null || echo 0)" -gt 200 ]; then
    tail -100 "$EVENTS" > "$EVENTS.tmp" && mv "$EVENTS.tmp" "$EVENTS"
fi
SCRIPT
chmod +x ~/.agent-light/send.sh

## Step 2: Setup remote HTTP state server

First, check if default port 8547 is available on the remote server:

```bash
ss -tlnp 2>/dev/null | grep :8547 || netstat -tlnp 2>/dev/null | grep :8547
```

If output is empty, port 8547 is free — use it. If occupied, pick another port (e.g., 8548, 8549, ...) and use that port in all subsequent steps. Record the chosen port:

```bash
AGENT_LIGHT_PORT=8547  # change if 8547 is occupied
```

Then create and start the server:

The server keeps an append-only event queue file. On each GET request it atomically
renames the queue file, reads all buffered event frames (one per line, e.g.
`nW\nnP\nnS`), returns them, and the batch is consumed (deleted). The atomic rename
avoids racing with send.sh appends. When there are no new events, it returns an empty
body. Unlike the old mtime-dedup approach, this preserves ALL events that occurred
within a polling window — transient states (`P`/`E`/`S`) are never overwritten and lost.

cat > ~/.agent-light/agent_light_server.py << 'PYEOF'
import os, sys

port = int(os.environ.get('AGENT_LIGHT_PORT', '8547'))
EVENTS = '/tmp/agent_light_events'

if sys.version_info[0] >= 3:
    from http.server import HTTPServer, BaseHTTPRequestHandler
else:
    from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        body = ''
        try:
            # atomic rename before read to avoid racing with send.sh appends
            tmp = EVENTS + '.consuming'
            os.rename(EVENTS, tmp)          # raises if no events queued -> empty
            with open(tmp) as f:
                body = f.read()
            os.remove(tmp)
        except OSError:
            body = ''
        self.send_response(200)
        self.end_headers()
        data = body.encode() if sys.version_info[0] >= 3 else body
        self.wfile.write(data)
    def log_message(self, *args):
        pass

HTTPServer(('0.0.0.0', port), Handler).serve_forever()
PYEOF

AGENT_LIGHT_PORT=${AGENT_LIGHT_PORT:-8547} nohup python ~/.agent-light/agent_light_server.py > /dev/null 2>&1 &

Verify it works: append an event then run `curl http://localhost:$AGENT_LIGHT_PORT` twice.
- After `~/.agent-light/send.sh W`, the first curl returns the queued frame(s) (e.g. `nW`).
- The immediate second call returns an empty body (queue already consumed).
If you get "Connection refused", the port may still be occupied — try another port.

> Note: the event queue is consumed by a single poll client. If the local poll client
> restarts, any un-consumed backlog is delivered on its next pull; frames already
> consumed by a previous instance are not replayed (the next real event re-syncs).

## Step 3: Configure hooks for current agent (on remote server)

Detect which agent is running, then configure accordingly:

### If Claude Code:
Merge the following hooks into `~/.claude/settings.json`.

Light mapping:
- UserPromptSubmit → W (working)
- PreToolUse → W (working)
- PostToolUse → W (working)
- PostToolBatch → W (working)
- SubagentStart → W (working)
- PermissionRequest → P (waiting for approval)
- PermissionDenied → P (denied by auto mode, may retry)
- Notification (permission_prompt / idle_prompt / agent_needs_input) → P (waiting for user)
- StopFailure → E (turn ended on an API error — the only red trigger)
- Stop → I (idle)
- SessionStart → I (idle)
- SessionEnd → I (idle)

Agent Light hooks run synchronously with a short timeout so lifecycle state frames
remain ordered. Background hooks can overlap and let an older state overwrite a
newer one.

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PreToolUse": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PostToolUse": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PostToolBatch": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "SubagentStart": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PermissionRequest": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh P", "timeout": 3 }
        ]
      }
    ],
    "PermissionDenied": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh P", "timeout": 3 }
        ]
      }
    ],
    "Notification": [
      {
        "matcher": "permission_prompt|idle_prompt|agent_needs_input",
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh P", "timeout": 3 }
        ]
      }
    ],
    "StopFailure": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh E", "timeout": 3 }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh I", "timeout": 3 }
        ]
      }
    ],
    "SessionStart": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh I", "timeout": 3 }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh I", "timeout": 3 }
        ]
      }
    ]
  }
}
```

### If Codex CLI:

Merge the following hooks into `~/.codex/hooks.json`.
Reference: [official Codex Hooks documentation](https://learn.chatgpt.com/docs/hooks).

Light mapping:
- UserPromptSubmit / PreToolUse / PostToolUse → W (working)
- PreCompact / PostCompact → W (working)
- SubagentStart / SubagentStop → W (parent turn is still working)
- SessionStart (source=compact) → W (continue working after compaction)
- PermissionRequest → P (waiting for approval)
- SessionStart (source=startup / resume / clear) → I (idle)
- Stop / SessionEnd → I (idle)
- No reliable terminal success or error event → do not emit S or E

Codex supports background hooks, but Agent Light deliberately uses synchronous
hooks with a short timeout. Status frames must preserve lifecycle order; background
hooks may finish out of order and allow an older I/P frame to overwrite a newer W.

```json
{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|clear",
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh I", "timeout": 3 }
        ]
      },
      {
        "matcher": "compact",
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PreToolUse": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PostToolUse": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PreCompact": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PostCompact": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "SubagentStart": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "SubagentStop": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh W", "timeout": 3 }
        ]
      }
    ],
    "PermissionRequest": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh P", "timeout": 3 }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh I", "timeout": 3 }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          { "type": "command", "command": "~/.agent-light/send.sh I", "timeout": 3 }
        ]
      }
    ]
  }
}
```

After installing the hooks, complete the trust review in Codex CLI. If `codex` is
not available in your terminal, install it with the official macOS/Linux installer:

```bash
curl -fsSL https://chatgpt.com/codex/install.sh | sh
```

Start Codex:

```bash
codex
```

When the hook review appears, select:

```text
2. Trust all and continue
```

If the review does not open automatically, run `/hooks` in Codex CLI. After the
hooks are trusted, restart the Codex session in VS Code.

### Other Agents:
Cursor, CodeBuddy and TRAE require a separate integration. Do not install an
empty or guessed hooks file using this guide. Explain the limitation and consult
the installed Agent's Hook documentation before adapting the configuration.

### If Comate:
Create `~/.agent-light/comate-stop.py` to map the Stop event's status. Confirm
`python3` is available first; if it is missing, report the prerequisite.

```bash
cat > ~/.agent-light/comate-stop.py << 'PYTHON'
import json
import subprocess
import sys
from pathlib import Path

try:
    event = json.load(sys.stdin)
except (ValueError, TypeError):
    event = {}
status = event.get("status") if isinstance(event, dict) else None
state = {"completed": "S", "error": "E", "cancelled": "I"}.get(status, "I")
subprocess.run([str(Path.home() / ".agent-light" / "send.sh"), state], check=False)
PYTHON
```

Working events send W. Only `Stop` with `status=error` sends E; ordinary tool
failures stay in the working flow. `Stop` with `status=completed` sends S,
`status=cancelled` sends I. Comate has no native waiting-for-approval event.

Merge into `~/.comate/hooks.json`:
```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.agent-light/send.sh W",
            "timeout": 5
          }
        ]
      }
    ],
    "PreToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.agent-light/send.sh W",
            "timeout": 5
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.agent-light/send.sh W",
            "timeout": 5
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "python3 ~/.agent-light/comate-stop.py",
            "timeout": 5
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.agent-light/send.sh I",
            "timeout": 5
          }
        ]
      }
    ]
  }
}
```
Note: Comate does not have a direct equivalent for `PermissionRequest` or
`TaskCompleted` events. Success and terminal error are derived from `Stop.status`.

## Step 4: Configure IDE port forwarding

In the IDE port forwarding panel (VSCode Remote SSH / JetBrains Gateway / company remote plugin), add:
- Remote port: `8547`
- Local address: `localhost:8547`

Verify: On local machine, after `~/.agent-light/send.sh W` on the remote, run `curl http://localhost:8547` — the first call should return the queued frame(s) (e.g. `nW`), an immediate second call returns empty (queue already consumed).

## Step 5: Setup local polling client (requires user action)

**IMPORTANT: This step cannot be executed remotely by the Agent.**
In remote development mode, the Agent only has access to the remote server terminal, not the user's local machine.
You MUST ask the user to manually run the following commands in a LOCAL terminal (Terminal.app / iTerm2 / PowerShell on their machine).

Tell the user:
> Please open a terminal on your LOCAL machine (not the VSCode integrated terminal) and run the following commands:

```bash
mkdir -p ~/.agent-light
cat > ~/.agent-light/poll_remote.sh << 'SCRIPT'
#!/bin/bash
# Poll remote event queue and forward each frame to local hardware/simulator.
# The server returns ALL buffered event frames (one per line) and consumes them.
# This client splits by line and forwards each frame with a small gap, so transient
# states within a polling window are all reproduced (not overwritten).
#   - no new events -> server returns empty -> nothing to send
#   - multiple events in a window -> multiple lines -> each forwarded in order
#   - a crashed agent (no new appends) -> server returns empty -> firmware times out

# Frame gap (seconds): must be >= simulator poll interval so each frame gets sampled
FRAME_GAP=0.12

if [[ "$OSTYPE" == "darwin"* ]]; then
    PORT=$(ls /dev/cu.usbmodem* 2>/dev/null | head -1)
elif [[ "$OSTYPE" == "linux"* ]]; then
    PORT=$(ls /dev/ttyACM* 2>/dev/null | head -1)
fi

while true; do
    RESP=$(curl -s --max-time 1 http://localhost:8547 2>/dev/null)
    if [ -n "$RESP" ]; then
        printf '%s\n' "$RESP" | while IFS= read -r FRAME; do
            [ -z "$FRAME" ] && continue
            TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S' 2>/dev/null)
            echo "[$TIMESTAMP] recv frame=$FRAME" >> /tmp/agent_light.log

            printf '%s' "$FRAME" > /tmp/agent_light_state       # for simulator
            [ -n "$PORT" ] && printf '%s' "$FRAME" > "$PORT"    # for hardware
            sleep "$FRAME_GAP"
        done
    fi
    sleep 1
done
SCRIPT
chmod +x ~/.agent-light/poll_remote.sh
nohup ~/.agent-light/poll_remote.sh > /dev/null 2>&1 &
```

After the user confirms they have executed the commands, proceed to Step 6.

## Step 6: Verify installation

On the remote server, run:
~/.agent-light/send.sh C

Ask the user: "Do you see the LEDs flash in sequence (red → yellow → green)?"
If yes, the remote-to-local connection is working. Then submit a simple Agent
task and confirm that the green LED breathes during work and returns to idle when
the response ends (Comate may first show solid green for 2 seconds). Only report
installation as verified after this actual Hook-driven task. The polling interval
and network add latency; typically allow 1-2 seconds, longer for queued frames.
If no, proceed to Troubleshooting.

## Troubleshooting
- Remote server curl localhost:8547 fails: check python server is running (`ps aux | grep agent_light_server`)
- Local curl localhost:8547 fails: check IDE port forwarding is active
- LEDs not responding: check local USB device (`ls /dev/cu.usbmodem* /dev/ttyACM*`)
- High latency: normal, expect 1-2s delay due to polling interval
- Server uses Python 2: if only Python 3 available, replace `BaseHTTPServer` with `http.server` module
