diff --git a/README.md b/README.md index d1aa067..91948d1 100644 --- a/README.md +++ b/README.md @@ -93,14 +93,19 @@ a third user service, in userspace (no root). It's a pinned release, checked aga Create a Newt site in Pangolin (*Sites → Add Site → Newt*, which gives an endpoint, ID and secret), then: ```bash -llmhost install-newt --endpoint https://pangolin.example.com --newt-id +llmhost install-newt --api-url https://llm-api.example.com \ + --endpoint https://pangolin.example.com --newt-id ``` +`--api-url` is where clients will reach the API: a domain you'll add as a resource on Pangolin, not Pangolin's own +address (`--endpoint`). It's asked for first, because llm-host uses it to describe the resource and to print the +right `opencode-install.sh` command everywhere it gives one. + It asks for the site secret, or reads `$LLMHOST_NEWT_SECRET`; it's never taken as a flag, so it stays out of shell history. The secret is stored in `~/.config/llm-host/newt_secret` (mode 600) and handed to newt in its environment at start, never written into a service file or `config.json`. Running it again changes only what you give it. -Then add one HTTP resource in Pangolin, for the API: a host of your choice → `:`, +Then add one HTTP resource in Pangolin, for the API: the `--api-url` host → `:`, with Pangolin's own authentication off, since llm-host checks the API key. Point it at the LAN IP, not `localhost`, which llm-host treats as local. Clients use `https:///v1` with the key; for opencode, see [`opencode-install.sh`](#connecting-opencode). @@ -171,15 +176,27 @@ page. While OIDC is on, it's the only way in, and codes come back with `remove-o - **The key alone:** it explains the risk and asks before going on (`--force` skips the question). Then it describes the Pangolin resource to add (the dashboard's host → `:`) and, once you -press Enter, checks the public URL reaches this dashboard. +press Enter, checks the public URL reaches this dashboard. It records only that the dashboard is public, not where. + +### Which address clients are given + +Setup's closing message, `llmhost opencode-config` and the dashboard's **Connect** dialog all print the +`opencode-install.sh` command, for these addresses: + +| state | commands shown | +|---|---| +| no tunnel | the local network (`http://.local:`) | +| `install-newt` done, dashboard local | the internet (`--api-url`), then the local network | +| `expose-dashboard` done | the internet only, since the dashboard is then seen from outside | `llmhost status` shows the tunnel and sign-in settings. `setup` and `update` keep them, and `update` moves newt to a newly pinned release. Each step has an undo: `remove-newt`, `remove-oidc`, `remove-otp`. ## Connecting opencode -**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official -installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` +**On the server itself**, setup handles it: if opencode isn't installed it offers to install it, through +`opencode-install.sh --install-only` like any other machine (which runs opencode's official installer, into +`~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` pointing at `http://localhost:/v1` and reading the key straight from llm-host's key file. It shows up in opencode as **LLMHost (Local)**. Other providers and your default model are left alone; the first change backs the file up as `opencode.json.before-llmhost`. @@ -187,8 +204,9 @@ the file up as `opencode.json.before-llmhost`. (`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`. A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead. -**On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner -that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (mybox.local)` +**On another machine**, use `opencode-install.sh` (below); setup ends by printing the exact command for this +server. To do it by hand instead, run `llmhost opencode-config` on the server. It prints a provider block and a +one-liner that copies the API key over. That block is named **LLMHost ()** — e.g. `LLMHost (mybox.local)` — under the provider id `llmhost-`. **On any machine, in one step**, run `opencode-install.sh` from this repo. It needs only the API's address and diff --git a/llmhost/cli.py b/llmhost/cli.py index 7a2e0dd..3fc483e 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -119,7 +119,7 @@ def carried_settings(old, names): longer fit lose their setting along with their plan.""" kept = {k: v for k, v in (old.get("reasoning") or {}).items() if k in names} out = {"reasoning": kept} if kept else {} - for k in ("newt", "dashboard_auth", "dashboard_key_login"): # set by install-*/expose-dashboard, not the plan + for k in ("newt", "dashboard_auth", "dashboard_key_login", "dashboard_public"): # set by install-*/expose-dashboard if old.get(k) is not None: # dashboard_key_login is False when it matters out[k] = old[k] return out @@ -208,7 +208,11 @@ Done. Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch progress with: llmhost watch"}""") if not a.no_opencode: setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode) - say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.") + say("\nOther machines: connect their opencode to this server with one line there. It installs\n" + "opencode if needed, asks for the API key (show it here with `llmhost key`), and adds the\n" + "server to opencode.json.") + for where, url in opencode.client_targets(cfg, host): + say(f" {where}:\n {opencode.remote_command(url)}") if os.environ.get("LLMHOST_PATH_NOTE"): say("\n" + os.environ["LLMHOST_PATH_NOTE"]) @@ -358,7 +362,9 @@ def cmd_status(a): + (["authenticator code"] if paths.OTP_SECRET_FILE.exists() else []) say(f"sign-in {' or '.join(ways)}") if cfg.get("newt"): - say(f"tunnel newt -> {cfg['newt']['endpoint']}") + api = cfg["newt"].get("api_url") + say(f"tunnel newt -> {cfg['newt']['endpoint']}" + (f"; API at {api}/v1" if api else "")) + say(f"dashboard {'public (expose-dashboard)' if cfg.get('dashboard_public') else 'local network only'}") def cmd_models(a): @@ -546,8 +552,16 @@ def cmd_install_newt(a): old_n = cfg.get("newt") or {} newt.platform_tag() # fail before asking anything on a platform newt doesn't ship for - say("Pangolin site (Pangolin: Sites -> Add Site -> Newt):") - endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint", a.endpoint, old_n.get("endpoint"), "--endpoint")) + api_url = _ask("The API's public URL, as clients will reach it (e.g. https://llm-api.example.com)", + a.api_url, old_n.get("api_url"), "--api-url").strip().rstrip("/") + api_url = _check_url("API URL", api_url[:-3] if api_url.endswith("/v1") else api_url) + + say("\nPangolin site (Pangolin: Sites -> Add Site -> Newt):") + endpoint = _check_url("Pangolin endpoint", _ask(" Pangolin endpoint (your Pangolin server, not the API's URL)", + a.endpoint, old_n.get("endpoint"), "--endpoint")) + if urllib.parse.urlsplit(endpoint).netloc == urllib.parse.urlsplit(api_url).netloc: + sys.exit("The Pangolin endpoint is the Pangolin server itself; the API's URL is a resource on it, " + "so the two can't be the same.") site_id = _ask(" Newt ID", a.newt_id, old_n.get("id"), "--newt-id") have_secret = paths.NEWT_SECRET_FILE.exists() and old_n newt_secret = _ask(" Newt secret", None, "keep" if have_secret else None, secret=True, env="LLMHOST_NEWT_SECRET") @@ -555,7 +569,7 @@ def cmd_install_newt(a): newt.ensure_binary(say) if newt_secret != "keep": paths.save_secret(paths.NEWT_SECRET_FILE, newt_secret) - cfg["newt"] = {"endpoint": endpoint, "id": site_id} + cfg["newt"] = {"endpoint": endpoint, "id": site_id, "api_url": api_url} paths.save_config(cfg) service.install("newt") if not service.restart("newt"): @@ -563,12 +577,13 @@ def cmd_install_newt(a): ip = lan_ip() say(f""" Done. newt is running. In Pangolin, add an HTTP resource on this site for the API: - -> http://{ip}:{cfg['api_port']} + {urllib.parse.urlsplit(api_url).netloc} -> http://{ip}:{cfg['api_port']} with Pangolin's own authentication off (llm-host checks the API key). Point it at {ip}, not localhost: requests from localhost count as local here. -Clients then use https:///v1 with the API key; for opencode, see the dashboard's -Connect button, or opencode-install.sh in the llm-host repo. +Clients then use {api_url}/v1 with the API key. To connect opencode on another machine, run +this there (it asks for the key, which `llmhost key` shows): + {opencode.remote_command(api_url)} The dashboard stays on your local network. To put it online too, first give it a sign-in that isn't the API key you hand out (`llmhost install-oidc` or `llmhost install-otp`), then @@ -583,6 +598,7 @@ def cmd_remove_newt(a): shutil.rmtree(paths.NEWT_DIR, ignore_errors=True) paths.NEWT_SECRET_FILE.unlink(missing_ok=True) had = bool(cfg.pop("newt", None)) + cfg.pop("dashboard_public", None) # nothing is public without the tunnel paths.save_config(cfg) say("Removed newt; nothing is reachable from the internet through it now." if had else "newt wasn't installed.") @@ -760,6 +776,10 @@ In Pangolin, on the same site as the API, add an HTTP resource: authentication {pangolin_auth}""") if oidc_on: say(f" and make sure your OIDC client allows the redirect URI {public_url}/auth/callback") + # Only that it's public, not where: what's handed to clients is the API's address, and + # a public dashboard is seen from outside, so it stops offering the LAN one. + cfg["dashboard_public"] = True + paths.save_config(cfg) if not sys.stdin.isatty(): return input("\nPress Enter once the resource is saved, to check it from here... ") @@ -788,24 +808,32 @@ def cmd_download(a): def cmd_opencode(a): cfg = _service_check() - host = a.host or default_host() + if a.host: # an address given explicitly: that one, as before + targets = [("", f"http://{a.host}:{cfg['api_port']}")] + else: + targets = opencode.client_targets(cfg, default_host()) + base = targets[0][1] + host = urllib.parse.urlsplit(base).hostname prov = a.provider or opencode.remote_provider(host) keyfile = opencode.remote_key_file(prov) snippet = { "$schema": "https://opencode.ai/config.json", - "provider": {prov: opencode.provider_block(cfg, host, keyfile, host)}, + "provider": {prov: opencode.provider_block(cfg, host, keyfile, host, base_url=base + "/v1")}, "model": f"{prov}/{plan.SERVED_ALIAS}", # the block's only entry } if a.json: say(json.dumps(snippet, indent=2)) return - say(f"""(On this machine itself, `llmhost opencode-setup` does all of this automatically.) + say("(On this machine itself, `llmhost opencode-setup` does all of this automatically.)\n\n" + "On another machine, run this there. It installs opencode if needed, asks for the API key\n" + "(`llmhost key` shows it here), and adds this server to opencode.json:") + for where, url in targets: + say(f" {where}:\n {opencode.remote_command(url)}" if where else f" {opencode.remote_command(url)}") + say(f""" +Or by hand, for {base}/v1: -On another machine running opencode: - -1. Save the API key: - mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{host} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile} - (or paste the output of `llmhost key` into {keyfile}) +1. Save the API key: paste the output of `llmhost key` into {keyfile} (mode 600), or + mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{default_host()} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile} 2. Merge this into ~/.config/opencode/opencode.json: """) @@ -1001,6 +1029,7 @@ def main(argv=None): sub.add_parser("key", help="print the API key").set_defaults(fn=cmd_key) s = sub.add_parser("install-newt", help="reach the API from the internet through a Pangolin tunnel (dashboard stays local)") s.add_argument("--endpoint", help="Pangolin server, e.g. https://pangolin.example.com") + s.add_argument("--api-url", help="the API's public address, e.g. https://llm-api.example.com (a resource on Pangolin)") s.add_argument("--newt-id", help="the site's Newt ID (its secret: prompted, or $LLMHOST_NEWT_SECRET)") s.set_defaults(fn=cmd_install_newt) sub.add_parser("remove-newt", help="undo install-newt: stop the tunnel").set_defaults(fn=cmd_remove_newt) diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 090bb7a..1c2855a 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -17,6 +17,7 @@ never overwritten. Other providers and settings are left untouched. """ import json import os +import re import shutil import subprocess from pathlib import Path @@ -28,7 +29,8 @@ PROVIDER = "llmhost" DISPLAY = "LLMHost" LOCAL_LABEL = "Local" LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]") -INSTALL_URL = "https://opencode.ai/install" +INSTALL_SCRIPT = paths.SRC / "opencode-install.sh" +DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too def find(): @@ -40,12 +42,70 @@ def find(): def install(log=print): - """Run opencode's official installer (installs to ~/.opencode/bin, adds it to PATH).""" - log(f"$ curl -fsSL {INSTALL_URL} | bash") - r = subprocess.run(["bash", "-c", f"set -o pipefail; curl -fsSL {INSTALL_URL} | bash"]) + """Install opencode the way every machine does: through llm-host's opencode-install.sh, + which runs opencode's official installer (into ~/.opencode/bin, added to PATH). Only + the install step: this machine's provider is configure()'s, since it reads the key + file in place and is kept in sync on every switch.""" + log(f"$ {INSTALL_SCRIPT.name} --install-only") + r = subprocess.run(["bash", str(INSTALL_SCRIPT), "--install-only"]) return find() if r.returncode == 0 else None +def raw_file_url(repo, ref, name): + """Where a file in `repo` at `ref` is fetched raw: GitHub's raw host, or the + /raw/branch/ path Gitea and Forgejo use. None for a remote that isn't https.""" + m = re.match(r"^https://([^/]+)/(.+?)(\.git)?/?$", repo or "") + if not m: + return None + host, path = m.group(1), m.group(2) + if host.lower() == "github.com": + return f"https://raw.githubusercontent.com/{path}/{ref}/{name}" + return f"https://{host}/{path}/raw/branch/{ref}/{name}" + + +_installer = None + + +def installer_url(): + """opencode-install.sh's URL in the repo this server was installed from, so the command + handed to other machines follows a fork and needs nothing but the API to work. Falls + back to the main repo.""" + global _installer + if _installer is None: + def git(*args): + try: + r = subprocess.run(["git", "-C", str(paths.SRC), *args], capture_output=True, text=True, timeout=5) + return r.stdout.strip() if r.returncode == 0 else "" + except (OSError, subprocess.TimeoutExpired): + return "" + ref = git("rev-parse", "--abbrev-ref", "HEAD") + _installer = (raw_file_url(git("config", "--get", "remote.origin.url"), + ref if ref and ref != "HEAD" else "main", INSTALL_SCRIPT.name) + or raw_file_url(DEFAULT_REPO, "main", INSTALL_SCRIPT.name)) + return _installer + + +def remote_command(base_url): + """The one line another machine runs to connect its opencode to this server.""" + return f'/bin/bash -c "$(curl -fsSL {installer_url()})" -- --url {base_url}' + + +def client_targets(cfg, lan_host): + """Where other machines reach the API, as [(where, base URL)], most useful first. + + The API's public address (recorded by `llmhost install-newt`) when there is one, and + the local-network address too unless the dashboard is public -- a public dashboard + is seen from outside, where a LAN address is only noise.""" + lan = ("on your local network", f"http://{lan_host}:{cfg['api_port']}") + public = (cfg.get("newt") or {}).get("api_url") + if not public: + return [lan] + out = [("from the internet", public)] + if not cfg.get("dashboard_public"): + out.append(lan) + return out + + def config_dir(): return Path(os.environ.get("XDG_CONFIG_HOME") or paths.HOME / ".config") / "opencode" @@ -139,7 +199,7 @@ def effort_variants(): return {level: {"disabled": True} for level in OPENCODE_EFFORTS} -def provider_block(cfg, host, key_path, label, mark_loaded=False): +def provider_block(cfg, host, key_path, label, mark_loaded=False, base_url=None): # A single entry, keyed by the alias the API also answers to. Listing every model that # fits would be a menu of four things that 404 and one that works, and naming the loaded # one would break every client's saved default on each `llmhost switch`. @@ -157,7 +217,7 @@ def provider_block(cfg, host, key_path, label, mark_loaded=False): return { "npm": "@ai-sdk/openai-compatible", "name": f"{DISPLAY} ({label})", - "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, + "options": {"baseURL": base_url or f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, "models": models, } diff --git a/llmhost/web/index.html b/llmhost/web/index.html index 6ba2d48..dfea050 100644 --- a/llmhost/web/index.html +++ b/llmhost/web/index.html @@ -173,7 +173,9 @@ pre { .dialog .actions { display: flex; justify-content: flex-end; } .dialog details.manual { margin-bottom: 12px; font-size: 13px; } .dialog details.manual summary { cursor: pointer; color: var(--muted); margin-bottom: 8px; } -#cx-install { white-space: pre-wrap; overflow-wrap: anywhere; } +.dialog .snip pre.cmd { white-space: pre-wrap; overflow-wrap: anywhere; } +#cx-installs .where { font-size: 12.5px; color: var(--muted); margin: 0 0 4px; } +#cx-installs .snip { margin: 0 0 14px; } .toast { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); background: var(--text); color: var(--bg); padding: 8px 14px; border-radius: 8px; font-size: 13px; opacity: 0; transition: opacity .25s; pointer-events: none; } .toast.show { opacity: 1; } @@ -308,15 +310,12 @@ pre {

Add to opencode

-

The API's address, as the machine running opencode reaches it:

-
-

Then run this there, or send it to whoever you're giving access, with the key. It needs only the API, not this - dashboard: it installs opencode if it's missing, asks for the key (hidden), saves it, and adds this server to - opencode.json, keeping their other settings:

-
+

Run this on the machine with opencode, or send it to whoever you're giving access, with the key. It needs + only the API, not this dashboard: it installs opencode if it's missing, asks for the key (hidden), saves it, + and adds this server to opencode.json, keeping their other settings.

+
- Or set it up by hand + Or set it up by hand
  1. Save the key where the provider reads it (paste it at the prompt; it stays out of your shell history):
  2. @@ -427,7 +426,22 @@ function closeConnect() { // filled in here: baseURL, and the provider id and label named after its host. function renderOpencode() { if (!CONNECT) return; - let url = $("cx-url").value.trim().replace(/\/+$/, ""); + // One command per address the API is reached at (server's choice; see client_targets). + const box = $("cx-installs"); box.textContent = ""; + for (const t of CONNECT.targets) { + if (CONNECT.targets.length > 1) { + const w = document.createElement("div"); w.className = "where"; + w.textContent = t.where[0].toUpperCase() + t.where.slice(1) + ":"; box.appendChild(w); + } + const snip = document.createElement("div"); snip.className = "snip"; + const pre = document.createElement("pre"); pre.className = "cmd"; pre.textContent = t.command; + const b = document.createElement("button"); b.className = "small"; b.textContent = "Copy"; + b.onclick = async () => toast(await copyText(t.command) ? "Copied" : "Couldn't copy; select it and copy by hand"); + snip.append(pre, b); box.appendChild(snip); + } + // By hand: for the first (most useful) address. + let url = CONNECT.targets[0].url.replace(/\/+$/, ""); + $("cx-manual-title").textContent = `Or set it up by hand (for ${url})`; let host = ""; try { host = new URL(url).hostname; } catch (e) {} if (url && !/\/v1$/.test(url)) url += "/v1"; @@ -450,27 +464,16 @@ function renderOpencode() { // One line: pasted as two, the first line's `read` would swallow the second as the key. `mkdir -p ~/.config/opencode && printf 'API key: ' && stty -echo && read -r k; stty echo; echo; ` + `[ -n "$k" ] && (umask 077 && printf '%s\\n' "$k" > ${keyfile}) && echo "saved ${keyfile}"; unset k`; - $("cx-install").textContent = url - ? `/bin/bash -c "$(curl -fsSL ${CONNECT.installer})" -- --url ${url.replace(/\/v1$/, "")}` - : "Type the API's address above first."; $("cx-pick").textContent = `${block.name} → ${Object.values(block.models)[0]?.name || CONNECT.model}`; - try { localStorage.setItem("llmhost-api-url", $("cx-url").value.trim()); } catch (e) {} } $("connect").onclick = async () => { let c; try { c = await api("/api/connect"); } catch (e) { if (e.message !== "unauthorized") toast("Couldn't load: " + e.message); return; } CONNECT = c; $("cx-key").value = c.key; - // The public API address can't be known here, so remember what the viewer typed; on a - // plain-http LAN visit the API is on this same host, at its own port. - let saved = ""; - try { saved = localStorage.getItem("llmhost-api-url") || ""; } catch (e) {} - if (!saved && location.protocol === "http:") saved = `http://${location.hostname}:${c.api_port}/v1`; - $("cx-url").value = saved; renderOpencode(); $("connect-modal").classList.add("show"); $("cx-close").focus(); }; -$("cx-url").addEventListener("input", renderOpencode); document.querySelectorAll("#connect-modal [data-copy]").forEach((b) => { b.onclick = async () => toast(await copyText($(b.dataset.copy).textContent) ? "Copied" : "Couldn't copy; select it and copy by hand"); }); diff --git a/llmhost/web/server.py b/llmhost/web/server.py index 8b65794..9deac44 100644 --- a/llmhost/web/server.py +++ b/llmhost/web/server.py @@ -417,42 +417,8 @@ class Sampler: threading.Thread(target=fn, args=("model",), daemon=True).start() -DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too - - -def raw_file_url(repo, ref, name): - """Where a file in `repo` at `ref` is fetched raw: GitHub's raw host, or the - /raw/branch/ path Gitea and Forgejo use. None for a remote that isn't https.""" - m = re.match(r"^https://([^/]+)/(.+?)(\.git)?/?$", repo or "") - if not m: - return None - host, path = m.group(1), m.group(2) - if host.lower() == "github.com": - return f"https://raw.githubusercontent.com/{path}/{ref}/{name}" - return f"https://{host}/{path}/raw/branch/{ref}/{name}" - - -_installer = None - - -def installer_url(): - """The opencode installer's URL in the repo this server was installed from, so the - command the Connect dialog gives out works for people who can't reach this dashboard - (an API-only tunnel) and follows a fork. Falls back to the main repo.""" - global _installer - if _installer is None: - import subprocess - def git(*args): - try: - r = subprocess.run(["git", "-C", str(paths.SRC), *args], capture_output=True, text=True, timeout=5) - return r.stdout.strip() if r.returncode == 0 else "" - except (OSError, subprocess.TimeoutExpired): - return "" - ref = git("rev-parse", "--abbrev-ref", "HEAD") - _installer = (raw_file_url(git("config", "--get", "remote.origin.url"), - ref if ref and ref != "HEAD" else "main", "opencode-install.sh") - or raw_file_url(DEFAULT_REPO, "main", "opencode-install.sh")) - return _installer +# The opencode installer's URL is worked out once, from the repo this was installed from. +raw_file_url, installer_url = opencode.raw_file_url, opencode.installer_url def make_handler(sampler, key, oidc=None, otp=None, key_login=True): @@ -602,17 +568,19 @@ def make_handler(sampler, key, oidc=None, otp=None, key_login=True): if self.authed(): self.send_json(200, sampler.snapshot()) elif path == "/api/connect": - # What the Connect dialog hands to clients: the key, and opencode's provider - # block from the same builder as `llmhost opencode-config`. The public API - # address can't be known here, so the page fills in baseURL, the provider id - # and its label from what the viewer types. Behind the same sign-in as - # everything else; send_json marks it no-store. + # What the Connect dialog hands to clients: the key; the API's addresses with + # the opencode-install.sh command for each, chosen by the same rule as setup and + # `llmhost opencode-config` (opencode.client_targets); and opencode's provider + # block for setting it up by hand, whose address-dependent parts the page fills + # in. Behind the same sign-in as everything else; send_json marks it no-store. if self.authed(): cfg = paths.load_config() or sampler.cfg + h = socket.gethostname() + targets = [{"where": w, "url": u, "command": opencode.remote_command(u)} + for w, u in opencode.client_targets(cfg, h if "." in h else h + ".local")] block = opencode.provider_block(cfg, "HOST", "KEYFILE", "LABEL") - self.send_json(200, {"key": key, "api_port": cfg["api_port"], - "model": plan.SERVED_ALIAS, "opencode": block, - "installer": installer_url()}) + self.send_json(200, {"key": key, "model": plan.SERVED_ALIAS, "opencode": block, + "targets": targets}) elif path == "/api/logs": if self.authed(): lines = [l for l in service.logs("model", 1500) diff --git a/opencode-install.sh b/opencode-install.sh index a58fa87..d162cf2 100755 --- a/opencode-install.sh +++ b/opencode-install.sh @@ -24,6 +24,7 @@ # --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 +# --install-only only install opencode (no --url or key needed); `llmhost setup` uses this # --remove take this server back out of opencode's config # Written for bash 3.2 so it runs on stock macOS. set -euo pipefail @@ -44,12 +45,13 @@ Connect opencode to an llm-host server, installing opencode first if needed. --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 + --install-only only install opencode (no --url or key needed) --remove take this server back out of opencode's config EOF } [ "${1:-}" = "--" ] && shift -URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0 +URL=""; KEY="${LLMHOST_API_KEY:-}"; DEFAULT="ask"; INSTALL=1; REMOVE=0; INSTALL_ONLY=0 while [ $# -gt 0 ]; do case "$1" in --url) URL="${2:-}"; shift 2 ;; @@ -59,12 +61,30 @@ while [ $# -gt 0 ]; do --default) DEFAULT="yes"; shift ;; --no-default) DEFAULT="no"; shift ;; --skip-install) INSTALL=0; shift ;; + --install-only) INSTALL_ONLY=1; shift ;; --remove) REMOVE=1; shift ;; -h|--help) usage; exit 0 ;; *) die "unknown option: $1 (see --help)" ;; esac done +find_opencode() { + OC="$(command -v opencode || true)" + if [ -z "$OC" ] && [ -x "$HOME/.opencode/bin/opencode" ]; then OC="$HOME/.opencode/bin/opencode"; fi +} +install_opencode() { + say "Installing opencode (official installer)" + curl -fsSL https://opencode.ai/install | bash + find_opencode + [ -n "$OC" ] || die "opencode didn't install; see the output above" +} + +if [ "$INSTALL_ONLY" = 1 ]; then + find_opencode + if [ -n "$OC" ]; then say "opencode is already installed ($OC)"; else install_opencode; fi + exit 0 +fi + # 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 @@ -168,15 +188,10 @@ fi say "Server OK" # ---- opencode ------------------------------------------------------------------------ -OC="$(command -v opencode || true)" -[ -n "$OC" ] || { [ -x "$HOME/.opencode/bin/opencode" ] && OC="$HOME/.opencode/bin/opencode"; } || true +find_opencode 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" + install_opencode else warn "opencode isn't installed; configuring it anyway (--skip-install)" fi diff --git a/tests/test_dashboard_auth.py b/tests/test_dashboard_auth.py index 7c543b0..3ce7e19 100644 --- a/tests/test_dashboard_auth.py +++ b/tests/test_dashboard_auth.py @@ -109,8 +109,20 @@ check("opencode block is the openai-compatible provider", blk["npm"] == "@ai-sdk check("opencode block offers the one alias", list(blk["models"]) == [cx["model"]] == ["default"], blk["models"]) check("opencode block leaves the address to the page", "LABEL" in blk["name"] and "HOST" in blk["options"]["baseURL"], blk) check("the key isn't inlined in the block", KEY not in json.dumps(blk)) -check("installer URL is a raw file in the repo", cx["installer"].startswith("https://") - and cx["installer"].endswith("/opencode-install.sh"), cx["installer"]) +check("one address before any tunnel: the LAN", len(cx["targets"]) == 1 + and cx["targets"][0]["url"].endswith(f":{harness.config()['api_port']}"), cx["targets"]) +check("with its opencode-install.sh command", "/opencode-install.sh)\" -- --url http://" in cx["targets"][0]["command"], + cx["targets"]) +c2 = harness.config(); c2["newt"] = {"endpoint": "https://p.example.test", "id": "x", "api_url": "https://llm-api.example.test"} +paths.save_config(c2) +cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2]) +check("tunnel, local dashboard: internet then LAN", [t["where"] for t in cx["targets"]] + == ["from the internet", "on your local network"] and cx["targets"][0]["url"] == "https://llm-api.example.test", cx["targets"]) +c2["dashboard_public"] = True +paths.save_config(c2) +cx = json.loads(req(srv, "GET", "/api/connect", {"Authorization": f"Bearer {KEY}"})[2]) +check("public dashboard: the internet only", [t["url"] for t in cx["targets"]] == ["https://llm-api.example.test"], cx["targets"]) +paths.save_config(harness.config()) R = web.raw_file_url check("raw URL for a Gitea/Forgejo repo", R("https://git.example.com/pub/llm-host.git", "main", "f.sh") == "https://git.example.com/pub/llm-host/raw/branch/main/f.sh") diff --git a/tests/test_newt.py b/tests/test_newt.py index a4c0e1b..d2e1fa7 100644 --- a/tests/test_newt.py +++ b/tests/test_newt.py @@ -77,7 +77,9 @@ cfg = harness.config() paths.save_config(cfg) paths.api_key(create=True) -NEWT_ARGS = ["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "site123"] +NEWT_ARGS = ["install-newt", "--api-url", "https://llm-api.example.test", "--endpoint", "https://pangolin.example.test", + "--newt-id", "site123"] +NEWT_CONF = {"endpoint": "https://pangolin.example.test", "id": "site123", "api_url": "https://llm-api.example.test"} OIDC_ARGS = ["install-oidc", "--public-url", "https://dash.example.test", "--issuer", ISSUER, "--client-id", "client-from-provider", "--allow-group", "llm-admins"] @@ -102,13 +104,25 @@ check("download URL is the pinned GitHub release", fetches[-1].startswith(f"https://github.com/fosrl/newt/releases/download/{newt.VERSION}/newt_"), fetches) print("\n3. install-newt: the API only") +print("\n3a. the client commands before the tunnel: the local network only") +code, out = run(["opencode-config"]) +check("opencode-config: one command, the LAN address", code == 0 and out.count("opencode-install.sh") == 1 + and f"--url http://{cli.default_host()}:{cfg['api_port']}" in out, out) +code, out = run(["install-newt", "--endpoint", "https://pangolin.example.test", "--newt-id", "x"], + {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) +check("the API's public URL is required", code != 0 and "--api-url" in out, out) +code, out = run(["install-newt", "--api-url", "https://pangolin.example.test", "--endpoint", "https://pangolin.example.test", + "--newt-id", "x"], {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) +check("API URL = Pangolin endpoint is refused", code != 0 and "can't be the same" in out, out) code, out = run(NEWT_ARGS) check("missing secret without a terminal -> error", code != 0 and "LLMHOST_NEWT_SECRET" in out, out) calls.clear() code, out = run(NEWT_ARGS, {"LLMHOST_NEWT_SECRET": NEWT_SECRET}) c = paths.load_config() check("succeeds", code == 0, out) -check("newt config saved", c.get("newt") == {"endpoint": "https://pangolin.example.test", "id": "site123"}, c.get("newt")) +check("newt config saved, with the API's public URL", c.get("newt") == NEWT_CONF, c.get("newt")) +check("the resource is named by the API's host", f"llm-api.example.test -> http://" in out, out) +check("prints the opencode command for the public URL", "opencode-install.sh)\" -- --url https://llm-api.example.test" in out, out) check("dashboard sign-in untouched", "dashboard_auth" not in c and not paths.OIDC_SECRET_FILE.exists()) check("newt service installed and started", ("install", "newt") in calls and ("restart", "newt") in calls, calls) check("dashboard not restarted", ("restart", "web") not in calls, calls) @@ -119,8 +133,18 @@ check("secret saved 0600, not in config or output", and NEWT_SECRET not in paths.CONFIG_FILE.read_text() and NEWT_SECRET not in out) code, out = run(["install-newt", "--newt-id", "site456"]) c = paths.load_config() -check("re-run keeps what it isn't given", code == 0 and c["newt"] == {"endpoint": "https://pangolin.example.test", "id": "site456"} +check("re-run keeps what it isn't given", code == 0 and c["newt"] == {**NEWT_CONF, "id": "site456"} and paths.NEWT_SECRET_FILE.read_text().strip() == NEWT_SECRET, out) +code, out = run(["install-newt", "--api-url", "https://llm-api.example.test/v1/"]) +check("a trailing /v1 is dropped", code == 0 and paths.load_config()["newt"]["api_url"] == "https://llm-api.example.test", out) + +print("\n3b. tunnel up, dashboard local: both commands") +code, out = run(["opencode-config"]) +check("opencode-config: internet first, then local", code == 0 and out.count("opencode-install.sh") == 2 + and out.index("--url https://llm-api.example.test") < out.index(f"--url http://{cli.default_host()}"), out) +check("by hand: for the public URL", '"baseURL": "https://llm-api.example.test/v1"' in out, out) +code, out = run(["status"]) +check("status: API URL and a local dashboard", "API at https://llm-api.example.test/v1" in out and "local network only" in out, out) print("\n4. newt starts with its credentials in the environment, not its arguments") seen = {} @@ -141,6 +165,12 @@ check("refused when you say no", code != 0 and "Not published" in out, out) code, out = run(["expose-dashboard", "--public-url", "https://dash.example.test", "--force"]) check("--force walks through it anyway", code == 0 and f":{paths.load_config()['web_port']}" in out and "dash.example.test" in out, out) +c = paths.load_config() +check("records that the dashboard is public, not where", c.get("dashboard_public") is True + and "dash.example.test" not in json.dumps({k: v for k, v in c.items() if k != "dashboard_auth"}), c.get("dashboard_public")) +code, out = run(["opencode-config"]) +check("dashboard public: only the internet command", code == 0 and out.count("opencode-install.sh") == 1 + and "--url https://llm-api.example.test" in out and f"http://{cli.default_host()}" not in out.split("Or by hand")[0], out) print("\n6. install-oidc") code, out = run(OIDC_ARGS) @@ -209,6 +239,7 @@ code, out = run(["remove-newt"]) c = paths.load_config() check("newt removed", code == 0 and ("uninstall", "newt") in calls and "newt" not in c and not paths.NEWT_SECRET_FILE.exists() and not newt.binary().exists(), out) +check("and the dashboard no longer counts as public", "dashboard_public" not in c) check("rest of the config untouched", c.get("api_port") == cfg.get("api_port") and c.get("models") == cfg.get("models")) code, out = run(["expose-dashboard"]) check("expose-dashboard needs newt first", code != 0 and "install-newt" in out, out) diff --git a/tests/test_opencode.py b/tests/test_opencode.py index 048a0db..e25415b 100644 --- a/tests/test_opencode.py +++ b/tests/test_opencode.py @@ -327,4 +327,10 @@ check("a non-reasoning model gets no variants", "variants" not in nr["models"][" check("one entry only, named for the alias, so the client can't pick a model either", list(q["models"]) == [plan.SERVED_ALIAS], list(q["models"])) +print("\nthe command handed to other machines") +cmd = opencode.remote_command("http://mybox.local:1134") +check("fetches opencode-install.sh from a repo and passes the URL", + cmd.startswith('/bin/bash -c "$(curl -fsSL https://') and '/opencode-install.sh)" -- --url http://mybox.local:1134' in cmd, cmd) +check("the script it names is in this repo", (harness.REPO / "opencode-install.sh").exists()) + check.done(ROOT) diff --git a/tests/test_opencode_install.py b/tests/test_opencode_install.py index 2677103..30c1c24 100644 --- a/tests/test_opencode_install.py +++ b/tests/test_opencode_install.py @@ -172,7 +172,22 @@ code, out = run(home, b, oc, "--url", URL) check("a .jsonc is never rewritten; the block is printed", code == 0 and "by hand" in out and (cd / "opencode.jsonc").read_text().startswith("{ // mine") and not (cd / "opencode.json").exists(), out) -print("\n5. --help works when run as `bash -c`") +print("\n5. --install-only, which `llmhost setup` uses") +home, b, oc = sandbox(with_opencode=False) +code, out = run(home, b, oc, "--install-only", key=None) +check("installs without a URL or key", code == 0 and (home / ".opencode/bin/opencode").exists(), out) +check("touches no config", not (home / ".config/opencode").exists()) +code, out = run(home, b, oc, "--install-only", key=None) +check("a second run finds it", code == 0 and "already installed" in out, out) +home, b, oc = sandbox(with_opencode=False) +env = {"HOME": str(home), "PATH": f"{b}:/usr/bin:/bin", "FAKE_OPENCODE": str(oc), + "LLMHOST_HOME": str(home / "lh"), "LLMHOST_CONFIG": str(home / "lhc"), "PYTHONPATH": str(harness.REPO)} +r = subprocess.run([sys.executable, "-c", "from llmhost import opencode; print('FOUND', opencode.install(lambda *_: None))"], + env=env, capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, start_new_session=True) +check("llm-host's own opencode install goes through the script", + r.returncode == 0 and f"FOUND {home}/.opencode/bin/opencode" in r.stdout, r.stdout + r.stderr) + +print("\n6. --help works when run as `bash -c`") r = subprocess.run(["bash", "-c", SCRIPT.read_text(), "--", "--help"], capture_output=True, text=True) check("prints usage", r.returncode == 0 and "--url" in r.stdout, r.stdout + r.stderr)