Hand out the right opencode command: the API's public URL, and setup uses the install script
install-newt now asks for the API's public URL first (--api-url) and records it; it names the Pangolin resource and refuses an endpoint on the same host. expose-dashboard records only that the dashboard is public. One rule (opencode.client_targets) decides which opencode-install.sh commands are shown -- local only without a tunnel; internet and local with one; internet only once the dashboard is public -- and setup's closing message, `llmhost opencode-config` and the dashboard's Connect dialog all use it. Setup's offer to install opencode now goes through opencode-install.sh --install-only, a new mode that only installs opencode; this machine's own provider is still configured by llm-host, which keeps it in sync on every switch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c8b70afdbf
commit
3e9ebeed42
10 changed files with 266 additions and 109 deletions
|
|
@ -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:
|
||||
<a host of your choice> -> 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://<that host>/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)
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 {
|
|||
<div class="keyrow"><input id="cx-key" type="password" readonly autocomplete="off" aria-label="API key"><button id="cx-show">Show</button><button id="cx-copy">Copy</button></div>
|
||||
|
||||
<h4>Add to opencode</h4>
|
||||
<p>The API's address, as the machine running opencode reaches it:</p>
|
||||
<div class="keyrow"><input id="cx-url" type="url" spellcheck="false" autocomplete="off"
|
||||
placeholder="https://llm-api.example.com" aria-label="API base URL"></div>
|
||||
<p>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
|
||||
<code>opencode.json</code>, keeping their other settings:</p>
|
||||
<div class="snip" style="margin-bottom:14px"><pre id="cx-install"></pre><button class="small" data-copy="cx-install">Copy</button></div>
|
||||
<p>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 <code>opencode.json</code>, keeping their other settings.</p>
|
||||
<div id="cx-installs"></div>
|
||||
<details class="manual">
|
||||
<summary>Or set it up by hand</summary>
|
||||
<summary id="cx-manual-title">Or set it up by hand</summary>
|
||||
<ol>
|
||||
<li>Save the key where the provider reads it (paste it at the prompt; it stays out of your shell history):
|
||||
<div class="snip"><pre id="cx-keycmd"></pre><button class="small" data-copy="cx-keycmd">Copy</button></div></li>
|
||||
|
|
@ -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");
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue