#!/usr/bin/env bash # netra.sh — install Netra Runtime (https://api.netra.sh/v1) and every model it # serves into every agentic harness already installed on this machine. # # Works on: Linux, macOS, Windows (Git Bash / MSYS2 / Cygwin). # # Harness coverage (writes a real config where the tool has one): # config writers : claude-code, codex, opencode, pi, dsh (DeepSeek Harness), # crush, goose, aider, continue, qwen-code, cline, roo-code, # kilo-code (VS Code settings.json) # env-only : amp, auggie, droid, kimi, mistral-vibe, iflow, grok, # cursor-agent, copilot, openhands, codebuff # needs manual : gemini-cli (Google generateContent protocol), Cursor/ # Windsurf/Kiro/Trae IDEs (GUI-only model pickers) # # Everything written is idempotent and backed up to .netra.bak. # # Usage: # ./netra.sh # detect harnesses, install, verify # ./netra.sh --dry-run # show what would change, write nothing # ./netra.sh --api-key sk_live_x # non-interactive # ./netra.sh --list-models # print the Netra catalog and exit # ./netra.sh --only claude-code,pi --yes # ./netra.sh --uninstall # remove netra.sh's managed config + backups # # Design notes: # * Idempotent. Re-running only rewrites blocks marked "netra.sh managed". # * Every file it touches is backed up to .netra.bak before the first write. # * Secrets: the key lands in ~/.netra/credentials (0600), the shell env file, # and in per-harness configs that cannot read env vars (Claude Code, aider). # * No associative arrays / no bash4-only features: runs on macOS bash 3.2. set -u VERSION="1.0.0" DEFAULT_BASE="https://api.netra.sh/v1" DEFAULT_PROVIDER="netra" NETRA_HOME="$HOME/.netra" CRED_FILE="$NETRA_HOME/credentials" ENV_FILE="$NETRA_HOME/env" CONFIG_FILE="$NETRA_HOME/config" MGR_BEGIN="# >>> netra.sh managed >>>" MGR_END="# <<< netra.sh managed <<<" TOML_BEGIN="# >>> netra.sh managed >>>" TOML_END="# <<< netra.sh managed <<<" BASE_URL="${NETRA_BASE_URL:-$DEFAULT_BASE}" API_KEY="${NETRA_API_KEY:-${NETRA_RUNTIME_API_KEY:-}}" PROVIDER_ID="$DEFAULT_PROVIDER" WANT_MODEL="" DRY_RUN=0 ASSUME_YES=0 DO_ENV=1 DO_VERIFY=1 UNINSTALL=0 LIST_ONLY=0 VERBOSE=0 ONLY="" SKIP="" TMPDIR_N="" SELF_URL="${NETRA_SELF_URL:-https://agent.netra.sh/netra.sh}" cleanup() { [ -n "$TMPDIR_N" ] && rm -rf "$TMPDIR_N" 2>/dev/null; } trap cleanup EXIT INT TERM # ---------------------------------------------------------------- ui ---------- if [ -t 1 ] && [ "${NO_COLOR:-}" = "" ]; then C_B=$'\033[1m'; C_G=$'\033[32m'; C_Y=$'\033[33m'; C_R=$'\033[31m'; C_D=$'\033[2m'; C_0=$'\033[0m' else C_B=""; C_G=""; C_Y=""; C_R=""; C_D=""; C_0="" fi say() { printf '%s\n' "$*"; } info() { printf '%s\n' "$*"; } ok() { printf '%s[ ok ]%s %s\n' "$C_G" "$C_0" "$*"; } warn() { printf '%s[warn]%s %s\n' "$C_Y" "$C_0" "$*"; } err() { printf '%s[fail]%s %s\n' "$C_R" "$C_0" "$*" >&2; } dbg() { [ "$VERBOSE" = 1 ] && printf '%s[dbg ] %s%s\n' "$C_D" "$*" "$C_0"; return 0; } head2(){ printf '\n%s== %s ==%s\n' "$C_B" "$*" "$C_0"; } usage() { cat </dev/null 2>&1; } have_any() { for h in "$@"; do have "$h" && return 0; done; return 1; } # ---------------------------------------------------------------- tty --------- # `curl -fsSL https://agent.netra.sh | bash` replaces stdin with the script, so # prompts must talk to the controlling terminal instead of stdin. TTY_DEV="" detect_tty() { TTY_DEV="" if [ -t 0 ]; then return 0; fi if [ -r /dev/tty ] && { : < /dev/tty; } 2>/dev/null; then TTY_DEV=/dev/tty; return 0; fi return 1 } read_prompt() { # read_prompt [silent] -> REPLY (empty if no terminal) _p="$1"; _silent="${2:-}" detect_tty || { REPLY=""; return 1; } if [ -n "$TTY_DEV" ]; then printf '%s' "$_p" > "$TTY_DEV" 2>/dev/null; else printf '%s' "$_p"; fi if [ "$_silent" = silent ]; then stty -echo 2>/dev/null < "${TTY_DEV:-/dev/tty}"; fi if [ -n "$TTY_DEV" ]; then read -r REPLY < "$TTY_DEV" || REPLY=""; else read -r REPLY || REPLY=""; fi if [ "$_silent" = silent ]; then stty echo 2>/dev/null < "${TTY_DEV:-/dev/tty}"; printf '\n'; fi return 0 } # --------------------------------------------------------------- helpers ------ mktmp() { TMPDIR_N="${TMPDIR:-/tmp}/netra.sh.$$" mkdir -p "$TMPDIR_N" || exit 1 # NOTE: these two depend on TMPDIR_N, so they must be initialised here and not # at the top of the script. MODELS_TSV="$TMPDIR_N/models.tsv" STATUS_FILE="$TMPDIR_N/status.tsv" : > "$STATUS_FILE" } # pick a JSON engine: python3/python/node/powershell/jq (each candidate is # actually executed — Windows ships a "python3" Store stub that only errors) JSON_ENGINE="" engine_works() { case "$1" in python3|python) [ "$("$1" -c 'print("ok")' 2>/dev/null)" = ok ] ;; node) [ "$("$1" -e 'process.stdout.write("ok")' 2>/dev/null)" = ok ] ;; powershell) [ "$(powershell.exe -NoProfile -Command 'Write-Output ok' 2>/dev/null | tr -d '\r')" = ok ] ;; jq) [ "$(echo '{}' | jq -e . >/dev/null 2>&1 && echo ok)" = ok ] ;; *) return 1 ;; esac } detect_json_engine() { for cand in python3 python node jq; do if have "$cand" && engine_works "$cand"; then JSON_ENGINE=$cand; break; fi done if [ -z "$JSON_ENGINE" ] && [ "$IS_WINDOWS" = 1 ] && have powershell.exe && engine_works powershell; then JSON_ENGINE=powershell fi dbg "json_engine=$JSON_ENGINE" } fetch_auth() { # url outfile [--no-hdr] _u="$1"; _o="$2"; _auth=1 [ "${3:-}" = "--no-hdr" ] && _auth=0 if have curl; then if [ "$_auth" = 1 ] && [ -n "$API_KEY" ]; then curl -fsSL --max-time 40 -H "Authorization: Bearer $API_KEY" -H "Accept: application/json" "$_u" -o "$_o" 2>/dev/null else curl -fsSL --max-time 40 -H "Accept: application/json" "$_u" -o "$_o" 2>/dev/null fi; return $? fi if have wget; then if [ "$_auth" = 1 ] && [ -n "$API_KEY" ]; then wget -q -T 40 --header="Authorization: Bearer $API_KEY" --header="Accept: application/json" -O "$_o" "$_u" 2>/dev/null else wget -q -T 40 --header="Accept: application/json" -O "$_o" "$_u" 2>/dev/null fi; return $? fi if have powershell.exe; then powershell.exe -NoProfile -Command "\$ProgressPreference='SilentlyContinue'; \$h=@{}; if('$API_KEY' -ne ''){\$h['Authorization']='Bearer $API_KEY'}; Invoke-RestMethod -Uri '$_u' -Headers \$h -TimeoutSec 40 | ConvertTo-Json -Depth 20 | Out-File -Encoding utf8 '$_o'" >/dev/null 2>&1 return $? fi return 1 } # json_merge — deep-merges patch into dst (objects merged, arrays replaced) json_merge_file() { _dst="$1"; _patch="$2" case "$JSON_ENGINE" in python3|python) "$JSON_ENGINE" - "$_dst" "$_patch" <<'PY' import json, sys, os, tempfile dst, patch = sys.argv[1], sys.argv[2] def load(p): try: with open(p, 'r', encoding='utf-8-sig') as f: s = f.read().strip() return json.loads(s) if s else {} except FileNotFoundError: return {} except Exception: return {} def merge(a, b): if isinstance(a, dict) and isinstance(b, dict): out = dict(a) for k, v in b.items(): out[k] = merge(a.get(k), v) if k in a else v return out return b new = merge(load(dst), json.load(open(patch, 'r', encoding='utf-8'))) d = os.path.dirname(dst) or '.' fd, tmp = tempfile.mkstemp(dir=d, prefix='.netra-tmp-') with os.fdopen(fd, 'w', encoding='utf-8') as f: json.dump(new, f, indent=2, ensure_ascii=False) f.write('\n') os.replace(tmp, dst) PY ;; node) node -e ' const fs=require("fs"); const [dst,patch]=process.argv.slice(1); const load=p=>{try{const s=fs.readFileSync(p,"utf8").trim();return s?JSON.parse(s):{}}catch(e){return {}}}; const merge=(a,b)=>{if(a&&b&&typeof a==="object"&&typeof b==="object"&&!Array.isArray(a)&&!Array.isArray(b)){const o={...a};for(const k in b)o[k]=k in a?merge(a[k],b[k]):b[k];return o}return b}; const out=merge(load(dst),JSON.parse(fs.readFileSync(patch,"utf8"))); fs.writeFileSync(dst+".netra-tmp",JSON.stringify(out,null,2)+"\n");fs.renameSync(dst+".netra-tmp",dst); ' "$_dst" "$_patch" ;; jq) _cur="$TMPDIR_N/cur.json"; [ -f "$_dst" ] && cp "$_dst" "$_cur" || echo '{}' > "$_cur" jq -s '.[0] * .[1]' "$_cur" "$_patch" > "$TMPDIR_N/merged.json" && mv "$TMPDIR_N/merged.json" "$_dst" ;; powershell) powershell.exe -NoProfile -Command " \$dst='$_dst'; \$patch='$_patch'; function M(\$a,\$b){ if(\$a -is [hashtable] -and \$b -is [hashtable]){ \$o=@{}; foreach(\$k in \$a.Keys){\$o[\$k]=\$a[\$k]}; foreach(\$k in \$b.Keys){ if(\$o.ContainsKey(\$k)){\$o[\$k]=M \$o[\$k] \$b[\$k]} else {\$o[\$k]=\$b[\$k]} }; return \$o } return \$b } \$a=@{}; if(Test-Path \$dst){ try{ \$j=Get-Content \$dst -Raw | ConvertFrom-Json; \$a=ConvertTo-Hashtable \$j }catch{} } function ConvertTo-Hashtable(\$o){ \$h=@{}; if(\$o -is [System.Management.Automation.PSCustomObject]){ foreach(\$p in \$o.PSObject.Properties){\$h[\$p.Name]=\$p.Value} } elseif(\$o -is [array]){ return ,(\$o | ForEach-Object { ConvertTo-Hashtable \$_ }) } else { return \$o }; foreach(\$k in @(\$h.Keys)){ \$h[\$k]=ConvertTo-Hashtable \$h[\$k] }; return \$h } \$b=ConvertTo-Hashtable (Get-Content \$patch -Raw | ConvertFrom-Json) \$m=M \$a \$b; \$m | ConvertTo-Json -Depth 30 | Out-File -Encoding utf8 \$dst " >/dev/null 2>&1 ;; esac } backup_once() { # backup_once [ -f "$1" ] || return 0 [ -f "$1.netra.bak" ] || cp "$1" "$1.netra.bak" 2>/dev/null return 0 } apply_json() { # apply_json _f="$1" if [ "$DRY_RUN" = 1 ]; then info " ${C_D}would merge into${C_0} $_f" return 0 fi mkdir -p "$(dirname "$_f")" backup_once "$_f" [ -f "$_f" ] || printf '{}\n' > "$_f" if json_merge_file "$_f" "$2"; then return 0; fi err " JSON merge failed for $_f" return 1 } block_strip() { # block_strip -> writes to stdout awk -v b="$2" -v e="$3" ' $0==b {skip=1; next} $0==e {skip=0; next} !skip {line[++n]=$0} END { while (n>0 && line[n] ~ /^[ \t]*$/) n-- for (i=1; i<=n; i++) print line[i] } ' "$1" } apply_block() { # apply_block _f="$1"; _blk="$2" if [ "$DRY_RUN" = 1 ]; then info " ${C_D}would write managed block into${C_0} $_f"; return 0; fi mkdir -p "$(dirname "$_f")" backup_once "$_f" if [ -f "$_f" ]; then block_strip "$_f" "$MGR_BEGIN" "$MGR_END" > "$TMPDIR_N/stripped" 2>/dev/null || : > "$TMPDIR_N/stripped"; else : > "$TMPDIR_N/stripped"; fi if [ -s "$TMPDIR_N/stripped" ]; then { cat "$TMPDIR_N/stripped"; echo; cat "$_blk"; } > "$TMPDIR_N/out" else cat "$_blk" > "$TMPDIR_N/out" fi # never write a byte-identical rerun if [ -f "$_f" ] && cmp -s "$TMPDIR_N/out" "$_f"; then return 0; fi mv "$TMPDIR_N/out" "$_f"; return 0 } conf_contains() { [ -f "$1" ] && grep -q -- "$2" "$1" 2>/dev/null; } # --------------------------------------------------------------- models ------- MODELS_TSV="" # set by mktmp (needs TMPDIR_N) MODEL_COUNT=0 DEFAULT_MODEL="" parse_models() { # parse_models case "$JSON_ENGINE" in python3|python) "$JSON_ENGINE" - "$1" > "$MODELS_TSV" <<'PY' import json, sys try: d = json.load(open(sys.argv[1], 'r', encoding='utf-8-sig')) except Exception as e: sys.stderr.write("parse error: %s\n" % e); sys.exit(1) def fnum(x): try: return float(x) except Exception: return 0.0 rows = d.get('data') if isinstance(d, dict) else d for m in (rows or []): mid = (m.get('id') or '').strip() if not mid: continue sp = m.get('supported_parameters') or [] pr = m.get('pricing') or {} tp = m.get('top_provider') or {} dp = m.get('default_parameters') or {} mx = tp.get('max_completion_tokens') or dp.get('max_tokens') or 0 mods = (m.get('architecture') or {}).get('input_modalities') or ['text'] name = (m.get('name') or mid).replace('\t', ' ') print('\t'.join([mid, name, str(int(m.get('context_length') or 0)), str(int(mx or 0)), '1' if 'reasoning' in sp else '0', '%.9f' % fnum(pr.get('prompt')), '%.9f' % fnum(pr.get('completion')), ','.join(mods)])) PY ;; node) node -e ' const fs=require("fs");const d=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); const rows=d.data||d;const f=x=>{const n=parseFloat(x);return isFinite(n)?n:0}; for(const m of (rows||[])){if(!m.id)continue;const sp=m.supported_parameters||[];const pr=m.pricing||{};const tp=m.top_provider||{};const dp=m.default_parameters||{}; console.log([m.id,(m.name||m.id).replace(/\t/g," "),m.context_length||0,tp.max_completion_tokens||dp.max_tokens||0,sp.includes("reasoning")?1:0,f(pr.prompt).toFixed(9),f(pr.completion).toFixed(9),((m.architecture||{}).input_modalities||["text"]).join(",")].join("\t"))} ' "$1" > "$MODELS_TSV" ;; powershell) powershell.exe -NoProfile -Command " \$d = Get-Content '$1' -Raw | ConvertFrom-Json foreach(\$m in \$d.data){ \$sp = @(); if(\$m.supported_parameters){\$sp=\$m.supported_parameters} \$mx = 0; if(\$m.top_provider.max_completion_tokens){\$mx=\$m.top_provider.max_completion_tokens} elseif(\$m.default_parameters.max_tokens){\$mx=\$m.default_parameters.max_tokens} \$mods = 'text'; if(\$m.architecture.input_modalities){\$mods=(\$m.architecture.input_modalities -join ',')} \$r = 0; if(\$sp -contains 'reasoning'){\$r = 1} '\$(\$m.id)' + \"\`t\" + '\$(\$m.name)' + \"\`t\" + '\$(\$m.context_length)' + \"\`t\" + '\$mx' + \"\`t\" + '\$r' + \"\`t\" + '\$(\$m.pricing.prompt)' + \"\`t\" + '\$(\$m.pricing.completion)' + \"\`t\" + \$mods }" > "$MODELS_TSV" 2>/dev/null ;; *) return 1 ;; esac MODEL_COUNT=$(grep -c . "$MODELS_TSV" 2>/dev/null || echo 0) [ "${MODEL_COUNT:-0}" -gt 0 ] 2>/dev/null } pick_default_model() { [ -n "$WANT_MODEL" ] && { DEFAULT_MODEL="$WANT_MODEL"; return 0; } _m="$(awk -F'\t' 'index($1,":uncensored")==0 {print $1; exit}' "$MODELS_TSV" 2>/dev/null)" [ -z "$_m" ] && _m="$(awk -F'\t' 'NR==1{print $1}' "$MODELS_TSV" 2>/dev/null)" DEFAULT_MODEL="$_m" [ -n "$DEFAULT_MODEL" ] } model_field() { awk -F'\t' -v id="$1" -v f="$2" '$1==id{print $f; exit}' "$MODELS_TSV" 2>/dev/null; } model_ids() { awk -F'\t' '{print $1}' "$MODELS_TSV" 2>/dev/null; } json_escape() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'; } per_mtok() { awk -v p="$1" 'BEGIN{printf "%.4f", p*1000000}'; } load_models_catalog() { mkdir -p "$NETRA_HOME" _json="$TMPDIR_N/models.json" info "Fetching catalog: $BASE_URL/models" if ! fetch_auth "$BASE_URL/models" "$_json"; then err "could not fetch $BASE_URL/models" info " check network / proxy, or pass --base-url" return 1 fi if ! parse_models "$_json"; then err "could not parse catalog JSON (engine: ${JSON_ENGINE:-none})" return 1 fi if [ "${MODEL_COUNT:-0}" -lt 1 ]; then err "catalog is empty — is your API key valid for $BASE_URL ?" head -c 300 "$_json" >&2; echo >&2 return 1 fi [ "$DRY_RUN" = 0 ] && cp "$_json" "$NETRA_HOME/models.json" 2>/dev/null pick_default_model || { err "no usable model in catalog"; return 1; } ok "catalog: $MODEL_COUNT model(s); default model: $DEFAULT_MODEL" return 0 } # ------------------------------------------------------------- detection ------ # id | label | binaries | dirs (relative to $HOME unless absolute) # --------------------------------------------------------------- HARNESSES='claude-code|Claude Code|claude|.claude codex|Codex CLI|codex|.codex opencode|OpenCode|opencode|.config/opencode .local/share/opencode pi|pi|pi|.pi dsh|DeepSeek Harness|dsh|.dsh "AppData/Local/Programs/DeepSeek Harness" crush|Crush|crush|.config/crush AppData/Roaming/crush goose|Goose|goose|.config/goose aider|Aider|aider|.aider.conf.yml continue|Continue|cn|.continue qwen-code|Qwen Code|qwen|.qwen cline|Cline|cline|.vscode/extensions/saoudrizwan.claude-dev* roo-code|Roo Code||.vscode/extensions/RooVeterinaryInc.roo-cline* kilo-code|Kilo Code||.vscode/extensions/kilocode.kilo-code* gemini-cli|Gemini CLI|gemini|.gemini amp|Amp|amp|.config/amp auggie|Augment Auggie|auggie| droid|Factory Droid|droid|.factory kimi|Kimi Code|kimi|.kimi mistral-vibe|Mistral Vibe|vibe|.vibe iflow|iFlow CLI|iflow|.iflow grok|Grok Build|grok|.grok cursor-agent|Cursor CLI|cursor-agent|.cursor copilot|GitHub Copilot CLI|copilot|.copilot openhands|OpenHands|openhands|.openhands codebuff|Codebuff|codebuff|.codebuff' wanted() { # wanted _id="$1" if [ -n "$ONLY" ]; then case ",$ONLY," in *",$_id,"*) : ;; *) return 1 ;; esac; fi if [ -n "$SKIP" ]; then case ",$SKIP," in *",$_id,"*) return 1 ;; esac; fi return 0 } dir_exists() { # dir_exists (supports trailing *) _p="$1" case "$_p" in /*|[A-Za-z]:*) _full="$_p" ;; *) _full="$HOME/$_p" ;; esac case "$_p" in *'*') set -- $_full; [ -e "$1" ] 2>/dev/null ;; *) [ -e "$_full" ] ;; esac } harness_installed() { # harness_installed _bins="$1"; _dirs="$2" for b in $_bins; do have "$b" && return 0; done for d in $_dirs; do dir_exists "$d" && return 0; done return 1 } DETECTED="" detect_all() { printf '%s\n' "$HARNESSES" > "$TMPDIR_N/registry.txt" while IFS='|' read -r id label bins dirs; do [ -z "$id" ] && continue if harness_installed "$bins" "$dirs"; then DETECTED="$DETECTED$id|$label " dbg "detected $id ($bins $dirs)" fi done < "$TMPDIR_N/registry.txt" return 0 } # -------------------------------------------------------------- adapters ------ STATUS_FILE="" # set by mktmp (needs TMPDIR_N) record() { printf '%s\t%s\t%s\n' "$1" "$2" "$3" >> "$STATUS_FILE"; } cfgdir_xdg() { mkdir -p "$HOME/.config/$1" 2>/dev/null; echo "$HOME/.config/$1"; } cfgdir_appdata() { # windows-native config dirs used by some tools if [ -n "${APPDATA:-}" ] && [ -d "$APPDATA/$1" ]; then echo "$APPDATA/$1"; else mkdir -p "$HOME/AppData/Roaming/$1" 2>/dev/null; echo "$HOME/AppData/Roaming/$1"; fi } # -- shared JSON fragments ----------------------------------------------------- gen_models_object() { # opencode-style {"id":{"name":...}} : > "$TMPDIR_N/models_obj.json" printf '{' >> "$TMPDIR_N/models_obj.json" _first=1 while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue [ "$_first" = 1 ] || printf ',' >> "$TMPDIR_N/models_obj.json" _first=0 printf '"%s":{"name":"%s"}' "$(json_escape "$mid")" "$(json_escape "$name")" >> "$TMPDIR_N/models_obj.json" done < "$MODELS_TSV" printf '}' >> "$TMPDIR_N/models_obj.json" } gen_models_array() { # crush-style [{id,name,context_window,...}] : > "$TMPDIR_N/models_arr.json" printf '[' >> "$TMPDIR_N/models_arr.json" _first=1 while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue [ "$_first" = 1 ] || printf ',' >> "$TMPDIR_N/models_arr.json" _first=0 _cw="${ctx:-0}"; [ "$_cw" = 0 ] && _cw=131072 _mt="${mx:-0}"; [ "$_mt" = 0 ] && _mt=8192 printf '{"id":"%s","name":"%s","context_window":%s,"default_max_tokens":%s}' \ "$(json_escape "$mid")" "$(json_escape "$name")" "$_cw" "$_mt" >> "$TMPDIR_N/models_arr.json" done < "$MODELS_TSV" printf ']' >> "$TMPDIR_N/models_arr.json" } # -- 1. Claude Code ------------------------------------------------------------ install_claude_code() { f="$HOME/.claude/settings.json" cat > "$TMPDIR_N/patch.json" < "$TMPDIR_N/stripped" 2>/dev/null || cp "$f" "$TMPDIR_N/stripped" else : > "$TMPDIR_N/stripped" fi # rewrite top-level model/model_provider (only valid before the first [table]); # every other byte of the user's file is preserved verbatim. if ! awk -v m="$DEFAULT_MODEL" -v p="$PROVIDER_ID" ' BEGIN { tbl=0; sm=0; sp=0; emitted=0 } /^[ \t]*\[/ { if (emitted==0) { if (!sm) { print "model = \"" m "\""; sm=1 } if (!sp) { print "model_provider = \"" p "\""; sp=1 } emitted=1 } tbl=1 } tbl==0 && /^[ \t]*model[ \t]*=/ { if(!sm){ print "model = \"" m "\""; sm=1 }; next } tbl==0 && /^[ \t]*model_provider[ \t]*=/ { if(!sp){ print "model_provider = \"" p "\""; sp=1 }; next } { print } END { if (emitted==0) { if (!sm) print "model = \"" m "\"" if (!sp) print "model_provider = \"" p "\"" } } ' "$TMPDIR_N/stripped" > "$TMPDIR_N/step1"; then cp "$TMPDIR_N/stripped" "$TMPDIR_N/step1" warn " codex: could not rewrite top-level model keys; left file as-is" fi { cat "$TMPDIR_N/step1" printf '\n%s\n' "$TOML_BEGIN" echo "# Netra Runtime gateway (written by netra.sh)" printf '[model_providers.%s]\n' "$PROVIDER_ID" echo "name = \"Netra Runtime\"" echo "base_url = \"$BASE_URL\"" echo "env_key = \"NETRA_API_KEY\"" echo "wire_api = \"chat\"" echo "request_max_retries = 6" echo "stream_max_retries = 6" printf '%s\n' "$TOML_END" } > "$TMPDIR_N/codex.toml" if [ -f "$TMPDIR_N/codex.toml" ] && [ -s "$TMPDIR_N/codex.toml" ]; then if [ -f "$f" ] && cmp -s "$TMPDIR_N/codex.toml" "$f"; then :; else mv "$TMPDIR_N/codex.toml" "$f"; fi else err " codex: refusing to write empty config"; return 1 fi record codex configured "$f" } # -- 3. OpenCode --------------------------------------------------------------- install_opencode() { d="$(cfgdir_xdg opencode)" f="$d/opencode.json" gen_models_object cat > "$TMPDIR_N/patch.json" < "$TMPDIR_N/pi_models.json"; printf '[' >> "$TMPDIR_N/pi_models.json"; _first=1 while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue [ "$_first" = 1 ] || printf ',' >> "$TMPDIR_N/pi_models.json"; _first=0 _cw="${ctx:-0}"; [ "$_cw" = 0 ] && _cw=131072 _mt="${mx:-0}"; [ "$_mt" = 0 ] && _mt=8192 _cin="$(per_mtok "$pin")"; _cout="$(per_mtok "$pout")" _inp='["text"]'; case "$mods" in *image*) _inp='["text","image"]' ;; esac printf '{"id":"%s","name":"%s","reasoning":%s,"input":%s,"cost":{"input":%s,"output":%s,"cacheRead":%s,"cacheWrite":0},"contextWindow":%s,"maxTokens":%s,"compat":{"maxTokensField":"max_tokens","supportsDeveloperRole":false}}' \ "$(json_escape "$mid")" "$(json_escape "$name")" \ "$([ "$reasoning" = 1 ] && echo true || echo false)" "$_inp" \ "$_cin" "$_cout" "$_cin" "$_cw" "$_mt" >> "$TMPDIR_N/pi_models.json" done < "$MODELS_TSV" printf ']' >> "$TMPDIR_N/pi_models.json" cat > "$TMPDIR_N/patch.json" < "$TMPDIR_N/patch2.json" </dev/null printf 'NETRA_API_KEY=%s\n' "$API_KEY" >> "$d/.env" else awk -v k="NETRA_API_KEY=$API_KEY" ' /^NETRA_API_KEY=/ {print k; next} {print} ' "$d/.env" > "$d/.env.netra-tmp" && mv "$d/.env.netra-tmp" "$d/.env" fi fi if [ -f "$f" ] && conf_contains "$f" "api.netra.sh" && ! conf_contains "$f" "$MGR_BEGIN"; then # user already has a hand-written Netra route: leave it alone record dsh already-configured "$f" return 0 fi { printf '\n%s\n' "$MGR_BEGIN" echo "# Netra Runtime route (written by netra.sh). Credential: NETRA_API_KEY from ~/.dsh/.env." echo "- id: llm-pi-ai" echo " name: '@deepseek-ai/dsh-llm-pi-ai'" echo " config:" echo " providers:" printf ' %s:\n' "$PROVIDER_ID" echo " displayName: Netra Runtime" echo " apiKeyEnv: NETRA_API_KEY" echo " api: openai-completions" echo " baseURL: $BASE_URL" echo " models:" while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue _cw="${ctx:-0}"; [ "$_cw" = 0 ] && _cw=131072 _mt="${mx:-0}"; [ "$_mt" = 0 ] && _mt=8192 printf ' - id: %s\n' "$mid" printf ' name: %s\n' "$name" printf ' contextWindow: %s\n' "$_cw" printf ' maxTokens: %s\n' "$_mt" done < "$MODELS_TSV" printf '%s\n' "$MGR_END" } > "$TMPDIR_N/blk.yml" apply_block "$f" "$TMPDIR_N/blk.yml" || return 1 record dsh configured "$f" } # -- 6. Crush ----------------------------------------------------------------- install_crush() { d="$(cfgdir_xdg crush)" f="$d/crush.json" gen_models_array cat > "$TMPDIR_N/patch.json" < "$TMPDIR_N/g1" grep -q '^[ \t]*GOOSE_PROVIDER:' "$TMPDIR_N/g1" || printf 'GOOSE_PROVIDER: openai\n' >> "$TMPDIR_N/g1" grep -q '^[ \t]*GOOSE_MODEL:' "$TMPDIR_N/g1" || printf 'GOOSE_MODEL: %s\n' "$DEFAULT_MODEL" >> "$TMPDIR_N/g1" mv "$TMPDIR_N/g1" "$f" # keys must live in env, not config.yaml if ! conf_contains "$d/.env" "OPENAI_API_KEY="; then touch "$d/.env"; chmod 600 "$d/.env" 2>/dev/null { echo "OPENAI_API_KEY=$API_KEY"; echo "OPENAI_HOST=https://api.netra.sh"; echo "OPENAI_BASE_PATH=v1/chat/completions"; } >> "$d/.env" fi else info " ${C_D}would set${C_0} GOOSE_PROVIDER/GOOSE_MODEL in $f" fi record goose configured "$f (+ $d/.env)" } # -- 8. Aider ----------------------------------------------------------------- install_aider() { f="$HOME/.aider.conf.yml" if [ "$DRY_RUN" = 0 ]; then backup_once "$f"; touch "$f" awk -v base="$BASE_URL" -v key="$API_KEY" -v model="openai/$DEFAULT_MODEL" ' /^[ \t]*openai-api-base:/ {print "openai-api-base: " base; next} /^[ \t]*openai-api-key:/ {print "openai-api-key: " key; next} /^[ \t]*model:/ {print "model: " model; next} {print} ' "$f" > "$TMPDIR_N/a1" grep -q '^[ \t]*openai-api-base:' "$TMPDIR_N/a1" || printf 'openai-api-base: %s\n' "$BASE_URL" >> "$TMPDIR_N/a1" grep -q '^[ \t]*openai-api-key:' "$TMPDIR_N/a1" || printf 'openai-api-key: %s\n' "$API_KEY" >> "$TMPDIR_N/a1" grep -q '^[ \t]*model:' "$TMPDIR_N/a1" || printf 'model: openai/%s\n' "$DEFAULT_MODEL" >> "$TMPDIR_N/a1" mv "$TMPDIR_N/a1" "$f"; chmod 600 "$f" 2>/dev/null else info " ${C_D}would set${C_0} openai-api-base/model in $f" fi record aider configured "$f" } # -- 9. Continue -------------------------------------------------------------- install_continue() { d="$HOME/.continue" f="$d/config.yaml" mkdir -p "$d" if [ "$DRY_RUN" = 0 ]; then backup_once "$f"; fi # one entry per catalog model, appended into the existing models: list : > "$TMPDIR_N/entries" while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue { printf ' - name: %s\n' "$(printf '%s' "$name" | tr -d '\r')" printf ' provider: openai\n' printf ' model: %s\n' "$mid" printf ' apiBase: %s\n' "$BASE_URL" printf ' apiKey: ${{ secrets.NETRA_API_KEY }}\n' [ "${ctx:-0}" != 0 ] && printf ' defaultCompletionOptions:\n contextLength: %s\n' "$ctx" printf ' roles:\n - chat\n - edit\n - apply\n' } >> "$TMPDIR_N/entries" done < "$MODELS_TSV" if [ "$DRY_RUN" = 1 ]; then info " ${C_D}would append $(grep -c '^ - name:' "$TMPDIR_N/entries") model(s) to${C_0} $f"; record continue configured "$f"; return 0; fi if [ ! -f "$f" ]; then { echo "name: netra" echo "version: 0.0.1" echo "schema: v1" echo "models:" cat "$TMPDIR_N/entries" } > "$f" else if grep -q "$MGR_BEGIN" "$f"; then awk -v b="$MGR_BEGIN" -v e="$MGR_END" '$0==b{s=1} s==0{print} $0==e{s=0}' "$f" > "$TMPDIR_N/c1" cp "$TMPDIR_N/c1" "$f" fi awk -v entf="$TMPDIR_N/entries" -v b="$MGR_BEGIN" -v e="$MGR_END" ' /^models:[ \t]*$/ && !done { print print b while ((getline line < entf) > 0) print line close(entf) print e done=1 next } {print} ' "$f" > "$TMPDIR_N/c2" if ! grep -q '^models:' "$TMPDIR_N/c2"; then { cat "$TMPDIR_N/c2"; echo "models:"; echo "$MGR_BEGIN"; cat "$TMPDIR_N/entries"; echo "$MGR_END"; } > "$TMPDIR_N/c2" fi mv "$TMPDIR_N/c2" "$f" fi record continue configured "$f" } # -- 10. Qwen Code ------------------------------------------------------------ install_qwen_code() { d="$HOME/.qwen"; f="$d/settings.json" # one modelProviders entry per catalog model : > "$TMPDIR_N/qwen_models.json"; printf '[' >> "$TMPDIR_N/qwen_models.json"; _first=1 while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue [ "$_first" = 1 ] || printf ',' >> "$TMPDIR_N/qwen_models.json"; _first=0 printf '{"id":"%s","name":"%s","baseUrl":"%s","envKey":"OPENAI_API_KEY"}' \ "$(json_escape "$mid")" "$(json_escape "$name")" "$BASE_URL" >> "$TMPDIR_N/qwen_models.json" done < "$MODELS_TSV" printf ']' >> "$TMPDIR_N/qwen_models.json" cat > "$TMPDIR_N/patch.json" < ns="$1" _done=0 for f in $(vscode_settings_paths); do _dir="$(dirname "$f")" [ -d "$_dir" ] || continue cat > "$TMPDIR_N/patch.json" < "$TMPDIR_N/env.new" </dev/null cat > "$TMPDIR_N/cfg.new" < "$TMPDIR_N/cfg.a" 2>/dev/null grep -v '"installed_at"' "$CONFIG_FILE" > "$TMPDIR_N/cfg.b" 2>/dev/null if cmp -s "$TMPDIR_N/cfg.a" "$TMPDIR_N/cfg.b"; then mv "$TMPDIR_N/cfg.b" /dev/null 2>/dev/null; :; else mv "$TMPDIR_N/cfg.new" "$CONFIG_FILE"; fi else mv "$TMPDIR_N/cfg.new" "$CONFIG_FILE" fi umask "$umask_save" # credentials file (no secrets in config) umask_save="$(umask)"; umask 077 printf 'NETRA_API_KEY=%s\nNETRA_BASE_URL=%s\n' "$API_KEY" "$BASE_URL" > "$CRED_FILE" chmod 600 "$CRED_FILE" 2>/dev/null umask "$umask_save" [ "$DO_ENV" = 1 ] || { info " env file written, shell rc untouched (--no-env)"; return 0; } _src=". \"$ENV_FILE\"" # prefer the rc file this OS/shell actually reads; create one if none exists case "$OS" in windows) _rcs="$HOME/.bash_profile $HOME/.bashrc $HOME/.profile" ;; macos) _rcs="$HOME/.zshrc $HOME/.zprofile $HOME/.bash_profile $HOME/.profile" ;; *) _rcs="$HOME/.bashrc $HOME/.profile $HOME/.zshrc" ;; esac _touched=0 for rc in $_rcs; do if [ ! -f "$rc" ]; then [ "$_touched" = 1 ] && continue : > "$rc" || continue info " created $rc" fi if ! grep -q "$MGR_BEGIN" "$rc" 2>/dev/null; then { printf '\n%s\n' "$MGR_BEGIN" printf '%s\n' "$_src" printf '%s\n' "$MGR_END" } >> "$rc" info " sourced $ENV_FILE from $rc" fi _touched=1 [ "$OS" = windows ] && [ "$rc" = "$HOME/.bash_profile" ] && break [ "$OS" = macos ] && [ "$rc" = "$HOME/.zshrc" ] && break [ "$OS" = linux ] && [ "$rc" = "$HOME/.bashrc" ] && break done if [ "$HAVE_SETX" = 1 ]; then setx NETRA_API_KEY "$API_KEY" >/dev/null 2>&1 && setx NETRA_BASE_URL "$BASE_URL" >/dev/null 2>&1 \ && info " persisted NETRA_API_KEY/NETRA_BASE_URL as Windows user env vars" fi } # keep a runnable copy so `curl | bash` users can roll back later install_self_copy() { [ "$DRY_RUN" = 1 ] && return 0 mkdir -p "$NETRA_HOME" if [ -f "$0" ] && [ -r "$0" ] && head -c 80 "$0" 2>/dev/null | grep -q 'netra.sh'; then cp "$0" "$NETRA_HOME/netra.sh" 2>/dev/null elif have curl; then curl -fsSL --max-time 30 "$SELF_URL" -o "$NETRA_HOME/netra.sh" 2>/dev/null elif have wget; then wget -q -O "$NETRA_HOME/netra.sh" --timeout=30 "$SELF_URL" 2>/dev/null fi chmod +x "$NETRA_HOME/netra.sh" 2>/dev/null [ -s "$NETRA_HOME/netra.sh" ] && dbg "saved runnable copy to $NETRA_HOME/netra.sh" return 0 } # --------------------------------------------------------------- verify ------- verify_one() { # verify_one _body="$TMPDIR_N/body.json" cat > "$_body" </dev/null)" elif have wget; then _out="$(wget -q -T 45 -O - --header="Authorization: Bearer $API_KEY" \ --header="Content-Type: application/json" --post-file="$_body" "$BASE_URL/chat/completions" 2>/dev/null)" else return 0 fi printf '%s' "$_out" | grep -q '"choices"' && return 0 printf '%s' "$_out" | grep -q '"content"' && return 0 printf '%s' "$_out" | head -c 200; echo; return 1 } do_verify() { head2 "Verify" _okc=0; _fail=0 while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue if verify_one "$mid" >/dev/null 2>&1; then ok "inference OK: $mid"; _okc=$((_okc+1)) else warn "no response: $mid"; _fail=$((_fail+1)) fi done < "$MODELS_TSV" info " $_okc model(s) answered, $_fail failed" } # ------------------------------------------------------------- uninstall ------ do_uninstall() { head2 "Uninstall" # remove env sourcing blocks for rc in "$HOME/.bash_profile" "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.zprofile" "$HOME/.profile"; do [ -f "$rc" ] || continue if grep -q "$MGR_BEGIN" "$rc" 2>/dev/null; then block_strip "$rc" "$MGR_BEGIN" "$MGR_END" > "$TMPDIR_N/rc" && mv "$TMPDIR_N/rc" "$rc" info " cleaned $rc" fi done # restore JSON/config backups for f in "$HOME/.claude/settings.json" "$HOME/.codex/config.toml" "$HOME/.config/opencode/opencode.json" \ "$HOME/.pi/agent/models.json" "$HOME/.pi/agent/settings.json" "$HOME/.dsh/cordis.patch.yml" \ "$HOME/.config/crush/crush.json" "$HOME/.config/goose/config.yaml" "$HOME/.aider.conf.yml" \ "$HOME/.continue/config.yaml" "$HOME/.qwen/settings.json"; do if [ -f "$f.netra.bak" ]; then mv "$f.netra.bak" "$f" && info " restored $f" elif [ -f "$f" ] && grep -q "$MGR_BEGIN" "$f" 2>/dev/null; then block_strip "$f" "$MGR_BEGIN" "$MGR_END" > "$TMPDIR_N/f" && mv "$TMPDIR_N/f" "$f" info " removed managed block from $f" fi done [ "$DRY_RUN" = 0 ] && rm -rf "$NETRA_HOME" && info " removed $NETRA_HOME" ok "uninstalled (restart your harnesses)" } # ------------------------------------------------------------------ main ------ main() { mktmp detect_platform detect_json_engine printf '%snetra.sh v%s%s · %s / %s\n' "$C_B" "$VERSION" "$C_0" "$OS" "$ARCH" if [ "$UNINSTALL" = 1 ]; then do_uninstall; exit 0; fi if [ -z "$JSON_ENGINE" ]; then err "need one of python3, python, node, powershell, or jq to merge configs" exit 1 fi # --- api key if [ -z "$API_KEY" ] && [ -f "$CRED_FILE" ]; then API_KEY="$(awk -F= '/^NETRA_API_KEY=/{sub(/^NETRA_API_KEY=/,""); print; exit}' "$CRED_FILE")" fi if [ -z "$API_KEY" ]; then if read_prompt 'Netra API key (sk_live_...): ' silent; then API_KEY="$REPLY"; fi if [ -z "$API_KEY" ]; then err "no API key found (stdin is not a terminal, so nothing could be asked)." info " export NETRA_API_KEY=sk_live_... then re-run, or:" info " curl -fsSL https://agent.netra.sh | bash -s -- --api-key sk_live_..." info " create a key at https://app.netra.sh (Console → API keys)" exit 2 fi fi case "$API_KEY" in sk_*|nrt_*|dsk_*) : ;; *) warn "key does not look like a Netra key (expected sk_live_...)" ;; esac # --- catalog head2 "Catalog" load_models_catalog || exit 1 if [ "$LIST_ONLY" = 1 ]; then printf '\n%-58s %-10s %s\n' "MODEL ID" "CONTEXT" "PRICE/MTOK in/out" while IFS="$(printf '\t')" read -r mid name ctx mx reasoning pin pout mods; do [ -z "$mid" ] && continue printf '%-58s %-10s %s/%s%s\n' "$mid" "$ctx" "$(per_mtok "$pin")" "$(per_mtok "$pout")" \ "$([ "$reasoning" = 1 ] && echo ' [reasoning]')" done < "$MODELS_TSV" exit 0 fi # --- detect head2 "Detected harnesses" detect_all if [ -z "$DETECTED" ]; then warn "no known agentic harness found in PATH or ~/. dirs" info " install one (claude-code, codex, opencode, crush, goose, aider, ...) and re-run" info " env scaffolding is still written to $ENV_FILE" else printf '%s' "$DETECTED" | while IFS='|' read -r id label; do [ -z "$id" ] && continue wanted "$id" && printf ' · %-14s %s\n' "$id" "$label" done fi if [ "$ASSUME_YES" = 0 ] && [ "$DRY_RUN" = 0 ]; then if read_prompt '\nWrite Netra config for the harnesses above? [Y/n] '; then case "$REPLY" in n|N|no|NO) info "aborted (re-run with -y to skip this prompt)"; exit 1 ;; esac fi fi # --- install head2 "Install" if [ "$DO_ENV" = 1 ] || [ "$DRY_RUN" = 0 ]; then if [ "$DRY_RUN" = 1 ]; then info " would write $ENV_FILE + source it from your shell rc" else install_self_copy write_env fi fi _n=0 printf '%s' "$DETECTED" | while IFS='|' read -r id label; do [ -z "$id" ] && continue wanted "$id" || continue info "→ $label ($id)" dispatch "$id" || warn " $id failed; see above" done if [ "$DO_VERIFY" = 1 ] && [ "$DRY_RUN" = 0 ]; then do_verify; fi # --- summary head2 "Summary" if [ -f "$STATUS_FILE" ]; then while IFS="$(printf '\t')" read -r id st where; do case "$st" in configured) printf ' %s✓%s %-14s %s\n' "$C_G" "$C_0" "$id" "$where" ;; already-configured) printf ' %s=%s %-14s %s\n' "$C_G" "$C_0" "$id" "$where (left untouched)" ;; env-only) printf ' %s~%s %-14s %s\n' "$C_Y" "$C_0" "$id" "$where" ;; needs-manual) printf ' %s!%s %-14s %s\n' "$C_Y" "$C_0" "$id" "$where" ;; *) printf ' ? %-14s %s\n' "$id" "$where" ;; esac done < "$STATUS_FILE" fi echo info "Models installed: $MODEL_COUNT · default: $DEFAULT_MODEL" info "Env: $ENV_FILE (source it: . $ENV_FILE)" info "Catalog: $NETRA_HOME/models.json" [ "$DRY_RUN" = 1 ] && warn "dry run: nothing was written" info "Restart your harnesses (new shell) for env changes to apply." info "Note: Claude Code warns about 'unrecognized model' for Netra model ids — harmless, requests still route to Netra." if [ -x "$NETRA_HOME/netra.sh" ]; then info "Rollback: $NETRA_HOME/netra.sh --uninstall" else info "Rollback: curl -fsSL $SELF_URL | bash -s -- --uninstall" fi } main "$@"