# Helpers for running an agent with curl and jq. Each one is a single curl or jq call.
# Usage (from this folder):  source helpers.sh
# The groq/ folder has a helpers.sh with the same names for Groq's API.

ask() {          # send convo.json, save reply.json, print the text and any tool request
  curl -s https://api.anthropic.com/v1/messages \
    -H "content-type: application/json" \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -d @convo.json > reply.json
  jq -r 'if .type == "error" then "error: \(.error.message)" else
           .content[] | if .type == "text" then .text
           elif .type == "tool_use" then "→ \(.name) \(.input | tojson)"
           else empty end end' reply.json
}

stop_reason() {  # end_turn, tool_use, max_tokens... or error
  jq -r '.stop_reason // "error"' reply.json
}

tool_arg() {     # an argument of the tool the model asked for:  tool_arg path
  jq -r --arg k "$1" '.content[] | select(.type == "tool_use") | .input[$k]' reply.json
}

fresh() {        # start a new convo.json from a request file, keeping only its settings
  jq '.messages |= map(select(.role == "system"))' "$1" > convo.json
}

say() {          # add your message:  say "what's my name?"
  jq --arg t "$1" '.messages += [{role: "user", content: $t}]' \
    convo.json > convo.tmp && mv convo.tmp convo.json
}

remember() {     # add the model's reply (all of it, thinking blocks included)
  jq -e '.content' reply.json > /dev/null || return 1
  jq --slurpfile r reply.json '.messages += [{role: "assistant", content: $r[0].content}]' \
    convo.json > convo.tmp && mv convo.tmp convo.json
}

answer() {       # send a tool's output back:  read_file notes.txt | answer
  jq -e 'any(.content[]?; .type == "tool_use")' reply.json > /dev/null \
    || { echo "reply.json has no tool call to answer"; return 1; }
  local out; out=$(cat)
  jq --slurpfile r reply.json --arg out "$out" \
    '.messages += [{role: "user", content: [{type: "tool_result",
       tool_use_id: ($r[0].content[] | select(.type == "tool_use") | .id),
       content: $out}]}]' \
    convo.json > convo.tmp && mv convo.tmp convo.json
}

read_file() {    # the tool itself: print a file, or say it doesn't exist
  if [ -f "$1" ]; then head -c 20000 "$1"; else echo "No such file: $1"; fi
}

history() {      # one line per message, so you can see the conversation grow
  jq -c '.messages[] | {role, content: (if (.content | type) == "string"
           then .content else [.content[] | .type] end)}' convo.json
}
