#!/usr/bin/env bash
# ollie:parallel read
# description: Escalate a hard task to a stronger model. Returns immediately; the stronger model reports back to your prompt when done. Use when stuck — complex reasoning, debugging, architecture decisions.
# Args: <instruction> [id]
set -euo pipefail

OLLIE="${OLLIE:-$HOME/mnt/ollie}"
BACKEND="${OLLIE_ESCALATE_BACKEND:-openrouter}"
MODEL="${OLLIE_ESCALATE_MODEL:-anthropic/claude-sonnet-4-20250514}"

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

[ -z "${OLLIE_SESSION_ID:-}" ] && die "OLLIE_SESSION_ID not set (escalate must run inside a session)"

instruction="${1:-}"
[ -z "$instruction" ] && die "instruction required"

id="${2:-escalate-$(date +%s%N)-$$-$(hostname -s)}"
[ -n "$OLLIE_SESSION_ID" ] && id="${OLLIE_SESSION_ID}__${id}"

kv="name=${id}
cwd=$(pwd)
backend=${BACKEND}
model=${MODEL}
agent=expert"
printf '%s\n' "$kv" > "$OLLIE/s/new" || die "failed to create session"

B="$OLLIE/s/$id"
wait=0.1
for _ in 1 2 3 4 5 6 7 8; do
    [ -d "$B" ] && break
    sleep "$wait"
    wait=$(awk "BEGIN{printf \"%.2f\", $wait * 2}")
done
[ -d "$B" ] || die "timeout waiting for session $id"

prompt="[parent_session_id=${OLLIE_SESSION_ID}]
[session_id=${id}]

You are an expert agent escalated to handle a task that a weaker model could not resolve. Apply rigorous reasoning to produce a correct, complete answer.

TERMINATION RULES (mandatory — follow exactly):
1. Complete the task using whatever tools are needed.
2. When finished (success or failure), write your result to: ${OLLIE}/s/${OLLIE_SESSION_ID}/prompt
   Use file_write with this exact format and nothing after it:

   [from=${id}]
   STATUS: done
   SUMMARY: <concise answer or confirmation>

   On failure, use:
   [from=${id}]
   STATUS: error
   REASON: <why the task could not be completed>

3. After writing the result, STOP. Do not call any more tools. Do not write again.
4. Do not re-read the file to verify. Do not retry the write. One write, then stop.

TASK:
${instruction}"

printf '%s\n' "$prompt" > "$B/prompt" || die "failed to submit prompt"
printf 'session=%s\npath=%s\nbackend=%s\nmodel=%s\n' "$id" "$B" "$BACKEND" "$MODEL"