diff --git a/README.md b/README.md index 613e484..3faf03a 100644 --- a/README.md +++ b/README.md @@ -120,31 +120,43 @@ HA's core *OpenAI Conversation* integration only talks to the official OpenAI en so it cannot use forgeway. HA's core **Ollama** integration can: it takes an arbitrary server URL, and its client keeps the URL path, so an endpoint prefix is a valid server. -**Lounge HA — configured and proven 2026-09-18.** Integration entry -`https://forgeway.dmz.lounge.falkvinge.net/local-optimistic`, conversation agent -**`conversation.forgeway_optimistic`** (model `gpt-oss:120b`, think off, no device -control). A real question through HA's own conversation API came back from forge: -*"Home Assistant is an open-source platform for local home automation and smart-device -control."* +**Lounge HA has both privacy flavours, configured and proven 2026-09-18.** Two separate +integration entries on the split-horizon alias, named so that picking one in a dropdown +reads as a data-residency choice rather than a mode name: -Why that URL and not the `.services.` alias: HA lives on the sandbox VLAN -(`192.168.120.0/22`), which **cannot reach the k8s ingress `172.19.10.11`** — the alias -resolves correctly there and then fails to connect. What that VLAN *can* reach is the -entrance HAProxy, whose certificate covers `*.dmz.lounge.falkvinge.net` and which already -has firewall clearance into the `172.19.10.80-98:80` band. So: +| What a dropdown shows (agent) | Entity | Integration entry | Server URL | +|---|---|---|---| +| **Local only — private (fails if forge is down)** | `conversation.forgeway_local_only` | *Forgeway local-strict @ forgeway.services.falkvinge.net — local only, private (fails if forge is down)* | `https://forgeway.services.falkvinge.net/local-strict` | +| **Local preferred — falls back to OpenAI cloud** | `conversation.forgeway_local_preferred` | *Forgeway local-optimistic @ forgeway.services.falkvinge.net — local preferred (falls back to OpenAI cloud)* | `https://forgeway.services.falkvinge.net/local-optimistic` | -``` -forgeway.dmz.lounge.falkvinge.net → entrance HAProxy 172.20.0.101 → 172.19.10.90:80 (HA, and any client HAProxy reaches) -forgeway.services.falkvinge.net → ingress-nginx 172.19.10.11 → forgeway Service (DMZ-side clients, local-first alias) -forgeway.lounge.falkvinge.net → ingress-nginx 172.19.10.11 (explicit per-site name, http) -``` +Both: model `gpt-oss:120b`, think off, no API key, no device control (the *Control Home +Assistant* box is deliberately unticked — ticking it hands the LLM the Assist tools). +Neither is the default assistant; that is *Settings → Voice assistants → Assist → +Conversation agent*. -The entrance is a public edge and the router has no authentication, so the HAProxy vhost -is **fenced to RFC1918 sources** (`http-request deny` for anything else); the router's -own raw Service IP stays unreachable from outside as before. If you would rather HA use -the `.services.` alias, the one-line pfSense change is: pass `192.168.120.12` (or the -sandbox net) → `172.19.10.11` TCP 443. Then re-run `scripts/ha_setup_ollama.py` with the -alias URL. +Proven by behaviour, through HA's own conversation API, not by "the integration loaded": + +| | forge available | forge unavailable (dead-upstream instance, never by stopping Ollama) | +|---|---|---| +| Local only | real answer from forge | HA error, **no answer, no cloud** | +| Local preferred | real answer from forge | real answer in ~1 s, served by gpt-5.4-mini (router log: *falling back to cloud*) | + +The unavailable column was produced by publishing a throwaway forgeway instance with a +dead upstream under a temporary `.services.` name, pointing two temporary HA entries at +it, asking through each, and removing all of it afterwards. + +**Network prerequisites, verified from HA's side.** `.services.` names are internal-only +by convention: `forgeway.services.falkvinge.net` is NXDOMAIN on public DNS and answers +only on the internal `.201` resolvers, so an entry that *loads* proves HA resolved it +internally. HA lives on the sandbox VLAN, which cannot reach the k8s ingress by default; +Rick opened `192.168.120.12 → 172.19.10.11` on pfSense (HA's IP only — the neighbouring +scripthost still cannot connect, as intended). Both entries loaded and answered after +that, which is the proof the rule works. + +**The alternative path**, kept as a documented fallback: `forgeway.dmz.lounge.falkvinge.net` +goes through the entrance HAProxy (`172.20.0.101` → `172.19.10.90:80`), fenced to RFC1918 +sources because that edge is public. It was HA's route before the pfSense rule existed +and needs no rule; it is not used by either entry now. **What HA sends and how it is handled.** `list()` → `/api/tags` with a 5 s timeout, so tags never wait on a model load (a cold `gpt-oss:120b` takes ~25–30 s); the list is @@ -155,18 +167,22 @@ all passed to forge untouched. HA reads `message.content`, `message.thinking`, separately regardless of `think`, so a normal answer is never empty. HA shows the thinking as a collapsible block. -**To make it the default assistant / let it control the house** (your call, in the HA -UI): *Settings → Voice assistants → Assist → Conversation agent → "forgeway optimistic"*; -and on the integration's conversation subentry, tick *Control Home Assistant* to grant -the Assist API (tools). Both were left off deliberately. - -Re-run the setup at any time — it is idempotent and ends with a real conversation: +Managing it headlessly (idempotent; every `setup` ends with a real conversation): ```bash -python3 scripts/ha_setup_ollama.py http://192.168.120.12:8123 \ - https://forgeway.dmz.lounge.falkvinge.net/local-optimistic --name "forgeway optimistic" [--assist] +.venv/bin/python scripts/ha_ollama.py list +.venv/bin/python scripts/ha_ollama.py setup https://forgeway.services.falkvinge.net/local-strict \ + --agent "Local only — private (fails if forge is down)" --title "…" --entity-id conversation.forgeway_local_only +.venv/bin/python scripts/ha_ollama.py ask conversation.forgeway_local_preferred "Is the kitchen light on?" +.venv/bin/python scripts/ha_ollama.py delete ``` +REST config flows create entries and subentries; the WebSocket API renames entries, +devices and entity ids. HA exposes neither `entry.data` (the URL) nor a subentry rename, +so entry titles carry the URL and mode, and the pre-existing optimistic subentry still +reads *Forge Conversation* in the integration's subentry list (rename it in the UI if it +bothers you; the agent name users see is the device/entity name above). + ## The Ollama dialect, and the cloud fallback through it forge *is* Ollama, so on the forge path the router is a raw proxy: the response — diff --git a/REPORT.md b/REPORT.md index 809c70e..d37f632 100644 --- a/REPORT.md +++ b/REPORT.md @@ -356,3 +356,61 @@ corrects an assumption from this morning. Changes made: | Local smoke | `scripts/local-smoke-ollama.sh` (uses `ollama==0.6.2`, the version HA pins) | | Edge vhost | `lounge-haproxy-config` `27ce8e4` | | Cluster repos | `lounge-cluster-config` `c2c2c3e`, `serenity-cluster-config` `f35dc0a` | + +--- + +# Addendum 3, 2026-09-18 late — both privacy flavours in Home Assistant, on the alias + +Rick opened `192.168.120.12 → 172.19.10.11` on pfSense. Both HA Ollama entries now sit on +the split-horizon alias, named so a dropdown reads as a data-residency choice: + +| Agent name (what a dropdown shows) | Entity | Server URL | +|---|---|---| +| **Local only — private (fails if forge is down)** | `conversation.forgeway_local_only` | `https://forgeway.services.falkvinge.net/local-strict` | +| **Local preferred — falls back to OpenAI cloud** | `conversation.forgeway_local_preferred` | `https://forgeway.services.falkvinge.net/local-optimistic` | + +Entry titles: *Forgeway local-strict @ … — local only, private (fails if forge is down)* +and *Forgeway local-optimistic @ … — local preferred (falls back to OpenAI cloud)*. Model +`gpt-oss:120b` on both, no API key, think off, no device control, neither made the +default assistant. The optimistic entry already existed when I started (created on +Rick's side after the pfSense change, agent "Forge Conversation"); I reused it and +renamed entry, device and entity rather than duplicating it. HA has no API to rename a +subentry, so its subentry list still says "Forge Conversation" — cosmetic, UI-renameable. +My earlier `.dmz.lounge` entry was already gone. + +**Created programmatically**, no hands needed: REST config flows for entries and +subentries, WebSocket for renames. One trap found and fixed in the tooling: renaming an +entry triggers a reload, and a subentry flow started during it aborts with +`entry_not_loaded` — wait for `state: loaded` first. + +## Proof by behaviour, through HA's own conversation API + +| | forge available | forge unavailable | +|---|---|---| +| Local only (strict) | *"Home Assistant is an open-source platform that lets you automate and control smart home devices."* (33 s, from forge) | **no answer, no cloud** — HA raised its Ollama error (REST surface: HTTP 500 from the conversation API; the integration logs *Unexpected error talking to Ollama server* with the 503 body per its source — I could not read HA's log to quote it, `/api/error_log` is gone in 2026.9) | +| Local preferred (optimistic) | *"Home Assistant is an open-source home automation platform that lets you control and automate smart devices locally."* (66 s, from forge; pod log shows no fallback) | *"Home Assistant is an open-source home automation platform …"* in **1.3 s**, router log: *falling back to cloud gpt-5.4-mini* | + +The "unavailable" column: a throwaway forgeway instance with upstream `127.0.0.1:1` +published under a temporary `forgeway-deadproof.services.falkvinge.net` (Ingress + a +temporary Technitium CNAME), two temporary HA entries pointed at it, one question through +each, then everything removed — entries, Ingress, Service, Deployment, DNS record. Ollama +on forge was never touched. + +## Route and DNS, verified from HA's side rather than assumed + +- The alias is **NXDOMAIN on 1.1.1.1 and 9.9.9.9** and answers only on `172.19.1.201` / + `172.19.10.201` (→ `ingress.dmz.lounge.falkvinge.net` → `172.19.10.11`). HA's entries + *loading* (which requires `/api/tags` over TLS with the `*.services.` cert) is therefore + proof that HA resolves the name through the internal resolvers. HA's Supervisor API + (which would show the resolver list directly) refuses the long-lived token (401), so + this behavioural proof is the strongest available. +- The pfSense rule covers HA's IP only: the scripthost on the same VLAN still cannot + connect to `172.19.10.11`. Intended, and a useful negative control. +- The entrance-HAProxy path via `forgeway.dmz.lounge.falkvinge.net` stays as a documented, + fenced alternative; nothing uses it now. Say the word and I remove the vhost and record. + +## Nothing left for Rick unless wanted + +- Default assistant: *Settings → Voice assistants → Assist → Conversation agent*. +- Device control: tick *Control Home Assistant* on a subentry (deliberately off). +- Cosmetic: rename the optimistic subentry "Forge Conversation" in the UI. diff --git a/scripts/ha_ollama.py b/scripts/ha_ollama.py new file mode 100644 index 0000000..48a9a43 --- /dev/null +++ b/scripts/ha_ollama.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Manage Home Assistant's Ollama integration entries for forgeway, headlessly. + + ha_ollama.py setup --agent "" --title "" [--entity-id conversation.x] [--assist] + ha_ollama.py ask "" + ha_ollama.py list + ha_ollama.py delete + +`setup` is idempotent (same URL → same entry; same agent name → same subentry) and +ends with a REAL conversation through the new agent, printed verbatim. REST drives the +config flows; the WebSocket API renames the entry and the entity id. The long-lived +token comes from `pass hassio/lounge-token` inside this process and only ever travels +as a header. HA base URL: --ha (default http://192.168.120.12:8123). +""" +from __future__ import annotations + +import argparse +import asyncio +import json +import subprocess +import sys +import time +import urllib.error +import urllib.request + +import websockets + + +def token() -> str: + return subprocess.run(["pass", "hassio/lounge-token"], capture_output=True, text=True, check=True).stdout.strip() + + +class HA: + def __init__(self, base: str): + self.base = base.rstrip("/") + self.tok = token() + + def rest(self, method: str, path: str, body: dict | None = None): + req = urllib.request.Request( + f"{self.base}{path}", + data=json.dumps(body).encode() if body is not None else None, + headers={"Authorization": f"Bearer {self.tok}", "Content-Type": "application/json"}, + method=method, + ) + try: + with urllib.request.urlopen(req, timeout=180) as r: + raw = r.read().decode() + try: + return r.status, json.loads(raw) + except ValueError: + return r.status, raw + except urllib.error.HTTPError as e: + raw = e.read().decode("utf-8", "replace") + try: + return e.code, json.loads(raw) + except ValueError: + return e.code, raw + + async def ws(self, *commands: dict) -> list[dict]: + url = self.base.replace("https://", "wss://").replace("http://", "ws://") + "/api/websocket" + out = [] + async with websockets.connect(url, max_size=16_000_000) as sock: + await sock.recv() + await sock.send(json.dumps({"type": "auth", "access_token": self.tok})) + if json.loads(await sock.recv()).get("type") != "auth_ok": + raise SystemExit("websocket auth failed") + for i, cmd in enumerate(commands, start=1): + await sock.send(json.dumps({"id": i, **cmd})) + while True: + msg = json.loads(await sock.recv()) + if msg.get("id") == i: + out.append(msg) + break + return out + + # ---- helpers ------------------------------------------------------------ + def entries(self) -> list[dict]: + """Ollama entries with their subentries (REST lists entries; only the + WebSocket API lists subentries; HA never exposes entry.data/url).""" + st, full = self.rest("GET", "/api/config/config_entries/entry") + ents = [e for e in full if e["domain"] == "ollama"] + cmds = [{"type": "config_entries/subentries/list", "entry_id": e["entry_id"]} for e in ents] + subs = asyncio.run(self.ws(*cmds)) if cmds else [] + for e, r in zip(ents, subs): + e["subentries"] = r.get("result") or [] + return ents + + def entry_for(self, url: str) -> dict | None: + """Match by title == url (fresh entries) or by the mode token we always + put in our titles ('local-strict' / 'local-optimistic') on the same host.""" + mode = url.rstrip("/").rsplit("/", 1)[-1] + host = url.split("//", 1)[-1].split("/", 1)[0] + for e in self.entries(): + t = e.get("title", "") + if t == url or (mode in t and host in t): + return e + return None + + def wait_loaded(self, entry_id: str, timeout: float = 90) -> str: + """Creating or renaming an entry (re)loads it asynchronously; a subentry + flow started meanwhile aborts with entry_not_loaded.""" + deadline = time.time() + timeout + state = "?" + while time.time() < deadline: + st, full = self.rest("GET", "/api/config/config_entries/entry") + e = next((x for x in full if x["entry_id"] == entry_id), None) + state = e["state"] if e else "missing" + if state == "loaded": + return state + time.sleep(2) + return state + + def conversation_entities(self) -> list[dict]: + r = asyncio.run(self.ws({"type": "config/entity_registry/list"}))[0].get("result", []) + return [x for x in r if x["entity_id"].startswith("conversation.")] + + +# --------------------------------------------------------------------------- + +def cmd_setup(ha: HA, a: argparse.Namespace) -> int: + url = a.forgeway_url.rstrip("/") + entry = ha.entry_for(url) + if entry: + print(f"[entry] reusing {entry['entry_id'][:8]} '{entry['title']}' ({entry['state']})") + else: + st, flow = ha.rest("POST", "/api/config/config_entries/flow", {"handler": "ollama"}) + if st != 200 or flow.get("type") != "form": + print(f"[entry] cannot start config flow: {st} {flow}") + return 1 + st, res = ha.rest("POST", f"/api/config/config_entries/flow/{flow['flow_id']}", {"url": url}) + if res.get("type") != "create_entry": + # HA validated the URL by calling /api/tags with a 5 s timeout + print(f"[entry] flow did not create an entry: {st} {json.dumps(res)[:400]}") + return 1 + entry = res["result"] + print(f"[entry] created {entry['entry_id'][:8]} for {url}") + entry_id = entry["entry_id"] + + if a.title and entry.get("title") != a.title: + r = asyncio.run(ha.ws({"type": "config_entries/update", "entry_id": entry_id, "title": a.title}))[0] + print(f"[entry] title → {a.title!r}: {'ok' if r.get('success') else r.get('error')}") + + state = ha.wait_loaded(entry_id) + if state != "loaded": + print(f"[entry] not loaded (state={state}); HA could not talk to {url}/api/tags") + return 1 + + # conversation subentry + entry = next(e for e in ha.entries() if e["entry_id"] == entry_id) + subs = entry.get("subentries") or [] + sub = next((s for s in subs if s.get("subentry_type") == "conversation" and s.get("title") == a.agent), None) + if sub: + print(f"[agent] reusing subentry '{a.agent}'") + else: + st, flow = ha.rest("POST", "/api/config/config_entries/subentries/flow", {"handler": [entry_id, "conversation"]}) + if st != 200 or flow.get("type") != "form": + print(f"[agent] cannot start subentry flow: {st} {json.dumps(flow)[:300]}") + return 1 + listed = [o["value"] for f in flow.get("data_schema", []) if f.get("name") == "model" + for o in (f.get("selector", {}).get("select", {}).get("options") or []) if isinstance(o, dict)] + print(f"[agent] models HA fetched from forgeway: {[m for m in listed if 'gpt-oss' in m] or listed[:3]}") + data = {"name": a.agent, "model": a.model, "num_ctx": 8192, "max_history": 20, "keep_alive": -1, "think": False} + if a.assist: + data["llm_hass_api"] = ["assist"] + st, res = ha.rest("POST", f"/api/config/config_entries/subentries/flow/{flow['flow_id']}", data) + if res.get("type") != "create_entry": + print(f"[agent] subentry flow failed: {st} {json.dumps(res)[:400]}") + return 1 + print(f"[agent] created '{a.agent}' (model {a.model}, think=False, assist={a.assist})") + + # entity: the registry leaves name/original_name empty for these entities + # (entity name = device name), so match on the subentry id — exact. + entry = next(e for e in ha.entries() if e["entry_id"] == entry_id) + sub = next((s for s in entry.get("subentries") or [] if s.get("subentry_type") == "conversation" and s.get("title") == a.agent), None) + entity_id = None + for _ in range(40): + for x in ha.conversation_entities(): + if sub and x.get("config_subentry_id") == sub["subentry_id"]: + entity_id = x["entity_id"] + if entity_id: + break + time.sleep(2) + if not entity_id: + print("[entity] conversation entity did not appear") + return 1 + if a.entity_id and entity_id != a.entity_id: + r = asyncio.run(ha.ws({"type": "config/entity_registry/update", "entity_id": entity_id, "new_entity_id": a.entity_id}))[0] + if r.get("success"): + entity_id = a.entity_id + time.sleep(2) + print(f"[entity] id → {a.entity_id}: {'ok' if r.get('success') else r.get('error')}") + print(f"[entity] {entity_id}") + return cmd_ask(ha, argparse.Namespace(agent_entity_id=entity_id, question=a.question)) + + +def cmd_ask(ha: HA, a: argparse.Namespace) -> int: + started = time.perf_counter() + st, res = ha.rest("POST", "/api/conversation/process", {"text": a.question, "agent_id": a.agent_entity_id, "language": "en"}) + took = time.perf_counter() - started + resp = res.get("response", {}) if isinstance(res, dict) else {} + speech = ((resp.get("speech") or {}).get("plain") or {}).get("speech") + rtype = resp.get("response_type") + code = (resp.get("data") or {}).get("code") + print(f"[ask] {a.agent_entity_id}: HTTP {st} response_type={rtype}{' code=' + code if code else ''} took={took:.1f}s") + print(f"[ask] Q: {a.question}") + print(f"[ask] A: {speech!r}") + return 0 if st == 200 and speech and rtype != "error" else 2 + + +def cmd_list(ha: HA, a: argparse.Namespace) -> int: + for e in ha.entries(): + print(f"{e['entry_id'][:8]} {e['state']:<10} {e['title']}") + for s in e.get("subentries") or []: + print(f" └─ {s['subentry_type']}: {s['title']}") + for x in ha.conversation_entities(): + print(f"entity {x['entity_id']} ({x.get('name') or x.get('original_name')})") + return 0 + + +def cmd_delete(ha: HA, a: argparse.Namespace) -> int: + url = a.forgeway_url.rstrip("/") + entry = ha.entry_for(url) + if not entry: + print(f"[delete] no entry for {url}") + return 0 + st, res = ha.rest("DELETE", f"/api/config/config_entries/entry/{entry['entry_id']}") + print(f"[delete] {entry['entry_id'][:8]} '{entry['title']}': HTTP {st} {json.dumps(res)[:100]}") + return 0 if st == 200 else 1 + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--ha", default="http://192.168.120.12:8123") + sub = ap.add_subparsers(dest="cmd", required=True) + s = sub.add_parser("setup"); s.add_argument("forgeway_url"); s.add_argument("--agent", required=True) + s.add_argument("--title"); s.add_argument("--entity-id"); s.add_argument("--model", default="gpt-oss:120b") + s.add_argument("--assist", action="store_true"); s.add_argument("--question", default="In one short sentence, what is Home Assistant?") + q = sub.add_parser("ask"); q.add_argument("agent_entity_id"); q.add_argument("question") + sub.add_parser("list") + d = sub.add_parser("delete"); d.add_argument("forgeway_url") + a = ap.parse_args() + ha = HA(a.ha) + return {"setup": cmd_setup, "ask": cmd_ask, "list": cmd_list, "delete": cmd_delete}[a.cmd](ha, a) + + +if __name__ == "__main__": + raise SystemExit(main())