330 lines
17 KiB
Python
330 lines
17 KiB
Python
"""opencode integration: provider naming, ownership, removal, the credential cache."""
|
|
import json, os, shutil, pathlib
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import harness
|
|
|
|
ROOT = harness.setup()
|
|
from llmhost import opencode, paths, plan
|
|
|
|
harness.guard(paths, ROOT)
|
|
CFG = harness.config()
|
|
OC = opencode.config_file()
|
|
check = harness.Checks()
|
|
|
|
def reset(data=None):
|
|
shutil.rmtree(OC.parent, ignore_errors=True)
|
|
if data is not None:
|
|
OC.parent.mkdir(parents=True, exist_ok=True)
|
|
OC.write_text(json.dumps(data, indent=2))
|
|
|
|
def load():
|
|
return json.loads(OC.read_text())
|
|
|
|
def remote(host, prov=None):
|
|
prov = prov or opencode.remote_provider(host)
|
|
return prov, opencode.provider_block(CFG, host, opencode.remote_key_file(prov), host)
|
|
|
|
print("\n1. fresh install")
|
|
reset()
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
d = load()
|
|
check("status added", st == "added", st)
|
|
check("id is llmhost", prov == "llmhost", prov)
|
|
check('name is "LLMHost (Local)"', d["provider"]["llmhost"]["name"] == "LLMHost (Local)", d["provider"]["llmhost"]["name"])
|
|
check("baseURL localhost", d["provider"]["llmhost"]["options"]["baseURL"] == "http://localhost:1134/v1")
|
|
check("apiKey -> llm-host key file", str(paths.KEY_FILE) in d["provider"]["llmhost"]["options"]["apiKey"])
|
|
check("model set to the alias", d["model"] == "llmhost/default", d.get("model"))
|
|
mods = d["provider"]["llmhost"]["models"]
|
|
check("exactly one entry", list(mods) == ["default"], list(mods))
|
|
check("keyed by the API alias", list(mods) == [plan.SERVED_ALIAS])
|
|
check("label names the loaded model", mods["default"]["name"] == "Default model \u00b7 Ornith 1.5 9B (Local)", mods["default"]["name"])
|
|
check("limits come from the loaded model",
|
|
mods["default"]["limit"]["context"] == next(m["est_context"] for m in CFG["models"] if m["name"] == CFG["active"]),
|
|
mods["default"]["limit"])
|
|
check("reasoning flag from the loaded model", mods["default"].get("reasoning") is True, mods["default"])
|
|
|
|
print("\n2. local + remote side by side")
|
|
rp, rb = remote("mybox.local")
|
|
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
d = load()
|
|
check("remote id is llmhost-mybox", rp == "llmhost-mybox", rp)
|
|
check('remote name is "LLMHost (mybox.local)"', rb["name"] == "LLMHost (mybox.local)", rb["name"])
|
|
check("remote has one entry too", list(rb["models"]) == ["default"], list(rb["models"]))
|
|
check("remote label names no model (it would go stale)",
|
|
rb["models"]["default"]["name"] == "Default model (mybox.local)", rb["models"]["default"]["name"])
|
|
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-mybox"], sorted(d["provider"]))
|
|
check("remote untouched", d["provider"][rp] == rb)
|
|
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
|
|
|
|
print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)")
|
|
_, rb2 = remote("mybox.local", prov="llmhost")
|
|
reset({"provider": {"llmhost": rb2}})
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
d = load()
|
|
check("did not reuse `llmhost`", prov == "llmhost-local", prov)
|
|
check("remote block intact", d["provider"]["llmhost"] == rb2)
|
|
check("local under llmhost-local", d["provider"]["llmhost-local"]["options"]["baseURL"] == "http://localhost:1134/v1")
|
|
|
|
print("\n4. user renamed the local provider (gap 2)")
|
|
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/default"})
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
d = load()
|
|
check("recognised under new name", prov == "mymac", prov)
|
|
check("no duplicate added", list(d["provider"]) == ["mymac"], list(d["provider"]))
|
|
check("nothing to change -> unchanged", st == "unchanged", st)
|
|
# But a stale per-model default IS a change worth making.
|
|
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/ornith-1.5-9b"})
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("a stale default makes it an update", st == "updated", st)
|
|
check("and it is migrated", load()["model"] == "mymac/default", load().get("model"))
|
|
|
|
print("\n5. uninstall: remove local, keep remote, repoint model")
|
|
rp, rb = remote("mybox.local")
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/default"})
|
|
st, path, removed, new_model = opencode.remove(local=True)
|
|
d = load()
|
|
check("status removed", st == "removed", st)
|
|
check("removed only local", removed == ["llmhost"], removed)
|
|
check("remote survives", list(d["provider"]) == [rp], list(d["provider"]))
|
|
check("model repointed to the surviving provider's entry",
|
|
new_model == f"{rp}/{plan.SERVED_ALIAS}" and d["model"] == new_model, (new_model, d.get("model")))
|
|
# An older remote block, pasted before the single-entry change, still lists every model;
|
|
# the fallback takes its first in plan order rather than whichever name sorts first.
|
|
legacy = {**rb, "models": {m["name"]: {"name": m["name"]} for m in CFG["models"]}}
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: legacy}, "model": "llmhost/default"})
|
|
st, path, removed, new_model = opencode.remove(local=True)
|
|
check("legacy multi-model block falls back to its first",
|
|
new_model == f"{rp}/{CFG['models'][0]['name']}", new_model)
|
|
|
|
print("\n6. uninstall must NOT glob llmhost*")
|
|
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
|
st, path, removed, new_model = opencode.remove(local=True)
|
|
check("nothing matched", st == "none" and removed == [], (st, removed))
|
|
check("remote still there", list(load()["provider"]) == [rp])
|
|
|
|
print("\n7. retiring a remote server (gap 3)")
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
|
st, path, removed, new_model = opencode.remove(local=False, host="mybox.local")
|
|
d = load()
|
|
check("removed the remote", removed == [rp], removed)
|
|
check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"]))
|
|
check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model"))
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}})
|
|
st, path, removed, _ = opencode.remove(local=False, host="mybox")
|
|
check("short hostname also matches", removed == [rp], removed)
|
|
|
|
print("\n8. --all drops the model key when nothing is left")
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"})
|
|
st, path, removed, new_model = opencode.remove(local=False, every=True)
|
|
d = load()
|
|
check("both removed", sorted(removed) == ["llmhost", rp], removed)
|
|
check("model key dropped", "model" not in d and new_model is None, d)
|
|
check("provider key dropped", "provider" not in d, d)
|
|
|
|
print("\n9. foreign providers are never touched")
|
|
foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (mybox)",
|
|
"options": {"baseURL": "http://mybox.local:1134/v1", "apiKey": "{file:~/.config/opencode/mybox-vllm.key}"},
|
|
"models": {"x": {"name": "x"}}}
|
|
reset({"provider": {"mybox-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "mybox-vllm/x"})
|
|
st, path, removed, new_model = opencode.remove(local=True)
|
|
d = load()
|
|
check("only ours removed", removed == ["llmhost"], removed)
|
|
check("foreign intact", d["provider"]["mybox-vllm"] == foreign)
|
|
check("foreign model untouched", d["model"] == "mybox-vllm/x", d.get("model"))
|
|
st, path, removed, _ = opencode.remove(local=False, every=True)
|
|
check("--all skips foreign", removed == [], removed)
|
|
|
|
print("\n10. .jsonc with comments is left alone")
|
|
shutil.rmtree(OC.parent, ignore_errors=True)
|
|
OC.parent.mkdir(parents=True, exist_ok=True)
|
|
j = OC.parent / "opencode.jsonc"
|
|
orig = '{\n // mine\n "provider": {}\n}\n'
|
|
j.write_text(orig)
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("configure reports has-comments", st == "has-comments", st)
|
|
check("file unchanged", j.read_text() == orig)
|
|
st, path, removed, _ = opencode.remove(local=True)
|
|
check("remove reports has-comments", st == "has-comments", st)
|
|
check("file still unchanged", j.read_text() == orig)
|
|
check("snippet has the new name", '"LLMHost (Local)"' in opencode.snippet(CFG))
|
|
|
|
print("\n11. unparsable JSON is left alone")
|
|
reset(); OC.parent.mkdir(parents=True, exist_ok=True); OC.write_text("{ broken")
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("configure reports unparsable", st == "unparsable", st)
|
|
check("file unchanged", OC.read_text() == "{ broken")
|
|
|
|
print("\n12. missing/garbage blocks don't crash the fingerprint")
|
|
reset({"provider": {"a": None, "b": "nope", "c": {}, "d": {"options": {}}}})
|
|
check("no crash, nothing ours", opencode.local_ids(load()["provider"]) == [])
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("still installs", prov == "llmhost" and st == "added", (prov, st))
|
|
|
|
print("\n13. --host must not take a foreign provider on the same host (regression)")
|
|
rp, rb = remote("mybox.local")
|
|
reset({"provider": {rp: rb, "mybox-vllm": foreign, "llmhost": opencode.local_block(CFG)},
|
|
"model": "mybox-vllm/x"})
|
|
st, path, removed, new_model = opencode.remove(local=False, host="mybox.local")
|
|
d = load()
|
|
check("removed only ours", removed == [rp], removed)
|
|
check("foreign on same host survives", "mybox-vllm" in d["provider"])
|
|
check("local survives", "llmhost" in d["provider"])
|
|
check("foreign model untouched", d["model"] == "mybox-vllm/x", d.get("model"))
|
|
|
|
print("\n14. a stale cached key is cleared on configure")
|
|
def put_auth(d, mode=0o600):
|
|
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True)
|
|
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
|
|
with os.fdopen(fd, "w") as fh: json.dump(d, fh)
|
|
return f
|
|
|
|
def get_auth():
|
|
return json.loads(opencode.auth_file().read_text())
|
|
|
|
reset()
|
|
af = put_auth({"llmhost": {"type": "api", "key": "sk-STALE"}, "anthropic": {"type": "oauth", "t": 1}})
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
a = get_auth()
|
|
check("reported clearing the cache", authcl is True, authcl)
|
|
check("stale llmhost entry gone", "llmhost" not in a, a)
|
|
check("other providers' creds untouched", a.get("anthropic") == {"type": "oauth", "t": 1}, a)
|
|
check("file mode preserved (0600)", oct(af.stat().st_mode & 0o777) == "0o600", oct(af.stat().st_mode & 0o777))
|
|
|
|
print("\n15. nothing cached -> nothing reported, no file created")
|
|
reset(); opencode.auth_file().unlink(missing_ok=True)
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("no clear reported", authcl is False, authcl)
|
|
check("no auth.json invented", not opencode.auth_file().exists())
|
|
reset(); put_auth({"other": {"type": "api", "key": "x"}})
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("untouched when we have no entry", authcl is False and get_auth() == {"other": {"type": "api", "key": "x"}})
|
|
|
|
print("\n16. an unreadable auth store is left alone, not repaired")
|
|
reset()
|
|
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True); f.write_text("{ not json")
|
|
st, path, prov, authcl = opencode.configure(CFG)
|
|
check("no crash", st == "added", st)
|
|
check("left verbatim", f.read_text() == "{ not json")
|
|
check("reported nothing cleared", authcl is False, authcl)
|
|
|
|
print("\n17. remove() takes the cached key with the provider")
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-mybox": remote("mybox.local")[1]}})
|
|
put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-mybox": {"type": "api", "key": "sk-B"}})
|
|
st, path, removed, _ = opencode.remove(local=True)
|
|
a = get_auth()
|
|
check("local cred cleared", "llmhost" not in a, a)
|
|
check("remote cred kept", a.get("llmhost-mybox") == {"type": "api", "key": "sk-B"}, a)
|
|
|
|
print("\n18. purge --keep-key keeps the API key through a purge")
|
|
from llmhost import cli
|
|
cli_shim = pathlib.Path(ROOT) / "bin/llmhost"
|
|
cli_shim.parent.mkdir(parents=True, exist_ok=True)
|
|
paths.SHIM = cli_shim # never touch the real launcher from a test
|
|
|
|
for name in ("DATA", "CONFIG_DIR", "KEY_FILE", "SHIM"):
|
|
val = str(getattr(paths, name))
|
|
if not val.startswith(ROOT):
|
|
sys.exit(f"ABORT: paths.{name} = {val} is outside the sandbox {ROOT}; "
|
|
"purge() would delete a real install")
|
|
|
|
def seed():
|
|
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
paths.DATA.mkdir(parents=True, exist_ok=True)
|
|
(paths.DATA / "venv-mlx").mkdir(exist_ok=True)
|
|
key = paths.api_key(create=True)
|
|
paths.save_config({"active": "x"})
|
|
cli_shim.write_text("#!/bin/sh\n")
|
|
return key
|
|
|
|
key = seed()
|
|
kept = cli.purge(keep_key=True)
|
|
check("reported the kept path", kept == paths.KEY_FILE, kept)
|
|
check("key file survives", paths.KEY_FILE.exists())
|
|
check("key value unchanged", paths.KEY_FILE.read_text().strip() == key.strip(), paths.KEY_FILE.read_text())
|
|
check("key mode is 0600", oct(paths.KEY_FILE.stat().st_mode & 0o777) == "0o600", oct(paths.KEY_FILE.stat().st_mode & 0o777))
|
|
check("config.json gone", not paths.CONFIG_FILE.exists())
|
|
check("data dir gone", not paths.DATA.exists())
|
|
check("launcher gone", not cli_shim.exists())
|
|
check("a reinstall would reuse it", paths.api_key(create=True).strip() == key.strip())
|
|
|
|
print("\n19. purge without --keep-key removes everything")
|
|
key2 = seed()
|
|
kept = cli.purge(keep_key=False)
|
|
check("reported nothing kept", kept is None, kept)
|
|
check("key file gone", not paths.KEY_FILE.exists())
|
|
check("config dir gone", not paths.CONFIG_DIR.exists())
|
|
check("a reinstall mints a different key", paths.api_key(create=True).strip() != key2.strip())
|
|
|
|
print("\n20. sync() refreshes an existing block after a switch")
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/default"})
|
|
switched = dict(CFG, active="qwen3-coder")
|
|
prov = opencode.sync(switched)
|
|
d = load()
|
|
mods = d["provider"]["llmhost"]["models"]
|
|
check("reported the provider", prov == "llmhost", prov)
|
|
check("still one entry, same id", list(mods) == ["default"], list(mods))
|
|
check("label follows the switch", "Qwen3 Coder 30B A3B" in mods["default"]["name"], mods["default"]["name"])
|
|
check("the client's saved default still resolves", d["model"] == "llmhost/default", d.get("model"))
|
|
check("reasoning dropped for a non-reasoning model", "reasoning" not in mods["default"], mods["default"])
|
|
check("idempotent", opencode.sync(switched) is None)
|
|
|
|
print("\n21. sync() never wires opencode up on its own")
|
|
reset()
|
|
check("no config file -> no-op", opencode.sync(CFG) is None)
|
|
check("still no config file", not opencode.config_file().exists())
|
|
reset({"provider": {"mybox-vllm": foreign}, "model": "mybox-vllm/x"})
|
|
check("no local block -> no-op", opencode.sync(CFG) is None)
|
|
check("foreign provider untouched", load()["provider"] == {"mybox-vllm": foreign})
|
|
reset({"provider": {"mymac": opencode.local_block(CFG)}})
|
|
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
|
|
|
|
check.section("22. a default naming a specific model is migrated to the alias")
|
|
for old_model, expect in (("llmhost/qwen3.8-27b", "llmhost/default"),
|
|
("llmhost/ornith-1.5-9b", "llmhost/default"),
|
|
("llmhost/default", "llmhost/default"),
|
|
("mybox-vllm/qwen3.8-27b", "mybox-vllm/qwen3.8-27b"),
|
|
("llmhost-mybox/qwen3.8-27b", "llmhost-mybox/qwen3.8-27b")):
|
|
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": old_model})
|
|
opencode.configure(CFG)
|
|
got = load().get("model")
|
|
check(f"{old_model} -> {expect}", got == expect, got)
|
|
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/qwen3-coder"})
|
|
opencode.sync(dict(CFG, active="qwen3-coder"))
|
|
check("migrated under a renamed provider too", load()["model"] == "mymac/default", load().get("model"))
|
|
|
|
check.section("23. opencode-config's default points at an entry its block has")
|
|
import argparse, io, contextlib
|
|
cli._service_check = lambda: CFG
|
|
buf = io.StringIO()
|
|
with contextlib.redirect_stdout(buf):
|
|
cli.cmd_opencode(argparse.Namespace(host="mybox.local", provider=None, json=True))
|
|
snip = json.loads(buf.getvalue())
|
|
prov_id, block = next(iter(snip["provider"].items()))
|
|
check("provider named after the host", prov_id == "llmhost-mybox", prov_id)
|
|
check("model is <provider>/<an entry in the block>",
|
|
snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"],
|
|
(snip["model"], list(block["models"])))
|
|
|
|
check.section("24. the block never offers a reasoning chooser of its own")
|
|
check("opencode's whole menu is switched off",
|
|
opencode.effort_variants() == {l: {"disabled": True} for l in ("low", "medium", "high")},
|
|
opencode.effort_variants())
|
|
q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "mybox.local", "k", "mybox.local")
|
|
ent = q["models"]["default"]
|
|
check("a reasoning model is marked as one (so thinking blocks render)", ent.get("reasoning") is True, ent)
|
|
check("but every effort level is disabled",
|
|
ent.get("variants") == {l: {"disabled": True} for l in ("low", "medium", "high")}, ent)
|
|
check("no variant carries a reasoningEffort to send",
|
|
not any("reasoningEffort" in v for v in ent["variants"].values()), ent["variants"])
|
|
check("the model levels from the catalog are not offered either",
|
|
not ({"xhigh"} & set(ent["variants"])), ent["variants"])
|
|
nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "mybox.local", "k", "mybox.local")
|
|
check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"])
|
|
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"]))
|
|
|
|
check.done(ROOT)
|