#!/usr/bin/env bash
# The one line a signed-in owner copies off my.5dive.ai/self-host (DIVE-6816):
#
#   curl -fsSL <api>/connector/link.sh | sudo bash -s <code> [<secret>]
#
# Links this server to a 5dive.app account for CHAT ONLY. Nothing listens here:
# no web server, no open port, no certificate. This server only calls out to
# 5dive (as Telegram polling does), so it works behind NAT, CGNAT or IPv6.
# (DIVE-8361: one exception, once, at link: for at most 35 seconds a listener
# answers one random path, so 5dive.app can count which servers the internet
# can reach. It stops by itself; see the reporter's reach().)
#
#   1. installs 5dive if it is missing (an existing install and its agents stay);
#   2. trades the one-time code for this server's token (/etc/5dive/connectord.env);
#   3. turns on the 5dive.app chat channel (`dashboard`) for its claude/codex agents;
#   4. installs 5dive-chat-report and a timer: once a minute it tells 5dive.app
#      which agents this server has, and gives chat to agents added later;
#   5. with a <secret> (DIVE-6878): turns on encrypted chat. The browser made the
#      secret and put it in the line; it pairs that browser with this server's
#      chat key (`5dive chat e2e enable`), so 5dive.app carries only ciphertext.
#
# Undo: sudo 5dive-chat-report --unlink
#
# Quiet by default (DIVE-7023): the 5dive install's own output (apt, nvm, the
# health check) goes to /var/log/5dive-install.log and the terminal gets one
# line per step. `... | sudo bash -s CODE --verbose` prints all of it. A failed
# install prints the end of that log, with internal row ids taken out.
#
# The code rides on the command line, not in a URL, so no web server logs it,
# and this script never prints it or the token. The secret too, and more: it is
# never sent anywhere (not to 5dive.app either), never logged, and it reaches
# `5dive chat e2e enable` on stdin, never on a command line. Served by the 5dive API, which
# fills in __API__.
set -euo pipefail

