#!/usr/bin/env bash # ============================================================================== # safe-run.sh — Hayes FLOP Tribe Free Local Agent Survival Runner # Homepage : https://hayesfloptribe.com # Skill : https://hayesfloptribe.com/skill.md # # SECURITY & COMPLIANCE: # - Runs 100% locally. NEVER sends private keys, mnemonics, or seeds anywhere. # - Reads signing URI exclusively from the local FLOP_URI environment variable. # - claim-wait is strictly polite SINGLE-WALLET backoff (>= 180s + jitter). # No multi-wallet loops, no proxy rotation, no CAPTCHA/Turnstile bypass. # ============================================================================== set -euo pipefail DEFAULT_INDEXER="https://hayesfloptribe.com" INDEXER_URL="${FLOP_INDEXER_URL:-$DEFAULT_INDEXER}" DEFAULT_RPC="wss://testnet.flop.network" UA="HayesFLOPTribe-SafeRun/1.0" log() { printf '[%s] %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$*"; } die() { log "ERROR: $*" >&2; exit 1; } need_cmd() { command -v "$1" >/dev/null 2>&1 || die "Missing required tool '$1'. Install it and retry." } usage() { cat <<'EOF' Usage: ./safe-run.sh infer [options] Wait for affordable gas, run inference via offer/direct/force, max 1 cross-operator fallback retry ./safe-run.sh rescue [options] Wait until feeMultiplier fits your balance, verify expiry, run computeChannel.timeout locally ./safe-run.sh claim-wait [options] Polite single-wallet faucet wait (>=180s backoff + jitter), optionally chain into infer Common options: --indexer Offer indexer base URL (default: https://hayesfloptribe.com) --dry-run Print what would execute without submitting transactions -h, --help Show this help infer options: --model Model slug (default: qwen/qwen3-14b) --budget Total wallet budget incl. gas reserve (default: 10) --via Routing mode: offer (default), direct, or force (--force-open) --max-tokens Max completion tokens (default: 256) --max-turns Min required turns (default: 1) --prompt Prompt text (default: "Hello from Hayes FLOP Tribe!") --interval Poll interval seconds, min 10 (default: 25) --max-wait Stop waiting after N seconds, 0 = forever (default: 0) --rpc-timeout Optional --rpc-timeout flag passed to flop CLI --strict-gas Add strictGas=1 (block red gas even when budget >= 15 FLOP) rescue options: --channel Stuck channel ID (numeric or 0x..., required) --balance Free FLOP balance available for timeout gas (auto-computes safe max multiplier) --max-mult Explicit feeMultiplier ceiling (overrides --balance calculation) --rpc Testnet WebSocket RPC (default: wss://testnet.flop.network) --interval Poll interval seconds, min 10 (default: 25) --max-wait Stop waiting after N seconds, 0 = forever (default: 0) (Requires local FLOP_URI env var unless --dry-run is set.) claim-wait options (strictly single-wallet polite backoff): --status-only Print cached official faucet status from /api/faucet and exit --cmd Your single-wallet faucet claim command (run politely with >=180s backoff) --min-wait Minimum seconds between retries, hard floor 180 (default: 180) --max-attempts Max polite attempts, hard cap 48 (default: 12) --address Optional public 5... address to watch via /api/wallet-check --target-balance Stop waiting once free balance >= target (default: 1) --then-infer After funding succeeds, automatically run 'infer' with passed --model/--budget/--prompt EOF } url_encode() { jq -rn --arg v "$1" '$v|@uri' } cmd_infer() { need_cmd curl need_cmd jq local model="qwen/qwen3-14b" local budget="10" local via="offer" local max_tokens="256" local max_turns="1" local prompt="Hello from Hayes FLOP Tribe!" local interval="25" local max_wait="0" local rpc_timeout="" local strict_gas="0" local dry_run="0" while [[ $# -gt 0 ]]; do case "$1" in --model) model="$2"; shift 2 ;; --budget) budget="$2"; shift 2 ;; --via) via="$2"; shift 2 ;; --max-tokens) max_tokens="$2"; shift 2 ;; --max-turns) max_turns="$2"; shift 2 ;; --prompt) prompt="$2"; shift 2 ;; --interval) interval="$2"; shift 2 ;; --max-wait) max_wait="$2"; shift 2 ;; --rpc-timeout) rpc_timeout="$2"; shift 2 ;; --strict-gas) strict_gas="1"; shift ;; --indexer) INDEXER_URL="${2%/}"; shift 2 ;; --dry-run) dry_run="1"; shift ;; -h|--help) usage; exit 0 ;; *) die "Unknown infer option: $1" ;; esac done [[ "$via" == "offer" || "$via" == "direct" || "$via" == "force" ]] || die "--via must be offer, direct, or force" (( interval < 10 )) && interval=10 [[ "$dry_run" == "0" ]] && need_cmd flop local started=$(date +%s) local q_model q_model=$(url_encode "$model") local q_budget q_budget=$(url_encode "$budget") local q_turns q_turns=$(url_encode "$max_turns") log "Watching ${INDEXER_URL}/api/pick (model=${model}, budget=${budget} F, via=${via}, interval=${interval}s)" while true; do local url="${INDEXER_URL}/api/pick?model=${q_model}&budget=${q_budget}&maxTurns=${q_turns}" [[ "$strict_gas" == "1" ]] && url="${url}&strictGas=1" local resp="" if ! resp=$(curl -fsSL --max-time 12 -A "$UA" "$url" 2>/dev/null); then log "Indexer temporarily unreachable; retrying in ${interval}s..." sleep "$interval" continue fi local ok advice mult gstat reserve wait_sec ok=$(jq -r '.ok // false' <<<"$resp") advice=$(jq -r '.advice // "unknown"' <<<"$resp") mult=$(jq -r '.feeMultiplier // .gas.feeMultiplier // "?"' <<<"$resp") gstat=$(jq -r '.gasStatus // .gas.status // "?"' <<<"$resp") reserve=$(jq -r '.gasReserveFlop // .gas.recommendedGasReserveFlop // "?"' <<<"$resp") wait_sec=$(jq -r '.recommendedWaitSec // 0' <<<"$resp") if [[ "$ok" == "true" ]]; then local p_name p_op p_miner p_ep p_model p_lat escrow p_name=$(jq -r '.primary.name // ""' <<<"$resp") p_op=$(jq -r '.primary.operator // ""' <<<"$resp") p_miner=$(jq -r '.primary.miner // ""' <<<"$resp") p_ep=$(jq -r '.primary.endpoint // ""' <<<"$resp") p_model=$(jq -r '.primary.model // ""' <<<"$resp") p_lat=$(jq -r '.primary.latencyMs // "?"' <<<"$resp") escrow=$(jq -r '.escrowFlop // 4.5' <<<"$resp") log "GO! gas=${mult}x (${gstat}, advice=${advice}) | primary=${p_name} (${p_op}, ${p_lat}ms) | escrow=${escrow} F (reserve=${reserve} F)" local -a cmd if [[ "$via" == "offer" ]]; then cmd=(flop agent infer --via offer --offer-indexer-url "$INDEXER_URL" --model "${p_model:-$model}" --max-flop "$escrow" --max-tokens "$max_tokens" --prompt "$prompt") else cmd=(flop agent infer --miner "$p_miner" --endpoint "$p_ep" --model "${p_model:-$model}" --max-flop "$escrow" --max-tokens "$max_tokens" --prompt "$prompt") [[ "$via" == "force" ]] && cmd+=(--force-open) fi [[ -n "$rpc_timeout" ]] && cmd+=(--rpc-timeout "$rpc_timeout") if [[ "$dry_run" == "1" ]]; then printf 'DRY-RUN primary: ' printf '%q ' FLOP_INDEXER_URL="$INDEXER_URL" "${cmd[@]}" printf '\n' exit 0 fi set +e FLOP_INDEXER_URL="$INDEXER_URL" "${cmd[@]}" local rc=$? set -e if [[ $rc -eq 0 ]]; then log "Inference succeeded on primary (${p_name})." exit 0 fi # 最多重试 1 次跨运营方备选矿机,防止无限循环白烧 Gas local fb_miner fb_ep fb_name fb_op fb_model fb_esc fb_miner=$(jq -r '.fallbacks[0].miner // ""' <<<"$resp") fb_ep=$(jq -r '.fallbacks[0].endpoint // ""' <<<"$resp") fb_name=$(jq -r '.fallbacks[0].name // ""' <<<"$resp") fb_op=$(jq -r '.fallbacks[0].operator // ""' <<<"$resp") fb_model=$(jq -r '.fallbacks[0].model // ""' <<<"$resp") fb_esc=$(jq -r '.fallbacks[0].escrowFlop // .escrowFlop // 4.5' <<<"$resp") if [[ -z "$fb_miner" || -z "$fb_ep" ]]; then die "Primary exited with code ${rc} and no fallback miner available. Verify on-chain state before retrying." fi log "WARN: primary failed (exit=${rc}). Retrying ONCE on cross-operator fallback ${fb_name} (${fb_op})..." local -a fb_cmd=(flop agent infer --miner "$fb_miner" --endpoint "$fb_ep" --model "${fb_model:-$model}" --max-flop "$fb_esc" --max-tokens "$max_tokens" --prompt "$prompt") [[ "$via" == "force" ]] && fb_cmd+=(--force-open) [[ -n "$rpc_timeout" ]] && fb_cmd+=(--rpc-timeout "$rpc_timeout") FLOP_INDEXER_URL="$INDEXER_URL" "${fb_cmd[@]}" log "Fallback succeeded (${fb_name})." exit 0 fi local extra="" if [[ "$advice" == "insufficient_budget" ]]; then local need_min need_min=$(jq -r '.minRequiredBudgetFlop // "?"' <<<"$resp") extra=" | need>=${need_min} F at current gas" fi local sleep_s="$interval" if [[ "$wait_sec" =~ ^[0-9]+$ ]] && (( wait_sec > sleep_s )); then sleep_s=$(( wait_sec > 120 ? 120 : wait_sec )) fi log "WAIT advice=${advice} | gas=${mult}x (${gstat}) | reserve=${reserve} F${extra} | next check in ${sleep_s}s" if (( max_wait > 0 )); then local elapsed=$(( $(date +%s) - started )) if (( elapsed >= max_wait )); then die "Timed out after ${elapsed}s waiting for affordable gas (no transaction sent)." fi fi sleep "$sleep_s" done } cmd_rescue() { need_cmd curl need_cmd jq local chan_id="" local balance="" local max_mult="" local rpc="$DEFAULT_RPC" local interval="25" local max_wait="0" local dry_run="0" while [[ $# -gt 0 ]]; do case "$1" in --channel) chan_id="$2"; shift 2 ;; --balance) balance="$2"; shift 2 ;; --max-mult) max_mult="$2"; shift 2 ;; --rpc) rpc="$2"; shift 2 ;; --interval) interval="$2"; shift 2 ;; --max-wait) max_wait="$2"; shift 2 ;; --indexer) INDEXER_URL="${2%/}"; shift 2 ;; --dry-run) dry_run="1"; shift ;; --uri|--seed|--mnemonic) die "Refusing seed/URI on command line. Export FLOP_URI env var locally instead." ;; -h|--help) usage; exit 0 ;; *) die "Unknown rescue option: $1" ;; esac done [[ -n "$chan_id" ]] || die "--channel is required" [[ "$chan_id" =~ ^[0-9]+$ || "$chan_id" =~ ^0x[0-9a-fA-F]{1,64}$ ]] || die "Invalid --channel format" [[ -n "$balance" || -n "$max_mult" ]] || die "Provide --balance (auto-threshold) or --max-mult " (( interval < 10 )) && interval=10 if [[ "$dry_run" == "0" ]]; then need_cmd node [[ -n "${FLOP_URI:-}" ]] || die "Set FLOP_URI environment variable locally first (never paste seeds into scripts or websites)." fi local started=$(date +%s) log "Auto-rescue watching gas for channel=${chan_id} (rpc=${rpc}, interval=${interval}s)" while true; do local gresp="" if ! gresp=$(curl -fsSL --max-time 12 -A "$UA" "${INDEXER_URL}/api/gas" 2>/dev/null); then log "Gas API temporarily unreachable; retrying in ${interval}s..." sleep "$interval" continue fi local cur_mult timeout_per_mult eff_max cur_mult=$(jq -r '.feeMultiplier // empty' <<<"$gresp") timeout_per_mult=$(jq -r '.feeCalibration.timeoutBasePerMultFlop // 0.015017' <<<"$gresp") if [[ -n "$max_mult" ]]; then eff_max="$max_mult" else eff_max=$(awk -v b="$balance" -v p="$timeout_per_mult" 'BEGIN { if (p <= 0) print 0; else printf "%d", int((b * 0.85) / p) }') fi if [[ -z "$cur_mult" ]]; then log "No feeMultiplier yet; sleeping ${interval}s..." sleep "$interval" continue fi local is_ok is_ok=$(awk -v c="$cur_mult" -v m="$eff_max" 'BEGIN { print (c <= m && m > 0) ? 1 : 0 }') if [[ "$is_ok" == "1" ]]; then local est_fee est_fee=$(awk -v c="$cur_mult" -v p="$timeout_per_mult" 'BEGIN { printf "%.3f", c * p }') log "Gas fits! current=${cur_mult}x <= max=${eff_max}x (est timeout fee ~${est_fee} F)." if [[ "$dry_run" == "1" ]]; then log "DRY-RUN: would check expiry and submit computeChannel.timeout(${chan_id}) via ${rpc}" exit 0 fi set +e CHANNEL_ID="$chan_id" FLOP_RPC="$rpc" node --input-type=module -e ' const { ApiPromise, WsProvider, Keyring } = await import("@polkadot/api"); const api = await ApiPromise.create({ provider: new WsProvider(process.env.FLOP_RPC) }); try { const head = (await api.rpc.chain.getHeader(await api.rpc.chain.getFinalizedHead())).number.toNumber(); const opt = await api.query.computeChannel.channels(process.env.CHANNEL_ID); if (opt.isNone) { console.log("RESCUE_DONE: channel already closed or not found."); process.exit(0); } const ch = opt.toJSON(); const openedAt = Number(ch?.openedAt ?? ch?.opened_at ?? 0); const maxDur = Number(ch?.maxDuration ?? ch?.max_duration ?? 0); if (openedAt > 0 && maxDur > 0 && head <= openedAt + maxDur) { const rem = (openedAt + maxDur) - head; console.log("RESCUE_NOT_EXPIRED: finalizedHead=" + head + " unlockBlock=" + (openedAt + maxDur) + " remainingBlocks=" + rem); process.exit(42); } const signer = new Keyring({ type: "sr25519" }).addFromUri(process.env.FLOP_URI); await new Promise((resolve, reject) => { api.tx.computeChannel.timeout(process.env.CHANNEL_ID) .signAndSend(signer, ({ status, dispatchError }) => { if (dispatchError) return reject(new Error(dispatchError.toString())); if (status.isFinalized) { console.log("RESCUE_FINALIZED: " + status.asFinalized.toHex()); resolve(); } }).catch(reject); }); } finally { await api.disconnect(); } ' local nrc=$? set -e if [[ $nrc -eq 0 ]]; then log "Rescue finished." exit 0 elif [[ $nrc -eq 42 ]]; then log "Channel not expired yet; sleeping ${interval}s..." else die "Rescue transaction/check exited with code ${nrc}. Make sure @polkadot/api is installed locally." fi else log "WAIT gas=${cur_mult}x > target<=${eff_max}x (timeoutPerMult=${timeout_per_mult}) | sleeping ${interval}s" fi if (( max_wait > 0 )); then local elapsed=$(( $(date +%s) - started )) if (( elapsed >= max_wait )); then die "Timed out after ${elapsed}s waiting for low rescue gas." fi fi sleep "$interval" done } cmd_claim_wait() { need_cmd curl need_cmd jq local claim_cmd="" local status_only="0" local min_wait="180" local max_attempts="12" local address="" local target_bal="1" local then_infer="0" local dry_run="0" local -a infer_args=() while [[ $# -gt 0 ]]; do case "$1" in --cmd) claim_cmd="$2"; shift 2 ;; --status-only) status_only="1"; shift ;; --min-wait) min_wait="$2"; shift 2 ;; --max-attempts) max_attempts="$2"; shift 2 ;; --address) address="$2"; shift 2 ;; --target-balance) target_bal="$2"; shift 2 ;; --then-infer) then_infer="1"; shift ;; --model|--budget|--via|--max-tokens|--max-turns|--prompt|--interval|--max-wait|--rpc-timeout) infer_args+=("$1" "$2"); shift 2 ;; --strict-gas) infer_args+=("$1"); shift ;; --indexer) INDEXER_URL="${2%/}"; shift 2 ;; --dry-run) dry_run="1"; shift ;; -h|--help) usage; exit 0 ;; *) die "Unknown claim-wait option: $1" ;; esac done if (( min_wait < 180 )); then log "Enforcing polite floor: raising --min-wait from ${min_wait}s to 180s." min_wait=180 fi if (( max_attempts > 48 )); then log "Enforcing polite cap: lowering --max-attempts from ${max_attempts} to 48." max_attempts=48 fi local fresp fresp=$(curl -fsSL --max-time 12 -A "$UA" "${INDEXER_URL}/api/faucet") || die "Could not fetch /api/faucet" if [[ "$status_only" == "1" ]]; then jq '{status, funded, balanceFlop, pendingGrants, queuePressure, dailyRemainingFlop: .dailyCap.remainingFlop, agent: {grantFlop: .agent.grantFlop, refillFlop: .agent.refillFlop, minRefillSpend: .agent.minimumRefillSpendFlop, cooldownSec: .agent.cooldownSeconds}, perClient, cachedAt}' <<<"$fresp" exit 0 fi [[ -n "$claim_cmd" ]] || die "Provide --cmd '' or pass --status-only" log "Polite SINGLE-WALLET mode: min_wait=${min_wait}s + jitter (10-45s), max_attempts=${max_attempts}." log "Note: Human Turnstile verification (chatStarter) must be completed manually in a browser." local attempt=0 local funded_ok=0 while (( attempt < max_attempts )); do attempt=$(( attempt + 1 )) if [[ -n "$address" ]]; then local wresp="" if wresp=$(curl -fsSL --max-time 12 -A "$UA" "${INDEXER_URL}/api/wallet-check?address=$(url_encode "$address")" 2>/dev/null); then local free_now free_now=$(jq -r '.balances.freeFlop // 0' <<<"$wresp") local reached reached=$(awk -v f="$free_now" -v t="$target_bal" 'BEGIN { print (f >= t) ? 1 : 0 }') if [[ "$reached" == "1" ]]; then log "Wallet ${address} already has ${free_now} FLOP (>= ${target_bal} FLOP)." funded_ok=1 break fi fi fi local st funded pending fresp=$(curl -fsSL --max-time 12 -A "$UA" "${INDEXER_URL}/api/faucet" 2>/dev/null || true) st=$(jq -r '.status // "unknown"' <<<"$fresp" 2>/dev/null || echo "unknown") funded=$(jq -r '.funded // false' <<<"$fresp" 2>/dev/null || echo "false") pending=$(jq -r '.pendingGrants // "?"' <<<"$fresp" 2>/dev/null || echo "?") if [[ "$st" != "open" || "$funded" != "true" ]]; then local jit=$(( 10 + RANDOM % 36 )) local wait_s=$(( min_wait + jit )) log "[${attempt}/${max_attempts}] Faucet status=${st} funded=${funded} (skipping claim call). Waiting ${wait_s}s..." sleep "$wait_s" continue fi log "[${attempt}/${max_attempts}] Faucet OPEN (pending=${pending}). Running single-wallet command..." if [[ "$dry_run" == "1" ]]; then log "DRY-RUN: bash -lc "${claim_cmd}"" exit 0 fi local out="" set +e out=$(bash -lc "$claim_cmd" 2>&1) local crc=$? set -e printf '%s\n' "$out" if [[ $crc -eq 0 ]]; then log "Claim command succeeded on attempt ${attempt}!" funded_ok=1 break fi # 尊重官方返回的 retry_after / Retry-After local retry_after retry_after=$(printf '%s' "$out" | grep -oiE 'retry[_-]?after[" :=]+[0-9]+' | grep -oE '[0-9]+' | head -n1 || true) local base_wait="$min_wait" if [[ "$retry_after" =~ ^[0-9]+$ ]] && (( retry_after > base_wait )); then base_wait="$retry_after" fi local jit=$(( 10 + RANDOM % 36 )) local wait_s=$(( base_wait + jit )) log "Attempt ${attempt} returned exit=${crc}; respecting backoff ${wait_s}s (base=${base_wait}s + jitter=${jit}s)..." sleep "$wait_s" done if [[ "$funded_ok" != "1" ]]; then die "Reached max_attempts (${max_attempts}) without confirmed funding." fi if [[ "$then_infer" == "1" ]]; then log "Chaining into safe-run.sh infer..." cmd_infer "${infer_args[@]}" fi } main() { local sub="${1:-}" case "$sub" in infer) shift; cmd_infer "$@" ;; rescue) shift; cmd_rescue "$@" ;; claim-wait) shift; cmd_claim_wait "$@" ;; -h|--help|"") usage ;; *) die "Unknown subcommand '$sub'. Run './safe-run.sh --help'." ;; esac } main "$@"