#!/usr/bin/env bash # AGENT_API · agentgw.cloud — one-command Claude Code setup (macOS, Linux, Git Bash on Windows): # curl -fsSL https://agentgw.cloud/install.sh | bash # Writes ONLY ~/.claude/settings.json (the file as it was before the first run stays as settings.json.before-agentgw) and # ~/.claude/agentgw-statusline.sh. The key is read from the terminal (never from the command line) and is sent only to the # agentgw address below, to check it. Unattended: AGENTGW_API_KEY, AGENTGW_VARIANT (1..n), AGENTGW_STATUSLINE (1, 0, replace), # AGENTGW_NONINTERACTIVE=1 (never prompt). Child processes get &2; } TTY=0 if [ -z "${AGENTGW_NONINTERACTIVE:-}" ] && (exec /dev/null && [ -w /dev/tty ]; then TTY=1; fi ask() { local a=''; printf '%s' "$1" > /dev/tty; IFS= read -r a < /dev/tty || a=''; printf '%s' "$a"; } say '' say "$M_title" say '' command -v curl >/dev/null 2>&1 || { err "$M_noCurl"; exit 1; } # 1) Claude Code itself if ! command -v claude >/dev/null 2>&1; then say "$M_noClaude" if [ "$TTY" = 1 ] && [ -z "${AGENTGW_API_KEY:-}" ]; then case "$(ask "$M_askInstallClaude")" in [nN]*) say "$M_installLaterSh" ;; *) bash -c 'curl -fsSL https://claude.ai/install.sh | bash' /dev/tty IFS= read -rs KEY < /dev/tty || KEY='' printf '\n' > /dev/tty else err "$M_needTty"; exit 1 fi fi KEY=$(printf '%s' "$KEY" | tr -d '[:space:]') [ -n "$KEY" ] || { err "$M_keyEmpty"; exit 1; } case "$KEY" in *[!A-Za-z0-9_.-]*) err "$M_keyChars"; exit 1 ;; esac # 4) check it — nothing is written unless the gateway accepts it say "$M_checking" RESP=$(printf 'header = "x-api-key: %s"\n' "$KEY" | curl -sS -m 20 -K - -w '\n%{http_code}' "$BASE/v1/usage/brief?format=text&lang=$AGW_LANG" 2>/dev/null) || true CODE=$(printf '%s' "$RESP" | tail -n 1) BODY=$(printf '%s' "$RESP" | sed '$d' | head -n 1) LINE=''; OURS=0 case "$BODY" in 'AGW|'*) OURS=1; LINE=${BODY#AGW|} ;; esac if [ "$OURS" = 1 ] && [ "$CODE" = 200 ]; then say "$M_keyOk $LINE" elif [ "$OURS" = 1 ]; then err "$M_keyRejected $LINE"; exit 1 else err "$M_netFailA ${CODE:-000}$M_netFailB"; exit 1 fi # 5) the status line DIR="$HOME/.claude" SETTINGS="$DIR/settings.json" SL_MODE=set case "${AGENTGW_STATUSLINE:-}" in 0|no|off) SL_MODE=off ;; replace) SL_MODE=replace ;; esac if [ -z "${AGENTGW_STATUSLINE:-}" ] && [ "$TTY" = 1 ] && [ -z "${AGENTGW_API_KEY:-}" ]; then case "$(ask "$M_askStatusline")" in [nN]*) SL_MODE=off ;; esac fi if [ "$SL_MODE" = set ] && [ -f "$SETTINGS" ] && grep -q '"statusLine"' "$SETTINGS" 2>/dev/null && ! grep -q 'agentgw-statusline' "$SETTINGS" 2>/dev/null; then SL_MODE=keep if [ -z "${AGENTGW_STATUSLINE:-}" ] && [ "$TTY" = 1 ] && [ -z "${AGENTGW_API_KEY:-}" ]; then case "$(ask "$M_askReplace")" in [yY]*) SL_MODE=replace ;; esac fi fi mkdir -p "$DIR" SL_PATH="$DIR/agentgw-statusline.sh" SL_CMD='' if [ "$SL_MODE" = set ] || [ "$SL_MODE" = replace ]; then cat > "$SL_PATH.tmp" <<'AGW_STATUSLINE_EOF' #!/usr/bin/env bash # agentgw.cloud status line for Claude Code (installed by the agentgw installer). Prints: agentgw · model · the key's quota. # The quota is fetched at most once a minute and kept in ~/.claude/.agentgw-status. The key is read from Claude Code's # environment or ~/.claude/settings.json, sent only to the agentgw address, and never printed. AGW_BASES=' https://agentgw.cloud ' AGW_LANG='vi' AGW_STALE='(cũ)' AGW_NOBAL='không lấy được số dư' input=$(cat 2>/dev/null) model=$(printf '%s' "$input" | sed -n 's/.*"display_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1) prefix='agentgw'; [ -n "$model" ] && prefix="agentgw · $model" settings="$HOME/.claude/settings.json" key=${ANTHROPIC_AUTH_TOKEN:-${ANTHROPIC_API_KEY:-}}; base=${ANTHROPIC_BASE_URL:-} if [ -f "$settings" ]; then [ -n "$key" ] || key=$(sed -n 's/.*"ANTHROPIC_AUTH_TOKEN"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$settings" | head -n 1) [ -n "$key" ] || key=$(sed -n 's/.*"ANTHROPIC_API_KEY"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$settings" | head -n 1) [ -n "$base" ] || base=$(sed -n 's/.*"ANTHROPIC_BASE_URL"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$settings" | head -n 1) fi while [ "${base%/}" != "$base" ]; do base=${base%/}; done case "$AGW_BASES" in *" $base "*) ;; *) printf '%s\n' "$prefix"; exit 0 ;; esac case "$key" in ''|*[!A-Za-z0-9_.-]*) printf '%s\n' "$prefix"; exit 0 ;; esac cache="$HOME/.claude/.agentgw-status" now=$(date +%s); stamp=0; good=''; state='' if [ -f "$cache" ]; then stamp=$(sed -n '1p' "$cache" 2>/dev/null); good=$(sed -n '2p' "$cache" 2>/dev/null); state=$(sed -n '3p' "$cache" 2>/dev/null) case "$stamp" in ''|*[!0-9]*) stamp=0 ;; esac fi if [ $((now - stamp)) -ge 60 ]; then body=$(printf 'header = "x-api-key: %s"\n' "$key" | curl -s -m 4 -K - "$base/v1/usage/brief?format=text&lang=$AGW_LANG" 2>/dev/null | head -n 1) case "$body" in 'AGW|'*) good=${body#AGW|}; state=ok ;; *) state=stale ;; esac printf '%s\n%s\n%s\n' "$now" "$good" "$state" > "$cache.$$" 2>/dev/null && mv -f "$cache.$$" "$cache" 2>/dev/null fi if [ -z "$good" ]; then line=$AGW_NOBAL; elif [ "$state" = stale ]; then line="$good $AGW_STALE"; else line=$good; fi printf '%s · %s\n' "$prefix" "$line" AGW_STATUSLINE_EOF mv -f "$SL_PATH.tmp" "$SL_PATH" && chmod 700 "$SL_PATH" case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) SL_CMD="\"$(cygpath -m "$(command -v bash)")\" \"$(cygpath -m "$SL_PATH")\"" ;; *) SL_CMD="bash \"$SL_PATH\"" ;; esac fi # 6) settings.json — merged with node or python3; a missing or empty file is written directly say "$M_writing $SETTINGS" RUNNER='' if command -v node >/dev/null 2>&1; then RUNNER=node elif command -v python3 >/dev/null 2>&1; then RUNNER=python3 # macOS ships a python3 stub that opens an installer window when the developer tools are missing if [ "$(uname -s)" = Darwin ] && [ "$(command -v python3)" = /usr/bin/python3 ] && ! xcode-select -p >/dev/null 2>&1; then RUNNER=''; fi fi OUT='' if [ -n "$RUNNER" ]; then if [ "$RUNNER" = node ]; then OUT=$(AGW_SETTINGS="$SETTINGS" AGW_KEY="$KEY" AGW_ENV="$ENVJSON" AGW_MANAGED="$AGW_MANAGED" AGW_SL_MODE="$SL_MODE" AGW_SL_CMD="$SL_CMD" node -e 'const fs=require('\''fs'\'');const p=process.env.AGW_SETTINGS;let o={};let had=false; try{const t=fs.readFileSync(p,'\''utf8'\'');had=true;if(t.trim())o=JSON.parse(t.replace(/^\uFEFF/,'\'''\''));}catch(e){if(!e||e.code!=='\''ENOENT'\''){console.log('\''error=bad_json'\'');process.exit(3);}} if(typeof o!=='\''object'\''||o===null||Array.isArray(o)){console.log('\''error=bad_json'\'');process.exit(3);} const managed=JSON.parse(process.env.AGW_MANAGED),add=JSON.parse(process.env.AGW_ENV); const env=(o.env&&typeof o.env==='\''object'\''&&!Array.isArray(o.env))?o.env:{};const removed=[]; for(const k of managed){if(k in env&&!(k in add)&&(k!=='\''ANTHROPIC_AUTH_TOKEN'\''||env[k]!==process.env.AGW_KEY))removed.push(k);delete env[k];} Object.assign(env,add);env.ANTHROPIC_AUTH_TOKEN=process.env.AGW_KEY;o.env=env; if('\''apiKeyHelper'\'' in o){delete o.apiKeyHelper;removed.push('\''apiKeyHelper'\'');} const mode=process.env.AGW_SL_MODE,sl=o.statusLine,ours=!!(sl&&typeof sl==='\''object'\''&&String(sl.command||'\'''\'').includes('\''agentgw-statusline'\'')); if(mode==='\''replace'\''||(mode==='\''set'\''&&(!sl||ours)))o.statusLine={type:'\''command'\'',command:process.env.AGW_SL_CMD,padding:0};else if(mode==='\''off'\''&&ours)delete o.statusLine; const bak=p+'\''.before-agentgw'\'';if(had&&!fs.existsSync(bak)){fs.copyFileSync(p,bak);fs.chmodSync(bak,0o600);console.log('\''backup='\''+bak);} const tmp=p+'\''.agentgw-tmp'\'';fs.writeFileSync(tmp,JSON.stringify(o,null,2)+'\''\n'\'',{mode:0o600});fs.renameSync(tmp,p);fs.chmodSync(p,0o600); console.log('\''removed='\''+removed.join('\'','\''));' &1) else OUT=$(AGW_SETTINGS="$SETTINGS" AGW_KEY="$KEY" AGW_ENV="$ENVJSON" AGW_MANAGED="$AGW_MANAGED" AGW_SL_MODE="$SL_MODE" AGW_SL_CMD="$SL_CMD" python3 -c 'import json,os,sys,shutil p=os.environ['\''AGW_SETTINGS'\''];o={};had=False try: with open(p,encoding='\''utf-8-sig'\'') as f: t=f.read() had=True if t.strip(): o=json.loads(t) except FileNotFoundError: pass except Exception: print('\''error=bad_json'\''); sys.exit(3) if not isinstance(o,dict): print('\''error=bad_json'\''); sys.exit(3) managed=json.loads(os.environ['\''AGW_MANAGED'\'']); add=json.loads(os.environ['\''AGW_ENV'\'']) env=o.get('\''env'\'') if isinstance(o.get('\''env'\''),dict) else {} removed=[k for k in managed if k in env and k not in add and (k!='\''ANTHROPIC_AUTH_TOKEN'\'' or env[k]!=os.environ['\''AGW_KEY'\''])] for k in managed: env.pop(k,None) env.update(add); env['\''ANTHROPIC_AUTH_TOKEN'\'']=os.environ['\''AGW_KEY'\'']; o['\''env'\'']=env if '\''apiKeyHelper'\'' in o: del o['\''apiKeyHelper'\'']; removed.append('\''apiKeyHelper'\'') mode=os.environ.get('\''AGW_SL_MODE'\'','\'''\''); sl=o.get('\''statusLine'\'') ours=isinstance(sl,dict) and '\''agentgw-statusline'\'' in str(sl.get('\''command'\'','\'''\'')) if mode=='\''replace'\'' or (mode=='\''set'\'' and (not sl or ours)): o['\''statusLine'\'']={'\''type'\'':'\''command'\'','\''command'\'':os.environ['\''AGW_SL_CMD'\''],'\''padding'\'':0} elif mode=='\''off'\'' and ours: del o['\''statusLine'\''] bak=p+'\''.before-agentgw'\'' if had and not os.path.exists(bak): shutil.copyfile(p,bak); os.chmod(bak,0o600); print('\''backup='\''+bak) tmp=p+'\''.agentgw-tmp'\'' with os.fdopen(os.open(tmp,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600),'\''w'\'',encoding='\''utf-8'\'') as f: f.write(json.dumps(o,indent=2,ensure_ascii=False)+'\''\n'\'') os.replace(tmp,p); os.chmod(p,0o600) print('\''removed='\''+'\'','\''.join(removed))' &1) fi RC=$? if printf '%s' "$OUT" | grep -q '^error=bad_json'; then err "$M_badJson $SETTINGS"; exit 1; fi if [ "$RC" != 0 ]; then err "$M_badJson $SETTINGS"; exit 1; fi elif [ ! -s "$SETTINGS" ] || [ -z "$(tr -d '[:space:]' < "$SETTINGS")" ]; then E=${ENVJSON%\}} if [ "$E" = '{' ]; then E="{\"ANTHROPIC_AUTH_TOKEN\":\"$KEY\"}"; else E="$E,\"ANTHROPIC_AUTH_TOKEN\":\"$KEY\"}"; fi if [ -n "$SL_CMD" ]; then C=$(printf '%s' "$SL_CMD" | sed 's/\\/\\\\/g; s/"/\\"/g') printf '{\n "env": %s,\n "statusLine": {"type": "command", "command": "%s", "padding": 0}\n}\n' "$E" "$C" > "$SETTINGS.agentgw-tmp" else printf '{\n "env": %s\n}\n' "$E" > "$SETTINGS.agentgw-tmp" fi mv -f "$SETTINGS.agentgw-tmp" "$SETTINGS" && chmod 600 "$SETTINGS" else err "$M_noRuntime $AGW_SITE/setup"; exit 1 fi BACKUP=$(printf '%s\n' "$OUT" | sed -n 's/^backup=//p' | head -n 1) REMOVED=$(printf '%s\n' "$OUT" | sed -n 's/^removed=//p' | head -n 1) [ -n "$BACKUP" ] && say "$M_backup $BACKUP" [ -n "$REMOVED" ] && say "$M_removed $REMOVED" # 7) the agentgw tools in Claude Code (MCP): only where the gateway offers them (GET /v1/mcp answers 405). The key stays in # settings.json: Claude Code asks the helper for the header each time it connects. if [ "${AGENTGW_MCP:-1}" != 0 ] && command -v claude >/dev/null 2>&1; then MC=$(curl -s -o /dev/null -m 10 -w '%{http_code}' "$BASE/v1/mcp" 2>/dev/null) || MC=000 WANT=0 [ "$MC" = 405 ] && WANT=1 if [ "$WANT" = 1 ] && [ -z "${AGENTGW_MCP:-}" ] && [ "$TTY" = 1 ] && [ -z "${AGENTGW_API_KEY:-}" ]; then case "$(ask "$M_askMcp")" in [nN]*) WANT=0 ;; esac fi if [ "$WANT" = 1 ]; then HP="$DIR/agentgw-mcp-headers.sh" cat > "$HP.tmp" <<'AGW_MCP_EOF' #!/usr/bin/env bash # agentgw.cloud MCP header for Claude Code (installed by the agentgw installer): prints the API key from # ~/.claude/settings.json as the header Claude Code sends to the agentgw tools. Nothing else reads or keeps it. k=$(sed -n 's/.*"ANTHROPIC_AUTH_TOKEN"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$HOME/.claude/settings.json" 2>/dev/null | head -n 1) [ -n "$k" ] || k=$(sed -n 's/.*"ANTHROPIC_API_KEY"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$HOME/.claude/settings.json" 2>/dev/null | head -n 1) case "$k" in ''|*[!A-Za-z0-9_.-]*) printf '{}\n' ;; *) printf '{"x-api-key":"%s"}\n' "$k" ;; esac AGW_MCP_EOF mv -f "$HP.tmp" "$HP" && chmod 700 "$HP" case "$(uname -s 2>/dev/null)" in MINGW*|MSYS*|CYGWIN*) HCMD="\"$(cygpath -m "$(command -v bash)")\" \"$(cygpath -m "$HP")\"" ;; *) HCMD="bash \"$HP\"" ;; esac HJ=$(printf '%s' "$HCMD" | sed 's/\\/\\\\/g; s/"/\\"/g') claude mcp remove agentgw -s user >/dev/null 2>&1 /dev/null 2>&1 /dev/null 2>&1; then say "$M_shellEnvA $v $M_shellEnvSh"; fi done say '' say "$M_done" say "$M_trust" [ -n "$SL_CMD" ] && say "$M_statuslineOn" [ -f "$SETTINGS.before-agentgw" ] && say "$M_restore $SETTINGS.before-agentgw" exit 0