# All in a function: bash reads the whole script before running any of it, so
# nothing below can eat the rest of the script off stdin.
main() {
  local API='https://api.5dive.com' code='' secret='' verbose=0 arg
  for arg in "$@"; do
    case "$arg" in
      -v|--verbose) verbose=1 ;;
      *) if [[ -z "$code" ]]; then code=$arg; elif [[ -z "$secret" ]]; then secret=$arg; fi ;;
    esac
  done
  [[ $EUID -eq 0 ]] || { echo "error: run it with sudo (... | sudo bash -s CODE)" >&2; exit 1; }
  [[ -n "$code" ]] || { echo "error: no code. Copy the whole line from 5dive.app again." >&2; exit 1; }
  [[ "$code" =~ ^[A-Za-z0-9-]{8,12}$ ]] || { echo "error: that is not a code from 5dive.app. Copy the whole line again." >&2; exit 1; }
  [[ -z "$secret" || "$secret" =~ ^[A-Za-z0-9_-]{43}$ ]] || { echo "error: the end of that line is not from 5dive.app. Copy the whole line again." >&2; exit 1; }
  for b in curl systemctl; do
    command -v "$b" >/dev/null || { echo "error: $b is required" >&2; exit 1; }
  done
  # Not local: the EXIT trap runs after main has returned.
  tmp=$(umask 077; mktemp -d); trap 'rm -rf "$tmp"' EXIT

  if command -v 5dive >/dev/null; then
    echo "5dive is already installed: keeping it and its agents."
  else
    echo "Downloading 5dive..."
    curl -fsSL --max-time 120 https://install.5dive.ai -o "$tmp/5dive.sh" \
      || { echo "error: could not download 5dive from install.5dive.ai. Check this server's internet connection and run the line again." >&2; exit 1; }
    echo "Installing 5dive (takes a few minutes)..."
    ( umask 077; : >"$LOG" )
    # FIVEDIVE_APP_HINT=0: the installer's own "talk to your agents from your phone"
    # steps are the connector's, the flow this line replaces (DIVE-6824).
    if (( verbose )); then
      FIVEDIVE_APP_HINT=0 bash "$tmp/5dive.sh" </dev/null 2>&1 | tee -a "$LOG" | no_ids \
        || { echo "error: installing 5dive failed. Details: $LOG" >&2; exit 1; }
    elif ! FIVEDIVE_APP_HINT=0 bash "$tmp/5dive.sh" </dev/null >>"$LOG" 2>&1; then
      echo "error: installing 5dive failed. The end of $LOG:" >&2
      tail -n 40 "$LOG" | no_ids >&2
      exit 1
    fi
    hash -r
    echo "Details: $LOG"
  fi
  for b in 5dive jq; do
    command -v "$b" >/dev/null || { echo "error: $b is not on PATH after installing 5dive" >&2; exit 1; }
  done

  echo "Linking this server to your 5dive.app account..."
  # The code goes in a file, not in curl's argv, so `ps` on this server never shows it.
  jq -cn --arg code "$code" '{code: $code}' >"$tmp/code.json"
  local status
  status=$(curl -sS --max-time 30 -o "$tmp/link.json" -w '%{http_code}' \
    -H 'content-type: application/json' --data-binary @"$tmp/code.json" \
    "$API/connector/chat/link") || { echo "error: could not reach $API. Check this server's internet connection and run the line again." >&2; exit 1; }
  rm -f "$tmp/code.json"
  if [[ "$status" != 200 ]]; then
    local msg
    msg=$(jq -r '.message // .error // empty' "$tmp/link.json" 2>/dev/null || true)
    echo "error: ${msg:-5dive.app refused the link (HTTP $status).}" | no_ids >&2
    exit 1
  fi
  local token appname
  token=$(jq -r '.token // empty' "$tmp/link.json")
  # DIVE-8361: this server's free <name>.5dive.app, when 5dive.app gave it one.
  appname=$(jq -r '.name // empty' "$tmp/link.json" 2>/dev/null) || appname=""
  rm -f "$tmp/link.json"
  [[ "$token" =~ ^[0-9a-f]{64}$ ]] || { echo "error: 5dive.app sent no usable token" >&2; exit 1; }

  # The token file, exactly where and how the 5dive plugins read it.
  mkdir -p /etc/5dive
  ( umask 027; printf 'CONNECTORD_TOKEN=%s\n' "$token" >/etc/5dive/connectord.env.tmp )
  if getent group claude-keys >/dev/null; then chgrp claude-keys /etc/5dive/connectord.env.tmp
  elif getent group claude >/dev/null; then chgrp claude /etc/5dive/connectord.env.tmp; fi
  chmod 640 /etc/5dive/connectord.env.tmp
  mv -f /etc/5dive/connectord.env.tmp /etc/5dive/connectord.env
  token=
  # The marker: this server talks to 5dive.app by polling only.
  ( umask 022; printf 'API=%s\nLINKED_AT=%s\n' "$API" "$(date -u +%FT%TZ)" >/etc/5dive/chat-only.tmp )
  chmod 644 /etc/5dive/chat-only.tmp
  mv -f /etc/5dive/chat-only.tmp /etc/5dive/chat-only
  if [[ "$appname" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$ ]]; then
    ( umask 022; printf 'NAME=%s.5dive.app\n' "$appname" >/etc/5dive/app-name.tmp )
    mv -f /etc/5dive/app-name.tmp /etc/5dive/app-name
  fi

  # A connector from an earlier link would still be listening: stop it.
  if [[ -d /etc/5dive-connector ]] || systemctl cat 5dive-connector.service >/dev/null 2>&1; then
    systemctl disable --now 5dive-connector.service 5dive-connector-tls.service 5dive-connector-tls.timer \
      5dive-connector-ip.service 5dive-connector-ip.timer >/dev/null 2>&1 || true
    echo "Stopped the old 5dive connector: it is not needed for chat."
  fi

  # The chat file dirs, as a managed box's update.sh makes them (DIVE-848):
  # app uploads land in chat-uploads, agents copy reply files into chat-downloads.
  if getent passwd claude >/dev/null; then
    install -d -m 0755 -o claude -g claude /home/claude/chat-uploads
    install -d -m 2775 -o claude -g claude /home/claude/chat-downloads
  fi

  echo "Turning on 5dive.app chat for your agents..."
  install -d -m 0700 /var/lib/5dive-chat
  touch /var/lib/5dive-chat/seen
  local list name channels out ver chat=0 all=0
  list=$(5dive agent list --json 2>/dev/null | jq -c '.data // [] | .[] | {name, type, channels}' 2>/dev/null || true)
  ver=$(5dive --version 2>/dev/null </dev/null | grep -oE '[0-9]+[.][0-9]+[.][0-9]+' | head -n1 || true)
  # DIVE-8244: every agent is offered chat and this server's 5dive says which
  # kinds can (it refuses the rest). A list of kinds kept here went stale: it
  # named two kinds long after Hermes, OpenCode and others could chat, so their
  # owners linked and found nothing to chat with.
  while IFS= read -r a; do
    [[ -n "$a" ]] || continue
    name=$(jq -r '.name // empty' <<<"$a")
    channels=$(jq -r '.channels // empty' <<<"$a")
    [[ "$name" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || continue
    all=$((all + 1))
    if [[ ",$channels," == *,dashboard,* ]]; then
      chat=$((chat + 1))
      echo "  $name: chat already on"
    else
      if [[ -z "$channels" || "$channels" == none ]]; then channels=dashboard; else channels="$channels,dashboard"; fi
      if out=$(5dive agent config "$name" set "channels=$channels" 2>&1 </dev/null); then
        chat=$((chat + 1))
        echo "  $name: chat on"
      elif no_chat_kind "$out"; then
        # Not marked seen: the reporter offers it again once 5dive is updated.
        printf '%s %s\n' "$name" "$ver" >>/var/lib/5dive-chat/nochat
        echo "  $name: this kind of agent cannot chat on this 5dive version"
        continue
      else
        echo "  $name: could not turn chat on. Try: sudo 5dive agent config $name set channels=$channels" >&2
      fi
    fi
    grep -qxF "$name" /var/lib/5dive-chat/seen || printf '%s\n' "$name" >>/var/lib/5dive-chat/seen
  done <<<"$list"

  install_reporter "$API"

  # DIVE-8361 (step 5): can the internet reach this server? A 30-second check,
  # counted by 5dive.app; nothing stays open after it.
  echo "Checking whether this server can be reached from the internet (30 seconds)..."
  /usr/local/bin/5dive-chat-report --reach </dev/null >/dev/null 2>&1 || true
  if [[ -r /etc/5dive/app-name ]]; then
    echo "This server's web address: https://$(sed -n 's/^NAME=//p' /etc/5dive/app-name | head -n1)"
  fi

  [[ -n "$secret" ]] && enable_e2e "$secret"
  secret=

  # DIVE-8292: a server whose 5dive can sign in from the app (its reporter asks
  # for the sign-in and the hire) is told to do that first.
  local app=0
  if command -v systemd-run >/dev/null \
    && [[ "$(5dive agent auth submit 0000000000000000 --code=- </dev/null 2>&1 || true)" == *"no callback code on stdin"* ]]; then
    app=1
  fi

  echo
  say_linked "$chat" "$all" "$app"
  echo "Nothing listens on this server: it only calls out to 5dive.app, as Telegram does."
  echo "To unlink: sudo 5dive-chat-report --unlink"
}

LOG=/var/log/5dive-install.log

# DIVE-8244: `5dive agent config` refusing chat for this kind of agent, as
# opposed to failing. Both are its own words since chat came to the CLI.
no_chat_kind() {
  [[ "$1" == *"channels=dashboard requires type="* || "$1" == *"does not support channels"* ]]
}

# DIVE-6878: encrypted chat. printf is a builtin, so the secret reaches the CLI
# on stdin without ever being a process argument; the CLI's own errors never
# carry it, and nothing here prints it. A server whose 5dive is too old to do
# it still links, and chat works, unencrypted: the app says so.
enable_e2e() {
  local secret=$1
  echo "Turning on encrypted chat..."
  if ! 5dive chat --help >/dev/null 2>&1 </dev/null; then
    echo "warning: this server's 5dive is too old for encrypted chat. Run: sudo 5dive self-update, then copy the line from 5dive.app again." >&2
    return 0
  fi
  if ! printf '%s\n' "$secret" | 5dive chat e2e enable - >/dev/null 2>"$tmp/e2e.err"; then
    local why
    why=$(tail -n 1 "$tmp/e2e.err" | sed 's/^error: //' | no_ids)
    echo "warning: encrypted chat could not be turned on: ${why//"$secret"/[redacted]}. Chat works, unencrypted. Copy the line from 5dive.app again to retry." >&2
  else
    echo "Encrypted chat is ready: it pairs with the browser you copied this line from within a minute."
  fi
  rm -f "$tmp/e2e.err"
}

# Internal row ids mean nothing to the owner reading this (DIVE-7023): drop
# "(DIVE-123)" and "(DIVE-1, DIVE-2)" whole, and any bare one left over.
no_ids() {
  sed -E 's/ ?\((DIVE-[0-9]+[,;/ ]*)+\)//g; s/DIVE-[0-9]+//g'
}

# The last word (DIVE-6824): a fresh server has no agents, so it says so and gives
# the one command that makes the first (5dive init: the AI, its sign-in, the agent).
# 5dive.app shows the same step until the agent arrives.
# DIVE-8065: $1 counts the agents that got chat, $2 every agent. A server whose
# agents all cannot chat has agents, so "no agents yet" was false there.
# DIVE-8292: $3 is 1 when this 5dive can sign in and hire from the app.
# DIVE-8244: and naming two kinds was false too (Hermes, OpenCode and more chat
# now). Its 5dive refused them, so it is older than they need: update it, and
# the reporter offers chat again (it retries an agent when 5dive's version moves).
say_linked() {
  if (( ${1:-0} > 0 )); then
    echo "Linked. Open 5dive.app: your agents are there, ready to chat."
  elif (( ${2:-0} > 0 )); then
    echo "Linked. Your agents here cannot chat in 5dive.app on this 5dive version. Update it:"
    echo "  sudo 5dive self-update"
    echo "Chat turns on by itself a minute later, for each agent that can chat. Or add a new one: sudo 5dive init"
  elif (( ${3:-0} )); then
    # DIVE-8292: 7 of 10 self-host testers stopped here. The app does it all now.
    echo "Linked. Now make your first agent in 5dive.app: open it and tap Sign in with Claude or ChatGPT."
    echo "Or here in the terminal: sudo 5dive init"
  else
    echo "Linked. This server has no agents yet. Make your first one:"
    echo "  sudo 5dive init"
    echo "It sets up your agent and its AI, and it shows up in 5dive.app a minute later."
  fi
}

# The reporter and its timer. The helper reads the API from the marker, so this
# heredoc is quoted and nothing in it is expanded here.
install_reporter() {
  cat >/usr/local/bin/5dive-chat-report.tmp <<'REPORTER'
#!/usr/bin/env bash
# 5dive.app chat on a self-hosted server (DIVE-6816), run once a minute by
# 5dive-chat-report.timer. Calls OUT only:
#   - tells 5dive.app which agents this server has (name, type, channels,
#     createdAt, active, enabled, health, the model each runs (DIVE-6888), its
#     own Telegram bot's public @username, never its token; nothing else), and
#     whether it can hear and speak voice notes (DIVE-6873), and its teams
#     (project keys, members, who reports to whom; DIVE-6891), and the sites
#     its browser is signed in to (`5dive browser ls`: names and last checks,
#     never a password, cookie or page; DIVE-7133), and its AI logins (`5dive
#     account list`: names, kinds, agents and provider names, never a token
#     or key; DIVE-7256), and each Teams agent's public Add to Teams link
#     (DIVE-8043: that link only, never its app id, password or tenant),
#     when that changed;
#   - turns chat on for an agent added since the link. An agent you turned chat
#     off for later stays off: each agent is offered once (/var/lib/5dive-chat/seen);
#     one this 5dive cannot chat with is offered again after an update (DIVE-8244);
#   - sends `5dive export` (the team's names, types, roles, models; no memory,
#     files, keys or tokens leave with it: 5dive keeps only what a copy to 5dive
#     cloud carries), when it changed (DIVE-6818);
#   - asks 5dive.app what it holds for this server (DIVE-7102): an agent's new
#     Telegram bot (the owner tapped Connect Telegram) or a secret the owner sent
#     from 5dive.app, so nobody types one into chat. Each is applied with the
#     value on stdin, never on a command line and never printed, then acked.
#     And (DIVE-7253) a setting the owner changed on an agent's sheet in the
#     app: its model, or removing it, each one fixed 5dive command. And
#     (DIVE-8292) the first agent, for a server with no terminal: a Claude
#     sign-in (its link goes back to 5dive.app, the code the owner pastes there
#     comes back on stdin) and the hire. While one is under way, or the owner
#     has that screen open, it asks every few seconds (`--fast`, its own unit,
#     at most 15 minutes) instead of once a minute.
# If 5dive.app no longer knows this server (unlinked there), it stops.
#
#   - DIVE-8361: every 5 minutes, asks 5dive.app for this server's free
#     <name>.5dive.app. 5dive.app points the name at the address the call comes
#     FROM (nothing about the address is sent), so a home line's new IP is
#     followed within ~5 minutes; the name goes to /etc/5dive/app-name, where
#     `5dive secret https` finds it. DIVE-8446: this call only KEEPS a name;
#     the first one is made when `5dive secret https` first needs it (it asks
#     /server/selfhost/name?new=1 itself). `--reach` (once, at link): see reach().
#
#   sudo 5dive-chat-report --unlink   removes the token, the marker and the timer
set -euo pipefail

APP_NAME_FILE=/etc/5dive/app-name
APP_NAME_EVERY_S=300

# DIVE-8361: keep the name 5dive.app answered, written only when it changed.
save_app_name() {
  local host=$1 have=""
  [[ "$host" =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.5dive\.app$ ]] || return 0
  have=$(sed -n 's/^NAME=//p' "$APP_NAME_FILE" 2>/dev/null | head -n1) || have=""
  [[ "$have" == "$host" ]] && return 0
  ( umask 022; printf 'NAME=%s\n' "$host" >"$APP_NAME_FILE.tmp" ) || return 0
  mv -f "$APP_NAME_FILE.tmp" "$APP_NAME_FILE" || true
  return 0
}

# DIVE-8361 (plan §4a): the name call, at most every APP_NAME_EVERY_S. Never
# fails the report. The answer's ip is the address 5dive.app saw.
app_name() {
  local api=$1 tmp=$2 state=$3 force=${4:-} last=0 now host
  now=$(date +%s)
  last=$(head -c 20 "$state/name-at" 2>/dev/null) || last=0
  [[ "$last" =~ ^[0-9]+$ ]] || last=0
  if [[ -z "$force" ]] && (( now - last < APP_NAME_EVERY_S )); then return 0; fi
  printf '%s\n' "$now" >"$state/name-at" 2>/dev/null || true
  # --ipv4 on this call only: the name is an A record, and 5dive.app's address
  # has IPv6 too, so a dual-stack server would otherwise ask from an address the
  # name cannot hold. An IPv6-only server simply gets no name here (chat, and
  # every other call, stay on whatever works).
  curl -sS --ipv4 --max-time 20 -o "$tmp/name.json" -X POST -H @"$tmp/auth" \
    "$api/server/selfhost/name" 2>/dev/null || return 0
  host=$(jq -r '.host // empty' "$tmp/name.json" 2>/dev/null) || host=""
  save_app_name "$host"
  return 0
}

# One random path, answered on 80 and 443 (plain HTTP on both) for 35 s at most.
REACH_PY='
import sys, socketserver, threading, http.server
n = sys.argv[1]
class H(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        ok = self.path == "/.well-known/5dive-reach/" + n
        b = n.encode() if ok else b""
        self.send_response(200 if ok else 404)
        self.send_header("content-length", str(len(b)))
        self.end_headers()
        self.wfile.write(b)
    def log_message(self, *a):
        pass
class S(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True
for p in (80, 443):
    threading.Thread(target=S(("0.0.0.0", p), H).serve_forever, daemon=True).start()
threading.Event().wait(35)
'

port_free() { [[ -z "$(ss -Hltn "sport = :$1" 2>/dev/null)" ]]; }

# DIVE-8361 (plan §4b): once, at link. Whether the internet can reach this
# server, so 5dive.app can count reachable / home router / carrier NAT lines
# before anyone builds a relay. Only when 80 and 443 are both free: a listener
# answers one random path for 35 s, 5dive.app calls the address this call
# comes from back on both, and the listener stops. Also sent: whether that
# address is on this server, and whether one of its addresses is in the
# carrier range 100.64/10. Prints the class 5dive.app answered.
reach() {
  local api=$1 tmp=$2 state=$3 nonce ip="" ifs="" listening=false owns=false cgnat=false pid="" i
  app_name "$api" "$tmp" "$state" force
  ip=$(jq -r '.ip // empty' "$tmp/name.json" 2>/dev/null) || ip=""
  ifs=$(ip -o addr show scope global 2>/dev/null | awk '$3 == "inet" {print $4}' | cut -d/ -f1) || ifs=""
  if [[ -n "$ip" ]] && grep -qxF "$ip" <<<"$ifs"; then owns=true; fi
  if grep -qE '^100[.](6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])[.]' <<<"$ifs"; then cgnat=true; fi
  nonce=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
  if command -v python3 >/dev/null && command -v ss >/dev/null && port_free 80 && port_free 443; then
    timeout 40 python3 -c "$REACH_PY" "$nonce" >/dev/null 2>&1 &
    pid=$!
    for i in 1 2 3 4 5 6; do
      if ! port_free 80 && ! port_free 443; then listening=true; break; fi
      sleep 0.5
    done
  fi
  jq -cn --arg n "$nonce" --argjson l "$listening" --argjson o "$owns" --argjson c "$cgnat" \
    '{nonce: $n, listening: $l, ownsIp: $o, cgnat: $c}' >"$tmp/reach.json"
  curl -sS --ipv4 --max-time 30 -o "$tmp/reach.out" -X POST -H @"$tmp/auth" -H 'content-type: application/json' \
    --data-binary @"$tmp/reach.json" "$api/server/selfhost/reach" 2>/dev/null || true
  if [[ -n "$pid" ]]; then
    kill "$pid" 2>/dev/null || true
    wait "$pid" 2>/dev/null || true
  fi
  jq -r '.reach // empty' "$tmp/reach.out" 2>/dev/null || true
  return 0
}

main() {
  local mark=/etc/5dive/chat-only env=/etc/5dive/connectord.env state=/var/lib/5dive-chat
  [[ $EUID -eq 0 ]] || { echo "error: run it with sudo" >&2; exit 1; }
  [[ -f "$mark" ]] || { echo "this server is not linked to 5dive.app for chat" >&2; exit 0; }
  local api
  api=$(sed -n 's/^API=//p' "$mark" | head -n1)
  [[ "$api" =~ ^https?://[A-Za-z0-9.:-]+(/[A-Za-z0-9._/-]*)?$ ]] || { echo "error: bad API in $mark" >&2; exit 1; }
  # Not local: the EXIT trap runs after main has returned.
  tmp=$(umask 077; mktemp -d); trap 'rm -rf "$tmp"' EXIT
  if [[ -r "$env" ]]; then
    sed -n 's/^CONNECTORD_TOKEN=\(.*\)$/Authorization: Bearer \1/p' "$env" | head -n1 >"$tmp/auth"
  fi

  if [[ "${1:-}" == --unlink ]]; then
    # Tell 5dive.app first (best effort), then forget everything here.
    [[ -s "$tmp/auth" ]] && curl -sS --max-time 15 -o /dev/null -X POST -H @"$tmp/auth" "$api/connector/revoke" 2>/dev/null || true
    systemctl disable --now 5dive-chat-report.timer >/dev/null 2>&1 || true
    systemctl stop 5dive-chat-fast.service 5dive-chat-signin.service >/dev/null 2>&1 || true
    rm -f /etc/systemd/system/5dive-chat-report.timer /etc/systemd/system/5dive-chat-report.service
    systemctl daemon-reload >/dev/null 2>&1 || true
    rm -f "$env" "$mark" "$APP_NAME_FILE"
    rm -rf "$state"
    echo "Unlinked from 5dive.app. Your agents keep running; chat in 5dive.app is off."
    rm -f /usr/local/bin/5dive-chat-report
    exit 0
  fi

  [[ -s "$tmp/auth" ]] || exit 0
  command -v 5dive >/dev/null && command -v jq >/dev/null || exit 0
  install -d -m 0700 "$state"
  touch "$state/seen"

  # DIVE-8361: once, at link (the link script runs it).
  if [[ "${1:-}" == --reach ]]; then
    reach "$api" "$tmp" "$state"
    exit 0
  fi

  # DIVE-8292: only what 5dive.app holds, every few seconds, for a sign-in.
  if [[ "${1:-}" == --fast ]]; then
    fast_owed "$api" "$tmp" "$state"
    exit 0
  fi

  # DIVE-8361: this server's name follows its address (at most every 5 minutes).
  app_name "$api" "$tmp" "$state"

  local agents
  agents=$(5dive agent list --json 2>/dev/null | jq -c '.data // []' 2>/dev/null) || exit 0
  [[ -n "$agents" ]] || exit 0

  # This box's 5dive release: read once, for the chat offer below and the report.
  local ver=""
  ver=$(timeout 20 5dive --version 2>/dev/null </dev/null | grep -oE '[0-9]+[.][0-9]+[.][0-9]+' | head -n1) || ver=""

  # New agents get chat by default, once. DIVE-8244: every kind is offered and
  # this 5dive says which can chat. One it refused is not marked seen: it is
  # offered again when 5dive's version changes (`sudo 5dive self-update`).
  local a name channels out turned=0
  while IFS= read -r a; do
    [[ -n "$a" ]] || continue
    name=$(jq -r '.name // empty' <<<"$a")
    [[ "$name" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || continue
    grep -qxF "$name" "$state/seen" && continue
    grep -qxF "$name $ver" "$state/nochat" 2>/dev/null && continue
    channels=$(jq -r '.channels // empty' <<<"$a")
    if [[ ",$channels," != *,dashboard,* ]]; then
      if [[ -z "$channels" || "$channels" == none ]]; then channels=dashboard; else channels="$channels,dashboard"; fi
      if out=$(5dive agent config "$name" set "channels=$channels" 2>&1 </dev/null); then
        turned=1
      elif no_chat_kind "$out"; then
        printf '%s %s\n' "$name" "$ver" >>"$state/nochat"
        continue
      else
        echo "could not turn chat on for $name" >&2
      fi
    fi
    printf '%s\n' "$name" >>"$state/seen"
  done < <(jq -c '.[] | {name, channels}' <<<"$agents")
  # DIVE-6894: report the channels just set, not the list read before the loop;
  # else a new agent's first report says none and its chat waits a minute.
  if (( turned )); then
    agents=$(5dive agent list --json 2>/dev/null </dev/null | jq -c '.data // []' 2>/dev/null) || exit 0
    [[ -n "$agents" ]] || exit 0
  fi

  post_team "$api" "$tmp" "$state"

  # DIVE-6873: the voice plugin's two programs. Without them a voice note from
  # the app goes unheard and replies stay text, so 5dive.app asks for voice.
  local hear=false speak=false
  [[ -x /usr/local/bin/5dive-transcribe ]] && hear=true
  [[ -x /usr/local/bin/5dive-speak ]] && speak=true

  # DIVE-6891: which agents came in as which team (the project `team import`
  # made, its lead and members) and who reports to whom, so 5dive.app groups
  # the list by team. Keys and names only; null when either read fails.
  local teams=null projects="" tree=""
  if projects=$(5dive project ls --json 2>/dev/null </dev/null | jq -c '[.data.projects // [] | .[:50][] | {key, lead_agent, members}]' 2>/dev/null) \
    && tree=$(5dive org tree --json 2>/dev/null </dev/null | jq -c '[.data.tree // [] | .[:100][] | {name, reports_to}]' 2>/dev/null) \
    && [[ -n "$projects" && -n "$tree" ]]; then
    teams=$(jq -cn --argjson p "$projects" --argjson t "$tree" '{projects: $p, tree: $t}' 2>/dev/null) || teams=null
  fi

  # DIVE-7133: the browser's sites, one a line with its last check, so 5dive.app's
  # Browser screen lists them. null when the box has no browser.
  local browser=null ls_out=""
  if ls_out=$(timeout 20 5dive browser ls 2>/dev/null </dev/null); then
    browser=$(jq -cn --arg o "$ls_out" '{ls: $o[:16384]}' 2>/dev/null) || browser=null
  fi

  # DIVE-7256: the AI logins, so 5dive.app's AI tab lists them: each account's
  # name, the AI kinds it is signed in to, its agents, the kind new hires go to
  # and each kind's provider name. Names only, never a token, key or model.
  # null when the read fails.
  local accounts=null
  accounts=$(timeout 20 5dive account list --json 2>/dev/null </dev/null \
    | jq -c 'select(.ok == true) | [.data // [] | .[:20][] | {name, types, agents, default: (.default // null), signins: ((.signins // {}) | with_entries(.value = {provider: (.value.provider // null)}))}]' 2>/dev/null) \
    && [[ -n "$accounts" ]] || accounts=null

  # DIVE-7281: this box's 5dive release and whether nightly updates are on, so
  # 5dive.app says «Update available» when it is behind. null when the version
  # read fails; nightly null when the CLI cannot say (older than --status).
  local cli=null version=$ver nightly=""
  nightly=$(timeout 20 5dive self-update --status --json 2>/dev/null </dev/null | jq -r 'select(.ok == true) | .data.nightly // empty' 2>/dev/null) || nightly=""
  [[ "$nightly" == on || "$nightly" == off ]] || nightly=""
  if [[ -n "$version" ]]; then
    cli=$(jq -cn --arg v "$version" --arg n "$nightly" '{version: $v, nightly: (if $n == "" then null else $n end)}' 2>/dev/null) || cli=null
  fi

  # DIVE-8043: each Microsoft Teams agent's public Add to Teams link, so 5dive.app
  # draws its Open in Teams button (it cannot run `agent teams status` here).
  # Only agents on the teams channel are asked, and only the link leaves: never
  # the bot's app id, password, tenant or endpoint. A failed read sends none.
  local links='{}' tname tlink
  while IFS= read -r tname; do
    [[ "$tname" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || continue
    tlink=$(timeout 20 5dive agent teams status "$tname" --json 2>/dev/null </dev/null \
      | jq -r 'select(.ok == true) | .data | select(.connected == true) | .install_link // empty' 2>/dev/null) || tlink=""
    [[ "$tlink" =~ ^https://teams[.]microsoft[.]com/ && ${#tlink} -le 2000 ]] || continue
    links=$(jq -c --arg n "$tname" --arg l "$tlink" '. + {($n): $l}' <<<"$links" 2>/dev/null) || links='{}'
  done < <(jq -r '.[:50][] | select(("," + (.channels // "") + ",") | gsub("\\s"; "") | contains(",teams,")) | .name // empty' <<<"$agents" 2>/dev/null)

  # Report only what the app shows, and only when it changed (or hourly, so a
  # lost copy on 5dive's side heals).
  jq -c --argjson hear "$hear" --argjson speak "$speak" --argjson teams "$teams" --argjson browser "$browser" --argjson accounts "$accounts" --argjson cli "$cli" --argjson links "$links" \
    '{agents: [.[:50][] | {name, type, channels, createdAt, active, enabled, health, model, effort, liveModel, liveEffort, botUsername, teamsInstallLink: ($links[.name // ""] // null)}], voice: {hear: $hear, speak: $speak}, teams: $teams, browser: $browser, accounts: $accounts, cli: $cli}' \
    <<<"$agents" >"$tmp/body.json"
  local sum last="" at=0 now
  sum=$(sha256sum "$tmp/body.json" | cut -d' ' -f1)
  now=$(date +%s)
  [[ -f "$state/last" ]] && read -r last at <"$state/last" || true
  if [[ "$sum" != "$last" ]] || (( now - ${at:-0} >= 3600 )); then
    local status
    status=$(curl -sS --max-time 30 -o /dev/null -w '%{http_code}' -X POST -H @"$tmp/auth" \
      -H 'content-type: application/json' --data-binary @"$tmp/body.json" \
      "$api/server/selfhost/agents" 2>/dev/null) || status=000
    case "$status" in
      200) printf '%s %s\n' "$sum" "$now" >"$state/last" ;;
      401|403)
        # Unlinked in 5dive.app (or the server is no longer a chat-only one): stop asking.
        echo "5dive.app no longer knows this server; stopping. Link it again from 5dive.app." >&2
        systemctl disable --now 5dive-chat-report.timer >/dev/null 2>&1 || true
        exit 0 ;;
      *) : ;;
    esac
  fi

  # Every minute, whether the list changed or not: what 5dive.app holds for us.
  apply_owed "$api" "$tmp" "$state" "$agents" "$ver"
  # DIVE-8292: and faster while the owner signs in from the app.
  if [[ "$(cat "$tmp/owed-fast" 2>/dev/null)" == 1 || -f "$state/signin" ]]; then start_fast; fi

  # DIVE-6878: encrypted chat. Pairs the browser that made the link line, drops a
  # browser or phone revoked in the app. Best effort, and only when it is on.
  if [[ -d /etc/5dive/chat-e2e || -d /etc/5dive/chat-e2e.pairing ]]; then
    timeout 60 5dive chat devices sync </dev/null >/dev/null 2>&1 || true
  fi
}

# DIVE-7102: what 5dive.app holds for this server until it asks (nothing here
# listens, so it cannot be sent). A value is read into a shell variable and
# given to the command on stdin (printf is a shell builtin: no process ever
# carries it in its arguments), never printed, and cut out of any error sent
# back. Every file it touches is 0600 in the 0700 tmp dir.
# DIVE-8292: one puller at a time, so the minute run and the fast loop never
# apply one item twice. A directory, not flock: a process 5dive starts would
# inherit flock's descriptor and hold the lock for good. A holder that died is
# noticed by its pid and replaced.
owed_lock() {
  local l="$1/owed.lock" t="$1/owed.lock.$$" pid=""
  rm -rf "$t"; mkdir -m 0700 "$t" && printf '%s\n' "$$" >"$t/pid" || return 1
  mv -T "$t" "$l" 2>/dev/null && return 0
  read -r pid <"$l/pid" 2>/dev/null || true
  if [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then rm -rf "$t"; return 1; fi
  rm -rf "$l"
  mv -T "$t" "$l" 2>/dev/null && return 0
  rm -rf "$t"; return 1
}

# $tmp/owed-fast after a call: 1 (5dive.app asks for the fast loop), 0, or busy
# (another run holds the lock). Absent: the pull failed.
apply_owed() {
  local tmp=$2 state=$3
  rm -f "$tmp/owed-fast"
  if ! owed_lock "$state"; then echo busy >"$tmp/owed-fast"; return 0; fi
  apply_owed_locked "$@" || true
  signin_watch "$1" "$tmp" "$state" || true
  rm -rf "$state/owed.lock"
}

# DIVE-8292: this server's 5dive takes the sign-in code on stdin (`auth submit
# --code=-`; an older one would type "-" as the code) and systemd-run can keep
# a sign-in alive past this run. Asked once per 5dive version: an empty stdin is
# refused before any session is looked up, so the probe touches nothing.
takes_signin() {
  local state=$1 ver=$2 seen="" out
  command -v systemd-run >/dev/null || return 1
  [[ -f "$state/signin-cli" ]] && read -r seen <"$state/signin-cli" || true
  [[ "$seen" == "$ver yes" ]] && return 0
  [[ "$seen" == "$ver no" ]] && return 1
  out=$(timeout 20 5dive agent auth submit 0000000000000000 --code=- </dev/null 2>&1) || true
  if [[ "$out" == *"no callback code on stdin"* ]]; then printf '%s yes\n' "$ver" >"$state/signin-cli"; return 0; fi
  printf '%s no\n' "$ver" >"$state/signin-cli"
  return 1
}

apply_owed_locked() {
  local api=$1 tmp=$2 state=$3 agents=$4 ver=${5:-} status item id kind err ok kinds=telegram,secret,agent,aikey
  # bash's here-strings below carry a value: their scratch files go in the 0700 dir too.
  local TMPDIR=$tmp
  # kinds=agent: this reporter applies agent settings, so 5dive.app may hold them for it (DIVE-7253).
  # signin,hire: and makes the first agent from the app, when this 5dive can (DIVE-8292).
  # made: and hires the agents the owner made in the app before this server linked (DIVE-8385).
  takes_signin "$state" "$ver" && kinds+=,signin,hire,made
  status=$( (umask 077; curl -sS --max-time 30 -o "$tmp/owed.json" -w '%{http_code}' -H @"$tmp/auth" \
    "$api/server/selfhost/owed?kinds=$kinds" 2>/dev/null) ) || return 0
  [[ "$status" == 200 ]] || { rm -f "$tmp/owed.json"; return 0; }
  if jq -e '.fast == true' "$tmp/owed.json" >/dev/null 2>&1; then echo 1 >"$tmp/owed-fast"; else echo 0 >"$tmp/owed-fast"; fi
  # The fast loop reads the agent list only when something is owed.
  if [[ "$agents" == - ]] && jq -e '(.items // []) | length > 0' "$tmp/owed.json" >/dev/null 2>&1; then
    agents=$(5dive agent list --json 2>/dev/null </dev/null | jq -c '.data // []' 2>/dev/null) || agents='[]'
    [[ -n "$agents" ]] || agents='[]'
  fi
  ( umask 077; : >"$tmp/owed-done"; : >"$tmp/owed-failed" )
  while IFS= read -r item; do
    [[ -n "$item" ]] || continue
    id=$(jq -r '.id // empty' <<<"$item")
    kind=$(jq -r '.kind // empty' <<<"$item")
    [[ "$id" =~ ^[0-9a-f]{32}$ ]] || continue
    # Made 0600 first: a redirect into an existing file keeps its mode.
    ( umask 077; : >"$tmp/owed-err" )
    ok=0
    # Called as conditions, so a refusal is acked as failed instead of ending the run (set -e).
    case "$kind" in
      telegram) if owed_telegram "$item" "$agents" "$tmp"; then ok=1; rm -f "$state/last"; fi ;;
      secret) if owed_secret "$item" "$tmp"; then ok=1; fi ;;
      agent) if owed_agent "$item" "$agents" "$tmp"; then ok=1; rm -f "$state/last"; fi ;;
      aikey) if owed_aikey "$item" "$tmp"; then ok=1; rm -f "$state/last"; fi ;;
      signin) if owed_signin "$item" "$tmp" "$api" "$state"; then ok=1; fi ;;
      hire) if owed_hire "$item" "$agents" "$tmp"; then ok=1; rm -f "$state/last"; fi ;;
      made) if owed_made "$item" "$agents" "$tmp"; then ok=1; rm -f "$state/last"; fi ;;
      *) echo "unknown kind" >"$tmp/owed-err" ;;
    esac
    if (( ok )); then
      printf '%s\n' "$id" >>"$tmp/owed-done"
    else
      err=$(tail -c 300 "$tmp/owed-err" 2>/dev/null || true)
      printf '%s' "${err:-failed}" | jq -Rsc --arg id "$id" '{id: $id, error: .}' >>"$tmp/owed-failed"
    fi
  done < <(jq -c '.items // [] | .[]' "$tmp/owed.json" 2>/dev/null)
  rm -f "$tmp/owed.json" "$tmp/owed-err"
  [[ -s "$tmp/owed-done" || -s "$tmp/owed-failed" ]] || return 0
  ( umask 077; jq -cn --rawfile d "$tmp/owed-done" --slurpfile f "$tmp/owed-failed" \
    '{done: ($d | split("\n") | map(select(length > 0))), failed: $f}' >"$tmp/ack.json" ) || return 0
  curl -sS --max-time 30 -o /dev/null -X POST -H @"$tmp/auth" -H 'content-type: application/json' \
    --data-binary @"$tmp/ack.json" "$api/server/selfhost/owed/ack" 2>/dev/null || true
  rm -f "$tmp/ack.json" "$tmp/owed-done" "$tmp/owed-failed" "$tmp/owed-err"
}

# An agent's new Telegram bot: telegram joins its channels, the token goes on
# stdin (`telegram.token=-`), and only the owner who made the bot may talk to it.
# Returning 0 drops the report hash, so its @username reaches 5dive.app next minute.
owed_telegram() {
  local item=$1 agents=$2 tmp=$3 agent owner token channels rc=0
  agent=$(jq -r '.agent // empty' <<<"$item")
  owner=$(jq -r '.ownerTgId // empty' <<<"$item")
  [[ "$agent" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || { echo "bad agent name" >"$tmp/owed-err"; return 1; }
  [[ -z "$owner" || "$owner" =~ ^[0-9]{1,20}$ ]] || { echo "bad owner id" >"$tmp/owed-err"; return 1; }
  jq -e --arg n "$agent" 'any(.[]; .name == $n)' <<<"$agents" >/dev/null 2>&1 || { echo "no agent named $agent" >"$tmp/owed-err"; return 1; }
  channels=$(jq -r --arg n "$agent" '.[] | select(.name == $n) | .channels // empty' <<<"$agents")
  if [[ -z "$channels" || "$channels" == none ]]; then channels=telegram
  elif [[ ",$channels," != *,telegram,* ]]; then channels="$channels,telegram"; fi
  token=$(jq -r '.token // empty' <<<"$item")
  [[ -n "$token" ]] || { echo "no token" >"$tmp/owed-err"; return 1; }
  local args=(agent config "$agent" set "channels=$channels" telegram.token=-)
  [[ -n "$owner" ]] && args+=("telegram.allowed-users=$owner")
  printf '%s' "$token" | 5dive "${args[@]}" >/dev/null 2>"$tmp/owed-err" || rc=$?
  if (( rc )) && [[ -s "$tmp/owed-err" ]]; then
    local e; e=$(<"$tmp/owed-err"); printf '%s' "${e//"$token"/[redacted]}" >"$tmp/owed-err"
  fi
  token=
  return $rc
}

# A secret the owner sent from 5dive.app, written as `5dive secret write` writes any.
owed_secret() {
  local item=$1 tmp=$2 key connector value rc=0
  key=$(jq -r '.key // empty' <<<"$item")
  connector=$(jq -r '.connector // "tools"' <<<"$item")
  [[ "$key" =~ ^[A-Z][A-Z0-9_]{1,63}$ ]] || { echo "bad key name" >"$tmp/owed-err"; return 1; }
  [[ "$connector" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || { echo "bad connector" >"$tmp/owed-err"; return 1; }
  value=$(jq -r '.value // empty' <<<"$item")
  [[ -n "$value" ]] || { echo "no value" >"$tmp/owed-err"; return 1; }
  printf '%s' "$value" | 5dive secret write "$key" --connector="$connector" >/dev/null 2>"$tmp/owed-err" || rc=$?
  if (( rc )) && [[ -s "$tmp/owed-err" ]]; then
    local e; e=$(<"$tmp/owed-err"); printf '%s' "${e//"$value"/[redacted]}" >"$tmp/owed-err"
  fi
  value=
  return $rc
}

# DIVE-7256: an AI provider key from the app's AI tab, made an AI login the way
# 5dive.app's own AI page makes one (`account set --type=claude`, the key on
# stdin). `secret write` refuses these names (every agent loads tools.sh). No
# --replace: an account that already has a key is refused, never overwritten.
owed_aikey() {
  local item=$1 tmp=$2 account provider value rc=0
  account=$(jq -r '.account // empty' <<<"$item")
  provider=$(jq -r '.provider // empty' <<<"$item")
  [[ "$account" =~ ^[a-z][a-z0-9_-]{0,31}$ && "$account" != default ]] || { echo "bad account name" >"$tmp/owed-err"; return 1; }
  local args=(account set "$account" --type=claude)
  case "$provider" in
    openrouter) args+=(--provider=openrouter) ;;
    anthropic) ;; # the CLI's plain ANTHROPIC_API_KEY write: no --provider
    *) echo "bad provider" >"$tmp/owed-err"; return 1 ;;
  esac
  value=$(jq -r '.value // empty' <<<"$item")
  [[ -n "$value" ]] || { echo "no value" >"$tmp/owed-err"; return 1; }
  args+=(--api-key=-)
  printf '%s' "$value" | 5dive "${args[@]}" >/dev/null 2>"$tmp/owed-err" || rc=$?
  if (( rc )) && [[ -s "$tmp/owed-err" ]]; then
    local e; e=$(<"$tmp/owed-err"); printf '%s' "${e//"$value"/[redacted]}" >"$tmp/owed-err"
  fi
  value=
  return $rc
}

# DIVE-7253: a setting the owner changed on the agent's sheet in 5dive.app. The
# command is built here from checked values, never taken from the item. Returning
# 0 drops the report hash, so the new model (or the agent gone) reaches 5dive.app
# next minute.
owed_agent() {
  local item=$1 agents=$2 tmp=$3 agent op model effort
  agent=$(jq -r '.agent // empty' <<<"$item")
  op=$(jq -r '.op // empty' <<<"$item")
  [[ "$agent" =~ ^[a-z][a-z0-9-]{0,31}$ ]] || { echo "bad agent name" >"$tmp/owed-err"; return 1; }
  jq -e --arg n "$agent" 'any(.[]; .name == $n)' <<<"$agents" >/dev/null 2>&1 || { echo "no agent named $agent" >"$tmp/owed-err"; return 1; }
  case "$op" in
    model)
      model=$(jq -r '.model // empty' <<<"$item")
      effort=$(jq -r '.effort // empty' <<<"$item")
      [[ "$model" =~ ^[a-z0-9][a-z0-9.-]{0,63}$ ]] || { echo "bad model" >"$tmp/owed-err"; return 1; }
      [[ "$effort" =~ ^(low|medium|high|xhigh|max)$ ]] || { echo "bad effort" >"$tmp/owed-err"; return 1; }
      5dive agent config "$agent" set "model=$model" "effort=$effort" </dev/null >/dev/null 2>"$tmp/owed-err" ;;
    remove) 5dive agent rm "$agent" </dev/null >/dev/null 2>"$tmp/owed-err" ;;
    *) echo "unknown setting" >"$tmp/owed-err"; return 1 ;;
  esac
}

