Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(home-bridge): connect a three.ws agent to a real Home Assistant instance
nirholas480d8d7db7d5
diff --git a/docs/smart-home.md b/docs/smart-home.mdnew file mode 100644index 000000000..a6791f35e--- /dev/null+++ b/docs/smart-home.md@@ -0,0 +1,239 @@+# three.ws Home: the agent as the interface to your physical space++**Status:** research complete, architecture decided, implementation staged.+**Date:** 2026-09-02.+**Question asked:** can the three.ws 3D agent control a real home, and how much of it already exists in open source?++**Short answer:** almost all of it exists, and it is better than anything we would write.+Home Assistant already owns the device layer (90k stars, 1,500+ integrations, every+protocol we would otherwise implement) and, since the `mcp_server` integration, it speaks+Model Context Protocol natively. three.ws already speaks MCP in 40+ packages. The two+halves meet without either side inventing a protocol.++What is genuinely missing in the world, and what three.ws is uniquely positioned to build,+is the **face**: a real-time 3D presence that stands in a live model of your home, reacts+to it, and talks to you. Nobody ships that. That is the part we build.++---++## 1. Why this is not a side quest++Read the current product in one line: three.ws gives an AI a body, a voice, memory, and an+identity. Every one of those is currently confined to a browser tab.++A smart home is the first place where all four pay off at once:++- **Body**: a home has rooms and objects. An agent with a 3D presence can *be somewhere* in+ it rather than being a text box.+- **Voice**: hands-free is the only interface that works when you are carrying groceries.+ Voice is already the weakest-value feature on a website and the highest-value feature in+ a kitchen.+- **Memory**: "the usual" only means something to an agent that remembers your evenings.+- **Identity**: a household agent that persists across devices and rooms is exactly the+ agent-identity story we already tell on-chain.++It is also the natural bridge to the rest of the list (cars, offices, hotels, robots),+because every one of those already speaks the same protocols the home does.++---++## 2. The landscape, measured++All figures pulled from the GitHub API on 2026-09-02. Nothing here is quoted from a blog post.++### Device control layer++| Project | Stars | License | Last push | Language | Verdict |+|---|---|---|---|---|---|+| [home-assistant/core](https://github.com/home-assistant/core) | 90,225 | Apache-2.0 | 2026-09-02 | Python | **Adopt.** The device layer. 1,500+ integrations, local-first, already installed in millions of homes. |+| [homebridge/homebridge](https://github.com/homebridge/homebridge) | 25,472 | Apache-2.0 | 2026-08-30 | TypeScript | Skip. HomeKit-shaped; HA covers its device set and more. |+| [node-red/node-red](https://github.com/node-red/node-red) | 23,614 | Apache-2.0 | 2026-09-01 | JavaScript | Skip as a dependency. It is the automation UI we are replacing with natural language. |+| [Koenkk/zigbee2mqtt](https://github.com/Koenkk/zigbee2mqtt) | 15,592 | GPL-3.0 | 2026-09-02 | TypeScript | Indirect. Users run it; we reach it through HA. GPL keeps it out of our process anyway. |+| [esphome/esphome](https://github.com/esphome/esphome) | 11,628 | Apache-2.0 + GPL | 2026-09-02 | C++ | Indirect, and the DIY-hardware on-ramp later. |+| [project-chip/connectedhomeip](https://github.com/project-chip/connectedhomeip) | 8,916 | Apache-2.0 | 2026-09-02 | C++ | Reference only. The Matter spec implementation, C++, not our runtime. |+| [openhab/openhab-core](https://github.com/openhab/openhab-core) | 1,137 | EPL-2.0 | 2026-09-01 | Java | Skip. Real, mature, and an order of magnitude smaller in reach than HA. |+| [matter-js/matter.js](https://github.com/matter-js/matter.js) | 894 | Apache-2.0 | 2026-09-02 | TypeScript | **Phase 3.** A full Matter controller *and device* implementation in TypeScript. HA is migrating its own Matter integration onto it. This is how three.ws eventually talks to devices with no hub at all, and how a three.ws agent can *present itself* as a Matter device. |+| [zwave-js/zwave-js](https://github.com/zwave-js/zwave-js) | 887 | MIT | 2026-09-02 | TypeScript | Indirect. HA's Z-Wave layer is already this. |+| [Luligu/matterbridge](https://github.com/Luligu/matterbridge) | 963 | Apache-2.0 | 2026-09-02 | TypeScript | Reference. Best worked example of matter.js in the "expose things as Matter devices" direction. |++### Agent-to-home bridge++| Project | Stars | License | Last push | Verdict |+|---|---|---|---|---|+| [Home Assistant `mcp_server`](https://www.home-assistant.io/integrations/mcp_server/) | in core | Apache-2.0 | shipping | **Adopt.** First-party. Exposes `/api/mcp` over streamable HTTP, authenticated by OAuth (IndieAuth, no pre-registered client id, the client id is just our base URL) or a long-lived access token. This is the single most important finding in this document. |+| [home-assistant/home-assistant-js-websocket](https://github.com/home-assistant/home-assistant-js-websocket) | 410 | Apache-2.0 | 2026-08-31 | **Adopt.** First-party JS client, zero dependencies, auto-reconnect, auto-resubscribe. MCP gives us *actions*; this gives us the *live state stream* the 3D scene needs. |+| [homeassistant-ai/ha-mcp](https://github.com/homeassistant-ai/ha-mcp) | 4,601 | MIT | 2026-09-02 | Reference. The best third-party HA MCP server; useful as a tool-design reference, but adding a Python hop between us and a first-party endpoint is strictly worse. |+| [tevonsb/homeassistant-mcp](https://github.com/tevonsb/homeassistant-mcp) | 575 | Apache-2.0 | 2026-01-25 | Skip. Stalled since January. |++### Voice layer++| Project | Stars | License | Last push | Verdict |+|---|---|---|---|---|+| [pipecat-ai/pipecat](https://github.com/pipecat-ai/pipecat) | 15,144 | BSD-2 | 2026-09-02 | Reference. Python; our voice loop is already in the browser. |+| [livekit/livekit](https://github.com/livekit/livekit) + [livekit/agents](https://github.com/livekit/agents) | 20,660 / 13,966 | Apache-2.0 | 2026-09-02 | **Phase 4 candidate** for always-on room audio at scale. Not needed for v1. |+| [SYSTRAN/faster-whisper](https://github.com/SYSTRAN/faster-whisper) | 25,200 | MIT | 2025-11-19 | Indirect. This is what a local HA Assist pipeline already runs for STT. |+| [OHF-Voice/piper1-gpl](https://github.com/OHF-Voice/piper1-gpl) | 5,432 | GPL-3.0 | 2026-08-29 | Indirect, and GPL. Runs inside the user's HA, never inside our process. |+| [snakers4/silero-vad](https://github.com/snakers4/silero-vad) | 10,111 | MIT | 2026-08-24 | **Adopt** for barge-in in the browser voice loop. |+| [dscripka/openWakeWord](https://github.com/dscripka/openWakeWord) | 2,727 | Apache-2.0 | 2025-12-30 | Adopt for a browser wake word ("hey <agent name>"). |+| [rhasspy/wyoming-satellite](https://github.com/rhasspy/wyoming-satellite) | 1,244 | MIT | 2026-01-24 | **Adopt the protocol, not the code.** Wyoming is a tiny TCP + JSONL protocol. Speaking it makes the three.ws avatar a first-class HA voice satellite. |++### Adjacent, worth knowing++[blakeblackshear/frigate](https://github.com/blakeblackshear/frigate) (35,578, MIT) for camera+events, [ExperienceLovelace/ha-floorplan](https://github.com/ExperienceLovelace/ha-floorplan)+(1,601, Apache-2.0) as the closest prior art to our 3D scene and proof that the 2D version of+the idea already has an audience, and [hacs/integration](https://github.com/hacs/integration)+(7,674, MIT) as the distribution channel for any custom HA component we ship.++---++## 3. The decision++### Adopt outright++1. **Home Assistant as the device layer.** We write zero device drivers. Not one. Zigbee,+ Z-Wave, Matter, Thread, BLE, cloud APIs, IR blasters, the long tail of 1,500 integrations:+ that is a decade of work by 10,000 contributors and it is already in the user's house.+2. **`mcp_server` for actions.** The user's home becomes just another MCP server in an+ ecosystem where we already run 40+ of them. No new wire format, no new auth story, no+ custom command schema, and every capability the user exposes to their own LLM is exposed+ to their three.ws agent with identical permissions.+3. **`home-assistant-js-websocket` for state.** MCP is request/response. A living 3D scene+ needs a push stream. This library is first-party, dependency-free, and reconnects itself.+4. **HA scenes and scripts for macros.** "Good night" and "I'm leaving" are not new concepts+ we invent. They are `scene.turn_on` and `script.turn_on`, already modelled, already+ editable by the user in an interface they know. Our agent resolves intent to an existing+ scene, and only falls back to composing individual calls when no scene fits.++### Explicitly do not build++- A device driver, of any kind, for anything.+- A hub, a broker, or an automation rules engine.+- Another HA MCP server. The first-party one exists.+- A local speech stack. The user's HA already runs Whisper and Piper locally, or their+ browser already runs ours.++### What we build, because nobody has++1. **The live 3D home.** The agent standing in a scene that *is* the house: lights that dim+ when the real lights dim, a door that shows locked, a thermostat reading the real+ temperature. Everyone who has done this shipped a flat SVG floorplan. We already ship a+ Three.js renderer, an avatar pipeline, and a physics-capable scene. This is the thing+ people screenshot.+2. **The avatar as a Wyoming satellite.** Today an HA voice assistant is a speaker with an+ LED ring. Point an HA pipeline at a three.ws agent and it gains a face, an expression,+ lip sync, and a body that turns toward you. That is a genuinely new product for 90k+ stars' worth of existing users, and it is a distribution channel, not just a feature.+3. **Home as agent memory.** An agent that remembers your house across sessions, and whose+ on-chain identity is the same identity that holds its wallet and its skills, is a+ different object from a voice assistant. This is where the rest of the platform pays off.++---++## 4. Architecture++```+ three.ws agent (browser: 3D avatar, voice loop, lip sync)+ |+ | 1. actions 2. live state 3. voice+ v v v+ +--------------+ +------------------------+ +-------------------++ | MCP client | | WS state subscriber | | Wyoming endpoint |+ | @mcp/sdk | | home-assistant-js-ws | | (we speak it) |+ +------+-------+ +-----------+------------+ +---------+---------++ | | |+ +-----------+-----------+--------------------------++ v+ Home Assistant ( /api/mcp , /api/websocket )+ |+ Zigbee | Z-Wave | Matter | Thread | BLE | Wi-Fi | 1,500 integrations+```++**Three independent channels, one connection record.** A home is stored once (base URL plus+credential); the three channels are three views of it. Losing one does not break the others:+if MCP is unreachable the scene still renders live state, and if the state socket drops the+agent can still act.++### Reachability, stated honestly++Home Assistant lives on a LAN. three.ws runs in the cloud and is served over HTTPS, so a+browser tab cannot open `http://homeassistant.local:8123` (mixed content), and our servers+cannot route to RFC1918 space. This is the real engineering constraint and it has three+honest answers, in order of preference:++1. **Remote HTTPS URL.** Home Assistant Cloud, or the user's own reverse proxy or tunnel.+ Works today with a long-lived token, zero new code on their side. This is v1.+2. **Browser-local direct connect.** For users who open three.ws from inside their own+ network, over a local HTTPS origin. Narrow, but zero-latency and fully private.+3. **A three.ws HA add-on that dials out.** A small custom component that opens an outbound+ WebSocket to three.ws and relays the two channels. This is the only option that works for+ an untouched LAN-only install, it is the one that ships through HACS, and it is phase 2.++We will not pretend option 1 covers everyone, and we will not ship option 3 as a stub.++### Permission model++Non-negotiable, and it borrows the shape of the existing on-chain spend gate: **an action+that changes physical state in a home is confirmed, not inferred.** Reads are free. Writes+are scoped to what the user exposed to the LLM API in Home Assistant itself (HA already has+this control, so we inherit it rather than inventing a parallel one). Locks, garage doors,+alarm panels, and anything HA marks as a security entity require an explicit confirmation+every time until the user grants a standing allowance per entity. A voice channel that can+unlock a front door on a misheard phoneme is not a feature, and the first-party HA exposure+setting is the correct place for that boundary to live.++---++## 5. Build plan++Each phase is shippable on its own and none of them block on the next.++**Phase 1: connect and act.**+`packages/home-bridge/` holds one client with the two channels (MCP over+`@modelcontextprotocol/sdk`, which is already a dependency at `^1.29.0`, and state over+`home-assistant-js-websocket`). A home connection record, a `/home` connect flow that takes+a base URL and a long-lived token, and the home tools registered into the existing agent+tool catalog. Verified against a real Home Assistant instance in Docker, not a fixture.++**Phase 2: the 3D home.** `/home` renders a live scene from the entity registry: areas+become rooms, lights become lights, and the agent stands in it. Scene lighting is driven by+real light state. This is the phase that produces the screenshot.++**Phase 3: voice, both directions.** The browser voice loop gains wake word and barge-in+(openWakeWord, silero-vad). Separately, we speak Wyoming so a Home Assistant pipeline can+select a three.ws agent as its satellite and get a face.++**Phase 4: past the house.** matter.js lets an agent be a Matter controller with no hub, and+lets a three.ws agent present itself as a Matter device. That is the door to cars, offices,+and robots, and it is the same protocol either way.++---++## 6. Licensing++Everything we take into our own process is permissive: Apache-2.0 (Home Assistant, the JS+WebSocket client, matter.js, openWakeWord), MIT (Wyoming's reference implementation,+silero-vad), BSD-2 (pipecat, if we ever use it). The GPL-licensed pieces in this space+(zigbee2mqtt, Piper) run inside the user's own Home Assistant and are reached over a network+boundary, which is exactly where they belong. No copyleft enters the three.ws build.++One obligation we do take on: this plan is built on the back of a very large volunteer+project. The "open source first" rule in `CLAUDE.md` says we are participants, not+extractors. Anything we fix in `home-assistant-js-websocket` or matter.js goes upstream, and+the HA add-on in phase 2 ships publicly through HACS rather than only to our own users.++---++## Sources++- [home-assistant/core](https://github.com/home-assistant/core)+- [Home Assistant: Model Context Protocol Server integration](https://www.home-assistant.io/integrations/mcp_server/)+- [Home Assistant: Model Context Protocol integration](https://www.home-assistant.io/integrations/mcp/)+- [home-assistant/home-assistant-js-websocket](https://github.com/home-assistant/home-assistant-js-websocket)+- [Home Assistant WebSocket API reference](https://developers.home-assistant.io/docs/api/websocket/)+- [matter-js/matter.js](https://github.com/matter-js/matter.js) and [`@matter/main` on npm](https://www.npmjs.com/package/@matter/main)+- [rhasspy/wyoming-satellite](https://github.com/rhasspy/wyoming-satellite)+- [Home Assistant: about wake words](https://www.home-assistant.io/voice_control/about_wake_word/)+- [dscripka/openWakeWord](https://github.com/dscripka/openWakeWord), [snakers4/silero-vad](https://github.com/snakers4/silero-vad)+- [pipecat-ai/pipecat](https://github.com/pipecat-ai/pipecat), [livekit/agents](https://github.com/livekit/agents)+- [ExperienceLovelace/ha-floorplan](https://github.com/ExperienceLovelace/ha-floorplan)diff --git a/package-lock.json b/package-lock.jsonindex 4b2245065..d02ca928d 100644--- a/package-lock.json+++ b/package-lock.json@@ -69,7 +69,8 @@"packages/glb-diff","packages/witness","packages/portal",- "packages/tty-avatar"+ "packages/tty-avatar",+ "packages/home-bridge"],"dependencies": {"@0xsplits/splits-sdk": "^6.5.0",@@ -16688,6 +16689,10 @@"resolved": "packages/glb-diff","link": true},+ "node_modules/@three-ws/home-bridge": {+ "resolved": "packages/home-bridge",+ "link": true+ },"node_modules/@three-ws/ibm-watsonx-mcp": {"resolved": "packages/ibm-watsonx-mcp","link": true@@ -25820,6 +25825,12 @@"react-is": "^16.7.0"}},+ "node_modules/home-assistant-js-websocket": {+ "version": "9.6.0",+ "resolved": "https://registry.npmjs.org/home-assistant-js-websocket/-/home-assistant-js-websocket-9.6.0.tgz",+ "integrity": "sha512-TK8HWW6UjCsUdjIBQRB2sBbEya0VniOBFqFjgqSznJiB7YriNgN8jghyThxOkgxwrnt2eN6oWoZMCTSp1o7H+w==",+ "license": "Apache-2.0"+ },"node_modules/hono": {"version": "4.13.0","license": "MIT",@@ -40341,6 +40352,25 @@}}},+ "packages/home-bridge": {+ "name": "@three-ws/home-bridge",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "home-assistant-js-websocket": "^9.6.0"+ },+ "engines": {+ "node": ">=20"+ },+ "peerDependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0"+ },+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": true+ }+ }+ },"packages/ibm-watsonx-mcp": {"name": "@three-ws/ibm-watsonx-mcp","version": "0.2.1",diff --git a/package.json b/package.jsonindex 2d3ab42e1..59a13c999 100644--- a/package.json+++ b/package.json@@ -125,7 +125,8 @@"packages/glb-diff","packages/witness","packages/portal",- "packages/tty-avatar"+ "packages/tty-avatar",+ "packages/home-bridge"],"main": "src/app.js","browserslist": [diff --git a/packages/home-bridge/package.json b/packages/home-bridge/package.jsonnew file mode 100644index 000000000..d2e78ed8e--- /dev/null+++ b/packages/home-bridge/package.json@@ -0,0 +1,57 @@+{+ "name": "@three-ws/home-bridge",+ "version": "0.1.0",+ "description": "Connect a three.ws agent to a real Home Assistant instance: live entity state, safe service calls, a room graph for the 3D scene, and the optional Model Context Protocol capability channel.",+ "keywords": [+ "home-assistant",+ "smart-home",+ "iot",+ "agent",+ "mcp",+ "model-context-protocol",+ "voice",+ "3d",+ "three.ws"+ ],+ "author": "three.ws <[email protected]> (https://three.ws)",+ "license": "Apache-2.0",+ "homepage": "https://three.ws",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/nirholas/three.ws.git",+ "directory": "packages/home-bridge"+ },+ "type": "module",+ "main": "./src/index.js",+ "module": "./src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src",+ "README.md"+ ],+ "scripts": {+ "test": "vitest run --root ../.. packages/home-bridge/tests"+ },+ "dependencies": {+ "home-assistant-js-websocket": "^9.6.0"+ },+ "peerDependencies": {+ "@modelcontextprotocol/sdk": "^1.29.0"+ },+ "peerDependenciesMeta": {+ "@modelcontextprotocol/sdk": {+ "optional": true+ }+ },+ "engines": {+ "node": ">=20"+ },+ "bugs": {+ "url": "https://github.com/nirholas/three.ws/issues"+ },+ "publishConfig": {+ "access": "public"+ }+}diff --git a/packages/home-bridge/src/bridge.js b/packages/home-bridge/src/bridge.jsnew file mode 100644index 000000000..f736b9293--- /dev/null+++ b/packages/home-bridge/src/bridge.js@@ -0,0 +1,280 @@+import {+ callService,+ createConnection,+ createLongLivedTokenAuth,+ ERR_CANNOT_CONNECT,+ ERR_CONNECTION_LOST,+ ERR_INVALID_AUTH,+ ERR_INVALID_HTTPS_TO_HTTP,+ subscribeEntities,+} from 'home-assistant-js-websocket';++import { ERR, HomeBridgeError } from './errors.js';+import { resolveIntent } from './intents.js';+import { buildHomeGraph, domainOf } from './rooms.js';+import { classifyCall, createAllowList } from './safety.js';+import { normalizeBaseUrl } from './url.js';++/**+ * One live connection to one home.+ *+ * The state channel is Home Assistant's own WebSocket API through the+ * first-party `home-assistant-js-websocket` client, which reconnects and+ * resubscribes on its own. Everything above it (the room graph, the safety+ * gate, intent resolution) is a pure function of what arrives on that socket,+ * so a reconnect restores the whole surface without special cases.+ */+export class HomeBridge {+ #options;+ #connection = null;+ #unsubscribers = [];+ #states = {};+ #registries = { floors: [], areas: [], devices: [], entities: [] };+ #graph = { floors: [], rooms: [], unassigned: [] };+ #listeners = new Map();+ #rebuildTimer = null;+ #closed = false;++ /**+ * @param {object} options+ * @param {string} options.baseUrl the home's base URL, as the user typed it+ * @param {string} options.token a Home Assistant long-lived access token+ * @param {boolean} [options.requireSecure] reject plain http for remote hosts+ * @param {string[]} [options.allowedEntities] entities pre-approved for guarded actions+ * @param {number} [options.rebuildDelayMs] coalescing window for graph rebuilds+ */+ constructor(options) {+ const { http } = normalizeBaseUrl(options?.baseUrl, { requireSecure: options?.requireSecure });+ if (!options?.token) throw new HomeBridgeError(ERR.AUTH, 'A Home Assistant long-lived access token is required.');+ this.#options = { ...options, baseUrl: http, rebuildDelayMs: options.rebuildDelayMs ?? 80 };+ this.allowList = createAllowList(options.allowedEntities || []);+ }++ get baseUrl() {+ return this.#options.baseUrl;+ }++ get connected() {+ return Boolean(this.#connection?.connected);+ }++ /** The room graph the 3D scene renders. Rebuilt on every state burst. */+ get graph() {+ return this.#graph;+ }++ /** Raw entity states, keyed by entity id. */+ get states() {+ return this.#states;+ }++ on(event, handler) {+ if (!this.#listeners.has(event)) this.#listeners.set(event, new Set());+ this.#listeners.get(event).add(handler);+ return () => this.off(event, handler);+ }++ off(event, handler) {+ this.#listeners.get(event)?.delete(handler);+ }++ #emit(event, payload) {+ for (const handler of this.#listeners.get(event) || []) {+ try {+ handler(payload);+ } catch (err) {+ // A listener that throws must not take the socket down with it.+ if (event !== 'error') this.#emit('error', err);+ }+ }+ }++ /** Opens the state channel and loads the registries. Resolves once the graph is ready. */+ async connect() {+ if (this.#closed) throw new HomeBridgeError(ERR.NOT_CONNECTED, 'This bridge was closed. Create a new one.');+ if (this.#connection) return this.#graph;++ const auth = createLongLivedTokenAuth(this.#options.baseUrl, this.#options.token);+ try {+ this.#connection = await createConnection({ auth });+ } catch (err) {+ throw toBridgeError(err, this.#options.baseUrl);+ }++ this.#connection.addEventListener('ready', () => this.#emit('reconnected', undefined));+ this.#connection.addEventListener('disconnected', () => this.#emit('disconnected', undefined));++ this.#registries = await this.#loadRegistries();+ this.#unsubscribers.push(+ subscribeEntities(this.#connection, (entities) => {+ this.#states = entities;+ this.#scheduleRebuild();+ }),+ );++ await this.#waitForFirstStates();+ this.#rebuild();+ this.#emit('ready', this.#graph);+ return this.#graph;+ }++ async #waitForFirstStates() {+ if (Object.keys(this.#states).length) return;+ await new Promise((resolve) => {+ const timer = setTimeout(resolve, 5000);+ const stop = this.on('graph', () => {+ clearTimeout(timer);+ stop();+ resolve();+ });+ });+ }++ async #loadRegistries() {+ // floor_registry landed after the other three. An instance without it is+ // not broken, it just has no floors, so a failure here degrades to [].+ const [floors, areas, devices, entities] = await Promise.all([+ this.#list('config/floor_registry/list'),+ this.#list('config/area_registry/list'),+ this.#list('config/device_registry/list'),+ this.#list('config/entity_registry/list'),+ ]);+ return { floors, areas, devices, entities };+ }++ async #list(type) {+ try {+ const result = await this.#connection.sendMessagePromise({ type });+ return Array.isArray(result) ? result : [];+ } catch {+ return [];+ }+ }++ #scheduleRebuild() {+ if (this.#rebuildTimer) return;+ this.#rebuildTimer = setTimeout(() => {+ this.#rebuildTimer = null;+ this.#rebuild();+ }, this.#options.rebuildDelayMs);+ }++ #rebuild() {+ this.#graph = buildHomeGraph({ ...this.#registries, states: this.#states });+ this.#emit('graph', this.#graph);+ }++ /**+ * Call a Home Assistant service, subject to the physical-action gate.+ *+ * @param {string} domain e.g. "light"+ * @param {string} service e.g. "turn_on"+ * @param {object} [data] service data, including entity_id+ * @param {{ confirmed?: boolean }} [options] confirmed:true is the user's+ * explicit yes for a guarded action. Never set it from model output.+ */+ async call(domain, service, data = {}, options = {}) {+ this.#assertConnected();+ const entityId = firstEntityId(data);+ const verdict = classifyCall({+ domain,+ service,+ entityId,+ attributes: entityId ? this.#states[entityId]?.attributes : undefined,+ });++ if (verdict.guarded && !options.confirmed && !(entityId && this.allowList.has(entityId))) {+ const err = new HomeBridgeError(ERR.NEEDS_CONFIRMATION, verdict.reason);+ err.pending = { domain, service, data, risk: verdict.risk, entityId };+ throw err;+ }++ try {+ return await callService(this.#connection, domain, service, data);+ } catch (err) {+ throw toBridgeError(err, this.#options.baseUrl, `${domain}.${service} failed.`);+ }+ }++ /** Every scene and script in the house, as intent candidates. */+ macros() {+ const out = [];+ for (const [entityId, state] of Object.entries(this.#states)) {+ const domain = domainOf(entityId);+ if (domain !== 'scene' && domain !== 'script') continue;+ out.push({+ entityId,+ name: state.attributes?.friendly_name || entityId,+ kind: domain,+ aliases: [],+ });+ }+ return out.sort((a, b) => a.name.localeCompare(b.name));+ }++ /**+ * "Good night" to a real scene in this house, then run it.+ *+ * @param {string} phrase+ * @param {{ confirmed?: boolean, dryRun?: boolean }} [options]+ * @returns {Promise<{ ran: boolean, match: object|null }>}+ */+ async activate(phrase, options = {}) {+ this.#assertConnected();+ const match = resolveIntent(phrase, this.macros());+ if (!match) return { ran: false, match: null };+ if (options.dryRun) return { ran: false, match };+ await this.call(match.kind, 'turn_on', { entity_id: match.entityId }, options);+ return { ran: true, match };+ }++ #assertConnected() {+ if (!this.#connection || this.#closed) {+ throw new HomeBridgeError(ERR.NOT_CONNECTED, 'Call connect() before using this bridge.');+ }+ }++ close() {+ this.#closed = true;+ if (this.#rebuildTimer) clearTimeout(this.#rebuildTimer);+ this.#rebuildTimer = null;+ for (const stop of this.#unsubscribers) {+ try {+ stop();+ } catch {+ // An unsubscribe that fails on an already dead socket is not an error.+ }+ }+ this.#unsubscribers = [];+ this.#connection?.close();+ this.#connection = null;+ this.#listeners.clear();+ }+}++function firstEntityId(data) {+ const id = data?.entity_id;+ if (Array.isArray(id)) return id[0];+ return typeof id === 'string' ? id : undefined;+}++/**+ * The HA client throws bare numeric error codes. Translate them once, here, into+ * something a connect screen can actually say to a person.+ */+export function toBridgeError(err, baseUrl, prefix = '') {+ if (err instanceof HomeBridgeError) return err;+ const code = typeof err === 'number' ? err : err?.code;+ const say = (text) => (prefix ? `${prefix} ${text}` : text);+ switch (code) {+ case ERR_INVALID_AUTH:+ return new HomeBridgeError(ERR.AUTH, say('Home Assistant rejected that access token. Create a new long-lived token in your profile and try again.'), err);+ case ERR_CANNOT_CONNECT:+ case ERR_CONNECTION_LOST:+ return new HomeBridgeError(ERR.UNREACHABLE, say(`Could not reach ${baseUrl}. If it is only on your home network, three.ws cannot route to it: use your remote https URL.`), err);+ case ERR_INVALID_HTTPS_TO_HTTP:+ return new HomeBridgeError(ERR.BAD_URL, say('A page served over https cannot connect to a plain http home. Use your remote https URL.'), err);+ default:+ return new HomeBridgeError(ERR.CALL_FAILED, say(err?.message || String(err)), err);+ }+}diff --git a/packages/home-bridge/src/errors.js b/packages/home-bridge/src/errors.jsnew file mode 100644index 000000000..4c87a293a--- /dev/null+++ b/packages/home-bridge/src/errors.js@@ -0,0 +1,29 @@+/**+ * Every failure the bridge surfaces carries a machine-readable `code`, because+ * the UI has to tell "your token is wrong" apart from "your house is offline"+ * and the two need completely different recovery text.+ */+export class HomeBridgeError extends Error {+ constructor(code, message, cause) {+ super(message, cause ? { cause } : undefined);+ this.name = 'HomeBridgeError';+ this.code = code;+ }+}++export const ERR = {+ /** The base URL is not a URL, or is http:// where the page is https://. */+ BAD_URL: 'bad_url',+ /** Home Assistant rejected the access token. */+ AUTH: 'auth',+ /** The instance did not answer at all: wrong host, LAN-only, or offline. */+ UNREACHABLE: 'unreachable',+ /** Connected, but the request failed (unknown service, bad entity, and so on). */+ CALL_FAILED: 'call_failed',+ /** A guarded entity was targeted without an explicit confirmation. */+ NEEDS_CONFIRMATION: 'needs_confirmation',+ /** The `mcp_server` integration is not enabled on this instance. */+ NO_MCP: 'no_mcp',+ /** A method was used before connect(), or after close(). */+ NOT_CONNECTED: 'not_connected',+};diff --git a/packages/home-bridge/src/index.js b/packages/home-bridge/src/index.jsnew file mode 100644index 000000000..ab88084a6--- /dev/null+++ b/packages/home-bridge/src/index.js@@ -0,0 +1,7 @@+export { HomeBridge, toBridgeError } from './bridge.js';+export { ERR, HomeBridgeError } from './errors.js';+export { MACROS, matchMacro, resolveIntent } from './intents.js';+export { connectHomeMcp } from './mcp.js';+export { buildHomeGraph, domainOf, summarizeClimate, summarizeLighting, summarizeSecurity } from './rooms.js';+export { classifyCall, createAllowList, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';+export { isPrivateHost, normalizeBaseUrl } from './url.js';diff --git a/packages/home-bridge/src/intents.js b/packages/home-bridge/src/intents.jsnew file mode 100644index 000000000..c00057475--- /dev/null+++ b/packages/home-bridge/src/intents.js@@ -0,0 +1,147 @@+/**+ * "Good night" is not a feature we invent. It is a scene the user already built+ * in Home Assistant, in an editor they already know, and our job is to find it.+ *+ * This module maps a spoken phrase onto an existing `scene.*` or `script.*`+ * entity. Composing individual service calls is the fallback, never the first+ * move: a user's own "Bedtime" scene knows about the plant light and the fish+ * tank, and no amount of LLM reasoning over an entity list will.+ *+ * Matching is uFuzzy (already a three.ws dependency, ~7 kB, MIT) over the+ * candidate names, layered under a synonym table for the handful of macros that+ * every house has under a different name.+ */++import uFuzzy from '@leeoniya/ufuzzy';++import { domainOf } from './rooms.js';++const uf = new uFuzzy({ intraMode: 1, intraIns: 1, intraSub: 1, intraTrn: 1, intraDel: 1 });++/**+ * The canonical household macros. `triggers` are what a person says; `targets`+ * are the word stems that show up in what they named the scene.+ */+export const MACROS = {+ good_night: {+ label: 'Good night',+ triggers: ['good night', 'goodnight', 'night night', 'bedtime', 'going to bed', 'off to bed', 'time for bed', 'sleep now'],+ targets: ['night', 'bed', 'sleep', 'nacht', 'noche'],+ },+ leaving: {+ label: 'Leaving',+ triggers: ['im leaving', 'i am leaving', 'leaving now', 'heading out', 'goodbye', 'bye', 'see you later', 'going out', 'away mode', 'set away'],+ targets: ['away', 'leav', 'depart', 'out', 'goodbye', 'vacation'],+ },+ arriving: {+ label: 'Arriving',+ triggers: ['im home', 'i am home', 'im back', 'back home', 'just got in', 'welcome home', 'arriving'],+ targets: ['home', 'arriv', 'welcome', 'return', 'back'],+ },+ morning: {+ label: 'Good morning',+ triggers: ['good morning', 'morning', 'wake up', 'time to get up', 'rise and shine'],+ targets: ['morning', 'wake', 'sunrise', 'daybreak'],+ },+ movie: {+ label: 'Movie time',+ triggers: ['movie time', 'movie night', 'watch a movie', 'lets watch something', 'cinema mode', 'film night'],+ targets: ['movie', 'cinema', 'theater', 'theatre', 'film', 'netflix'],+ },+ focus: {+ label: 'Focus',+ triggers: ['time to work', 'focus mode', 'work mode', 'do not disturb', 'concentrate'],+ targets: ['focus', 'work', 'office', 'study', 'concentrat'],+ },+};++function normalize(text) {+ return String(text || '')+ .toLowerCase()+ .replace(/['’`]/g, '')+ .replace(/[^a-z0-9\s]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim();+}++/** Which canonical macro, if any, a phrase is asking for. */+export function matchMacro(phrase) {+ const p = normalize(phrase);+ if (!p) return null;+ let best = null;+ for (const [key, macro] of Object.entries(MACROS)) {+ for (const trigger of macro.triggers) {+ const t = normalize(trigger);+ let score = 0;+ if (p === t) score = 1;+ else if (p.includes(t)) score = 0.9 - Math.min(0.2, (p.length - t.length) / 100);+ else if (t.includes(p) && p.length >= 4) score = 0.7;+ if (score > (best?.score ?? 0)) best = { key, macro, score, trigger };+ }+ }+ return best && best.score >= 0.7 ? best : null;+}++/**+ * @param {string} phrase what the user said+ * @param {Array<{ entityId: string, name: string, aliases?: string[] }>} candidates+ * every `scene.*` and `script.*` entity in the house+ * @returns {{ entityId: string, name: string, kind: string, macro: string|null, confidence: number, reason: string }|null}+ */+export function resolveIntent(phrase, candidates = []) {+ const usable = candidates.filter((c) => {+ const d = domainOf(c.entityId);+ return d === 'scene' || d === 'script';+ });+ if (!usable.length) return null;++ const macro = matchMacro(phrase);+ const searchText = usable.map((c) => normalize([c.name, c.entityId.replace(/^[a-z_]+\./, '').replace(/_/g, ' '), ...(c.aliases || [])].join(' ')));++ // A macro hit looks for its own vocabulary in the scene names first. This is+ // what turns "good night" into the user's "Bedtime" scene, which no direct+ // string match on the phrase would ever find.+ if (macro) {+ let bestIdx = -1;+ let bestLen = 0;+ for (let i = 0; i < usable.length; i++) {+ for (const target of macro.macro.targets) {+ if (searchText[i].includes(target) && target.length > bestLen) {+ bestIdx = i;+ bestLen = target.length;+ }+ }+ }+ if (bestIdx >= 0) {+ const hit = usable[bestIdx];+ return {+ entityId: hit.entityId,+ name: hit.name,+ kind: domainOf(hit.entityId),+ macro: macro.key,+ confidence: Number(Math.min(0.99, 0.75 + macro.score * 0.2).toFixed(2)),+ reason: `"${phrase}" is the ${macro.macro.label} macro, and ${hit.name} is this home's version of it.`,+ };+ }+ }++ // No macro, or the house has no scene named for it: fall back to matching the+ // literal phrase against the scene names.+ const q = normalize(phrase);+ const idxs = q ? uf.filter(searchText, q) : null;+ if (idxs && idxs.length) {+ const info = uf.info(idxs, searchText, q);+ const order = uf.sort(info, searchText, q);+ const hit = usable[info.idx[order[0]]];+ return {+ entityId: hit.entityId,+ name: hit.name,+ kind: domainOf(hit.entityId),+ macro: macro?.key || null,+ confidence: 0.6,+ reason: `"${phrase}" matches the name of ${hit.name}.`,+ };+ }++ return null;+}diff --git a/packages/home-bridge/src/mcp.js b/packages/home-bridge/src/mcp.jsnew file mode 100644index 000000000..6897890e9--- /dev/null+++ b/packages/home-bridge/src/mcp.js@@ -0,0 +1,68 @@+/**+ * The optional capability channel.+ *+ * Home Assistant's first-party `mcp_server` integration exposes the exact set of+ * tools the user chose to give their own LLM, at `/api/mcp`, over streamable+ * HTTP. When a home has it enabled, an agent gets the user's curated tool+ * surface (with the user's own exposure rules) for free, and we do not have to+ * derive tools from the entity list ourselves.+ *+ * It is optional on purpose: `mcp_server` needs setting up, while the WebSocket+ * API in bridge.js works on every instance with nothing but a token. This is an+ * upgrade, never a requirement.+ */++import { ERR, HomeBridgeError } from './errors.js';+import { normalizeBaseUrl } from './url.js';++/**+ * @param {object} options+ * @param {string} options.baseUrl+ * @param {string} options.token long-lived access token+ * @param {string} [options.api] which Home Assistant LLM API to attach to. The+ * built-in Assist API lives at /api/mcp/assist; the bare /api/mcp uses the+ * instance default.+ * @param {string} [options.clientName] reported to Home Assistant in the handshake+ * @returns {Promise<{ client: object, tools: Array, close: () => Promise<void> }>}+ */+export async function connectHomeMcp({ baseUrl, token, api, clientName = 'three.ws' } = {}) {+ const { http } = normalizeBaseUrl(baseUrl);+ if (!token) throw new HomeBridgeError(ERR.AUTH, 'A Home Assistant long-lived access token is required.');++ let Client;+ let StreamableHTTPClientTransport;+ try {+ ({ Client } = await import('@modelcontextprotocol/sdk/client/index.js'));+ ({ StreamableHTTPClientTransport } = await import('@modelcontextprotocol/sdk/client/streamableHttp.js'));+ } catch (cause) {+ throw new HomeBridgeError(ERR.NO_MCP, 'The MCP channel needs @modelcontextprotocol/sdk installed alongside this package.', cause);+ }++ const url = new URL(`${http}/api/mcp${api ? `/${api}` : ''}`);+ const transport = new StreamableHTTPClientTransport(url, {+ requestInit: { headers: { authorization: `Bearer ${token}` } },+ });+ const client = new Client({ name: clientName, version: '0.1.0' }, { capabilities: {} });++ try {+ await client.connect(transport);+ } catch (cause) {+ // A 404 here is the ordinary case, not a fault: the integration is simply+ // not set up. Say which one it is so the UI can offer the right next step.+ const status = cause?.code ?? cause?.status;+ if (status === 404 || /404/.test(String(cause?.message || ''))) {+ throw new HomeBridgeError(ERR.NO_MCP, 'This home does not have the Model Context Protocol Server integration enabled. Add it in Settings, Devices and services, to give your agent your own curated tools.', cause);+ }+ if (status === 401 || status === 403) {+ throw new HomeBridgeError(ERR.AUTH, 'Home Assistant rejected that token on the MCP endpoint.', cause);+ }+ throw new HomeBridgeError(ERR.UNREACHABLE, `Could not open the MCP channel at ${url.href}.`, cause);+ }++ const { tools } = await client.listTools();+ return {+ client,+ tools,+ close: () => client.close(),+ };+}diff --git a/packages/home-bridge/src/rooms.js b/packages/home-bridge/src/rooms.jsnew file mode 100644index 000000000..ed9d1c520--- /dev/null+++ b/packages/home-bridge/src/rooms.js@@ -0,0 +1,165 @@+/**+ * Turns Home Assistant's four flat registries (floors, areas, devices,+ * entities) plus the current state map into the room graph the 3D scene+ * renders and the agent reasons over.+ *+ * Everything here is a pure function of data the bridge already fetched, so the+ * scene can rebuild on every state push without another round trip.+ */++/** Domains the 3D scene draws as something you can see or walk up to. */+const RENDERABLE_DOMAINS = new Set([+ 'light',+ 'switch',+ 'cover',+ 'lock',+ 'climate',+ 'media_player',+ 'fan',+ 'sensor',+ 'binary_sensor',+ 'camera',+ 'vacuum',+ 'alarm_control_panel',+]);++export function domainOf(entityId) {+ const i = String(entityId || '').indexOf('.');+ return i === -1 ? '' : entityId.slice(0, i);+}++/**+ * @param {object} input+ * @param {Array} input.floors config/floor_registry/list+ * @param {Array} input.areas config/area_registry/list+ * @param {Array} input.devices config/device_registry/list+ * @param {Array} input.entities config/entity_registry/list+ * @param {Record<string, object>} input.states entity_id to state object+ */+export function buildHomeGraph({ floors = [], areas = [], devices = [], entities = [], states = {} } = {}) {+ const deviceArea = new Map(devices.map((d) => [d.id, d.area_id || null]));++ const rooms = new Map(+ areas.map((a) => [+ a.area_id,+ {+ id: a.area_id,+ name: a.name,+ icon: a.icon || null,+ floorId: a.floor_id || null,+ aliases: a.aliases || [],+ entities: [],+ },+ ]),+ );++ const unassigned = [];+ const seen = new Set();++ for (const entry of entities) {+ if (entry.disabled_by || entry.hidden_by) continue;+ const entityId = entry.entity_id;+ seen.add(entityId);+ const areaId = entry.area_id || deviceArea.get(entry.device_id) || null;+ const item = describeEntity(entityId, entry, states[entityId]);+ if (!item) continue;+ const room = areaId && rooms.get(areaId);+ if (room) room.entities.push(item);+ else unassigned.push(item);+ }++ // Entities created in YAML never reach the entity registry, and the demo and+ // template integrations are full of them. Dropping them would silently hide+ // half of some houses, so pick them up from the state map directly.+ for (const [entityId, state] of Object.entries(states)) {+ if (seen.has(entityId)) continue;+ const item = describeEntity(entityId, null, state);+ if (item) unassigned.push(item);+ }++ const list = [...rooms.values()].map((room) => ({+ ...room,+ entities: room.entities.sort(byName),+ lighting: summarizeLighting(room.entities),+ climate: summarizeClimate(room.entities),+ secured: summarizeSecurity(room.entities),+ }));++ return {+ floors: floors.map((f) => ({ id: f.floor_id, name: f.name, level: f.level ?? 0, icon: f.icon || null })).sort((a, b) => a.level - b.level),+ rooms: list.sort(byName),+ unassigned: unassigned.sort(byName),+ };+}++function describeEntity(entityId, registryEntry, state) {+ const domain = domainOf(entityId);+ if (!RENDERABLE_DOMAINS.has(domain)) return null;+ const attributes = state?.attributes || {};+ return {+ entityId,+ domain,+ name: registryEntry?.name || attributes.friendly_name || registryEntry?.original_name || entityId,+ deviceClass: attributes.device_class || registryEntry?.device_class || registryEntry?.original_device_class || null,+ state: state?.state ?? 'unavailable',+ attributes,+ };+}++function byName(a, b) {+ return String(a.name).localeCompare(String(b.name));+}++/**+ * The numbers the 3D scene needs to light a room the way the real room is lit:+ * how many lights are on, the mean brightness as 0..1, and the mean colour of+ * the lights that report one.+ */+export function summarizeLighting(entities) {+ const lights = entities.filter((e) => e.domain === 'light');+ const on = lights.filter((e) => e.state === 'on');+ let brightness = 0;+ const rgb = [0, 0, 0];+ let coloured = 0;+ for (const light of on) {+ brightness += (Number(light.attributes.brightness) || 255) / 255;+ const c = light.attributes.rgb_color;+ if (Array.isArray(c) && c.length === 3) {+ rgb[0] += c[0];+ rgb[1] += c[1];+ rgb[2] += c[2];+ coloured += 1;+ }+ }+ return {+ total: lights.length,+ on: on.length,+ brightness: on.length ? Number((brightness / on.length).toFixed(3)) : 0,+ rgb: coloured ? rgb.map((v) => Math.round(v / coloured)) : null,+ };+}++export function summarizeClimate(entities) {+ const readings = entities+ .filter((e) => e.domain === 'climate' || (e.domain === 'sensor' && e.deviceClass === 'temperature'))+ .map((e) => (e.domain === 'climate' ? Number(e.attributes.current_temperature) : Number(e.state)))+ .filter((n) => Number.isFinite(n));+ if (!readings.length) return null;+ const mean = readings.reduce((a, b) => a + b, 0) / readings.length;+ return { temperature: Number(mean.toFixed(1)), sources: readings.length };+}++/**+ * "Is this room buttoned up?" in one object, so the scene can tint a door red+ * and the agent can answer "did I lock everything" without a second pass.+ */+export function summarizeSecurity(entities) {+ const locks = entities.filter((e) => e.domain === 'lock');+ const openings = entities.filter(+ (e) => e.domain === 'cover' || (e.domain === 'binary_sensor' && (e.deviceClass === 'door' || e.deviceClass === 'window' || e.deviceClass === 'garage_door')),+ );+ const unlocked = locks.filter((e) => e.state === 'unlocked').map((e) => e.entityId);+ const open = openings.filter((e) => e.state === 'open' || e.state === 'on').map((e) => e.entityId);+ if (!locks.length && !openings.length) return null;+ return { locks: locks.length, unlocked, openings: openings.length, open, secure: unlocked.length === 0 && open.length === 0 };+}diff --git a/packages/home-bridge/src/safety.js b/packages/home-bridge/src/safety.jsnew file mode 100644index 000000000..f1014adad--- /dev/null+++ b/packages/home-bridge/src/safety.js@@ -0,0 +1,86 @@+/**+ * The physical-action gate.+ *+ * A voice channel that can unlock a front door on a misheard phoneme is not a+ * feature. This module decides which calls the agent may make on its own and+ * which ones need the user to say yes, using the same shape as the on-chain+ * spend gate: reads are free, and the irreversible or security-relevant writes+ * stop and ask.+ *+ * The rule is deliberately asymmetric. Locking up, closing the garage, and+ * arming the alarm move the house toward safety and never prompt. Unlocking,+ * opening, and disarming move it away from safety and always do, until the user+ * grants a standing allowance for that specific entity.+ */++/** Domains where the unsafe direction needs confirmation every time. */+export const GUARDED_DOMAINS = new Set(['lock', 'alarm_control_panel', 'valve']);++/** Cover device classes that are an opening in the building envelope. */+export const GUARDED_COVER_CLASSES = new Set(['garage', 'gate', 'door']);++/** Services that move a guarded entity toward "open", "unlocked", or "off guard". */+const UNSAFE_SERVICES = new Set([+ 'unlock',+ 'open',+ 'open_cover',+ 'open_valve',+ 'set_cover_position',+ 'set_valve_position',+ 'alarm_disarm',+ 'toggle',+]);++/** Everything a read-only agent may do without ever prompting. */+export const READ_ONLY_SERVICES = new Set(['get_states', 'get_config', 'get_services']);++/**+ * @param {object} call+ * @param {string} call.domain e.g. "lock"+ * @param {string} call.service e.g. "unlock"+ * @param {string} [call.entityId]+ * @param {object} [call.attributes] the entity's current attributes, for device_class+ * @returns {{ guarded: boolean, risk: ('security'|'physical'|null), reason: string }}+ */+export function classifyCall({ domain, service, entityId, attributes = {} } = {}) {+ const d = String(domain || '').toLowerCase();+ const s = String(service || '').toLowerCase();+ const deviceClass = String(attributes.device_class || '').toLowerCase();+ const label = entityId || d;++ if (d === 'cover' && GUARDED_COVER_CLASSES.has(deviceClass)) {+ if (UNSAFE_SERVICES.has(s)) {+ return { guarded: true, risk: 'physical', reason: `Opening ${label} is a physical opening in the building.` };+ }+ return { guarded: false, risk: null, reason: '' };+ }++ if (d === 'alarm_control_panel') {+ if (s === 'alarm_disarm') {+ return { guarded: true, risk: 'security', reason: `Disarming ${label} turns the alarm system off.` };+ }+ return { guarded: false, risk: null, reason: '' };+ }++ if (GUARDED_DOMAINS.has(d) && UNSAFE_SERVICES.has(s)) {+ return { guarded: true, risk: d === 'lock' ? 'security' : 'physical', reason: `"${s}" on ${label} cannot be safely undone remotely.` };+ }++ return { guarded: false, risk: null, reason: '' };+}++/**+ * A standing allowance is per entity and per direction, never per domain: a user+ * who lets the agent open the office door has not let it open the front door.+ *+ * @param {Iterable<string>} entityIds entity ids the user has pre-approved+ */+export function createAllowList(entityIds = []) {+ const allowed = new Set(entityIds);+ return {+ has: (entityId) => allowed.has(entityId),+ add: (entityId) => allowed.add(entityId),+ remove: (entityId) => allowed.delete(entityId),+ list: () => [...allowed],+ };+}diff --git a/packages/home-bridge/src/url.js b/packages/home-bridge/src/url.jsnew file mode 100644index 000000000..e9ed109d7--- /dev/null+++ b/packages/home-bridge/src/url.js@@ -0,0 +1,68 @@+import { ERR, HomeBridgeError } from './errors.js';++/**+ * Home Assistant is reached at a base URL the user types by hand, so it arrives+ * with trailing slashes, a stray `/lovelace`, or no scheme at all. Normalize it+ * once, here, and let every other module assume it is clean.+ *+ * @param {string} input+ * @param {{ requireSecure?: boolean }} [options] requireSecure rejects http://+ * for non-loopback hosts, which is what a browser on an https origin needs:+ * mixed content would be blocked anyway, and failing early with a real reason+ * beats a silent network error.+ * @returns {{ http: string, ws: string, origin: string, secure: boolean, loopback: boolean }}+ */+export function normalizeBaseUrl(input, options = {}) {+ const raw = typeof input === 'string' ? input.trim() : '';+ if (!raw) throw new HomeBridgeError(ERR.BAD_URL, 'A Home Assistant URL is required.');++ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;+ let url;+ try {+ url = new URL(withScheme);+ } catch (cause) {+ throw new HomeBridgeError(ERR.BAD_URL, `"${raw}" is not a valid URL.`, cause);+ }++ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ throw new HomeBridgeError(ERR.BAD_URL, `Unsupported scheme "${url.protocol}". Use http or https.`);+ }++ const loopback = isLoopbackHost(url.hostname);+ const secure = url.protocol === 'https:';+ if (options.requireSecure && !secure && !loopback) {+ throw new HomeBridgeError(+ ERR.BAD_URL,+ `${url.origin} is plain http, which a page served over https cannot reach. Use your remote https URL, or connect from inside your network.`,+ );+ }++ // Home Assistant can live under a path prefix behind a reverse proxy, so keep+ // the path but drop the trailing slash: every caller appends its own.+ const path = url.pathname.replace(/\/+$/, '');+ const http = `${url.origin}${path}`;+ const ws = `${secure ? 'wss' : 'ws'}://${url.host}${path}/api/websocket`;+ return { http, ws, origin: url.origin, secure, loopback };+}++function isLoopbackHost(hostname) {+ const h = hostname.toLowerCase();+ if (h === 'localhost' || h === '::1' || h.endsWith('.localhost')) return true;+ return /^127(?:\.\d{1,3}){3}$/.test(h);+}++/**+ * True when the host is one a public three.ws server can never route to. The+ * connect UI uses this to explain the LAN problem up front instead of letting+ * the user wait out a timeout.+ */+export function isPrivateHost(hostname) {+ const h = String(hostname || '').toLowerCase();+ if (isLoopbackHost(h)) return true;+ if (h.endsWith('.local') || h.endsWith('.lan') || h.endsWith('.internal') || h === 'homeassistant') return true;+ if (/^10(?:\.\d{1,3}){3}$/.test(h)) return true;+ if (/^192\.168(?:\.\d{1,3}){2}$/.test(h)) return true;+ if (/^172\.(1[6-9]|2\d|3[01])(?:\.\d{1,3}){2}$/.test(h)) return true;+ if (/^169\.254(?:\.\d{1,3}){2}$/.test(h)) return true;+ return false;+}