#!/usr/bin/env bash set -euo pipefail THREELLAMA_GUIDE_URL="https://3llama.com/guides/opencode" OPENCODE_DESKTOP_URL="https://opencode.ai/desktop" OPENCODE_INSTALL_URL="https://opencode.ai/v2/install" read -r -d '' PY_SRC <<'PY' || true import json, os, re, sys def strip_jsonc(text): out, i, n, in_str, comments = [], 0, len(text), False, False while i < n: c = text[i] if in_str: out.append(c) if c == "\\" and i + 1 < n: out.append(text[i + 1]); i += 2; continue if c == '"': in_str = False i += 1; continue if c == '"': in_str = True; out.append(c); i += 1; continue if text.startswith("//", i): comments = True j = text.find("\n", i) i = n if j < 0 else j continue if text.startswith("/*", i): comments = True j = text.find("*/", i + 2) i = n if j < 0 else j + 2 continue out.append(c); i += 1 cleaned, result, in_str, i = "".join(out), [], False, 0 while i < len(cleaned): c = cleaned[i] if in_str: result.append(c) if c == "\\" and i + 1 < len(cleaned): result.append(cleaned[i + 1]); i += 2; continue if c == '"': in_str = False i += 1; continue if c == '"': in_str = True elif c == ",": j = i + 1 while j < len(cleaned) and cleaned[j] in " \t\r\n": j += 1 if j < len(cleaned) and cleaned[j] in "}]": i += 1; continue result.append(c); i += 1 return "".join(result), comments def load_config(path): if not os.path.exists(path): return {}, False with open(path, encoding="utf-8") as handle: text = handle.read() if not text.strip(): return {}, False cleaned, comments = strip_jsonc(text) data = json.loads(cleaned) if not isinstance(data, dict): raise ValueError("not an object") return data, comments def model_keys(ids_and_names): used, keys = set(), {} for model_id, name in ids_and_names: base = re.sub(r"[^a-z0-9.]+", "-", name.lower()).strip("-") or "model" key, suffix = base, 2 while key in used: key = f"{base}-{suffix}"; suffix += 1 used.add(key) keys[model_id] = key return keys def read_json(path): try: with open(path, encoding="utf-8") as handle: return json.load(handle) except (OSError, ValueError): return None def build_models(allowed_path, catalog_path): allowed = read_json(allowed_path) or {} ids = [item["id"] for item in allowed.get("data", []) if isinstance(item, dict) and isinstance(item.get("id"), str)] catalog = read_json(catalog_path) or {} details = {m["id"]: m for m in catalog.get("models", []) if isinstance(m, dict) and isinstance(m.get("id"), str)} keys = model_keys([(i, details.get(i, {}).get("name") or i) for i in ids]) models = {} for model_id in ids: info = details.get(model_id) if not info: models[keys[model_id]] = {"name": model_id, "modelID": model_id} continue entry = { "name": info.get("name") or model_id, "limit": {"context": info.get("contextLength"), "output": info.get("maxOutputTokens")}, "modelID": model_id, "capabilities": {"tools": bool(info.get("toolCall")), "input": ["text"], "output": ["text"]}, } if info.get("reasoning"): entry["compatibility"] = {"reasoningField": "reasoning"} pricing = info.get("pricing") or {} if "input" in pricing and "output" in pricing: cost = {"input": pricing["input"], "output": pricing["output"]} if pricing.get("cacheRead") is not None or pricing.get("cacheWrite") is not None: cost["cache"] = {k: v for k, v in (("read", pricing.get("cacheRead")), ("write", pricing.get("cacheWrite"))) if v is not None} entry["cost"] = cost models[keys[model_id]] = entry return models, len(details) > 0 def write_config(path, data): with open(path, "w", encoding="utf-8") as handle: json.dump(data, handle, indent=2, ensure_ascii=False) handle.write("\n") def remove_ours(data): for section in ("providers", "provider"): block = data.get(section) if isinstance(block, dict) and "3llama" in block: del block["3llama"] if not block: del data[section] def main(argv): mode = argv[1] if mode == "inspect": try: data, comments = load_config(argv[2]) except (OSError, ValueError): print("invalid"); return 0 model = data.get("model") if isinstance(data.get("model"), str) else "" print("ok"); print("comments" if comments else "plain"); print(model) return 0 if mode == "error": body = read_json(argv[2]) message = "" if isinstance(body, dict): error = body.get("error") if isinstance(error, dict): message = error.get("message") or "" message = message or body.get("detail") or body.get("title") or "" print(message) return 0 if mode == "write": config_path, out_path, allowed_path, catalog_path, base_url, key_ref, default_mode = argv[2:9] data, _ = load_config(config_path) models, detailed = build_models(allowed_path, catalog_path) remove_ours(data) data.setdefault("$schema", "https://opencode.ai/config.json") providers = data.get("providers") if isinstance(data.get("providers"), dict) else {} providers["3llama"] = { "name": "3llama", "package": "@opencode/ai/providers/openai-compatible", "settings": {"baseURL": base_url, "apiKey": key_ref}, "models": models, } data["providers"] = providers first = f"3llama/{next(iter(models))}" if models else None current = data.get("model") if isinstance(data.get("model"), str) else "" valid_current = current.startswith("3llama/") and current[len("3llama/"):] in models if first and (default_mode == "set" or (default_mode == "auto" and not valid_current and (not current or current.startswith("3llama/")))): data["model"] = first elif current.startswith("3llama/") and not valid_current: data.pop("model", None) write_config(out_path, data) print(data.get("model", "")) print("detailed" if detailed else "basic") for key, entry in models.items(): print(entry.get("name", key)) return 0 if mode == "remove": config_path, out_path = argv[2:4] data, _ = load_config(config_path) remove_ours(data) if isinstance(data.get("model"), str) and data["model"].startswith("3llama/"): del data["model"] write_config(out_path, data) return 0 return 2 sys.exit(main(sys.argv)) PY ASSUME_YES=0 HAS_TTY=0 pretty_path() { case "$1" in "$HOME"/*) printf '~%s' "${1#"$HOME"}" ;; *) printf '%s' "$1" ;; esac } main() { local api_url="${THREELLAMA_API_URL:-https://api.3llama.com}" api_url="${api_url%/}" local gateway_url="$api_url/v1" local config_dir="${XDG_CONFIG_HOME:-$HOME/.config}/opencode" local key_dir="$HOME/.config/3llama" local key_file="$key_dir/api-key" local key_ref="{file:~/.config/3llama/api-key}" local action="setup" setup_colors while [ $# -gt 0 ]; do case "$1" in --uninstall|--remove) action="remove" ;; -y|--yes) ASSUME_YES=1 ;; -h|--help) usage; return 0 ;; *) fail "Unknown option: $1 (run with --help to see the options)" ;; esac shift done HAS_TTY=0 if { : /dev/null; then HAS_TTY=1; fi printf '\n%s3llama × OpenCode%s\n' "$BOLD" "$RESET" printf '%sConnects OpenCode, the desktop app and the terminal app, to the models in your 3llama plan.%s\n\n' "$DIM" "$RESET" local platform platform="$(detect_platform)" command -v curl >/dev/null 2>&1 || fail "curl is required. Install it, then run this again." find_python "$platform" TMP_DIR="$(mktemp -d)" trap 'rm -rf "$TMP_DIR"' EXIT chmod 700 "$TMP_DIR" local config_file="$config_dir/opencode.json" if [ ! -f "$config_file" ] && [ -f "$config_dir/opencode.jsonc" ]; then config_file="$config_dir/opencode.jsonc"; fi if [ "$action" = "remove" ]; then remove_setup "$config_file" "$key_file" "$key_dir" return 0 fi check_opencode "$platform" step "Checking your API token" local token token="$(obtain_token "$key_file" "$gateway_url")" ok "Your token works, and your plan includes $(model_count "$TMP_DIR/models.json")." step "Getting model details" if curl -fsS --max-time 30 "$api_url/api-models/catalog" -o "$TMP_DIR/catalog.json" 2>/dev/null; then ok "Got names and limits for your models." else printf '{}' >"$TMP_DIR/catalog.json" warn "Couldn't load model names, so your models will be listed by their IDs. Run this again later to add their names and limits." fi step "Saving your token" mkdir -p "$key_dir" chmod 700 "$key_dir" (umask 077 && printf '%s' "$token" >"$key_file.tmp") mv -f "$key_file.tmp" "$key_file" chmod 600 "$key_file" ok "Saved to ${BOLD}~/.config/3llama/api-key${RESET}, readable only by you." step "Adding 3llama to OpenCode" mkdir -p "$config_dir" local inspect status comments current_model inspect="$(run_python inspect "$config_file")" status="$(sed -n 1p <<<"$inspect")" comments="$(sed -n 2p <<<"$inspect")" current_model="$(sed -n 3p <<<"$inspect")" if [ "$status" != "ok" ]; then fail "Your OpenCode configuration at $config_file isn't valid JSON, so it wasn't changed. Fix it, or move it aside, then run this again." fi local default_mode="auto" if [ -n "$current_model" ] && [ "${current_model#3llama/}" = "$current_model" ]; then if confirm "Your default model is ${BOLD}$current_model${RESET}. Make a 3llama model your default instead?" "y"; then default_mode="set" else default_mode="keep" fi fi local result run_python write "$config_file" "$TMP_DIR/opencode.json" "$TMP_DIR/models.json" "$TMP_DIR/catalog.json" "$gateway_url" "$key_ref" "$default_mode" >"$TMP_DIR/result.txt" || fail "Couldn't update your OpenCode configuration. Nothing was changed." result="$(cat "$TMP_DIR/result.txt")" local backup="" if [ -f "$config_file" ]; then backup="$config_file.backup-$(date +%Y%m%d-%H%M%S)" cp -p "$config_file" "$backup" fi mv -f "$TMP_DIR/opencode.json" "$config_file" ok "Updated ${BOLD}$(pretty_path "$config_file")${RESET}" if [ -n "$backup" ]; then printf ' %sYour previous configuration is saved at %s%s\n' "$DIM" "$(pretty_path "$backup")" "$RESET" fi if [ "$comments" = "comments" ]; then warn "Your configuration had comments. JSON can't keep them, so they're only in the backup." fi local default_model default_model="$(sed -n 1p <<<"$result")" printf '\n%sYour 3llama models%s\n' "$BOLD" "$RESET" sed -n '3,$p' <<<"$result" | while IFS= read -r name; do printf ' • %s\n' "$name"; done if [ -n "$default_model" ]; then printf ' %sDefault: %s%s\n' "$DIM" "$default_model" "$RESET" fi printf '\n%s%s✓ You’re all set.%s\n\n' "$BOLD" "$GREEN" "$RESET" printf '%sDesktop app:%s quit OpenCode if it’s open, then open it again and choose a 3llama model.\n' "$BOLD" "$RESET" printf '%sTerminal:%s go to your project folder, run %sopencode --standalone%s, then type %s/models%s.\n' "$BOLD" "$RESET" "$CYAN" "$RESET" "$CYAN" "$RESET" if [ "$platform" = "wsl" ]; then printf '\n%sThis set up OpenCode inside WSL. For the Windows desktop app, follow the manual steps at %s%s\n' "$DIM" "$THREELLAMA_GUIDE_URL" "$RESET" fi printf '\n%sPlan changed? Run this again to update your models. To undo it, run it with --uninstall.%s\n\n' "$DIM" "$RESET" } usage() { cat <&2; } ok() { printf '%s✓%s %s\n' "$GREEN" "$RESET" "$1" >&2; } warn() { printf '%s!%s %s\n' "$YELLOW" "$RESET" "$1" >&2; } fail() { printf '\n%s✗ %s%s\n\n' "$RED" "$1" "$RESET" >&2; exit 1; } confirm() { local prompt="$1" default="$2" answer hint="[Y/n]" [ "$default" = "n" ] && hint="[y/N]" if [ "$ASSUME_YES" -eq 1 ] || [ "$HAS_TTY" -eq 0 ]; then [ "$default" = "y" ]; return; fi printf '%s %s ' "$prompt" "$hint" >/dev/tty IFS= read -r answer /dev/null; then echo "wsl"; else echo "linux"; fi ;; MINGW*|MSYS*|CYGWIN*) fail "On Windows, run this in WSL, or follow the manual steps for the desktop app at $THREELLAMA_GUIDE_URL" ;; *) fail "This system isn't supported. Follow the manual steps at $THREELLAMA_GUIDE_URL" ;; esac } find_python() { local platform="$1" candidate for candidate in python3 python; do local path path="$(command -v "$candidate" 2>/dev/null)" || continue if [ "$platform" = "macos" ] && [ "$path" = "/usr/bin/$candidate" ] && ! xcode-select -p >/dev/null 2>&1; then continue; fi if "$path" -I -c 'import sys; sys.exit(0 if sys.version_info >= (3, 6) else 1)' >/dev/null 2>&1; then PYTHON="$path"; return 0 fi done case "$platform" in macos) fail "This needs Python 3, which comes with Apple's command line tools. Run ${BOLD}xcode-select --install${RESET}${RED}, then run this again." ;; *) fail "This needs Python 3. Install it (for example, ${BOLD}sudo apt install python3${RESET}${RED} or ${BOLD}sudo dnf install python3${RESET}${RED}), then run this again." ;; esac } run_python() { "$PYTHON" -I -c "$PY_SRC" "$@"; } check_opencode() { local platform="$1" cli="" desktop="" version="" step "Looking for OpenCode" if command -v opencode >/dev/null 2>&1; then cli="yes" version="$(opencode --version 2>/dev/null | head -n 1 | grep -Eo '[0-9]+(\.[0-9]+)+' | head -n 1 || true)" fi case "$platform" in macos) if compgen -G "/Applications/[Oo]pen[Cc]ode*.app" >/dev/null || compgen -G "$HOME/Applications/[Oo]pen[Cc]ode*.app" >/dev/null; then desktop="yes"; fi ;; linux) if command -v opencode-desktop >/dev/null 2>&1 || compgen -G "/usr/share/applications/*opencode*" >/dev/null || compgen -G "$HOME/.local/share/applications/*opencode*" >/dev/null; then desktop="yes"; fi ;; esac if [ -n "$version" ] && [ "${version%%.*}" = "1" ]; then fail "You have OpenCode $version. This sets up OpenCode 2, so update OpenCode first, then run this again. To keep OpenCode 1, copy its configuration from the API tokens page instead." fi if [ -n "$desktop" ]; then ok "Found the OpenCode desktop app."; fi if [ -n "$cli" ]; then ok "Found OpenCode in the terminal${version:+ ($version)}."; fi if [ -n "$desktop$cli" ]; then return 0; fi warn "OpenCode isn't installed yet." printf ' %sFor the desktop app, download it from %s%s\n' "$DIM" "$OPENCODE_DESKTOP_URL" "$RESET" >&2 if confirm "Install OpenCode for the terminal now?" "y" && { [ "$HAS_TTY" -eq 1 ] || [ "$ASSUME_YES" -eq 1 ]; }; then curl -fsSL "$OPENCODE_INSTALL_URL" | bash || fail "OpenCode couldn't be installed. Install it from https://opencode.ai, then run this again." ok "Installed OpenCode. Open a new terminal before you run it." else printf ' %sContinuing, so 3llama is ready when you install OpenCode.%s\n' "$DIM" "$RESET" >&2 fi } obtain_token() { local key_file="$1" gateway_url="$2" token="" attempt=0 if [ -n "${THREELLAMA_API_KEY:-}" ]; then token="$THREELLAMA_API_KEY" printf ' %sUsing the token in THREELLAMA_API_KEY.%s\n' "$DIM" "$RESET" >&2 elif [ -s "$key_file" ] && confirm "Use the token you saved before?" "y"; then token="$(cat "$key_file")" fi while :; do if [ -z "$token" ]; then [ "$HAS_TTY" -eq 1 ] || fail "No token found. Set THREELLAMA_API_KEY, or run this in a terminal so you can paste it." if [ "$attempt" -eq 0 ]; then printf ' %sCreate one on the API tokens page: https://3llama.com/api-keys%s\n' "$DIM" "$RESET" >/dev/tty fi printf 'Paste your API token (it stays hidden): ' >/dev/tty IFS= read -rs token /dev/tty fi token="$(printf '%s' "$token" | tr -d '[:space:]')" attempt=$((attempt + 1)) if [ -z "$token" ]; then [ "$attempt" -lt 3 ] && { warn "No token entered."; continue; } fail "No token entered." fi (umask 077 && printf 'Authorization: Bearer %s\n' "$token" >"$TMP_DIR/auth") local code code="$(curl -sS --max-time 30 -H @"$TMP_DIR/auth" -o "$TMP_DIR/models.json" -w '%{http_code}' "$gateway_url/models" 2>/dev/null || true)" rm -f "$TMP_DIR/auth" case "$code" in 200) if [ "$(model_total "$TMP_DIR/models.json")" -eq 0 ]; then fail "Your plan doesn't include any models you can use through the API. See your plan in the 3llama app." fi printf '%s' "$token" return 0 ;; 401) if [ "$HAS_TTY" -eq 1 ] && [ "$attempt" -lt 3 ]; then warn "That token wasn't recognized. Check that you copied all of it, or create a new one." token=""; continue fi fail "That token wasn't recognized. Create a new one at https://3llama.com/api-keys" ;; 402|403) local message message="$(run_python error "$TMP_DIR/models.json")" [ -n "$message" ] || message="Your plan doesn't include API access." fail "$message See your plan in the 3llama app." ;; 000|"") fail "Couldn't reach 3llama at $gateway_url. Check your internet connection, then try again." ;; *) fail "3llama couldn't check your token right now (HTTP $code). Try again in a few minutes." ;; esac done } model_total() { "$PYTHON" -I -c 'import json,sys; print(len(json.load(open(sys.argv[1])).get("data", [])))' "$1" 2>/dev/null || echo 0; } model_count() { local count count="$(model_total "$1")" if [ "$count" -eq 1 ]; then echo "1 model"; else echo "$count models"; fi } remove_setup() { local config_file="$1" key_file="$2" key_dir="$3" confirm "Remove 3llama from OpenCode and delete your saved token?" "y" || { printf 'Nothing was changed.\n'; return 0; } if [ -f "$config_file" ]; then local status status="$(run_python inspect "$config_file" | sed -n 1p)" [ "$status" = "ok" ] || fail "Your OpenCode configuration at $config_file isn't valid JSON, so it wasn't changed." run_python remove "$config_file" "$TMP_DIR/opencode.json" || fail "Couldn't update your OpenCode configuration." local backup backup="$config_file.backup-$(date +%Y%m%d-%H%M%S)" cp -p "$config_file" "$backup" mv -f "$TMP_DIR/opencode.json" "$config_file" local shown_config shown_backup shown_config="$(pretty_path "$config_file")" shown_backup="$(pretty_path "$backup")" ok "Removed 3llama from $shown_config. Your previous configuration is saved at $shown_backup" fi if [ -f "$key_file" ]; then rm -f "$key_file" rmdir "$key_dir" 2>/dev/null || true ok "Deleted your saved token." fi printf '\n%sTo stop the token working everywhere, revoke it at https://3llama.com/api-keys%s\n\n' "$DIM" "$RESET" } main "$@"