#!/usr/bin/env bash
#
# List and archive Claude Code remote environments.
#
# Why: Claude Code spins up remote environments from the desktop app but
# gives you no UI or CLI command to archive stale ones. The list and
# archive endpoints exist on the public API surface behind an undocumented
# beta flag. This script hits them directly using the OAuth bearer token
# that Claude Code stores at ~/.claude/.credentials.json.
#
# Usage:
#   claude-envs list                # list environments
#   claude-envs archive <env_id>    # archive one environment
#
# Tested against Claude Code 1.x as of May 2026. The endpoint, the beta
# header, and the credentials path are all undocumented and can change.
#
set -e

TOKEN=$(jq -r '.claudeAiOauth.accessToken' ~/.claude/.credentials.json)

HDRS=(
  -H "Authorization: Bearer $TOKEN"
  -H "anthropic-version: 2023-06-01"
  -H "anthropic-beta: environments-2025-11-01"
  -H "Content-Type: application/json"
)

case "$1" in
  list)
    echo "Trying /v1/environments ..."
    curl -sS "${HDRS[@]}" https://api.anthropic.com/v1/environments | jq
    echo "---"
    echo "Trying /v1/environments/bridge ..."
    curl -sS "${HDRS[@]}" https://api.anthropic.com/v1/environments/bridge | jq
    ;;
  archive)
    if [ -z "$2" ]; then echo "need env id"; exit 1; fi
    curl -sS -X DELETE "${HDRS[@]}" \
      "https://api.anthropic.com/v1/environments/bridge/$2" | jq
    echo "Done: $2"
    ;;
  *)
    echo "Usage:"
    echo "  $0 list                    # list environments"
    echo "  $0 archive <env_id>        # archive one environment"
    ;;
esac
