#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C

die() { printf 'jailbee-inbox: %s\n' "$1" >&2; exit 2; }

usage() {
    cat <<'USAGE'
Usage: jailbee-inbox wait [--timeout DUR]
       jailbee-inbox ls
       jailbee-inbox read <id> [--keep]
       jailbee-inbox runners [--json]
       jailbee-inbox send <type> [options]

  wait   Print the path of the oldest unread message (exit 0), waiting up to
         DUR (seconds, or <n>s|m|h; default 30m) for one to arrive; exit 1
         on timeout. --timeout 0 checks once. After an arrival, wait briefly
         for the burst to settle; then use ls to handle every unread message.
  ls     One line per unread message, oldest first:
         <id> <type> <from or ref> <kind or state> <first 60 chars of text>
  read   Pretty-print message <id> and move it to inbox/read/ (--keep leaves
         it in place); exit 1 if no unread message has that id.

  runners  List the default runner and the runners a spawn or restart may name
         (--agent/--profile/--model of send). --json prints one array.

  send   Write a manifest for the orchestrator's host into outbox/ and print
         its id. --wait [--timeout DUR] waits for its status (default 30m):
         exit 0 on done/queued/started, 1 on refused/failed, 3 on timeout.
         Text (body or prompt) comes from --text T, --file PATH or -
         (stdin); at most 65536 bytes, not empty.
           message  [--to C] [--kind note|question|done|blocked]
                    [--reply-to ID] + text
           spawn    [--branch B] [--new [--base B] | --ref REF | --pr N]
                    [--mount M]... [--loose] [--egress H]... [--note T]
                    [--on-done destroy|keep] [runner] + text
                    --branch is required except for --pr; the broker derives
                    the branch from the PR and ignores any supplied branch.
           restart  --child C [--on-done destroy|keep] [runner | --default-runner] + text
           import | update | stop   --child C
           destroy  --child C [--force]
         runner = --agent claude|claude-jb [--profile P (claude-jb only)]
                  [--model fable|opus|sonnet|haiku]; see `runners`.
                  --default-runner (restart only) clears the child's runner.

Environment: JAILBEE_ORCHESTRATION_DIR (default ~/.jailbee/orchestration),
JAILBEE_LITELLM_CONFIG (default /etc/jailbee/litellm.json), JAILBEE_DEFAULT_AGENT,
JAILBEE_INBOX_POLL (poll seconds without inotifywait; default 5),
JAILBEE_INBOX_SETTLE (quiet seconds after an arrival; default 1, 0 disables).
USAGE
}

base="${JAILBEE_ORCHESTRATION_DIR:-$HOME/.jailbee/orchestration}"
inbox="$base/inbox"
outbox="$base/outbox"
poll="${JAILBEE_INBOX_POLL:-5}"
settle="${JAILBEE_INBOX_SETTLE:-1}"
SETTLE_MAX=5
[[ "$settle" =~ ^([0-9]+\.?[0-9]*|\.[0-9]+)$ ]] \
    || die "JAILBEE_INBOX_SETTLE must be a non-negative number of seconds, got '$settle'"
WATCH_SLICE=10  # seconds; longest single inotifywait (see cmd_wait)
[[ "$poll" =~ ^([0-9]+\.?[0-9]*|\.[0-9]+)$ ]] \
    && [[ "$poll" =~ [1-9] ]] \
    || die "JAILBEE_INBOX_POLL must be a positive number of seconds, got '$poll'"

