#!/usr/bin/env bash
# ollie:parallel read
# description: Delegate a mechanical subtask to a cheaper/weaker model. Returns immediately; the worker reports back to your prompt when done. Use for tasks requiring no judgment — edits, lookups, transforms, formatting.
# Args: <instruction> [id]
set -euo pipefail

OLLIE="${OLLIE:-$HOME/mnt/ollie}"
BACKEND="${OLLIE_CASCADE_BACKEND:-openrouter}"
MODEL="${OLLIE_CASCADE_MODEL:-mistralai/devstral-small}"

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

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

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

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

kv="name=${id}
cwd=$(pwd)
backend=${BACKEND}
model=${MODEL}
agent=worker"
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 a worker agent. Read code, reason about implementation, and complete the task within its stated scope.

RULES:
1. Complete the task using whatever tools are needed.
2. Stay within scope — do not expand beyond what was asked.
3. When finished, write your result to: ${OLLIE}/s/${OLLIE_SESSION_ID}/prompt
   Format:

   [from=${id}]
   STATUS: done
   SUMMARY: <what was accomplished>

   On failure:
   [from=${id}]
   STATUS: error
   REASON: <why>

4. After writing the result, STOP. 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"
