#!/bin/bash # 20-opencode-router.sh — OpenCode Router on 127.0.0.1:8787 DIR="/data/script/opencode-router" CONFIG="$DIR/opencode-router.json" mkdir -p "$DIR" /tmp/logs LOG="/tmp/logs/opencode-router.log" cp -rn /opt/opencode-router/* "$DIR/" 2>/dev/null || true # Do NOT overwrite existing config on /data; seed default only if missing if [ ! -f "$CONFIG" ]; then cat > "$CONFIG" << 'EOF' { "host": "0.0.0.0", "port": 8787, "upstream": "https://opencode.ai/zen/v1", "ua": "opencode/1.19.0 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14", "autoUA": true, "injectSession": true, "defaultModel": "nemotron-3.5-lightning-free", "fallbackModels": [ "nemotron-3-ultra-free", "muse-spark-1.3-contributor-free", "muse-spark-1.2-contributor-free", "mimo-v2.6-flash-free", "longcat-2.5-preview-free", "nemotron-3.5-lightning-free", "mimo-v2.5-free", "space-bunny-free", "step-5-preview-free" ], "disabledModels": [ "ling-3.0-flash-fin-free" ], "modelAliases": {}, "responsesModels": [ "gpt-5*", "gpt-6*", "grok-*", "muse-spark-*" ], "rateLimitMax": 0, "rateLimitWindowMs": 60000, "proxyKey": "aman@g", "defaultUpstreamKey": "", "outboundProxy": "", "trustForwarded": false, "timeoutMs": 120000, "cacheMs": 0, "autoSync": false, "autoSyncIntervalMs": 0, "uaRefreshDays": 0, "uaRefreshMs": 0, "metaEndpoint": "https://models.dev/api.json", "metaTimeoutSec": 30, "metaSyncHours": 24 } EOF fi # Ship the pre-fixed index.html (relative asset + API paths) from the repo instead of # rewriting the HTML with sed on every start. Source of truth: # config/opencode-router/index.html — keeps /opencode/ from hijacking root /assets or /api. if [ -f /app/config/opencode-router/index.html ]; then mkdir -p "$DIR/public" cp -f /app/config/opencode-router/index.html "$DIR/public/index.html" fi # Prefill the UI's API key from the router config's proxyKey. The HTML committed to git # carries no secret — the key is read back from the config that already holds it. if [ -f "$DIR/public/index.html" ] && [ -f "$CONFIG" ]; then python3 - "$DIR/public/index.html" "$CONFIG" <<'PREFILL_EOF' 2>/dev/null || true import json, pathlib, sys html_path, cfg_path = sys.argv[1], sys.argv[2] try: key = (json.load(open(cfg_path)) or {}).get("proxyKey") or "" except Exception: key = "" if not key: sys.exit(0) needle = 'localStorage.getItem("opencodeKey") || ""' p = pathlib.Path(html_path) s = p.read_text(encoding="utf-8", errors="ignore") if needle in s: p.write_text(s.replace(needle, 'localStorage.getItem("opencodeKey") || ' + json.dumps(key), 1), encoding="utf-8") PREFILL_EOF fi if pgrep -f "$DIR/opencode-router" >/dev/null 2>&1; then echo "opencode-router already running" exit 0 fi cd "$DIR" || exit 1 chmod +x "$DIR/opencode-router" 2>/dev/null || true exec "$DIR/opencode-router" 8787 >> "$LOG" 2>&1