# Unread message files, oldest (lexicographically first) first. With
# --first, only the oldest: a `| head -n 1` would SIGPIPE the producer under
# pipefail once the listing outgrows the pipe buffer.
unread_files() {
    local f first=0
    [ "${1:-}" = "--first" ] && first=1
    shopt -s nullglob
    for f in "$inbox"/*.json; do
        if [[ -f "$f" && ! -L "$f" ]]; then
            printf '%s\n' "$f"
            [ "$first" -eq 0 ] || return 0
        fi
    done
    return 0
}

oldest() {
    unread_files --first
}

parse_duration() {
    local d="$1" n unit=s
    if [[ "$d" =~ ^([0-9]+)([smh]?)$ ]]; then
        n="${BASH_REMATCH[1]}"
        unit="${BASH_REMATCH[2]:-s}"
    else
        die "invalid duration '$d' (use seconds or <n>s|m|h)"
    fi
    case "$unit" in
        s) echo "$n" ;;
        m) echo $((n * 60)) ;;
        h) echo $((n * 3600)) ;;
    esac
}

# Milliseconds since the epoch (EPOCHREALTIME is "<sec>.<microsec>").
now_ms() {
    local t="${EPOCHREALTIME/./}"
    echo $((t / 1000))
}

# Replies are atomic renames from separate execs, not one batch write.
settle_inbox() {
    local deadline_ms="$1" settle_ms step_ms cap_ms quiet_ms current count previous
    settle_ms="$(jq -nr --arg s "$settle" --argjson max "$SETTLE_MAX" \
        '[($s | tonumber), $max] | min | . * 1000 | ceil')"
    [ "$settle_ms" -gt 0 ] || return 0
    current="$(now_ms)"
    cap_ms=$((current + SETTLE_MAX * 1000))
    [ "$cap_ms" -le "$deadline_ms" ] || cap_ms="$deadline_ms"
    quiet_ms=$((current + settle_ms))
    previous="$(unread_files | wc -l)"
    while :; do
        current="$(now_ms)"
        [ "$current" -lt "$cap_ms" ] && [ "$current" -lt "$quiet_ms" ] || break
        step_ms=$((settle_ms < 200 ? settle_ms : 200))
        [ "$step_ms" -le "$((cap_ms - current))" ] || step_ms=$((cap_ms - current))
        [ "$step_ms" -le "$((quiet_ms - current))" ] || step_ms=$((quiet_ms - current))
        sleep "$(printf '%d.%03d' "$((step_ms / 1000))" "$((step_ms % 1000))")"
        count="$(unread_files | wc -l)"
        if [ "$count" -gt "$previous" ]; then
            quiet_ms=$(( $(now_ms) + settle_ms ))
        fi
        previous="$count"
    done
}

cmd_wait() {
    local timeout=1800 first waited=0 status_ref="${wait_status_ref:-}"
    while [ $# -gt 0 ]; do
        case "$1" in
            --timeout)
                [ $# -ge 2 ] || die "--timeout needs a value"
                timeout="$(parse_duration "$2")"
                shift 2 ;;
            *) die "unknown argument '$1' (see --help)" ;;
        esac
    done
    mkdir -p "$inbox"
    local deadline_ms remaining_ms remaining rc slice
    deadline_ms=$(( $(now_ms) + timeout * 1000 ))
    while :; do
        if [ -n "$status_ref" ]; then first="$(find_status "$status_ref")"; else first="$(oldest)"; fi
        if [ -n "$first" ]; then
            if [ "$waited" -eq 1 ] && [ -z "$status_ref" ]; then
                settle_inbox "$deadline_ms"
                first="$(oldest)"
                [ -n "$first" ] || continue
            fi
            printf '%s\n' "$first"
            return 0
        fi
        remaining_ms=$((deadline_ms - $(now_ms)))
        [ "$remaining_ms" -gt 0 ] || return 1
        remaining=$(( (remaining_ms + 999) / 1000 ))
        waited=1
        if command -v inotifywait >/dev/null 2>&1; then
            # inotifywait only sees events after it has set its watch, so a
            # message that lands between the check above and the watch gives
            # no event. Each watch is therefore capped to WATCH_SLICE seconds
            # and followed by a re-check: the slice bounds the worst-case
            # latency of such a lost wakeup.
            slice=$(( remaining < WATCH_SLICE ? remaining : WATCH_SLICE ))
            rc=0
            inotifywait -q -t "$slice" -e close_write,moved_to "$inbox" >/dev/null 2>&1 || rc=$?
            # Exit 0 = event, 2 = timeout; anything else = the watch failed.
            if [ "$rc" -ne 0 ] && [ "$rc" -ne 2 ]; then sleep "$poll"; fi
        else
            sleep "$poll"
        fi
    done
}

find_status() {
    local f
    while IFS= read -r f; do
        if jq -e --arg ref "$1" '.type == "status" and .ref == $ref' "$f" >/dev/null 2>&1; then
            printf '%s\n' "$f"
            return 0
        fi
    done < <(unread_files)
}

wait_for_status() {
    local wait_status_ref="$1" path state id
    if ! path="$(cmd_wait --timeout "$2")"; then return 3; fi
    state="$(jq -r '.state' "$path")"
    id="$(message_id "$path")"
    cmd_read "$id" || return 1
    case "$state" in
        done|queued|started) return 0 ;;
        *) return 1 ;;
    esac
}

# Prints the message's id; fails (silently) on unreadable JSON.
message_id() {
    jq -er '.id | select(type == "string")' "$1" 2>/dev/null
}

cmd_ls() {
    [ $# -eq 0 ] || die "ls takes no arguments"
    local f line
    while IFS= read -r f; do
        # Every cell has C0, DEL and C1 characters replaced by "?" so a
        # child-written message cannot drive the reader's terminal.
        if ! line="$(jq -er '[
                .id,
                .type,
                (if .type == "status" then .ref else .from end),
                (if .type == "status" then .state else (.kind // "") end),
                (((.body // .detail // "") | tostring | .[0:60])
                 + (if .type == "message" and .imported_sha then " [imported \(.imported_sha[0:12])]" else "" end)
                 + (if .type == "message" and .import_error then " [import failed]" else "" end)
                 + (if .type == "message" and .on_done_reason then " [kept: \(.on_done_reason | tostring | .[0:60])]" else "" end))
            ] | map(if . == null then "-" else tostring end
                    | gsub("[\\x{00}-\\x{1f}\\x{7f}-\\x{9f}]"; "?")) | @tsv' "$f" 2>/dev/null)"; then
            printf 'jailbee-inbox: skipping unreadable message %s\n' "$f" >&2
            continue
        fi
        printf '%s\n' "$line"
    done < <(unread_files)
}

# The runners a spawn/restart may name, as one JSON array: the "omit runner"
# entry first, then claude and one claude-jb per profile. Without `claude` on
# PATH only the first is listed. Names are cleaned like `ls` cells (C1 only:
# jq escapes C0 itself in JSON output, and the text form cleans C0 as well).
runners_json() {
    local config="${JAILBEE_LITELLM_CONFIG:-/etc/jailbee/litellm.json}"
    local cfg=null grant=null have_claude=0
    if [ -r "$base/grant.json" ]; then
        grant="$(jq -sc 'if length == 1 then .[0] else null end' "$base/grant.json" 2>/dev/null)" || grant=null
    fi
    if [ -r "$config" ]; then
        cfg="$(jq -c . "$config" 2>/dev/null)" || {
            printf 'jailbee-inbox: cannot read %s (not valid JSON); no claude-jb runners listed\n' "$config" >&2
            cfg=null
        }
    fi
    command -v claude >/dev/null 2>&1 && have_claude=1
    jq -n --argjson cfg "$cfg" --argjson grant "$grant" --argjson have "$have_claude" \
        --arg agent "${JAILBEE_DEFAULT_AGENT:-unknown}" '
        def clean: gsub("[\\x{80}-\\x{9f}]"; "?");
        def tiers: ["fable", "opus", "sonnet", "haiku"];
        (if ($grant | type) == "object" and ($grant.default_runner | type) == "object"
            and ($grant.default_runner.agent | type) == "string"
            and ($grant.default_runner_source | type) == "string"
            and ([$grant.default_runner.profile, $grant.default_runner.model] | all(. == null or type == "string"))
         then $grant.default_runner | with_entries(.value |= if type == "string" then clean else . end)
         else null end) as $runner
        | [{runner: $runner, default: true, agent: ($agent | clean),
            source: (if $runner == null then null else $grant.default_runner_source | clean end)}]
        + (if $have == 1 then
            [{runner: {agent: "claude"}, models: tiers}]
            + [ ($cfg.profiles // {}) | to_entries | sort_by(.key)[]
                | .key as $name
                | ((.value.tiers // {}) | with_entries(select(.key as $k | tiers | index($k)))) as $al
                | {runner: {agent: "claude-jb", profile: ($name | clean)},
                   models: ($al | keys),
                   aliases: ($al | map_values(tostring | clean)),
                   default_profile: ($name == $cfg.default_profile)} ]
           else [] end)'
}

cmd_runners() {
    local json=0
    while [ $# -gt 0 ]; do
        case "$1" in
            --json) json=1; shift ;;
            *) die "unknown argument '$1' (see --help)" ;;
        esac
    done
    if [ "$json" -eq 1 ]; then
        runners_json
        return
    fi
    runners_json | jq -r '
        def clean: gsub("[\\x{00}-\\x{1f}\\x{7f}-\\x{9f}]"; "?");
        def pad($n): . + ([range($n - length) | " "] | join(""));
        (.[0].agent | clean) as $default
        | .[1:] as $rest
        | ($rest | map(
              (if .runner.agent == "claude" then "claude"
               else "claude-jb -P \(.runner.profile | clean)" + (if .default_profile then " (default)" else "" end)
               end)) ) as $labels
        | ([$labels[] | length] | max // 0) as $w
        | (if .[0].runner == null then "default: omit runner (\($default))"
           else .[0] | "default: \(.runner.agent | clean)"
             + (if .runner.profile != null then " -P \(.runner.profile | clean)" else "" end)
             + (if .runner.model != null then " \(.runner.model | clean)" else "" end)
             + " (from \(.source | clean))" end),
          ([range($rest | length)] | map(
              . as $i | $rest[$i] as $r
              | ($labels[$i] | pad($w)) + "  models: "
                + (if $r.runner.agent == "claude" then ($r.models | join(" "))
                   else ($r.models | map(. as $m | "\($m)=\($r.aliases[$m] | clean)") | join(" ")) end)
          )[])'
}

cmd_read() {
    local id="" keep=0 f fid pretty
    while [ $# -gt 0 ]; do
        case "$1" in
            --keep) keep=1; shift ;;
            -*) die "unknown option '$1' (see --help)" ;;
            *) [ -z "$id" ] || die "read takes one id"; id="$1"; shift ;;
        esac
    done
    [ -n "$id" ] || die "read needs a message id"
    while IFS= read -r f; do
        if ! fid="$(message_id "$f")"; then
            printf 'jailbee-inbox: skipping unreadable message %s\n' "$f" >&2
            continue
        fi
        if [ "$fid" = "$id" ]; then
            # A file that vanished since the scan (read by a concurrent
            # reader) counts as "no unread message with that id".
            # jq escapes C0 and DEL itself; C1 characters (e.g. U+009B, a
            # one-character CSI) would reach the terminal raw, so strings
            # and keys get them replaced by "?".
            pretty="$(jq 'def clean: gsub("[\\x{80}-\\x{9f}]"; "?");
                walk(if type == "string" then clean
                     elif type == "object" then with_entries(.key |= clean)
                     else . end)' "$f" 2>/dev/null)" || continue
            if [ "$keep" -eq 0 ]; then
                mkdir -p "$inbox/read"
                mv -- "$f" "$inbox/read/" 2>/dev/null || continue
            fi
            printf '%s\n' "$pretty"
            return 0
        fi
    done < <(unread_files)
    printf 'jailbee-inbox: no unread message with id %s\n' "$id" >&2
    return 1
}

# Writes one manifest (plus its body file) atomically into outbox/ and prints
# its id. Mirrors the cheap checks of the host's manifest validator so a bad
# request fails here rather than as a refusal status later.
MAX_TEXT_BYTES=65536

bad_usage() {
    printf 'jailbee-inbox: %s\n' "$1" >&2
    usage >&2
    exit 2
}

new_id() {
    local suffix
    suffix="$(od -An -N2 -tx1 /dev/urandom | tr -d ' \n')"
    printf '%s-%s-%s' "$1" "$(date -u +%Y%m%d%H%M%S)" "$suffix"
}

cmd_send() {
    [ $# -ge 1 ] || bad_usage "send needs a type"
    local type="$1"; shift
    case "$type" in
        message|spawn|import|update|restart|stop|destroy) ;;
        *) bad_usage "unknown message type '$type'" ;;
    esac
    local to="" kind="" reply_to="" branch="" new=0 base_branch="" loose=0 note="" child="" force=0
    local agent="" profile="" model="" default_runner=0 on_done="" wait=0 timeout="" ref="" pr=""
    local text="" text_set=0 file="" file_set=0 stdin=0
    local -a mounts=() egress=()
    local opt_val
    while [ $# -gt 0 ]; do
        opt_val=""
        case "$1" in
            --wait) wait=1; shift; continue ;;
            --new) new=1; shift; continue ;;
            --loose) loose=1; shift; continue ;;
            --force) force=1; shift; continue ;;
            --default-runner) default_runner=1; shift; continue ;;
            -) stdin=1; shift; continue ;;
            --text|--file|--to|--kind|--reply-to|--branch|--base|--ref|--pr|--mount|--egress|--note|--child|--agent|--profile|--model|--on-done|--timeout)
                [ $# -ge 2 ] || bad_usage "$1 needs a value"
                opt_val="$2"
                if [ "$1" != "--text" ] && [ -z "$opt_val" ]; then
                    bad_usage "$1 needs a non-empty value"
                fi
                ;;
            *) bad_usage "unknown argument '$1'" ;;
        esac
        case "$1" in
            --text) text="$opt_val"; text_set=1 ;;
            --file) file="$opt_val"; file_set=1 ;;
            --to) to="$opt_val" ;;
            --kind) kind="$opt_val" ;;
            --reply-to) reply_to="$opt_val" ;;
            --branch) branch="$opt_val" ;;
            --base) base_branch="$opt_val" ;;
            --ref) ref="$opt_val" ;;
            --pr) pr="$opt_val" ;;
            --mount) mounts+=("$opt_val") ;;
            --egress) egress+=("$opt_val") ;;
            --note) note="$opt_val" ;;
            --child) child="$opt_val" ;;
            --agent) agent="$opt_val" ;;
            --profile) profile="$opt_val" ;;
            --model) model="$opt_val" ;;
            --on-done) on_done="$opt_val" ;;
            --timeout) timeout="$opt_val" ;;
        esac
        shift 2
    done

    if [ -n "$timeout" ]; then
        [ "$wait" -eq 1 ] || bad_usage "--timeout needs --wait"
        parse_duration "$timeout" >/dev/null
    fi
    if [ -n "$on_done" ]; then
        [ "$type" = "spawn" ] || [ "$type" = "restart" ] || bad_usage "--on-done only applies to spawn and restart"
        case "$on_done" in destroy|keep) ;; *) bad_usage "--on-done must be destroy or keep" ;; esac
    fi
    # Which options belong to which type.
    local has_body=0
    case "$type" in message|spawn|restart) has_body=1 ;; esac
    local sources=$((text_set + file_set + stdin))
    if [ "$has_body" -eq 1 ]; then
        [ "$sources" -eq 1 ] || bad_usage "$type needs exactly one of --text, --file or -"
    else
        [ "$sources" -eq 0 ] || bad_usage "$type takes no text, file or stdin"
    fi
    if [ "$type" != "message" ] && { [ -n "$to" ] || [ -n "$kind" ] || [ -n "$reply_to" ]; }; then
        bad_usage "--to, --kind and --reply-to only apply to message"
    fi
    if [ "$type" != "spawn" ] && {
        [ -n "$branch" ] || [ "$new" -eq 1 ] || [ -n "$base_branch" ] || [ -n "$ref" ] || [ -n "$pr" ] || [ "$loose" -eq 1 ] \
            || [ -n "$note" ] || [ "${#mounts[@]}" -gt 0 ] || [ "${#egress[@]}" -gt 0 ]; }; then
        bad_usage "--branch, --new, --base, --mount, --loose, --egress and --note only apply to spawn"
    fi
    if [ "$type" != "destroy" ] && [ "$force" -eq 1 ]; then
        bad_usage "--force only applies to destroy"
    fi
    if [ "$type" != "spawn" ] && [ "$type" != "restart" ] && {
        [ -n "$agent" ] || [ -n "$profile" ] || [ -n "$model" ] || [ "$default_runner" -eq 1 ]; }; then
        bad_usage "--agent, --profile, --model and --default-runner only apply to spawn and restart"
    fi
    if [ "$default_runner" -eq 1 ]; then
        [ "$type" = "restart" ] || bad_usage "--default-runner only applies to restart"
        [ -z "$agent" ] || bad_usage "--default-runner cannot be combined with --agent"
    fi
    if [ -n "$agent" ]; then
        case "$agent" in
            claude|claude-jb) ;;
            *) bad_usage "--agent must be claude or claude-jb" ;;
        esac
    elif [ -n "$profile" ] || [ -n "$model" ]; then
        bad_usage "--profile and --model need --agent"
    fi
    if [ -n "$profile" ] && [ "$agent" != "claude-jb" ]; then
        bad_usage "--profile needs --agent claude-jb"
    fi
    if [ -n "$model" ]; then
        case "$model" in
            fable|opus|sonnet|haiku) ;;
            *) bad_usage "--model must be fable, opus, sonnet or haiku" ;;
        esac
    fi
    # The manifest's runner member: absent, a runner, or (restart) null.
    local runner_json="{}"
    if [ -n "$agent" ]; then
        runner_json="$(jq -nc --arg a "$agent" --arg p "$profile" --arg m "$model" \
            '{runner: ({agent: $a}
                + (if $p != "" then {profile: $p} else {} end)
                + (if $m != "" then {model: $m} else {} end))}')"
    elif [ "$default_runner" -eq 1 ]; then
        runner_json='{"runner": null}'
    fi
    if [ -n "$on_done" ]; then
        runner_json="$(jq -c --arg p "$on_done" '. + {on_done: $p}' <<<"$runner_json")"
    fi
    case "$type" in
        import|update|stop|destroy|restart)
            [ -n "$child" ] || bad_usage "$type needs --child" ;;
        *) [ -z "$child" ] || bad_usage "--child does not apply to $type" ;;
    esac
    if [ "$type" = "spawn" ]; then
        [ -z "$ref" ] || { [ -z "$pr" ] && [ "$new" -eq 0 ]; } || bad_usage "--ref cannot be combined with --pr or --new"
        if [ -n "$pr" ]; then
            [ "$new" -eq 0 ] && [ -z "$base_branch" ] || bad_usage "--pr cannot be combined with --new or --base"
            [[ "$pr" =~ ^[1-9][0-9]*$ ]] || bad_usage "--pr must be a positive integer"
            [ -n "$branch" ] || branch="pr-placeholder"
        fi
        [ -n "$branch" ] || bad_usage "spawn needs --branch"
        [ -z "$base_branch" ] || [ "$new" -eq 1 ] || bad_usage "--base needs --new"
    fi
    if [ "$type" = "message" ] && [ -n "$kind" ]; then
        case "$kind" in
            note|question|done|blocked) ;;
            *) bad_usage "--kind must be note, question, done or blocked" ;;
        esac
    fi

    mkdir -p "$outbox"
    local id attempt
    for attempt in 1 2; do
        id="$(new_id "$type")"
        if [ ! -e "$outbox/$id.json" ] && [ ! -e "$outbox/$id.md" ]; then break; fi
        id=""
    done
    if [ -z "$id" ]; then
        printf 'jailbee-inbox: could not find a free manifest id\n' >&2
        return 1
    fi

    local body_name="$id.md"
    # Globals: the EXIT trap runs after this function's locals are gone.
    body_tmp="$outbox/.$id.md.tmp"
    json_tmp="$outbox/.$id.json.tmp"
    trap 'rm -f -- "$body_tmp" "$json_tmp"' EXIT

    if [ "$has_body" -eq 1 ]; then
        if [ "$text_set" -eq 1 ]; then
            printf '%s' "$text" > "$body_tmp"
        elif [ "$file_set" -eq 1 ]; then
            [ -f "$file" ] && [ -r "$file" ] || die "cannot read file '$file'"
            cat -- "$file" > "$body_tmp"
        else
            cat > "$body_tmp"
        fi
        local size
        size="$(wc -c < "$body_tmp")"
        [ "$size" -gt 0 ] || die "the $type text is empty"
        [ "$size" -le "$MAX_TEXT_BYTES" ] || die "the $type text is $size bytes; the limit is $MAX_TEXT_BYTES"
    fi

    case "$type" in
        message)
            jq -n --arg id "$id" --arg bf "$body_name" --arg to "$to" --arg kind "$kind" \
                --arg reply "$reply_to" \
                '{version: 1, id: $id, type: "message", body_file: $bf}
                 + (if $to != "" then {to: $to} else {} end)
                 + (if $kind != "" then {kind: $kind} else {} end)
                 + (if $reply != "" then {in_reply_to: $reply} else {} end)' > "$json_tmp" ;;
        spawn)
            local mounts_json egress_json
            mounts_json="$(jq -nc '$ARGS.positional' --args "${mounts[@]}")"
            egress_json="$(jq -nc '$ARGS.positional' --args "${egress[@]}")"
            jq -n --arg id "$id" --arg pf "$body_name" --arg branch "$branch" \
                --arg base "$base_branch" --arg ref "$ref" --arg pr "$pr" --arg note "$note" --argjson new "$new" \
                --argjson loose "$loose" --argjson mounts "$mounts_json" \
                --argjson egress "$egress_json" --argjson runner "$runner_json" \
                '{version: 2, id: $id, type: "spawn", kind: (if $pr != "" then "pr" elif $new == 1 then "new" else "fork" end),
                  branch: $branch, prompt_file: $pf,
                  rights: {version: 1, mounts: $mounts, loose: ($loose == 1), egress: $egress}}
                 + (if $base != "" then {base: $base} else {} end)
                 + (if $ref != "" then {ref: $ref} else {} end)
                 + (if $pr != "" then {pr: ($pr | tonumber)} else {} end)
                 + (if $note != "" then {note: $note} else {} end) + $runner' > "$json_tmp" ;;
        restart)
            jq -n --arg id "$id" --arg pf "$body_name" --arg child "$child" \
                --argjson runner "$runner_json" \
                '{version: 1, id: $id, type: "restart", child: $child, prompt_file: $pf} + $runner' > "$json_tmp" ;;
        destroy)
            jq -n --arg id "$id" --arg child "$child" --argjson force "$force" \
                '{version: 1, id: $id, type: "destroy", child: $child}
                 + (if $force == 1 then {force: true} else {} end)' > "$json_tmp" ;;
        import|update|stop)
            jq -n --arg id "$id" --arg type "$type" --arg child "$child" \
                '{version: 1, id: $id, type: $type, child: $child}' > "$json_tmp" ;;
    esac

    # Body first: the broker reads it only once the manifest names it.
    if [ "$has_body" -eq 1 ]; then
        mv -- "$body_tmp" "$outbox/$body_name"
    fi
    if ! mv -- "$json_tmp" "$outbox/$id.json"; then
        [ "$has_body" -eq 1 ] && rm -f -- "$outbox/$body_name"
        printf 'jailbee-inbox: could not write the manifest\n' >&2
        return 1
    fi
    trap - EXIT
    printf '%s\n' "$id"
    if [ "$wait" -eq 1 ]; then
        wait_for_status "$id" "${timeout:-30m}"
    fi
}

[ $# -ge 1 ] || { usage >&2; exit 2; }
sub="$1"; shift
case "$sub" in
    wait) cmd_wait "$@" ;;
    ls) cmd_ls "$@" ;;
    read) cmd_read "$@" ;;
    runners) cmd_runners "$@" ;;
    send) cmd_send "$@" ;;
    -h|--help|help) usage ;;
    *) usage >&2; exit 2 ;;
esac
