#!/bin/bash # Clawd Hook Wrapper - Executes clawd via the hook system # This avoids direct binary calls and uses the gateway properly set -euo pipefail CLAWD_DIR="${HOME}/.claude/clawd" GATEWAY_PID_FILE="${CLAWD_DIR}/gateway.pid" LOG_DIR="${CLAWD_DIR}/logs" # Ensure log directory exists mkdir -p "${LOG_DIR}" log() { echo "[$(date -u +"%Y-%m-%d %H:%M:%S UTC")] [clawd-wrapper] $*" | tee -a "${LOG_DIR}/wrapper.log" } # Check if gateway is running check_gateway() { if [[ -f "$GATEWAY_PID_FILE" ]]; then local pid pid=$(cat "$GATEWAY_PID_FILE" 2>/dev/null || echo "") if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then return 0 fi fi # Check if Python gateway is running if pgrep -f "uvicorn.*clawd.*main" > /dev/null 2>&1; then return 0 fi # Check if clawdbot-gateway is running if pgrep -f "clawdbot-gateway" > /dev/null 2>&1; then return 0 fi return 1 } # Start the Python gateway if not running ensure_gateway() { if check_gateway; then log "Gateway already running" return 0 fi log "Starting Clawd gateway..." cd "${CLAWD_DIR}/gateway" # Activate venv and start source venv/bin/activate nohup python -m uvicorn main:app --host 127.0.0.1 --port 8766 > "${LOG_DIR}/gateway.log" 2>&1 & local pid=$! echo "$pid" > "$GATEWAY_PID_FILE" sleep 2 if kill -0 "$pid" 2>/dev/null; then log "Gateway started (PID: ${pid})" return 0 else log "ERROR: Failed to start gateway" return 1 fi } # Execute task via clawd using the agent command execute_clawd() { local task="$1" local agent="${2:-main}" local thinking="${3:-medium}" log "Executing task via clawd: ${task}" # Use clawdbot agent command with --local flag if command -v clawdbot >/dev/null 2>&1; then clawdbot agent --local --agent "$agent" --message "$task" --thinking "$thinking" 2>&1 elif [[ -x "${HOME}/.local/bin/clawdbot" ]]; then "${HOME}/.local/bin/clawdbot" agent --local --agent "$agent" --message "$task" --thinking "$thinking" 2>&1 else log "ERROR: clawdbot not found" echo "Error: clawdbot not found. Please install clawdbot first." >&2 return 1 fi } # Main entry point main() { local task="" local agent="main" local thinking="medium" # Parse arguments while [[ $# -gt 0 ]]; do case "$1" in --agent|-a) agent="$2" shift 2 ;; --thinking) thinking="$2" shift 2 ;; --task) task="$2" shift 2 ;; *) task="$1" shift ;; esac done # If no task, read from stdin if [[ -z "$task" ]]; then if [[ -t 0 ]]; then echo "Usage: $0 [--agent ] [--thinking ] --task " >&2 exit 1 else task=$(cat) fi fi log "Task: ${task}, Agent: ${agent}, Thinking: ${thinking}" # Ensure gateway is running ensure_gateway # Execute the task execute_clawd "$task" "$agent" "$thinking" } main "$@"