# DIVE-8292: the fast loop. Asks what 5dive.app holds every few seconds while it
# says `fast` (the owner has the first-agent screen open, or a sign-in or hire is
# under way), at most 15 minutes; the minute run starts it again when needed.
fast_owed() {
  local api=$1 tmp=$2 state=$3 until ver="" misses=0 f
  until=$(( $(date +%s) + ${FAST_SECS:-900} ))
  ver=$(timeout 20 5dive --version 2>/dev/null </dev/null | grep -oE '[0-9]+[.][0-9]+[.][0-9]+' | head -n1) || ver=""
  while (( $(date +%s) < until )); do
    apply_owed "$api" "$tmp" "$state" - "$ver"
    f=$(cat "$tmp/owed-fast" 2>/dev/null || true)
    case "$f" in
      0) [[ -f "$state/signin" ]] || break ;;
      1|busy) misses=0 ;;
      *) misses=$((misses + 1)); (( misses >= 5 )) && break ;;
    esac
    sleep "${FAST_EVERY:-3}"
  done
}

# Its own unit, so it outlives this minute's run; one at a time.
start_fast() {
  systemctl is-active --quiet 5dive-chat-fast.service >/dev/null 2>&1 && return 0
  systemctl reset-failed 5dive-chat-fast.service >/dev/null 2>&1 || true
  systemd-run --quiet --collect --unit=5dive-chat-fast -p RuntimeMaxSec=960 \
    /usr/local/bin/5dive-chat-report --fast </dev/null >/dev/null 2>&1 || true
}

