#!/bin/bash # Connect opencode to an llm-host server -- installing opencode first if it isn't there. # # /bin/bash -c "$(curl -fsSL https://git.neilbantoc.dev/pub/llm-host/raw/branch/main/opencode-install.sh)" \ # -- --url https://llm-api.example.com # # It needs only the API's address and key: not llm-host, and not its dashboard. # # It asks for the API key (hidden). To pass it instead, use --key or $LLMHOST_API_KEY; # note that a key given on the command line ends up in your shell history. # # What it does, all in your home directory (no sudo): # 1. checks the server answers with that key # 2. installs opencode with the official installer, unless it's already installed # 3. saves the key to ~/.config/opencode/llmhost-.key (mode 600) # 4. adds an llmhost- provider to ~/.config/opencode/opencode.json, keeping # everything else in it (backed up first as opencode.json.before-llmhost), and # makes it the default model if you have none (or say so) # 5. drops any key opencode cached for that provider, so the key file is what it uses # # Options: # --url URL the API's address (https://host or https://host/v1) # --key KEY the API key (default: $LLMHOST_API_KEY, else asked for) # --default make it opencode's default model without asking # --no-default leave opencode's default model alone # --skip-install don't install opencode, only configure it # --remove take this server back out of opencode's config # Written for bash 3.2 so it runs on stock macOS. set -euo pipefail if [ -t 1 ]; then B=$'\033[1m'; R=$'\033[31m'; Y=$'\033[33m'; G=$'\033[32m'; N=$'\033[0m'; else B=""; R=""; Y=""; G=""; N=""; fi say() { printf '%s==>%s %s\n' "$B" "$N" "$*"; } warn() { printf '%sWarning:%s %s\n' "$Y" "$N" "$*" >&2; } die() { printf '%sError:%s %s\n' "$R" "$N" "$*" >&2; exit 1; } usage() { cat <<'EOF' Connect opencode to an llm-host server, installing opencode first if needed. opencode-install.sh --url https://llm-api.example.com [options] --url URL the API's address (https://host or https://host/v1) --key KEY the API key (default: $LLMHOST_API_KEY, else asked for, hidden) --default make it opencode's default model without asking --no-default leave opencode's default model alone --skip-install don't install opencode, only configure it --remove take this server back out of opencode's config EOF } [ "${1:-}" = "--" ] && shift URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0 while [ $# -gt 0 ]; do case "$1" in --url) URL="${2:-}"; shift 2 ;; --url=*) URL="${1#*=}"; shift ;; --key) KEY="${2:-}"; shift 2 ;; --key=*) KEY="${1#*=}"; shift ;; --default) DEFAULT="yes"; shift ;; --no-default) DEFAULT="no"; shift ;; --skip-install) INSTALL=0; shift ;; --remove) REMOVE=1; shift ;; -h|--help) usage; exit 0 ;; *) die "unknown option: $1 (see --help)" ;; esac done # A terminal to ask on, even when this script arrived on stdin. TTY="" if [ -r /dev/tty ] && [ -w /dev/tty ] && (: /dev/null; then TTY=/dev/tty; fi if [ -z "$URL" ]; then [ -n "$TTY" ] || die "--url is required" printf 'API address (e.g. https://llm-api.example.com): ' >"$TTY"; read -r URL <"$TTY" fi URL="${URL%/}" case "$URL" in https://*|http://*) ;; *) die "--url should start with https:// (got '$URL')" ;; esac case "$URL" in */v1) ;; *) URL="$URL/v1" ;; esac HOST="$(printf '%s' "$URL" | sed -E 's#^[a-z]+://([^/:]+).*#\1#')" SHORT="$(printf '%s' "${HOST%%.*}" | tr 'A-Z' 'a-z' | tr -c 'a-z0-9-\n' '-')" PROV="llmhost-$SHORT" CONF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/opencode" CONF="$CONF_DIR/opencode.json" KEYFILE="$CONF_DIR/$PROV.key" AUTH="${XDG_DATA_HOME:-$HOME/.local/share}/opencode/auth.json" # JSON edits need Python. On a Mac without the command line tools, /usr/bin/python3 is # only a stub that pops up an installer, so don't call it there. PY="" if [ "$(uname -s)" = Darwin ] && [ "$(command -v python3 || true)" = /usr/bin/python3 ] \ && ! xcode-select -p >/dev/null 2>&1; then PY="" elif command -v python3 >/dev/null 2>&1; then PY="$(command -v python3)" fi # ---- remove -------------------------------------------------------------------------- if [ "$REMOVE" = 1 ]; then [ -n "$PY" ] || die "python3 is needed to edit $CONF; remove the \"$PROV\" provider from it by hand" "$PY" - "$CONF" "$PROV" "$AUTH" <<'PYEOF' import json, os, sys conf, prov, auth = sys.argv[1:4] try: c = json.load(open(conf)) except (OSError, ValueError): c = None if isinstance(c, dict) and prov in (c.get("provider") or {}): del c["provider"][prov] if not c["provider"]: del c["provider"] if str(c.get("model", "")).startswith(prov + "/"): del c["model"] print(f"opencode's default model was {prov}; pick another with /models.") tmp = conf + ".tmp" with open(tmp, "w") as f: json.dump(c, f, indent=2); f.write("\n") os.replace(tmp, conf) print(f"Removed the {prov} provider from {conf}.") else: print(f"No {prov} provider in {conf}.") try: a = json.load(open(auth)) if prov in a: del a[prov] json.dump(a, open(auth, "w"), indent=2) except (OSError, ValueError): pass PYEOF rm -f "$KEYFILE" say "Done. opencode itself is still installed." exit 0 fi # ---- the key, checked against the server --------------------------------------------- if [ -z "$KEY" ]; then [ -n "$TTY" ] || die "no API key: pass --key or set \$LLMHOST_API_KEY" printf 'API key (hidden): ' >"$TTY" stty -echo <"$TTY" 2>/dev/null || true read -r KEY <"$TTY" || true stty echo <"$TTY" 2>/dev/null || true printf '\n' >"$TTY" fi KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')" [ -n "$KEY" ] || die "no API key given" say "Checking $URL" TMP="$(mktemp)"; trap 'rm -f "$TMP"' EXIT # The key goes to curl on stdin (as a header file), not on its command line. CODE="$(printf 'Authorization: Bearer %s\n' "$KEY" | curl -sS -o "$TMP" -w '%{http_code}' \ --max-time 20 -H @- "$URL/models" 2>/dev/null || true)" case "$CODE" in 200) ;; 401|403) die "the server rejected that API key" ;; 000|"") die "couldn't reach $URL" ;; *) die "$URL/models answered HTTP $CODE; is that the llm-host API address?" ;; esac CTX=32768; REASONS=0 if [ -n "$PY" ]; then read -r CTX REASONS </dev/null || echo "32768 0") EOF fi say "Server OK" # ---- opencode ------------------------------------------------------------------------ OC="$(command -v opencode || true)" [ -n "$OC" ] || { [ -x "$HOME/.opencode/bin/opencode" ] && OC="$HOME/.opencode/bin/opencode"; } || true if [ -z "$OC" ]; then if [ "$INSTALL" = 1 ]; then say "Installing opencode (official installer)" curl -fsSL https://opencode.ai/install | bash OC="$HOME/.opencode/bin/opencode" [ -x "$OC" ] || OC="$(command -v opencode || true)" [ -n "$OC" ] || die "opencode didn't install; see the output above" else warn "opencode isn't installed; configuring it anyway (--skip-install)" fi else say "opencode is already installed ($OC)" fi # ---- key file ------------------------------------------------------------------------ mkdir -p "$CONF_DIR" ( umask 077; printf '%s\n' "$KEY" >"$KEYFILE" ) chmod 600 "$KEYFILE" say "Saved the key to $KEYFILE" # ---- opencode.json ------------------------------------------------------------------- print_block() { cat <"$TTY" read -r ans <"$TTY" || ans="" case "$ans" in y|Y|yes|YES) SET_DEFAULT=1 ;; esac fi ;; esac "$PY" - "$CONF" "$PROV" "$HOST" "$URL" "$KEYFILE" "$CTX" "$REASONS" "$SET_DEFAULT" "$AUTH" <<'PYEOF' import json, os, shutil, sys conf, prov, host, url, keyfile, ctx, reasons, set_default, auth = sys.argv[1:10] ctx = int(ctx) c = {} if os.path.exists(conf) and os.path.getsize(conf) > 0: try: c = json.load(open(conf)) except ValueError as e: sys.exit(f"Error: {conf} isn't valid JSON ({e}); fix it, or move it aside and run this again") if not isinstance(c, dict): sys.exit(f"Error: {conf} isn't a JSON object") backup = conf + ".before-llmhost" if not os.path.exists(backup): shutil.copy2(conf, backup) print(f"Backed up {conf} to {backup}") # The same entry as `llmhost opencode-config`: one model, `default`, which the server # answers to whatever is loaded; and, for a thinking model, opencode's own effort menu # switched off, since the effort is set on the dashboard and the server drops a client's. entry = {"name": f"Default model ({host})", "tool_call": True, "limit": {"context": ctx, "output": min(65536, ctx // 2)}} if reasons == "1": entry["reasoning"] = True entry["variants"] = {lvl: {"disabled": True} for lvl in ("low", "medium", "high")} c.setdefault("$schema", "https://opencode.ai/config.json") c.setdefault("provider", {})[prov] = { "npm": "@ai-sdk/openai-compatible", "name": f"LLMHost ({host})", "options": {"baseURL": url, "apiKey": "{file:" + keyfile + "}"}, "models": {"default": entry}, } if set_default == "1": c["model"] = f"{prov}/default" os.makedirs(os.path.dirname(conf), exist_ok=True) tmp = conf + ".tmp" with open(tmp, "w") as f: json.dump(c, f, indent=2); f.write("\n") os.replace(tmp, conf) print(f"Added the {prov} provider to {conf}" + (" and made it the default model" if set_default == "1" else "")) # opencode caches a key it was given interactively, and that copy wins over the config; # drop it so the key file is what's used. try: a = json.load(open(auth)) if prov in a: del a[prov] tmp = auth + ".tmp" with open(tmp, "w") as f: json.dump(a, f, indent=2) os.chmod(tmp, 0o600) os.replace(tmp, auth) print(f"Dropped the key opencode had cached for {prov}") except (OSError, ValueError): pass PYEOF # ---- check --------------------------------------------------------------------------- if [ -n "$OC" ] && "$OC" models 2>/dev/null | grep -q "^$PROV/default\$"; then say "${G}opencode sees $PROV/default${N}" elif [ -n "$OC" ]; then warn "opencode doesn't list $PROV/default yet; check $CONF" fi echo say "Done. Start opencode -- it shows the server as \"LLMHost ($HOST)\"." if [ "$SET_DEFAULT" != 1 ]; then echo " Your default model is unchanged; pick \"LLMHost ($HOST)\" with /models." fi case ":$PATH:" in *":$HOME/.opencode/bin:"*) ;; *) if [ "$OC" = "$HOME/.opencode/bin/opencode" ]; then echo " Open a new terminal first (or run: export PATH=\$HOME/.opencode/bin:\$PATH)." fi ;; esac echo " To take it out again: rerun this with --remove."