#!/usr/bin/env bash
# ncode — the installed ncode terminal client.
#
# Opens the saved session for a project directory (the current directory by
# default) with the same environment rules as the development launchers:
# provider settings come from the shell, or from ~/.secrets (NCODE_ENV_FILE)
# when no provider key is exported.
#
# The full-screen view starts the release; `-p` and `--plain` evaluate
# SwarmCodeCLI.Release.main/1 with only their own flags, after the choices
# below have been exported. Exit codes: 0 done, 1 the run failed, 2 usage,
# 3 startup refused.
set -euo pipefail

usage() {
  # A builtin, not a here-document: bash 5.3 writes a here-document into a
  # pipe, and a small (512-byte) pipe under macOS pipe-memory pressure left
  # the help waiting for ever (cli020 finisher).
  printf '%s\n' 'Usage: ncode [DIR] [--new | --continue | --resume ID] [--model M]
             [-p PROMPT [--json] [--fail-on-denied]] [--plain [--ndjson]]
       ncode settings [QUERY] [--dir DIR]
       ncode config COMMAND [ARGS]     (ncode config help lists them)
       ncode update [--yes]            install the latest ncode CLI
       ncode acp                       Agent Client Protocol agent over stdio (for editors)
       ncode help | version | doctor

Opens the saved session for DIR (default: the current directory).
With no flag it opens Home: recent work, live runs, resume (Esc continues the latest).

  settings [QUERY]  open Settings, at QUERY when given ('\''ncode settings providers'\'');
                    it opens even when no model provider is set up yet
  config COMMAND    read and change settings from scripts, dotfiles and SSH
  doctor            check the install, the providers and the database (config doctor)
                    (a folder with one of these names: ncode ./settings, ./config)

  --new             start a new conversation
  --continue, -c    continue the latest conversation, skipping Home
  --resume, -r [ID] open the conversation with this id, 6+ characters of it or its
                    title; without one, pick it from a list
  --model, -m M     use model M (or provider/model) for this session only
  -p PROMPT         run one turn in a new conversation (-c or --resume to continue
                    one) without the full-screen view, print the answer and exit;
                    approvals nobody can give are denied, and one stderr line says
                    which. PROMPT - reads the prompt from stdin; with a PROMPT,
                    piped stdin is sent after it
  --json            with -p: print one JSON object instead of the streamed answer
  --fail-on-denied  with -p or --plain: exit 1 when a tool call was denied
  --output-format F with -p: text (the default), json (= --json) or stream-json
                    (one JSON record per line, the last {"type":"summary",...})
  --max-turns N     with -p: stop the run after N turns of its lead (1-200)
  --max-budget-usd X  with -p: stop the run once it costs more than $X
  --approval MODE   with -p: read-only, auto or full for this run only
  --add-dir DIR     let agents read another folder (read-only, this session only;
                    repeat it, up to 8); works with the full-screen view and -p
  --image, -i PATH  with -p: attach an image (PNG, JPEG, GIF or WebP inside the
                    project folder; repeat it, up to 4)
  -o, --output-last-message FILE  with -p: also write the final answer to FILE
  --plain           line-by-line presenter for pipes, CI and SSH (type `help`);
                    chosen by itself when stdin or stdout is not a terminal
  --ndjson          with --plain: one JSON record per line
  --help, -h        this text
  --version, -V, -v the version

Examples:
  ncode
  ncode -p "explain this repo" --json
  ncode settings providers
  ncode config doctor

Exit codes: 0 done, 1 the run failed, 2 usage, 3 startup refused,
4 changed elsewhere (ncode config), 129/143 closed by SIGHUP/SIGTERM.

Provider settings (shell exports win; otherwise loaded from ~/.secrets or NCODE_ENV_FILE):
  NCODE_MODEL          model id (first run, when the app has no provider yet)
  NCODE_BASE_URL       endpoint; OpenAI-compatible URLs include /v1 (OPENAI_API_KEY
                       alone means api.openai.com, ANTHROPIC_API_KEY api.anthropic.com)
  NCODE_API_KEY        or OPENAI_API_KEY / ANTHROPIC_API_KEY
  NCODE_PROVIDER       openai (default) or anthropic
  NCODE_EFFORT         reasoning effort key
  NCODE_ENV_FILE       the file to load them from (default ~/.secrets)

Session:
  NCODE_CONVERSATION   latest, new, or a conversation id (the flags win; unset opens Home)
  NCODE_KEYMAP=vim     vim keys in the composer
  NCODE_ASCII=1        plain ASCII glyphs, for a terminal or font without symbols
  NCODE_THEME          dark or light
  NCODE_MOUSE=1        mouse wheel reports (/mouse in ncode)
  NCODE_COMPANION=0    do not serve the visual companion
  NCODE_CONFIG_DIR     the global folder: memory, skills, workflows, cli.json (absolute)
  NCODE_SHELL          the shell the model'\''s commands run in

The older SWARM_* names (SWARM_MODEL, SWARM_API_KEY, ...) still work; when both
are set, the NCODE_* one wins. swarmcode and swarm-code are old names of ncode.

Keys: type to write; Enter sends, Esc stops a turn, Ctrl-C twice quits,
Ctrl-P palette (also /resume, /new, /model, /approval), Ctrl-T select, ? every key,
Ctrl-F agents (side-panel hints), Ctrl-B panel (full, compact, hidden).
SWARM_PROJECT_ROOT is ignored; name the directory instead.'
}

