Files

119 lines
3.0 KiB
Bash
Executable File

#!/usr/bin/env bash
# delegate.sh — Send a task to another Atomizer agent via OpenClaw Hooks API
# Usage: delegate.sh <agent> <message> [--channel <discord-channel-id>] [--deliver] [--wait]
#
# Examples:
# delegate.sh webster "Find density of Ti-6Al-4V"
# delegate.sh nx-expert "Mesh the M2 mirror" --channel C0AEJV13TEU --deliver
# delegate.sh tech-lead "Review optimization results" --deliver
set -euo pipefail
# --- Port Map (from cluster config) ---
declare -A PORT_MAP=(
[manager]=18800
[tech-lead]=18804
[secretary]=18808
[auditor]=18812
[optimizer]=18816
[study-builder]=18820
[nx-expert]=18824
[webster]=18828
)
# --- Config ---
TOKEN="31422bb39bc9e7a4d34f789d8a7cbc582dece8dd170dadd1"
HOST="127.0.0.1"
# --- Parse args ---
if [[ $# -lt 2 ]]; then
echo "Usage: delegate.sh <agent> <message> [--channel <id>] [--deliver] [--wait]"
echo ""
echo "Agents: ${!PORT_MAP[*]}"
exit 1
fi
AGENT="$1"
MESSAGE="$2"
shift 2
CHANNEL=""
DELIVER="true"
WAIT=""
while [[ $# -gt 0 ]]; do
case "$1" in
--channel) CHANNEL="$2"; shift 2 ;;
--deliver) DELIVER="true"; shift ;;
--no-deliver) DELIVER="false"; shift ;;
--wait) WAIT="true"; shift ;;
*) echo "Unknown option: $1"; exit 1 ;;
esac
done
# --- Validate agent ---
PORT="${PORT_MAP[$AGENT]:-}"
if [[ -z "$PORT" ]]; then
echo "❌ Unknown agent: $AGENT"
echo "Available agents: ${!PORT_MAP[*]}"
exit 1
fi
# --- Don't delegate to yourself ---
SELF_PORT="${ATOMIZER_SELF_PORT:-}"
if [[ -n "$SELF_PORT" && "$PORT" == "$SELF_PORT" ]]; then
echo "❌ Cannot delegate to yourself"
exit 1
fi
# --- Check if target is running ---
if ! curl -sf "http://$HOST:$PORT/health" > /dev/null 2>&1; then
# Try a simple connection check instead
if ! timeout 2 bash -c "echo > /dev/tcp/$HOST/$PORT" 2>/dev/null; then
echo "❌ Agent '$AGENT' is not running on port $PORT"
exit 1
fi
fi
# --- Build payload ---
PAYLOAD=$(cat <<EOF
{
"message": $(printf '%s' "$MESSAGE" | python3 -c "import json,sys; print(json.dumps(sys.stdin.read()))"),
"name": "delegation",
"sessionKey": "hook:delegation:$(date +%s)",
"deliver": $DELIVER,
"channel": "discord"
}
EOF
)
# Add Discord channel routing if specified
if [[ -n "$CHANNEL" ]]; then
PAYLOAD=$(echo "$PAYLOAD" | python3 -c "
import json, sys
d = json.load(sys.stdin)
d['to'] = 'channel:$CHANNEL'
print(json.dumps(d))
")
fi
# --- Send ---
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "http://$HOST:$PORT/hooks/agent" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "$PAYLOAD")
HTTP_CODE=$(echo "$RESPONSE" | tail -1)
BODY=$(echo "$RESPONSE" | head -n -1)
if [[ "$HTTP_CODE" == "202" ]]; then
RUN_ID=$(echo "$BODY" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('runId','unknown'))" 2>/dev/null || echo "unknown")
echo "✅ Task delegated to $AGENT (port $PORT)"
echo " Run ID: $RUN_ID"
echo " Deliver to Discord: $DELIVER"
else
echo "❌ Delegation failed (HTTP $HTTP_CODE)"
echo " Response: $BODY"
exit 1
fi