#!/bin/bash
#
# Purpose : Run an AI agent inside Anthropic's sandbox runtime (srt). On
#           macOS, srt uses Seatbelt (sandbox-exec) to limit which files the
#           agent can read and write, and lets it reach the network only
#           through a proxy that lets through the domains in its config.
#
# sandbox/bin/<agent> links here, and `configure agents` puts sandbox/bin
# first on PATH, so typing an agent's name runs it sandboxed. `unsandboxed
# <agent>` runs the agent's real command instead.
#
# The config is sandbox/config/base.json, then sandbox/config/<agent>.json,
# then your own base.json and <agent>.json in ~/Library/Application Support/
# Federated Connector/sandbox, in the same format. Later files add to the
# lists in earlier ones. Domains in FEDERATED_SANDBOX_DOMAINS (space-
# separated) are allowed too.

# Wrapped in { ...; exit; } so bash reads the whole script up front; an update
# may replace this file while agents are running.
{

# This script, through the link in sandbox/bin
self="$0"
while [ -L "$self" ]; do
  link="$(readlink "$self")"
  case "$link" in
    /*) self="$link" ;;
    *) self="$(dirname "$self")/$link" ;;
  esac
done
SANDBOX="$(cd "$(dirname "$self")" && pwd -P)"
CONNECTOR="$(dirname "$SANDBOX")"
USER_CONFIG="$HOME/Library/Application Support/Federated Connector/sandbox"
name="$(basename "$0")"
source "$CONNECTOR/configure.d/lib/agents.sh" || exit 1

if [ "$name" = "unsandboxed" ]; then
  if [ $# -eq 0 ]; then
    echo "Usage: unsandboxed <agent> [arguments]"
    exit 2
  fi
  agent="$1"
  shift
  real="$(agent_path "$agent")" || { echo "$agent isn't installed."; exit 127; }
  exec "$real" "$@"
fi

agent="$name"
real="$(agent_path "$agent")" || { echo "$agent isn't installed. To install it: configure agents"; exit 127; }

# Commands that share another agent's sandbox config
case "$agent" in
  hermes-agent) profile=hermes ;;
  *) profile="$agent" ;;
esac

srt="$(srt_path)"
if [ -z "$srt" ]; then
  echo "The sandbox (srt) isn't installed; run: configure agents. To run $agent without it: unsandboxed $agent"
  exit 1
fi
# srt is a Node.js program; its own Node.js, if it has one, comes first
PATH="$(dirname "$srt"):$FC_TOOLS/node/bin:$PATH"

# The agent can change anything in the directory it starts in
case "$PWD" in
  "$HOME"|/)
    echo "Start $agent from a project directory. In the sandbox it can change anything in the directory it starts in, and this is $PWD."
    exit 1 ;;
esac

configs=("$SANDBOX/config/base.json")
[ -f "$SANDBOX/config/$profile.json" ] && configs+=("$SANDBOX/config/$profile.json")
for file in "$USER_CONFIG/base.json" "$USER_CONFIG/$profile.json"; do
  [ -f "$file" ] && configs+=("$file")
done

# Outside the folders the agent may change (or read), so it can't change its
# own rules; not in macOS' temp folder, which it may change (below). Named
# after this process, as srt replaces it (exec below) and nothing is left to
# remove it afterwards; files whose process has ended are removed here.
SETTINGS_DIR="$HOME/Library/Application Support/Federated Connector/sandbox-settings"
mkdir -p -m 700 "$SETTINGS_DIR" 2> /dev/null || [ -d "$SETTINGS_DIR" ] || exit 1

# macOS' mktemp, and other macOS tools, use your temp folder in /var/folders
# rather than TMPDIR (which srt points at one of its own), so the agent may
# change that folder too
USER_TEMP="$(getconf DARWIN_USER_TEMP_DIR 2> /dev/null)"
for old in "$SETTINGS_DIR"/*.json; do
  pid="${old%.json}"
  pid="${pid##*.}"
  [[ "$pid" =~ ^[0-9]+$ ]] && ! kill -0 "$pid" 2> /dev/null && rm -f "$old"
done
settings="$SETTINGS_DIR/$agent.$$.json"

# Objects are merged and lists joined, so later files only add to earlier ones
# shellcheck disable=SC2016
if ! osascript -l JavaScript -e '
function run(argv) {
  ObjC.import("Foundation");
  function read(path) {
    var s = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null);
    if (s.isNil()) throw new Error("could not read " + path);
    return JSON.parse(s.js);
  }
  function merge(a, b) {
    Object.keys(b).forEach(function (k) {
      var x = a[k], y = b[k];
      if (Array.isArray(x) && Array.isArray(y)) {
        a[k] = x.concat(y.filter(function (v) { return x.indexOf(v) < 0; }));
      } else if (x && y && typeof x === "object" && typeof y === "object" && !Array.isArray(x)) {
        merge(x, y);
      } else {
        a[k] = y;
      }
    });
    return a;
  }
  var out = argv[0], domains = argv[1].split(" ").filter(function (d) { return d; });
  var userTemp = argv[2];
  var config = argv.slice(3).reduce(function (c, path) { return merge(c, read(path)); }, {});
  config.network = config.network || {};
  merge(config.network, {allowedDomains: domains});
  if (userTemp) {
    config.filesystem = config.filesystem || {};
    merge(config.filesystem, {allowWrite: [userTemp.replace(/\/$/, "")]});
  }
  if (!$(JSON.stringify(config, null, 2)).writeToFileAtomicallyEncodingError(out, true, $.NSUTF8StringEncoding, null)) {
    throw new Error("could not write " + out);
  }
}' "$settings" "$FEDERATED_SANDBOX_DOMAINS" "$USER_TEMP" "${configs[@]}" > /dev/null; then
  echo "Couldn't read the sandbox config: ${configs[*]}"
  exit 1
fi
chmod 600 "$settings"

# On macOS the sandbox lets the agent reach the network only through srt's
# proxy, so nothing may go around it: srt would otherwise tell it to connect
# directly to private addresses (192.168.x.x and so on) and localhost, which
# the sandbox then blocks. Through the proxy, a server on your network that
# the config allows, e.g. one from `configure ai-servers`, can be reached.
exec "$srt" --settings "$settings" -- env NO_PROXY= no_proxy= "$real" "$@"
}