self="$0"
if command -v readlink >/dev/null 2>&1; then
  resolved=$(readlink -f -- "$self" 2>/dev/null || true)
  [[ -n "$resolved" ]] && self="$resolved"
fi
root=$(CDPATH= cd -- "$(dirname -- "$self")/.." && pwd)

version() {
  local data="$root/releases/start_erl.data" erts="" vsn=""
  if [[ -r "$data" ]]; then
    read -r erts vsn <"$data" || true
  fi
  echo "ncode ${vsn:-unknown}"
}

# cli020 B4: with --json on the command line a usage error also prints the
# -p summary object on stdout (the script reads stdout). The sentence is the
# launcher's own; control characters go and \ and " are escaped.
json_requested=0
if [[ "${1:-}" != "config" && "${1:-}" != "settings" ]]; then
  json_prev=""
  for json_arg in "$@"; do
    [[ "$json_arg" == "--" ]] && break
    case "$json_arg" in
      --json | --output-format=json) json_requested=1 ;;
      --output-format=stream-json) json_requested=2 ;;
      json) [[ "$json_prev" == "--output-format" ]] && json_requested=1 ;;
      stream-json) [[ "$json_prev" == "--output-format" ]] && json_requested=2 ;;
    esac
    json_prev="$json_arg"
  done
  unset json_arg json_prev
fi

json_failure() {
  [[ $json_requested -ge 1 ]] || return 0
  local text type=""
  # A stream-json stream ends with its summary record.
  [[ $json_requested -eq 2 ]] && type='"type":"summary",'

  text=$(printf '%s' "$1" | LC_ALL=C tr -d '\000-\037\177' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')
  # Every launcher failure is a usage error; the reason word is fixed.
  printf '{'"$type"'"state":"not_started","reason":"usage","conversation_id":null,"run_id":null,"text":"","error":"%s","question":null,"denied":[],"exit_code":%s}\n' \
    "$text" "$2"
}

die_usage() {
  echo "ncode: $1 Run 'ncode --help'." >&2
  json_failure "$1 Run 'ncode --help'." 2
  exit 2
}

# NCODE_* first, SWARM_* as the fallback: the release reads only the SWARM_*
# names, so an exported NCODE_X is copied over SWARM_X here, before anything
# below reads it. SWARM_PROJECT_ROOT has no NCODE_ twin (it is ignored).
# Keep this list in step with the one in scripts/dev/load_provider_env.sh
# (bin/load_provider_env.sh in the release).
for ncode_pair in MODEL:MODEL BASE_URL:BASE_URL API_KEY:API_KEY PROVIDER:PROVIDER \
  EFFORT:EFFORT CONVERSATION:CONVERSATION KEYMAP:KEYMAP ASCII:ASCII COMPANION:COMPANION \
  THEME:THEME MOUSE:MOUSE APPROVAL:APPROVAL ENV_FILE:ENV_FILE \
  CONFIG_DIR:CODE_CONFIG_DIR SHELL:CODE_SHELL; do
  ncode_name="NCODE_${ncode_pair%%:*}"
  if [[ -n ${!ncode_name+x} ]]; then
    export "SWARM_${ncode_pair#*:}=${!ncode_name}"
  fi
done
unset ncode_pair ncode_name

project=""
project_set=0
conversation=""
resume_picker=0
model=""
model_set=0
prompt=""
prompt_set=0
json=0
fail_on_denied=0
# cli020 B23: the other headless flags (with -p).
output_format=""
max_turns=""
max_budget=""
approval=""
images=()
output_file=""
add_dirs=()
plain=0
ndjson=0
seen=" "

once() {
  case "$seen" in
    *" $1 "*) die_usage "$1 is given twice." ;;
  esac
  seen="$seen$1 "
}

