#!/bin/bash
# claude-uaml-worker — Run Claude Code as a Tier-2 worker (no sudo, no host edits).
# Per §3 of the agent-ecosystem policy.
#
# Differences vs claude-uaml:
#   - Runs as the dedicated agent system user given as $1 (default: claude-agent).
#   - Read-only UAML token is exported via UAML_API_TOKEN_FILE.
#   - No bypassPermissions; Claude prompts before each action.
#   - Same UAML-aware MCP/API endpoints.
#
# Usage:
#   claude-uaml-worker              # runs as claude-agent
#   claude-uaml-worker hermes -- ask "summarise yesterday's logs"
set -euo pipefail

USER_NAME="${1:-claude-agent}"
shift || true

# Token resolution: per-user file under /etc/uaml/agent-tokens/<user>.tok
TOKEN_FILE="${UAML_API_TOKEN_FILE:-/etc/uaml/agent-tokens/${USER_NAME}.tok}"
if [[ -r "$TOKEN_FILE" ]]; then
  export UAML_API_TOKEN="$(cat "$TOKEN_FILE")"
fi

# Force agent_id header on every UAML call so the registry counts this
# session correctly. PARENT comes from the wrapper that may have
# launched us.
export UAML_AGENT_ID="${UAML_AGENT_ID:-${USER_NAME}-worker}"
export UAML_PARENT_AGENT_ID="${UAML_PARENT_AGENT_ID:-}"

exec sudo -u "$USER_NAME" -H -- bash -lc "
  cd ~ &&
  UAML_AGENT_ID='${UAML_AGENT_ID}' \
  UAML_PARENT_AGENT_ID='${UAML_PARENT_AGENT_ID}' \
  UAML_API_TOKEN='${UAML_API_TOKEN:-}' \
  claude $*
"