# DIVE-8292: a sign-in the owner started in 5dive.app, for a server with no
# terminal. start: `5dive agent auth start <claude|codex>` in its own unit (run
# inside this one, its login tmux died with it when this run ended: measured on
# a box, 2026-11-07); it installs Codex first when it is missing. The item is
# acked once the unit runs, and signin_watch takes it from there. submit
# (Claude): the code the owner pasted in 5dive.app goes to `auth submit
# --code=-` on stdin, never a command line, and is cut out of any error; done
# when the login is saved. Every command is built here from checked values.
# The AIs the app can sign in and hire here (DIVE-8292). An allow-list for
# values the API holds, not a list of kinds shown to anyone (DIVE-8244).
signin_type_ok() {
  case "$1" in claude|codex) return 0 ;; *) return 1 ;; esac
}

owed_signin() {
  local item=$1 tmp=$2 api=$3 state=$4 id op type account session code st out five i rc=0
  id=$(jq -r '.id // empty' <<<"$item")
  op=$(jq -r '.op // empty' <<<"$item")
  case "$op" in
    start)
      type=$(jq -r '.type // empty' <<<"$item")
      account=$(jq -r '.account // empty' <<<"$item")
      signin_type_ok "$type" || { echo "bad type" >"$tmp/owed-err"; return 1; }
      [[ "$account" =~ ^[a-z][a-z0-9_-]{0,31}$ && "$account" != default ]] || { echo "bad account name" >"$tmp/owed-err"; return 1; }
      five=$(command -v 5dive) || { echo "5dive is missing" >"$tmp/owed-err"; return 1; }
      # A newer start replaces an older login still waiting.
      systemctl stop 5dive-chat-signin.service >/dev/null 2>&1 || true
      systemctl reset-failed 5dive-chat-signin.service >/dev/null 2>&1 || true
      rm -f "$state/signin"
      ( umask 077; : >"$state/signin.out" )
      systemd-run --quiet --unit=5dive-chat-signin -p RemainAfterExit=yes \
        -p "StandardOutput=file:$state/signin.out" -p StandardError=null \
        "$five" agent auth start "$type" "--auth-profile=$account" --json </dev/null >/dev/null 2>"$tmp/owed-err" || return 1
      ( umask 077; jq -cn --arg id "$id" --arg t "$type" --argjson at "$(date +%s)" '{id: $id, type: $t, at: $at, session: "", posted: false}' >"$state/signin" )
      return 0 ;;
    submit)
      session=$(jq -r '.session // empty' <<<"$item")
      [[ "$session" =~ ^[0-9a-f]{16}$ ]] || { echo "bad session" >"$tmp/owed-err"; return 1; }
      code=$(jq -r '.code // empty' <<<"$item")
      [[ -n "$code" ]] || { echo "no code" >"$tmp/owed-err"; return 1; }
      printf '%s\n' "$code" | 5dive agent auth submit "$session" --code=- >/dev/null 2>"$tmp/owed-err" || rc=$?
      if (( rc == 0 )); then
        rc=1
        echo "Claude did not take the code in time" >"$tmp/owed-err"
        for ((i = 0; i < ${SIGNIN_CODE_WAIT:-90}; i++)); do
          out=$(timeout 20 5dive agent auth poll "$session" --json 2>/dev/null </dev/null) || out=""
          st=$(jq -r '.data.state // empty' <<<"$out" 2>/dev/null) || st=""
          if [[ "$st" == ok ]]; then rc=0; : >"$tmp/owed-err"; break; fi
          if [[ "$st" == error || "$st" == expired ]]; then
            jq -r '.data.error // "Claude refused the code"' <<<"$out" 2>/dev/null | head -c 300 >"$tmp/owed-err"
            break
          fi
          sleep 1
        done
      fi
      if (( rc )) && [[ -s "$tmp/owed-err" ]]; then
        local e; e=$(<"$tmp/owed-err"); printf '%s' "${e//"$code"/[redacted]}" >"$tmp/owed-err"
      fi
      code=
      # Signed in: the login is saved in its account, the unit holding it can go.
      (( rc )) || systemctl stop 5dive-chat-signin.service >/dev/null 2>&1 || true
      return $rc ;;
    *) echo "unknown sign-in step" >"$tmp/owed-err"; return 1 ;;
  esac
}