set_conversation() {
  [[ -z "$conversation" ]] || die_usage "choose one of --new, --continue and --resume."
  conversation="$1"
}

set_project() {
  [[ $project_set -eq 0 ]] || die_usage "name one directory at most."
  project="$1"
  project_set=1
}

# C-FEAT-10: a path given on the command line is the user's, relative to where
# the command ran; it is made absolute before anything changes directory.
abs_path() {
  case "$1" in
    /*) printf '%s' "$1" ;;
    *) printf '%s/%s' "$PWD" "$1" ;;
  esac
}

needs_file() {
  [[ -n "${2//[[:space:]]/}" ]] || die_usage "$1 needs a file."
}

# C-FEAT-12: --add-dir names a folder the agents may read (read-only, this
# session); it is resolved to its real path here, relative to where the command ran.
add_dir() {
  local resolved
  [[ -n "${1//[[:space:]]/}" ]] || die_usage "--add-dir needs a directory."
  resolved=$(cd -- "$1" 2>/dev/null && pwd -P) || die_usage "--add-dir needs a directory."
  add_dirs+=("$resolved")
}

needs_value() {
  [[ $2 -ge 2 && "$3" != "--" ]] || die_usage "$1 needs a value."
}

# C-FEAT-9: `ncode update [--yes]` downloads and runs the hosted installer
# (it checks the download's SHA-256). NCODE_INSTALL_URL points the download
# elsewhere; it exists for the tests and is not in --help.
update_cli() {
  local yes=0 answer=""
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --yes) yes=1 ;;
      *) die_usage "update takes --yes only." ;;
    esac
    shift
  done
  if [[ $yes -eq 0 ]]; then
    [[ -t 0 ]] || die_usage "ncode update needs --yes without a terminal."
    printf '%s' 'This downloads and runs the ncode installer from https://code.llmotions.com/install.sh (it checks the download'\''s SHA-256). Continue? [y/N] ' >&2
    read -r answer || true
    case "$answer" in
      y | Y) ;;
      *) echo "ncode: update cancelled." >&2; return 1 ;;
    esac
  fi
  curl -fsSL "${NCODE_INSTALL_URL:-https://code.llmotions.com/install.sh}" | sh
}

# pass74 S1-13/S1-14: `settings` and `config` as the first word are the
# subcommands; a folder of that name opens with ./settings or -- settings.
settings_mode=0
settings_query=""
# cli020 B16 (onboarding-10): the conventional words. A folder of that name
# opens with ./help, ./version or ./doctor.
if [[ $# -gt 0 ]]; then
  case "$1" in
    help) usage; exit 0 ;;
    version) version; exit 0 ;;
    doctor) shift; set -- config doctor "$@" ;;
    update) shift; update_cli "$@"; exit $? ;;
    # C-FEAT-13: an Agent Client Protocol agent on stdin and stdout. Nothing
    # else may reach stdout; the provider settings load as for -p.
    acp)
      shift
      [[ $# -eq 0 ]] || die_usage "acp takes no arguments."
      # shellcheck source=/dev/null
      . "$root/bin/load_provider_env.sh"
      unset SWARM_MODEL_OVERRIDE SWARM_CONVERSATION SWARM_RELEASE_TUI SWARM_SETTINGS_OPEN \
        SWARM_SETTINGS_ONLY SWARM_RESUME_PICKER SWARM_ADD_DIRS
      exec "$root/bin/swarm_code_cli" eval 'SwarmCodeCLI.Release.main(System.argv())' acp ;;
  esac
fi
if [[ $# -gt 0 && "$1" == "config" ]]; then
  shift
  export SWARM_PROJECT_ROOT="$PWD"
  unset SWARM_RELEASE_TUI SWARM_SETTINGS_OPEN SWARM_SETTINGS_ONLY
  stdin_secret=0
  if [[ "${1:-}" == "secret" && -t 0 ]]; then
    for arg in "$@"; do [[ "$arg" == "--stdin" ]] && stdin_secret=1; done
  fi
  if [[ $stdin_secret -eq 1 ]]; then
    # Secrets never come from argv; typed ones are not echoed.
    printf 'Paste the key, then Enter (not shown): ' >&2
    stty -echo
    trap 'stty echo' EXIT INT TERM
    set +e
    "$root/bin/swarm_code_cli" eval 'SwarmCodeCLI.Release.main(System.argv())' config "$@"
    code=$?
    stty echo
    printf '\n' >&2
    exit $code
  fi
  exec "$root/bin/swarm_code_cli" eval 'SwarmCodeCLI.Release.main(System.argv())' config "$@"
fi
if [[ $# -gt 0 && "$1" == "settings" ]]; then
  shift
  settings_mode=1
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --help | -h) usage; exit 0 ;;
      --dir) needs_value "$1" $# "${2:-}"; set_project "$2"; shift ;;
      --dir=*) set_project "${1#--dir=}" ;;
      -?*) die_usage "settings takes a query and --dir only." ;;
      *) settings_query="${settings_query:+$settings_query }$1" ;;
    esac
    shift
  done
  # The TUI opens at a query of 200 bytes at most (§3.10.1).
  if (($(printf '%s' "$settings_query" | LC_ALL=C wc -c) > 200)); then
    die_usage "the settings query is too long (200 bytes at most)."
  fi
fi

while [[ $# -gt 0 ]]; do
  case "$1" in
    --help | -h) usage; exit 0 ;;
    --version | -V | -v) version; exit 0 ;;
    --new) set_conversation new ;;
    --continue | -c) set_conversation latest ;;
    # cli020 B19: bare --resume opens the /resume picker; a value is an id,
    # 6 or more characters of one, or a title (the release resolves it).
    --resume | -r)
      if [[ $# -lt 2 || "$2" == "--" || "$2" == -* ]]; then
        set_conversation latest; resume_picker=1
      else
        set_conversation "$2"; shift
      fi ;;
    --resume=*) set_conversation "${1#--resume=}" ;;
    --model | -m) needs_value "$1" $# "${2:-}"; once --model; model="$2"; model_set=1; shift ;;
    --model=*) once --model; model="${1#--model=}"; model_set=1 ;;
    -p | --prompt | --print) needs_value "$1" $# "${2:-}"; once -p; prompt="$2"; prompt_set=1; shift ;;
    --prompt=*) once -p; prompt="${1#--prompt=}"; prompt_set=1 ;;
    --json) once --json; json=1 ;;
    --fail-on-denied) once --fail-on-denied; fail_on_denied=1 ;;
    --output-format) needs_value "$1" $# "${2:-}"; once --output-format; output_format="$2"; shift ;;
    --output-format=*) once --output-format; output_format="${1#--output-format=}" ;;
    --max-turns) needs_value "$1" $# "${2:-}"; once --max-turns; max_turns="$2"; shift ;;
    --max-turns=*) once --max-turns; max_turns="${1#--max-turns=}" ;;
    --max-budget-usd) needs_value "$1" $# "${2:-}"; once --max-budget-usd; max_budget="$2"; shift ;;
    --max-budget-usd=*) once --max-budget-usd; max_budget="${1#--max-budget-usd=}" ;;
    --approval) needs_value "$1" $# "${2:-}"; once --approval; approval="$2"; shift ;;
    --approval=*) once --approval; approval="${1#--approval=}" ;;
    --image | -i) needs_value "$1" $# "${2:-}"; needs_file "$1" "$2"; images+=("$(abs_path "$2")"); shift ;;
    --image=*) needs_file --image "${1#--image=}"; images+=("$(abs_path "${1#--image=}")") ;;
    -o | --output-last-message) needs_value "$1" $# "${2:-}"; needs_file "$1" "$2"; once -o; output_file="$(abs_path "$2")"; shift ;;
    --output-last-message=*) needs_file -o "${1#--output-last-message=}"; once -o; output_file="$(abs_path "${1#--output-last-message=}")" ;;
    --add-dir) needs_value "$1" $# "${2:-}"; add_dir "$2"; shift ;;
    --add-dir=*) add_dir "${1#--add-dir=}" ;;
    --plain) once --plain; plain=1 ;;
    --ndjson) once --ndjson; ndjson=1 ;;
    --)
      shift
      while [[ $# -gt 0 ]]; do set_project "$1"; shift; done
      break
      ;;
    -?*) die_usage "unknown option '$1'." ;;
    *) set_project "$1" ;;
  esac
  shift
done

[[ $json -eq 0 || $prompt_set -eq 1 ]] || die_usage "--json goes with -p."
for b23_flag in output-format max-turns max-budget-usd approval; do
  b23_var=${b23_flag//-/_}; [[ $b23_var == max_budget_usd ]] && b23_var=max_budget
  if [[ -n "${!b23_var}" && $prompt_set -eq 0 ]]; then die_usage "--$b23_flag goes with -p."; fi
done
unset b23_flag b23_var
case "$output_format" in
  "" | text) ;;
  json) json=1 ;;
  stream-json) [[ $json -eq 0 ]] || die_usage "--json and --output-format stream-json do not go together." ;;
  *) die_usage "--output-format is text, json or stream-json." ;;
esac
if [[ "$output_format" == text && $json -eq 1 ]]; then
  die_usage "--json and --output-format text do not go together."
fi
if [[ -n "$max_turns" ]] && ! [[ "$max_turns" =~ ^[0-9]{1,3}$ && 10#$max_turns -ge 1 && 10#$max_turns -le 200 ]]; then
  die_usage "--max-turns needs a number from 1 to 200."
fi
if [[ -n "$max_budget" ]] && ! [[ "$max_budget" =~ ^[0-9]{1,6}(\.[0-9]{1,6})?$ && "$max_budget" =~ [1-9] ]]; then
  die_usage "--max-budget-usd needs an amount above 0 (in dollars)."
fi
case "$approval" in
  "") unset SWARM_HEADLESS_APPROVAL ;;
  read-only) export SWARM_HEADLESS_APPROVAL=read_only ;;
  auto) export SWARM_HEADLESS_APPROVAL=auto ;;
  full) export SWARM_HEADLESS_APPROVAL=full_access ;;
  *) die_usage "--approval is read-only, auto or full." ;;
esac
[[ ${#images[@]} -eq 0 || $prompt_set -eq 1 ]] || die_usage "--image goes with -p."
[[ ${#images[@]} -le 4 ]] || die_usage "at most 4 --image."
[[ -z "$output_file" || $prompt_set -eq 1 ]] || die_usage "-o goes with -p."
[[ ${#add_dirs[@]} -le 8 ]] || die_usage "at most 8 --add-dir."
[[ $ndjson -eq 0 || $plain -eq 1 ]] || die_usage "--ndjson goes with --plain."
[[ $plain -eq 0 || $prompt_set -eq 0 ]] || die_usage "-p and --plain do not go together."
if [[ $fail_on_denied -eq 1 && $prompt_set -eq 0 && $plain -eq 0 ]]; then
  die_usage "--fail-on-denied goes with -p or --plain."
fi
if [[ $model_set -eq 1 && -z "${model//[[:space:]]/}" ]]; then
  die_usage "--model needs a model name."
fi
if [[ $prompt_set -eq 1 && -z "${prompt//[[:space:]]/}" ]]; then
  die_usage "-p needs a prompt."
fi
case "$conversation" in
  "" | new | latest) ;;
  *)
    if [[ -z "${conversation//[[:space:]]/}" || "$conversation" =~ [[:cntrl:]] ]]; then
      die_usage "--resume needs an id or a title."
    fi ;;
esac
if [[ $resume_picker -eq 1 && ( $prompt_set -eq 1 || $plain -eq 1 ) ]]; then
  die_usage "--resume needs an id or a title here; ncode --resume alone opens the picker."
fi

# The project is the directory named on the command line, else where the
# command was run. SWARM_PROJECT_ROOT is deliberately ignored: shells that
# source the environment file export it everywhere, and a command that opened
# the same project from every directory would be useless. Name the directory.
# shellcheck source=/dev/null
. "$root/bin/load_provider_env.sh"
if [[ $project_set -eq 1 ]]; then
  root_dir="$project"
else
  root_dir="$PWD"
fi
if [[ ! -d "$root_dir" && $project_set -eq 1 && "$project" != */* && "$project" != .* && "$project" != "~"* ]]; then
  # cli020 B16: a word that is no folder is most likely a command.
  echo "ncode: '$project' is not a folder or a command. Did you mean --help? (To open a folder named $project, use ./$project.)" >&2
  json_failure "'$project' is not a folder or a command." 2
  exit 2
