#!/bin/sh
# A reference launcher for OpenClaw's CLI as an OpenRig community harness. Copy it, own it, and change it: OpenRig
# doesn't ship or run it. It follows docs/reference/community-harness-presets.md (`names_conversation`):
#   - a new launch (OPENRIG_CONVERSATION set): OpenClaw's local chat starts on the session key OpenRig named;
#   - a resume (OPENRIG_RESUME_REF set): it first checks that this seat's sessions list the key, and stops if they
#     don't, so a gone conversation isn't quietly recreated under its old key.
# It runs `openclaw chat` (the TUI with --local): the agent runs in the seat's own pane, with no Gateway. Arguments after
# the launcher's name go to every launch and resume alike.
set -eu

openclaw="${OPENRIG_OPENCLAW:-openclaw}"

# Each seat gets its own OpenClaw state folder: --local needs it to itself, and seats don't share sessions.
# Its provider settings and credentials come from that folder's config or the environment, not the person's ~/.openclaw.
OPENCLAW_STATE_DIR="${OPENRIG_HOME:-$HOME/.openrig}/state/openclaw/${OPENRIG_NODE_ID:-${OPENRIG_SESSION_NAME:-default}}"
export OPENCLAW_STATE_DIR
mkdir -p "$OPENCLAW_STATE_DIR"

if [ -n "${OPENRIG_RESUME_REF:-}" ]; then
  key="$OPENRIG_RESUME_REF"
  # A key may be stored bare or as agent:<id>:<key>; either counts as this conversation.
  if ! "$openclaw" sessions --json --limit all | KEY="$key" node -e '
    let raw = ""; process.stdin.on("data", (chunk) => { raw += chunk; });
    process.stdin.on("end", () => {
      const key = process.env.KEY;
      const sessions = JSON.parse(raw).sessions || [];
      process.exit(sessions.some((s) => s.key === key || String(s.key).endsWith(`:${key}`)) ? 0 : 1);
    });'; then
    echo "openrig-openclaw-launch: this seat's OpenClaw sessions don't list \"$key\" (or couldn't be listed); not starting a new one under that key" >&2
    exit 3
  fi
  exec "$openclaw" chat --session "$key" "$@"
fi
if [ -n "${OPENRIG_CONVERSATION:-}" ]; then
  exec "$openclaw" chat --session "$OPENRIG_CONVERSATION" "$@"
fi
echo "openrig-openclaw-launch: OpenRig passed no conversation name; is names_conversation set in the preset?" >&2
exit 2