# DIVE-8292: the sign-in under way ($state/signin, from owed_signin start), one
# step per call, so the fast loop never waits on it: read the start's session,
# then post its link (and ChatGPT's user code) to 5dive.app; a ChatGPT device
# sign-in is then watched until the login lands (ok) or fails. Claude's goes on
# with the code the owner pastes (owed_signin submit). The link and code are cut
# out of any error sent back. Over after 15 minutes.
signin_watch() {
  local api=$1 tmp=$2 state=$3 f="$3/signin" id type sid posted at out st url code err
  [[ -f "$f" ]] || return 0
  id=$(jq -r '.id // empty' "$f" 2>/dev/null) || id=""
  type=$(jq -r '.type // empty' "$f" 2>/dev/null) || type=""
  sid=$(jq -r '.session // empty' "$f" 2>/dev/null) || sid=""
  posted=$(jq -r '.posted // false' "$f" 2>/dev/null) || posted=false
  at=$(jq -r '.at // 0' "$f" 2>/dev/null) || at=0
  [[ "$id" =~ ^[0-9a-f]{32}$ && "$at" =~ ^[0-9]+$ ]] && signin_type_ok "$type" || { rm -f "$f"; return 0; }
  if (( $(date +%s) - at > ${SIGNIN_SECS:-900} )); then
    signin_end "$api" "$tmp" "$state" "$id" error "the sign-in timed out: start it again"
    return 0
  fi
  if [[ -z "$sid" ]]; then
    sid=$(jq -r 'select(.ok == true) | .data.sessionId // empty' "$state/signin.out" 2>/dev/null | head -n1) || sid=""
    if [[ -z "$sid" ]]; then
      if jq -e 'select(.ok == false)' "$state/signin.out" >/dev/null 2>&1; then
        err=$(jq -r 'select(.ok == false) | .error.message // .error // empty' "$state/signin.out" 2>/dev/null | head -c 300) || err=""
        signin_end "$api" "$tmp" "$state" "$id" error "${err:-the sign-in did not start}"
      fi
      return 0
    fi
    [[ "$sid" =~ ^[0-9a-f]{16}$ ]] || { signin_end "$api" "$tmp" "$state" "$id" error "the sign-in did not start"; return 0; }
    ( umask 077; jq -c --arg s "$sid" '.session = $s' "$f" >"$f.tmp" && mv -f "$f.tmp" "$f" )
  fi
  out=$(timeout 20 5dive agent auth poll "$sid" --json 2>/dev/null </dev/null) || out=""
  st=$(jq -r '.data.state // empty' <<<"$out" 2>/dev/null) || st=""
  url=$(jq -r '.data.url // empty' <<<"$out" 2>/dev/null) || url=""
  code=$(jq -r '.data.code // empty' <<<"$out" 2>/dev/null) || code=""
  if [[ "$st" == error || "$st" == expired ]]; then
    err=$(jq -r '.data.error // empty' <<<"$out" 2>/dev/null | head -c 300) || err=""
    [[ -n "$url" ]] && err=${err//"$url"/[redacted]}
    [[ -n "$code" ]] && err=${err//"$code"/[redacted]}
    signin_end "$api" "$tmp" "$state" "$id" error "${err:-the sign-in ended: start it again}"
    return 0
  fi
  if [[ "$posted" != true ]]; then
    [[ -n "$url" ]] || return 0
    if ! [[ "$url" =~ ^https://[^[:space:]]+$ && ${#url} -le 2048 ]] || { [[ "$type" == codex ]] && ! [[ "$code" =~ ^[0-9A-Z]{4}-[0-9A-Z]{4,6}$ ]]; }; then
      signin_end "$api" "$tmp" "$state" "$id" error "the sign-in gave no usable link"
      return 0
    fi
    ( umask 077; if [[ "$type" == codex ]]; then
        jq -cn --arg id "$id" --arg s "$sid" --arg u "$url" --arg c "$code" '{id: $id, session: $s, url: $u, userCode: $c}'
      else
        jq -cn --arg id "$id" --arg s "$sid" --arg u "$url" '{id: $id, session: $s, url: $u}'
      fi >"$tmp/signin.json" )
    if [[ "$(signin_post "$api" "$tmp")" == 200 ]]; then
      # Claude's goes on when the owner pastes the code; ChatGPT's is watched here.
      if [[ "$type" != codex ]]; then rm -f "$f"
      else ( umask 077; jq -c '.posted = true' "$f" >"$f.tmp" && mv -f "$f.tmp" "$f" ); fi
    fi
    return 0
  fi
  # ChatGPT: the owner entered the code at the link; the login lands here.
  [[ "$st" == ok ]] && signin_end "$api" "$tmp" "$state" "$id" ok ""
  return 0
}

signin_post() {
  local api=$1 tmp=$2 status
  status=$(curl -sS --max-time 30 -o /dev/null -w '%{http_code}' -X POST -H @"$tmp/auth" -H 'content-type: application/json' \
    --data-binary @"$tmp/signin.json" "$api/server/selfhost/signin" 2>/dev/null) || status=000
  rm -f "$tmp/signin.json"
  printf '%s' "$status"
}

# The sign-in is over: say so, and let the login's unit go.
signin_end() {
  local api=$1 tmp=$2 state=$3 id=$4 how=$5 err=$6
  ( umask 077; jq -cn --arg id "$id" --arg s "$how" --arg e "$err" '{id: $id, state: $s} + (if $e == "" then {} else {error: $e} end)' >"$tmp/signin.json" )
  signin_post "$api" "$tmp" >/dev/null
  rm -f "$state/signin"
  systemctl stop 5dive-chat-signin.service >/dev/null 2>&1 || true
}

# DIVE-8292: the first agent, as `5dive init` makes it: Claude Code or Codex on
# the account just signed in, no channel named (so on this linked server `agent
# create` turns 5dive.app chat on), and create's own defaults (the first agent
# of a server gets admin). Then the report goes at once, not next minute.
owed_hire() {
  local item=$1 agents=$2 tmp=$3 name type account
  name=$(jq -r '.name // empty' <<<"$item")
  type=$(jq -r '.type // empty' <<<"$item")
  account=$(jq -r '.account // empty' <<<"$item")
  [[ "$name" =~ ^[a-z][a-z0-9-]{0,15}$ ]] || { echo "bad agent name" >"$tmp/owed-err"; return 1; }
  signin_type_ok "$type" || { echo "bad type" >"$tmp/owed-err"; return 1; }
  [[ "$account" =~ ^[a-z][a-z0-9_-]{0,31}$ && "$account" != default ]] || { echo "bad account name" >"$tmp/owed-err"; return 1; }
  if jq -e --arg n "$name" 'any(.[]; .name == $n)' <<<"${agents:-[]}" >/dev/null 2>&1; then
    echo "an agent named $name is already here" >"$tmp/owed-err"
    return 1
  fi
  timeout 600 5dive agent create "$name" "--type=$type" "--auth-profile=$account" </dev/null >/dev/null 2>"$tmp/owed-err" || return 1
  systemctl start --no-block 5dive-chat-report.service >/dev/null 2>&1 || true
}

# DIVE-8385: an agent the owner made in the app (the creator) while this server
# was not linked yet, hired here once it links: `5dive agent import` of her
# pack, by the signed link 5dive.app minted for it (a day to live), with no
# terminal. Off one, a server with no AI yet keeps her waiting and starts her
# when the first AI is added (the CLI's DIVE-7848). A taken name runs nothing.
owed_made() {
  local item=$1 agents=$2 tmp=$3 name url
  name=$(jq -r '.name // empty' <<<"$item")
  url=$(jq -r '.url // empty' <<<"$item")
  [[ "$name" =~ ^[a-z][a-z0-9-]{0,15}$ ]] || { echo "bad agent name" >"$tmp/owed-err"; return 1; }
  [[ "$url" =~ ^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?/custom-agent/packs/[a-z0-9]{12}\.tar\.gz\?e=[0-9]{1,12}\&sig=[0-9a-f]{64}$ ]] \
    || { echo "bad pack link" >"$tmp/owed-err"; return 1; }
  if jq -e --arg n "$name" 'any(.[]; .name == $n)' <<<"${agents:-[]}" >/dev/null 2>&1; then
    echo "an agent named $name is already here" >"$tmp/owed-err"
    return 1
  fi
  timeout 600 5dive agent import "--from-url=$url" "--as=$name" </dev/null >/dev/null 2>"$tmp/owed-err" || return 1
  systemctl start --no-block 5dive-chat-report.service >/dev/null 2>&1 || true
}

# DIVE-8244: `5dive agent config` refusing chat for this kind of agent, as
# opposed to failing (the link script's own copy of this test).
no_chat_kind() {
  [[ "$1" == *"channels=dashboard requires type="* || "$1" == *"does not support channels"* ]]
}

# The team, as `5dive export` prints it, when its hash changed. Best effort: an
# older CLI without export, or a failed post, just tries again next minute.
post_team() {
  local api=$1 tmp=$2 state=$3 sum last="" status
  5dive export >"$tmp/team.yaml" 2>/dev/null </dev/null || return 0
  [[ -s "$tmp/team.yaml" ]] || return 0
  (( $(wc -c <"$tmp/team.yaml") <= 262144 )) || return 0
  sum=$(sha256sum "$tmp/team.yaml" | cut -d' ' -f1)
  if [[ -f "$state/last-team" ]]; then read -r last <"$state/last-team" || true; fi
  [[ "$sum" == "$last" ]] && return 0
  status=$(curl -sS --max-time 30 -o /dev/null -w '%{http_code}' -X POST -H @"$tmp/auth" \
    -H 'content-type: application/yaml' --data-binary @"$tmp/team.yaml" \
    "$api/server/selfhost/team" 2>/dev/null) || return 0
  case "$status" in
    200) printf '%s\n' "$sum" >"$state/last-team" ;;
    401|403)
      echo "5dive.app no longer knows this server; stopping. Link it again from 5dive.app." >&2
      systemctl disable --now 5dive-chat-report.timer >/dev/null 2>&1 || true
      exit 0 ;;
    *) : ;;
  esac
}

main "$@"
REPORTER
  chmod 755 /usr/local/bin/5dive-chat-report.tmp
  mv -f /usr/local/bin/5dive-chat-report.tmp /usr/local/bin/5dive-chat-report

  cat >/etc/systemd/system/5dive-chat-report.service <<'UNIT'
[Unit]
Description=5dive.app chat: report this server's agents (outbound only)
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/5dive-chat-report
TimeoutStartSec=300
UNIT
  cat >/etc/systemd/system/5dive-chat-report.timer <<'UNIT'
[Unit]
Description=5dive.app chat: report this server's agents every minute

[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
AccuracySec=5s

[Install]
WantedBy=timers.target
UNIT
  rm -f /var/lib/5dive-chat/last /var/lib/5dive-chat/last-team
  systemctl daemon-reload
  systemctl enable --now 5dive-chat-report.timer >/dev/null 2>&1
  # Once now, so 5dive.app shows the agents (and moves on) without waiting a minute.
  systemctl start 5dive-chat-report.service >/dev/null 2>&1 \
    || echo "warning: the first report did not go through; it retries every minute (journalctl -u 5dive-chat-report)" >&2
}

main "$@"