fi
if [[ ! -d "$root_dir" ]]; then
  echo "ncode: '$root_dir' is not a directory." >&2
  json_failure "'$root_dir' is not a directory." 2
  exit 2
fi
SWARM_PROJECT_ROOT=$(cd -- "$root_dir" && pwd)
export SWARM_PROJECT_ROOT
export SWARM_TERMINAL_PORT="${SWARM_TERMINAL_PORT:-$root/bin/swarm-terminal-port}"
if [[ -n "$conversation" ]]; then
  export SWARM_CONVERSATION="$conversation"
elif [[ $prompt_set -eq 1 && -z "${SWARM_CONVERSATION:-}" ]]; then
  # pass71 F9 (review R6): a one-shot starts its own conversation; it used to
  # land in the conversation you were working in and carry all its context.
  export SWARM_CONVERSATION=new
fi
# A session's model override comes from --model alone: an export left in a
# shell or an environment file never changes which model answers.
if [[ $model_set -eq 1 ]]; then
  export SWARM_MODEL_OVERRIDE="$model"
else
  unset SWARM_MODEL_OVERRIDE
fi
unset SWARM_RELEASE_TUI SWARM_SETTINGS_OPEN SWARM_SETTINGS_ONLY SWARM_RESUME_PICKER SWARM_ADD_DIRS
# C-FEAT-12: the extra read folders, one per line, for the release to read.
if [[ ${#add_dirs[@]} -gt 0 ]]; then
  SWARM_ADD_DIRS=$(printf '%s\n' "${add_dirs[@]}")
  export SWARM_ADD_DIRS
fi

# cli020 B20 (onboarding-18): something on the terminal while the VM boots;
# the release erases it ("\r\e[2K") before its exit summary.
starting_line() {
  if [[ -t 1 ]]; then printf 'Starting ncode\342\200\246'; fi
}

headless() {
  if [[ $fail_on_denied -eq 1 ]]; then set -- "$@" --fail-on-denied; fi
  exec "$root/bin/swarm_code_cli" eval 'SwarmCodeCLI.Release.main(System.argv())' "$@"
}

if [[ $prompt_set -eq 1 ]]; then
  # cli020 B1: a prompt with a pipe or a file on stdin sends that stdin after
  # it; a terminal, /dev/null or a socket is never read (a script whose stdin
  # is an idle inherited terminal must not hang).
  unset SWARM_STDIN_PIPED
  if [[ "$prompt" != "-" ]] && { [[ -p /dev/stdin ]] || [[ -f /dev/stdin ]]; }; then
    export SWARM_STDIN_PIPED=1
  fi
  set -- -p "$prompt"
  if [[ $json -eq 1 ]]; then set -- "$@" --json; fi
  if [[ "$output_format" == stream-json ]]; then set -- "$@" --output-format stream-json; fi
  if [[ -n "$max_turns" ]]; then set -- "$@" --max-turns "$max_turns"; fi
  if [[ -n "$max_budget" ]]; then set -- "$@" --max-budget-usd "$max_budget"; fi
  for image in ${images[@]+"${images[@]}"}; do set -- "$@" --image "$image"; done
  if [[ -n "$output_file" ]]; then set -- "$@" --output-last-message "$output_file"; fi
  headless "$@"
fi

if [[ $settings_mode -eq 1 ]]; then
  if ! [[ -t 0 && -t 1 && "${TERM:-dumb}" != "dumb" ]]; then
    echo "ncode: settings needs a terminal; 'ncode config' changes settings from scripts." >&2
    exit 2
  fi
  export SWARM_SETTINGS_OPEN="$settings_query"
  export SWARM_SETTINGS_ONLY=1
  export SWARM_RELEASE_TUI=1
  starting_line
  exec "$root/bin/swarm_code_cli" start
fi

if [[ $plain -eq 0 ]] && ! [[ -t 0 && -t 1 && "${TERM:-dumb}" != "dumb" ]]; then
  if [[ $resume_picker -eq 1 ]]; then
    die_usage "--resume needs an id or a title without a terminal; ncode --resume alone opens the picker."
  fi
  echo "ncode: not a terminal, so the plain presenter answers (--plain)." >&2
  plain=1
fi
if [[ $plain -eq 1 ]]; then
  if [[ $ndjson -eq 1 ]]; then headless --plain --ndjson; else headless --plain; fi
fi

export SWARM_RELEASE_TUI=1
if [[ $resume_picker -eq 1 ]]; then export SWARM_RESUME_PICKER=1; fi
starting_line
exec "$root/bin/swarm_code_cli" start
