Skip to content

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.

feat(home): put the household API, the room model and the confirmation gate in place

nirholas5391d33c8084
diff --git a/.gitignore b/.gitignore
index 41c9a472e..654bbabc0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -535,6 +535,9 @@ download.zip
# .storage/auth, so the pattern is deliberately broad: any .ha-* directory at the
# repo root is a throwaway HA instance and never belongs in a commit.
.ha-*/
+# Same thing at fleet scale: scripts/home-fleet.mjs boots numbered Home Assistant
+# instances under .home-fleet/<n>/, each with its own token store.
+.home-fleet/
# Browser voice-loop runtime staged from node_modules by scripts/copy-voice-models.mjs
# (silero VAD + the onnxruntime-web wasm). Regenerated on every install and
diff --git a/api/_lib/home/errors.js b/api/_lib/home/errors.js
new file mode 100644
index 000000000..e051ef7e8
--- /dev/null
+++ b/api/_lib/home/errors.js
@@ -0,0 +1,170 @@
+// The one error contract the whole Home surface speaks.
+//
+// Three different readers consume a failure from /api/home/*: the connect UI,
+// which has to say something a person can act on; the agent tool layer, which
+// hands the result to a language model; and the bridge runtime itself. If each
+// route invented its own shape those three would disagree, and the disagreement
+// would surface as an agent treating a refusal as a success. So the vocabulary
+// lives here, once, and every route maps through `homeError`.
+//
+// The vocabulary is the `@three-ws/home-bridge` ERR set (bad_url, auth,
+// unreachable, call_failed, needs_confirmation, no_mcp, not_connected) plus the
+// transport codes a client library cannot produce on its own (not_found,
+// unauthorized, validation_error). One table for the client, not two.
+//
+// Two mappings in here are deliberate and worth stating out loud:
+//
+// * `needs_confirmation` is 409, not 403 and not 200. It is a conflict with
+// the current authorization state and it is retryable with the same body
+// plus a human's explicit yes. A 403 reads as terminal to every HTTP client
+// ever written, and a 200 with an error field reads as SUCCESS to a language
+// model, which is exactly how an agent talks itself into unlocking a door.
+// * `auth` is 400, not 401. A 401 from us would mean "your three.ws session is
+// bad"; this code means "Home Assistant rejected the token you gave us",
+// which is a problem with the submitted data. Conflating them makes a
+// browser log the user out because their house's token expired.
+//
+// The response body carries the code twice on purpose. `error` /
+// `error_description` is the platform-wide envelope that every existing three.ws
+// client and the shared `error()` helper in api/_lib/http.js already read;
+// `code` / `message` is the shape the Home surface's own clients (orders 04 and
+// 05) were specified against. Emitting both costs 30 bytes and means neither
+// reader needs a special case.
+
+import { ERR, HomeBridgeError } from '@three-ws/home-bridge';
+
+import { error as httpError } from '../http.js';
+
+/** The bridge vocabulary plus the codes only a transport can produce. */
+export const HOME_ERR = Object.freeze({
+ ...ERR,
+ /** Not this caller's home. Also what an unknown id returns: never confirm existence. */
+ NOT_FOUND: 'not_found',
+ /** No three.ws session and no valid bearer token. */
+ UNAUTHORIZED: 'unauthorized',
+ /** The request body or query is malformed. */
+ VALIDATION: 'validation_error',
+});
+
+/**
+ * HTTP status per code. Anything absent from this table is a bug in the caller,
+ * not a client error, so it falls through to 500 and gets reported.
+ */
+const STATUS_BY_CODE = Object.freeze({
+ [HOME_ERR.BAD_URL]: 400,
+ [HOME_ERR.AUTH]: 400,
+ [HOME_ERR.VALIDATION]: 400,
+ [HOME_ERR.UNAUTHORIZED]: 401,
+ [HOME_ERR.NOT_FOUND]: 404,
+ [HOME_ERR.NEEDS_CONFIRMATION]: 409,
+ [HOME_ERR.UNREACHABLE]: 502,
+ [HOME_ERR.CALL_FAILED]: 502,
+ [HOME_ERR.NOT_CONNECTED]: 503,
+ // no_mcp is not an error on any route: a home without the Model Context
+ // Protocol Server integration is an ordinary home. It reaches the client as
+ // `capabilities.mcp = false` plus the setting path to turn it on. It is
+ // mapped here only so a stray throw from the MCP probe still lands as a
+ // client-fixable 400 rather than a 500 someone has to page about.
+ [HOME_ERR.NO_MCP]: 400,
+});
+
+/**
+ * Build a coded failure. Returns (never throws) a `HomeBridgeError` so the
+ * runtime, the store and the routes all raise one class.
+ *
+ * @param {string} code one of HOME_ERR
+ * @param {string} message a sentence a person can act on
+ * @param {{ pending?: object, detail?: object, cause?: unknown }} [extra]
+ * @returns {HomeBridgeError}
+ */
+export function homeFailure(code, message, extra = {}) {
+ const err = new HomeBridgeError(code, message, extra.cause);
+ if (extra.pending) err.pending = extra.pending;
+ if (extra.detail) err.detail = extra.detail;
+ return err;
+}
+
+/** The 404 every ownership miss returns, worded so it reveals nothing. */
+export function notFound(what = 'home') {
+ return homeFailure(HOME_ERR.NOT_FOUND, `No such ${what}.`);
+}
+
+/**
+ * Normalize anything throwable into the wire shape, without deciding to send it.
+ * Exported so order 04's tools can render the same fields into a tool result and
+ * a test can assert the mapping without an HTTP round trip.
+ *
+ * @param {unknown} err
+ * @returns {{ status: number, code: string, message: string, pending: object|null, unexpected: boolean }}
+ */
+export function toHomeFailure(err) {
+ const code = err instanceof HomeBridgeError ? err.code : null;
+ const status = code ? STATUS_BY_CODE[code] : undefined;
+ if (!code || !status) {
+ return {
+ status: 500,
+ code: 'internal_error',
+ // Never echo an unknown throwable's message: it can carry a URL with a
+ // token in it, a stack, or a database string. The correlation id in the
+ // server log is how this one gets diagnosed.
+ message: 'Something went wrong reaching your home.',
+ pending: null,
+ unexpected: true,
+ };
+ }
+ return {
+ status,
+ code,
+ message: err.message || 'Your home could not be reached.',
+ pending: err.pending ? sanitizePending(err.pending) : null,
+ unexpected: false,
+ };
+}
+
+/**
+ * Send a coded failure. The single exit every /api/home/* route uses for a
+ * non-2xx, so the body shape cannot drift between them.
+ *
+ * A 5xx that did not come from the vocabulary is re-thrown to `wrap`, which owns
+ * correlation ids, Sentry capture and the ops alert. Swallowing it here would
+ * turn a real outage into a quiet 500 nobody sees.
+ *
+ * @param {import('node:http').ServerResponse} res
+ * @param {unknown} err
+ */
+export function homeError(res, err) {
+ const failure = toHomeFailure(err);
+ if (failure.unexpected) throw err;
+ return httpError(res, failure.status, failure.code, failure.message, {
+ code: failure.code,
+ message: failure.message,
+ ...(failure.pending ? { pending: failure.pending } : {}),
+ });
+}
+
+/**
+ * What a 409 tells the client about the action it must confirm.
+ *
+ * The point of `pending` is that the client can re-POST it verbatim with
+ * `confirmed: true` after a human says yes, so it has to carry the RESOLVED
+ * target (the entity id the gate actually matched), not the phrase or the area
+ * name the caller sent. Confirming "the door" and having a different door open
+ * is the failure mode this shape exists to prevent.
+ *
+ * Nothing but the known keys survives, because `pending` originates inside a
+ * bridge error whose `data` came from the caller and is echoed straight back
+ * into a model prompt in order 04.
+ */
+function sanitizePending(pending) {
+ const out = {};
+ if (pending.domain) out.domain = String(pending.domain);
+ if (pending.service) out.service = String(pending.service);
+ if (pending.tool) out.tool = String(pending.tool);
+ if (pending.entityId) out.entityId = String(pending.entityId);
+ if (Array.isArray(pending.targets)) out.targets = pending.targets.map(String);
+ if (pending.risk) out.risk = String(pending.risk);
+ if (pending.data && typeof pending.data === 'object') out.data = pending.data;
+ if (pending.arguments && typeof pending.arguments === 'object') out.arguments = pending.arguments;
+ if (pending.phrase) out.phrase = String(pending.phrase);
+ return out;
+}
diff --git a/api/_lib/home/runtime.js b/api/_lib/home/runtime.js
new file mode 100644
index 000000000..9c45ff8f5
--- /dev/null
+++ b/api/_lib/home/runtime.js
@@ -0,0 +1,520 @@
+// The bridge runtime: one pool of live Home Assistant connections per process.
+//
+// `packages/home-bridge` opens one WebSocket per HomeBridge and holds it. This
+// module decides who holds those sockets, for how long, and what happens when
+// the house, the credential, or the container goes away.
+//
+// The three facts about our own deployment that shape every choice here were
+// read off the running service, not assumed
+// (`gcloud run services describe three-ws-api --region us-central1`):
+//
+// * `minScale=6`, `maxScale=100`. There are always several instances and any
+// one of them may be recycled at any time.
+// * `sessionAffinity=false`. Two requests from the same browser land on
+// arbitrary instances, so a pooled socket is NEVER guaranteed to be there
+// for the next call. It is a cache with a good hit rate inside one request
+// and across the life of one SSE stream, and nothing more.
+// * `cpu-throttling=true`. Outside a request an instance gets close to no CPU,
+// so a background timer fires late or not at all and a held socket stops
+// draining frames. Eviction therefore runs on a timer AND opportunistically
+// on every acquire, and a pooled graph is always treated as possibly stale.
+//
+// The consequence, stated once so no caller has to rediscover it: the house is
+// the source of truth, this pool is a cache, and a cold instance reopening in a
+// few hundred milliseconds is the normal path rather than a failure.
+
+import { ERR, HomeBridge, HomeBridgeError } from '@three-ws/home-bridge';
+
+import {
+ getConnection,
+ getDecryptedToken,
+ HOME_STATUS,
+ listAllowedEntities,
+ recordHandshake,
+} from './store.js';
+
+/**
+ * Codes `acquire` adds to the bridge package's `ERR` vocabulary, so the route
+ * layer in order 03 maps ONE union of codes instead of two tables.
+ */
+export const HOME_RUNTIME_ERR = Object.freeze({
+ /** No such home for this user. Maps to 404, never 403: see store.getConnection. */
+ NOT_FOUND: 'home_not_found',
+ /** The home was disconnected; its ciphertext is gone and cannot be replayed. */
+ REVOKED: 'home_revoked',
+ /** Too many consecutive connect failures. Fails fast instead of timing out. */
+ BREAKER_OPEN: 'home_breaker_open',
+});
+
+/** Long enough that a page navigation or a chat turn reuses the socket, short enough that an abandoned tab does not hold a stranger's house open. */
+const IDLE_MS = 90_000;
+/** A house behind a slow tunnel is common; a hang is not. */
+const CONNECT_TIMEOUT_MS = 15_000;
+/** A socket plus a state map is roughly 1 to 3 MB of heap for a large house. */
+const DEFAULT_MAX_CONNECTIONS = 200;
+/** Consecutive connect failures that open the breaker for one home. */
+const BREAKER_THRESHOLD = 5;
+/** How long a revoked token or an offline house stops being retried on every page load. */
+const BREAKER_COOLDOWN_MS = 5 * 60_000;
+/** The sweep cadence. Advisory only under CPU throttling, which is why acquire sweeps too. */
+const SWEEP_MS = 30_000;
+
+/**
+ * Build a runtime over injectable dependencies.
+ *
+ * Every dependency defaults to the real one. Tests construct their own runtime
+ * with a counting bridge factory instead of mutating a global, so two test files
+ * can never leak pool state into each other.
+ *
+ * @param {object} [deps]
+ * @param {(input: { baseUrl: string, token: string, allowedEntities: string[] }) => object} [deps.createBridge]
+ * @param {typeof getConnection} [deps.getConnection]
+ * @param {typeof getDecryptedToken} [deps.getDecryptedToken]
+ * @param {typeof listAllowedEntities} [deps.listAllowedEntities]
+ * @param {typeof recordHandshake} [deps.recordHandshake]
+ * @param {() => number} [deps.now]
+ * @param {number} [deps.maxConnections]
+ * @param {number} [deps.idleMs]
+ * @param {number} [deps.connectTimeoutMs]
+ */
+export function createHomeRuntime(deps = {}) {
+ const createBridge = deps.createBridge || ((input) => new HomeBridge(input));
+ const readConnection = deps.getConnection || getConnection;
+ const readCredential = deps.getDecryptedToken || getDecryptedToken;
+ const readAllowed = deps.listAllowedEntities || listAllowedEntities;
+ const writeHandshake = deps.recordHandshake || recordHandshake;
+ const now = deps.now || (() => Date.now());
+ const maxConnections = deps.maxConnections ?? readMaxConnections();
+ const idleMs = deps.idleMs ?? IDLE_MS;
+ const connectTimeoutMs = deps.connectTimeoutMs ?? CONNECT_TIMEOUT_MS;
+
+ /** homeId -> pool entry. Keyed by home, not by user: a home has exactly one owner. */
+ const entries = new Map();
+ /** homeId -> { failures, openedUntil } */
+ const breakers = new Map();
+ let sweepTimer = null;
+
+ /**
+ * Check out a live bridge for one home.
+ *
+ * @param {string} homeId
+ * @param {string} userId the caller, proved by the route layer. Ownership is
+ * re-checked in SQL here, so a runtime call can never be the place an
+ * ownership check was forgotten.
+ * @returns {Promise<{ bridge: object, release: () => void, entry: object }>}
+ */
+ async function acquire(homeId, userId) {
+ // Under CPU throttling the interval below is unreliable, so every acquire
+ // pays for one cheap sweep. It is a Map walk over at most `maxConnections`.
+ evictIdle(now());
+
+ const breaker = breakers.get(homeId);
+ if (breaker && breaker.openedUntil > now()) {
+ const seconds = Math.ceil((breaker.openedUntil - now()) / 1000);
+ throw new HomeBridgeError(
+ HOME_RUNTIME_ERR.BREAKER_OPEN,
+ `This home failed to connect ${breaker.failures} times in a row, so three.ws stopped retrying for ${seconds} more seconds. Check that it is online and that its access token is still valid, then reconnect it.`,
+ );
+ }
+
+ const existing = entries.get(homeId);
+ if (existing) {
+ existing.refs += 1;
+ try {
+ await existing.ready;
+ } catch (err) {
+ existing.refs -= 1;
+ throw err;
+ }
+ return handle(existing);
+ }
+
+ const credential = await loadCredential(homeId, userId);
+ const pooled = entries.size < maxConnections;
+ const entry = openEntry({ homeId, userId, credential, pooled });
+ if (pooled) entries.set(homeId, entry);
+
+ try {
+ await entry.ready;
+ } catch (err) {
+ entries.delete(homeId);
+ throw err;
+ }
+ startSweep();
+ return handle(entry);
+ }
+
+ /**
+ * The shape every caller should use. Releases in a `finally`, so a throwing
+ * callback can never leak a socket.
+ *
+ * @template T
+ * @param {string} homeId
+ * @param {string} userId
+ * @param {(bridge: object) => Promise<T>} fn
+ * @returns {Promise<T>}
+ */
+ async function withHome(homeId, userId, fn) {
+ const { bridge, release } = await acquire(homeId, userId);
+ try {
+ return await fn(bridge);
+ } finally {
+ release();
+ }
+ }
+
+ /**
+ * The current room graph, without holding a reference past the call. A page
+ * load wants this; an SSE stream wants `subscribe`.
+ *
+ * @param {string} homeId
+ * @param {string} userId
+ * @returns {Promise<{ graph: object, stale: boolean, connected: boolean, status: string }>}
+ */
+ async function snapshot(homeId, userId) {
+ return withHome(homeId, userId, (bridge) => {
+ const entry = entries.get(homeId);
+ return {
+ graph: bridge.graph,
+ stale: entry ? entry.stale : false,
+ connected: Boolean(bridge.connected),
+ status: entry ? entry.status : HOME_STATUS.CONNECTED,
+ };
+ });
+ }
+
+ /**
+ * A live subscription, for SSE. Holds a reference for its whole lifetime, so
+ * the socket stays open while a browser is watching and starts its idle clock
+ * the moment the last watcher leaves.
+ *
+ * The listener is called immediately with the current graph, then on every
+ * rebuild and on every connectivity change. It is NEVER called with an empty
+ * graph because the socket dropped: a user watching their 3D home sees it go
+ * grey and stale, never watches their house vanish.
+ *
+ * @param {string} homeId
+ * @param {string} userId
+ * @param {(event: { graph: object, stale: boolean, connected: boolean, status: string }) => void} onGraph
+ * @returns {Promise<() => void>} unsubscribe
+ */
+ async function subscribe(homeId, userId, onGraph) {
+ const { bridge, release, entry } = await acquire(homeId, userId);
+ entry.subscribers.add(onGraph);
+ let live = true;
+
+ try {
+ onGraph(eventFor(entry, bridge));
+ } catch (err) {
+ console.warn('[home-runtime] a subscriber threw on its first event', { homeId, error: err?.message });
+ }
+
+ return () => {
+ if (!live) return;
+ live = false;
+ entry.subscribers.delete(onGraph);
+ release();
+ };
+ }
+
+ /**
+ * Close every pooled connection whose last reference was released more than
+ * the idle window ago. Exported so a test drives it deterministically rather
+ * than waiting out a wall clock.
+ *
+ * @param {number} [at] the current time in ms
+ * @returns {number} how many connections were closed
+ */
+ function evictIdle(at = now()) {
+ let closed = 0;
+ for (const [homeId, entry] of entries) {
+ if (entry.refs > 0) continue;
+ if (entry.idleSince === null || at - entry.idleSince < idleMs) continue;
+ closeEntry(entry);
+ entries.delete(homeId);
+ closed += 1;
+ }
+ if (!entries.size) stopSweep();
+ return closed;
+ }
+
+ /**
+ * The health probe's view of this instance. Shaped for order 13.
+ * @returns {{ open: number, subscribers: number, pooledCap: number, breakersOpen: number, byStatus: Record<string, number> }}
+ */
+ function stats() {
+ const byStatus = {};
+ let subscribers = 0;
+ for (const entry of entries.values()) {
+ byStatus[entry.status] = (byStatus[entry.status] || 0) + 1;
+ subscribers += entry.subscribers.size;
+ }
+ let breakersOpen = 0;
+ for (const breaker of breakers.values()) if (breaker.openedUntil > now()) breakersOpen += 1;
+ return { open: entries.size, subscribers, pooledCap: maxConnections, breakersOpen, byStatus };
+ }
+
+ /**
+ * Close every connection this process holds. Wired to SIGTERM: a container
+ * that dies without closing leaves the user's Home Assistant holding dead
+ * connections until its own timeout expires.
+ * @returns {number} how many were closed
+ */
+ function closeAll() {
+ const count = entries.size;
+ for (const entry of entries.values()) closeEntry(entry);
+ entries.clear();
+ stopSweep();
+ return count;
+ }
+
+ async function loadCredential(homeId, userId) {
+ const row = await readConnection(homeId, userId);
+ if (!row) {
+ throw new HomeBridgeError(
+ HOME_RUNTIME_ERR.NOT_FOUND,
+ 'That home is not connected to this account.',
+ );
+ }
+
+ let credential;
+ try {
+ credential = await readCredential(homeId, userId);
+ } catch (cause) {
+ // A ciphertext that will not decrypt is an account problem the user can
+ // fix by reconnecting, not a 500. Say so, and mark the row so the
+ // connect screen can explain it without opening a socket of its own.
+ await writeHandshake(homeId, {
+ status: HOME_STATUS.AUTH_FAILED,
+ statusDetail: 'The stored access token could not be read. Reconnect this home to store a new one.',
+ }).catch(() => null);
+ throw new HomeBridgeError(ERR.AUTH, 'The stored access token for this home could not be read. Reconnect the home to store a new one.', cause);
+ }
+
+ if (!credential) {
+ throw new HomeBridgeError(
+ HOME_RUNTIME_ERR.REVOKED,
+ 'This home was disconnected. Reconnect it to control it again.',
+ );
+ }
+ return credential;
+ }
+
+ function openEntry({ homeId, userId, credential, pooled }) {
+ const entry = {
+ homeId,
+ userId,
+ pooled,
+ bridge: null,
+ refs: 1,
+ idleSince: null,
+ openedAt: now(),
+ stale: false,
+ status: HOME_STATUS.PENDING,
+ lastGraph: { floors: [], rooms: [], unassigned: [] },
+ subscribers: new Set(),
+ closed: false,
+ };
+
+ entry.ready = (async () => {
+ const allowedEntities = await readAllowed(homeId).catch(() => []);
+ const bridge = createBridge({ baseUrl: credential.baseUrl, token: credential.token, allowedEntities });
+ entry.bridge = bridge;
+ wireEvents(entry, bridge);
+
+ try {
+ const graph = await withTimeout(
+ bridge.connect(),
+ connectTimeoutMs,
+ () => new HomeBridgeError(
+ ERR.UNREACHABLE,
+ `${credential.baseUrl} did not answer within ${Math.round(connectTimeoutMs / 1000)} seconds. If it is only on your home network, three.ws cannot route to it: use your remote https URL, or connect the three.ws add-on.`,
+ ),
+ );
+ entry.lastGraph = graph || entry.lastGraph;
+ entry.status = HOME_STATUS.CONNECTED;
+ entry.stale = false;
+ onConnectSuccess(homeId, entry, bridge);
+ return bridge;
+ } catch (err) {
+ entry.closed = true;
+ try {
+ bridge.close();
+ } catch {
+ // Closing a bridge that never opened is not an error.
+ }
+ onConnectFailure(homeId, err);
+ throw err;
+ }
+ })();
+
+ return entry;
+ }
+
+ function wireEvents(entry, bridge) {
+ bridge.on('graph', (graph) => {
+ // Never overwrite a real graph with an empty one. An empty house is
+ // legitimate, but an empty burst arriving on a dying socket is not, and
+ // the user must not watch their home vanish.
+ if (graph) entry.lastGraph = graph;
+ entry.stale = false;
+ notify(entry, bridge);
+ });
+ bridge.on('disconnected', () => {
+ entry.stale = true;
+ entry.status = HOME_STATUS.UNREACHABLE;
+ notify(entry, bridge);
+ });
+ bridge.on('reconnected', () => {
+ entry.stale = false;
+ entry.status = HOME_STATUS.CONNECTED;
+ notify(entry, bridge);
+ });
+ bridge.on('error', (err) => {
+ // Once per socket, not once per message: a malformed burst must not be
+ // able to fill the log.
+ if (entry.loggedError) return;
+ entry.loggedError = true;
+ console.warn('[home-runtime] bridge reported an error', { homeId: entry.homeId, error: err?.message || String(err) });
+ });
+ }
+
+ function notify(entry, bridge) {
+ if (!entry.subscribers.size) return;
+ const event = eventFor(entry, bridge);
+ for (const listener of entry.subscribers) {
+ try {
+ listener(event);
+ } catch (err) {
+ console.warn('[home-runtime] a subscriber threw', { homeId: entry.homeId, error: err?.message });
+ }
+ }
+ }
+
+ function eventFor(entry, bridge) {
+ return {
+ graph: entry.lastGraph,
+ stale: entry.stale,
+ connected: Boolean(bridge?.connected),
+ status: entry.status,
+ };
+ }
+
+ function onConnectSuccess(homeId, entry, bridge) {
+ breakers.delete(homeId);
+ const graph = entry.lastGraph;
+ // Measured from the socket that just opened, never inferred. The store
+ // merges capabilities, so writing the WebSocket half here cannot erase the
+ // MCP half that verify.js measured at connect time.
+ writeHandshake(homeId, {
+ status: HOME_STATUS.CONNECTED,
+ statusDetail: null,
+ capabilities: {
+ websocket: true,
+ entityCount: Object.keys(bridge.states || {}).length,
+ areaCount: graph?.rooms?.length ?? 0,
+ floorCount: graph?.floors?.length ?? 0,
+ haVersion: bridge.haVersion ?? null,
+ measuredAt: new Date().toISOString(),
+ },
+ }).catch((err) => {
+ console.warn('[home-runtime] handshake record dropped', { homeId, error: err?.message });
+ });
+ }
+
+ function onConnectFailure(homeId, err) {
+ const breaker = breakers.get(homeId) || { failures: 0, openedUntil: 0 };
+ breaker.failures += 1;
+ if (breaker.failures >= BREAKER_THRESHOLD) breaker.openedUntil = now() + BREAKER_COOLDOWN_MS;
+ breakers.set(homeId, breaker);
+
+ const status = err?.code === ERR.AUTH ? HOME_STATUS.AUTH_FAILED : HOME_STATUS.UNREACHABLE;
+ writeHandshake(homeId, {
+ status,
+ statusDetail: breaker.openedUntil > now()
+ ? `${err?.message || 'This home did not answer.'} three.ws has paused retries for five minutes.`
+ : err?.message || 'This home did not answer.',
+ }).catch(() => null);
+ }
+
+ function handle(entry) {
+ let released = false;
+ return {
+ bridge: entry.bridge,
+ entry,
+ release() {
+ if (released) return;
+ released = true;
+ entry.refs -= 1;
+ if (entry.refs > 0) return;
+ entry.idleSince = now();
+ // A connection that was never admitted to the pool (past the cap) has
+ // nobody to evict it later, so it closes the moment it is done.
+ if (!entry.pooled) closeEntry(entry);
+ },
+ };
+ }
+
+ function closeEntry(entry) {
+ if (entry.closed) return;
+ entry.closed = true;
+ entry.subscribers.clear();
+ try {
+ entry.bridge?.close();
+ } catch (err) {
+ console.warn('[home-runtime] close threw on an already dead socket', { homeId: entry.homeId, error: err?.message });
+ }
+ }
+
+ function startSweep() {
+ if (sweepTimer) return;
+ sweepTimer = setInterval(() => evictIdle(now()), SWEEP_MS);
+ // Never hold the process open for a cache.
+ sweepTimer.unref?.();
+ }
+
+ function stopSweep() {
+ if (!sweepTimer) return;
+ clearInterval(sweepTimer);
+ sweepTimer = null;
+ }
+
+ return { acquire, withHome, snapshot, subscribe, evictIdle, stats, closeAll };
+}
+
+function readMaxConnections() {
+ const raw = Number(process.env.HOME_MAX_CONNECTIONS);
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : DEFAULT_MAX_CONNECTIONS;
+}
+
+function withTimeout(promise, ms, makeError) {
+ let timer;
+ const timeout = new Promise((_resolve, reject) => {
+ timer = setTimeout(() => reject(makeError()), ms);
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+/** The process-wide runtime every endpoint should use. */
+const runtime = createHomeRuntime();
+
+export const acquire = runtime.acquire;
+export const withHome = runtime.withHome;
+export const snapshot = runtime.snapshot;
+export const subscribe = runtime.subscribe;
+export const evictIdle = runtime.evictIdle;
+export const stats = runtime.stats;
+export const closeAll = runtime.closeAll;
+
+// Cloud Run sends SIGTERM before it recycles a container. Closing here is the
+// difference between a clean disconnect and the user's Home Assistant holding
+// dead sockets until its own timeout expires. Registered once, and never in a
+// test process, which imports createHomeRuntime directly.
+if (!process.env.VITEST) {
+ for (const signal of ['SIGTERM', 'SIGINT']) {
+ process.once(signal, () => {
+ const closed = closeAll();
+ if (closed) console.log(`[home-runtime] closed ${closed} home connections on ${signal}`);
+ });
+ }
+}
diff --git a/api/_lib/home/verify.js b/api/_lib/home/verify.js
index 2116f472b..6efac1f2e 100644
--- a/api/_lib/home/verify.js
+++ b/api/_lib/home/verify.js
@@ -19,6 +19,8 @@ import { connectHomeMcp, ERR, HomeBridge, HomeBridgeError, normalizeBaseUrl } fr
const CONNECT_TIMEOUT_MS = 15_000;
/** The optional channel gets a shorter leash: it must never dominate connect latency. */
const MCP_TIMEOUT_MS = 8_000;
+/** The version lookup is a nicety: never let it hold up a connect. */
+const CONFIG_TIMEOUT_MS = 5_000;
/**
* Open a real connection, measure it, close it.
@@ -52,7 +54,7 @@ export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIM
try {
const states = bridge.states || {};
const entityCount = Object.keys(states).length;
- const mcp = await probeMcp({ baseUrl: http, token });
+ const [mcp, config] = await Promise.all([probeMcp({ baseUrl: http, token }), readConfig({ baseUrl: http, token })]);
return {
graph,
@@ -62,7 +64,8 @@ export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIM
areaCount: graph?.rooms?.length ?? 0,
floorCount: graph?.floors?.length ?? 0,
macroCount: bridge.macros().length,
- haVersion: readVersion(states),
+ haVersion: config.version,
+ locationName: config.locationName,
mcp: mcp.available,
mcpToolCount: mcp.toolCount,
mcpDetail: mcp.detail,
@@ -81,12 +84,32 @@ export async function verifyConnection({ baseUrl, token, timeoutMs = CONNECT_TIM
* on the state channel is any entity carrying the supervisor/core version
* attribute; when nothing does, we return null rather than inventing a number.
*/
-function readVersion(states) {
- for (const state of Object.values(states)) {
- const v = state?.attributes?.installed_version || state?.attributes?.version;
- if (typeof v === 'string' && /^\d+\.\d+/.test(v)) return v;
+/**
+ * Home Assistant's version, from the instance itself.
+ *
+ * Read from /api/config rather than scraped off entity attributes: a house full
+ * of `update.*` entities publishes half a dozen `installed_version` attributes
+ * belonging to add-ons and firmware, and picking one of those reports a
+ * confident, wrong number to the user. An unreadable version is null, never a
+ * guess, because the connect screen prints this verbatim.
+ */
+async function readConfig({ baseUrl, token }) {
+ try {
+ const res = await fetch(`${baseUrl}/api/config`, {
+ headers: { authorization: `Bearer ${token}` },
+ signal: AbortSignal.timeout(CONFIG_TIMEOUT_MS),
+ });
+ if (!res.ok) return { version: null, locationName: null };
+ const body = await res.json();
+ return {
+ version: typeof body?.version === 'string' ? body.version : null,
+ locationName: typeof body?.location_name === 'string' ? body.location_name : null,
+ };
+ } catch {
+ // The state channel already proved the instance is reachable and the token
+ // works, so a failure here costs a version string, not the connection.
+ return { version: null, locationName: null };
}
- return null;
}
async function probeMcp({ baseUrl, token }) {
diff --git a/api/_lib/migrations/20260903130000_home_schema_reconcile.sql b/api/_lib/migrations/20260903130000_home_schema_reconcile.sql
new file mode 100644
index 000000000..c12ee1119
--- /dev/null
+++ b/api/_lib/migrations/20260903130000_home_schema_reconcile.sql
@@ -0,0 +1,41 @@
+begin;
+
+-- Reconcile the home tables to every constraint their creating migration
+-- declares, for a database where they were created by a concurrent duplicate.
+--
+-- Two agents built the home schema in this shared worktree within minutes of
+-- each other, and both migrations used `create table if not exists`. The loser
+-- of that race is a silent no-op: the tables already existed, so the CHECK
+-- constraints written inside its CREATE TABLE were never created, and the
+-- database ends up weaker than the file of record
+-- (20260903030000_home_connections.sql) says it is. A schema that is weaker
+-- than its own migration claims is the worst kind of drift, because nothing
+-- reports it and every reader of the migration believes the guarantee holds.
+--
+-- Both statements are guarded by name, so this is a no-op on a database
+-- provisioned cleanly from that migration and a repair on one that raced.
+
+do $$
+begin
+ -- A relay connection with no relay id is unroutable, and a direct one that
+ -- carries a relay id is a contradiction. Both are bugs, so the database
+ -- refuses them rather than leaving the runtime to discover it at dial time.
+ if not exists (select 1 from pg_constraint where conname = 'home_connections_relay_chk') then
+ alter table home_connections
+ add constraint home_connections_relay_chk
+ check ((transport = 'relay') = (relay_id is not null));
+ end if;
+
+ -- Risk is the physical-action gate's verdict, not free text: 'security'
+ -- (locks, alarms, garage doors), 'physical' (anything else that moves in the
+ -- world), or null. An unconstrained column here would let a typo hide a
+ -- security-risk action from every query that filters on it.
+ if not exists (select 1 from pg_constraint where conname = 'home_action_log_risk_chk') then
+ alter table home_action_log
+ add constraint home_action_log_risk_chk
+ check (risk is null or risk in ('security', 'physical'));
+ end if;
+end
+$$;
+
+commit;
diff --git a/api/_lib/migrations/20260903140000_home_confirmations.sql b/api/_lib/migrations/20260903140000_home_confirmations.sql
new file mode 100644
index 000000000..221346ff8
--- /dev/null
+++ b/api/_lib/migrations/20260903140000_home_confirmations.sql
@@ -0,0 +1,107 @@
+begin;
+
+-- The pending-confirmation record: how a language model's request to open a
+-- physical building is carried across the model boundary without ever letting
+-- the model satisfy it.
+--
+-- Home Assistant's own Assist tools are polymorphic. Its published description
+-- of `intent__HassTurnOff` reads: "Turns off/closes a device or entity. For
+-- locks, this performs an 'unlock' action." So a model told to turn something
+-- off can open a front door, and nothing in the tool name says so. The gate in
+-- packages/home-bridge/src/safety.js catches that; this table is what makes the
+-- gate's verdict survive the trip through a model that may be fully hijacked.
+--
+-- The mechanism, stated once so nobody re-derives it wrong:
+--
+-- 1. The model's tool schema has no `confirmed` property at all. A model
+-- cannot set a field that does not exist in its schema. That, and not
+-- validation, is why a model cannot self-approve.
+-- 2. A guarded call returns a row from this table instead of acting. The row
+-- freezes the RESOLVED action (domain, service, service data, and the
+-- entity ids the gate actually resolved), so what a human is shown and
+-- what later executes cannot drift apart.
+-- 3. A human satisfies it out of band through a session-and-CSRF endpoint the
+-- model has no access to. Redemption is a single atomic claim.
+--
+-- Considered and rejected:
+--
+-- * A signed token (JWT) instead of a row. A JWT is stateless, which is
+-- exactly wrong here: single-use is the property that matters most, and it
+-- cannot be enforced without server state. A row that is claimed by an
+-- UPDATE ... WHERE redeemed_at IS NULL RETURNING gets single-use for free.
+--
+-- * Accepting the action alongside the id at redemption time. Then the
+-- confirmation would authorize whatever the caller re-sent, and a
+-- confirmation minted for lock.office_door could execute against
+-- lock.front_door. The action is frozen here at mint and read from here at
+-- redemption; the redeem endpoint takes an id and nothing else.
+--
+-- * A longer TTL "for convenience". This is a physical action with a human
+-- standing in front of it. 90 seconds is how long a person takes to read a
+-- sentence and press a button. A confirmation that has to survive longer
+-- (pushed to a phone, answered from another room) is a different flow with
+-- its own record, not a laxer default here.
+
+create table if not exists home_confirmations (
+ id uuid primary key default gen_random_uuid(),
+
+ -- Bound to the home AND the user at mint. Redemption re-checks both, so a
+ -- confirmation minted by one member of a household cannot be redeemed by
+ -- another, and one minted for the office cannot be spent on the house.
+ home_id uuid not null references home_connections(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+
+ -- The frozen, RESOLVED action. `service_data` is what will be passed to
+ -- Home Assistant verbatim; `entity_ids` is what the gate resolved, not the
+ -- raw argument the model produced (an argument can be a name, an area, or a
+ -- device class, and re-resolving it later could hit a different set).
+ domain text not null,
+ service text not null,
+ service_data jsonb not null default '{}'::jsonb,
+ entity_ids text[] not null default '{}',
+
+ -- Why the gate fired, and the plain-language sentence a human is shown.
+ -- The sentence is generated server-side from the resolved entities and
+ -- their friendly names; it is never model output, because the whole point
+ -- is that the human is told what will really happen.
+ risk text,
+ summary text not null,
+
+ -- Which surface asked: chat, mcp, voice, or api. An operator reviewing an
+ -- incident needs to know whether a door was opened from a phone or by a
+ -- model in a tool loop.
+ source text not null default 'api',
+
+ expires_at timestamptz not null,
+
+ -- Exactly one of these is set once the record is retired. Both null means
+ -- pending, which is what the redemption claim tests for.
+ redeemed_at timestamptz,
+ redeemed_by uuid references users(id) on delete set null,
+ expired_at timestamptz,
+
+ -- 'ok' or 'failed' after redemption: a confirmed unlock that Home Assistant
+ -- then refused is a materially different event from one that opened a door.
+ outcome text,
+
+ created_at timestamptz not null default now(),
+
+ constraint home_confirmations_source_chk
+ check (source in ('chat', 'mcp', 'voice', 'api')),
+ constraint home_confirmations_outcome_chk
+ check (outcome is null or outcome in ('ok', 'failed')),
+ constraint home_confirmations_risk_chk
+ check (risk is null or risk in ('security', 'physical'))
+);
+
+-- The redemption claim's index: id is the primary key, so this one serves the
+-- other two hot reads, the pending list for a home and the expiry sweep.
+create index if not exists home_confirmations_pending_idx
+ on home_confirmations (home_id, created_at desc)
+ where redeemed_at is null and expired_at is null;
+
+create index if not exists home_confirmations_expiry_idx
+ on home_confirmations (expires_at)
+ where redeemed_at is null and expired_at is null;
+
+commit;
diff --git a/api/home/[id]/members.js b/api/home/[id]/members.js
new file mode 100644
index 000000000..497b8612b
--- /dev/null
+++ b/api/home/[id]/members.js
@@ -0,0 +1,183 @@
+// The household roster: /api/home/:id/members
+//
+// GET list the members and the outstanding invitations
+// POST invite somebody, by email, to a named role and scope
+// PATCH change a member's role or scope
+// DELETE remove a member, or withdraw an invitation
+//
+// Every branch resolves the caller through api/_lib/home/members.js and acts on
+// what it says. There is no "or the connection belongs to you" path here: a
+// non-member gets 404 (never 403, which would confirm the home exists), and a
+// member who lacks the capability gets 403 naming their role, because "your
+// role cannot do this" and "that home does not exist" are different facts and
+// only one of them is safe to disclose.
+
+import { logAudit } from '../../_lib/audit.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import {
+ ASSIGNABLE_ROLES,
+ canAssignRole,
+ canManageMember,
+ createInvite,
+ listInvites,
+ listMembers,
+ normalizeScope,
+ removeMember,
+ requireMembership,
+ resolveMembership,
+ revokeInvite,
+ roleMatrix,
+ setMemberRole,
+} from '../../_lib/home/members.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { isUuid } from '../../_lib/validate.js';
+
+/** The invite link a new member follows. Absolute, because it is emailed. */
+function inviteUrl(req, token) {
+ const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+ const proto = /^localhost|^127\./.test(String(host)) ? 'http' : 'https';
+ return `${proto}://${host}/home/join?invite=${encodeURIComponent(token)}`;
+}
+
+function emailish(value) {
+ const v = String(value || '').trim().toLowerCase();
+ return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) && v.length <= 254 ? v : null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;
+
+ const homeId = req.query?.id;
+ if (!homeId || !isUuid(homeId)) return error(res, 400, 'bad_request', 'valid home id required');
+
+ const user = await getSessionUser(req, res).catch(() => null);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in to manage this household');
+
+ // Reading the roster is a plain member capability: you should be able to see
+ // who else has keys to the house you are in. Everything that changes it needs
+ // `invite`.
+ if (req.method === 'GET') {
+ const gate = await requireMembership(homeId, user.id, 'read');
+ if (!gate.ok) return error(res, gate.status, gate.code, gate.reason);
+ const [members, invites] = await Promise.all([listMembers(homeId), listInvites(homeId)]);
+ return json(res, 200, {
+ role: gate.role,
+ scope: gate.scope,
+ can_manage: gate.membership && canAssignRole(gate.role, 'member'),
+ assignable_roles: gate.role ? ASSIGNABLE_ROLES.filter((r) => canAssignRole(gate.role, r)) : [],
+ matrix: roleMatrix(),
+ members: members.map((m) => ({
+ user_id: m.userId,
+ role: m.role,
+ scoped: m.scoped,
+ scope: m.scope,
+ email: m.email,
+ username: m.username,
+ display_name: m.displayName,
+ created_at: m.createdAt,
+ can_manage: canManageMember(gate.role, m.role),
+ })),
+ invites: invites.map((i) => ({
+ id: i.id,
+ email: i.email,
+ role: i.role,
+ scope: i.scope,
+ expires_at: i.expiresAt,
+ created_at: i.createdAt,
+ })),
+ });
+ }
+
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const gate = await requireMembership(homeId, user.id, 'invite');
+ if (!gate.ok) return error(res, gate.status, gate.code, gate.reason);
+
+ const body = await readJson(req).catch(() => null);
+
+ if (req.method === 'POST') {
+ // An invite is a bearer credential for a role in a building. Rate limit it
+ // like one, per account, so a compromised session cannot spray keys.
+ const rl = await limits.homeInvite(user.id).catch(() => ({ success: true }));
+ if (rl && rl.success === false) return rateLimited(res, rl, 'too many invitations, try again shortly');
+
+ const email = emailish(body?.email);
+ if (!email) return error(res, 400, 'bad_request', 'a valid email address is required');
+
+ const role = String(body?.role || '').trim();
+ if (!canAssignRole(gate.role, role)) {
+ return error(res, 403, 'role_forbidden', `a ${gate.role} cannot invite somebody as ${role || 'that role'}`);
+ }
+
+ const invite = await createInvite({
+ homeId,
+ email,
+ role,
+ scope: normalizeScope(body?.scope, role),
+ invitedBy: user.id,
+ });
+
+ logAudit({ userId: user.id, action: 'household.invite', resourceId: homeId, meta: { email, role, scope: invite.scope }, req });
+
+ // The plaintext token exists in this response and nowhere else, ever.
+ return json(res, 201, {
+ invite: { id: invite.id, email: invite.email, role: invite.role, scope: invite.scope, expires_at: invite.expiresAt },
+ invite_url: inviteUrl(req, invite.token),
+ });
+ }
+
+ if (req.method === 'PATCH') {
+ const targetId = String(body?.user_id || '').trim();
+ if (!isUuid(targetId)) return error(res, 400, 'bad_request', 'user_id required');
+ if (targetId === user.id) return error(res, 400, 'bad_request', 'you cannot change your own role');
+
+ const target = await resolveMembership(homeId, targetId);
+ if (!target) return error(res, 404, 'not_found', 'that person is not in this household');
+ if (!canManageMember(gate.role, target.role)) {
+ return error(res, 403, 'role_forbidden', `a ${gate.role} cannot change a ${target.role}`);
+ }
+
+ const role = body?.role === undefined ? target.role : String(body.role).trim();
+ if (!canAssignRole(gate.role, role)) {
+ return error(res, 403, 'role_forbidden', `a ${gate.role} cannot assign the ${role || 'requested'} role`);
+ }
+
+ const scope = body?.scope === undefined ? target.scope : body.scope;
+ const updated = await setMemberRole({ homeId, userId: targetId, role, scope });
+ if (!updated) return error(res, 404, 'not_found', 'that person is not in this household');
+
+ logAudit({ userId: user.id, action: 'household.role_change', resourceId: homeId, meta: { target: targetId, from: target.role, to: updated.role, scope: updated.scope }, req });
+
+ return json(res, 200, { member: { user_id: updated.userId, role: updated.role, scope: updated.scope, scoped: updated.scoped } });
+ }
+
+ // DELETE: a member, or an outstanding invitation.
+ const inviteId = String(body?.invite_id || req.query?.invite_id || '').trim();
+ if (inviteId) {
+ if (!isUuid(inviteId)) return error(res, 400, 'bad_request', 'valid invite_id required');
+ const withdrawn = await revokeInvite({ homeId, inviteId });
+ if (!withdrawn) return error(res, 404, 'not_found', 'no such outstanding invitation');
+ logAudit({ userId: user.id, action: 'household.invite_revoked', resourceId: homeId, meta: { invite: inviteId }, req });
+ return json(res, 200, { revoked: true });
+ }
+
+ const targetId = String(body?.user_id || req.query?.user_id || '').trim();
+ if (!isUuid(targetId)) return error(res, 400, 'bad_request', 'user_id or invite_id required');
+ if (targetId === user.id) return error(res, 400, 'bad_request', 'you cannot remove yourself from a household you administer');
+
+ const target = await resolveMembership(homeId, targetId);
+ if (!target) return error(res, 404, 'not_found', 'that person is not in this household');
+ if (!canManageMember(gate.role, target.role)) {
+ return error(res, 403, 'role_forbidden', `a ${gate.role} cannot remove a ${target.role}`);
+ }
+
+ const { removed, grantsRevoked } = await removeMember({ homeId, userId: targetId });
+ if (!removed) return error(res, 404, 'not_found', 'that person is not in this household');
+
+ logAudit({ userId: user.id, action: 'household.member_removed', resourceId: homeId, meta: { target: targetId, role: target.role, grants_revoked: grantsRevoked.length }, req });
+
+ return json(res, 200, { removed: true, grants_revoked: grantsRevoked });
+});
diff --git a/packages/home-bridge/src/index.js b/packages/home-bridge/src/index.js
index 8bd0f62bb..87841d849 100644
--- a/packages/home-bridge/src/index.js
+++ b/packages/home-bridge/src/index.js
@@ -3,5 +3,5 @@ export { ERR, HomeBridgeError } from './errors.js';
export { MACROS, matchMacro, resolveIntent } from './intents.js';
export { connectHomeMcp } from './mcp.js';
export { buildHomeGraph, domainOf, flattenEntities, summarizeClimate, summarizeLighting, summarizeSecurity } from './rooms.js';
-export { classifyCall, classifyMcpCall, createAllowList, resolveMcpTargets, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';
+export { classifyCall, classifyMcpCall, createAllowList, isSafetyAction, isSafetyMcpCall, resolveMcpTargets, GUARDED_COVER_CLASSES, GUARDED_DOMAINS } from './safety.js';
export { isPrivateHost, normalizeBaseUrl } from './url.js';
diff --git a/packages/home-bridge/src/safety.js b/packages/home-bridge/src/safety.js
index 3d590087a..20c2b6a64 100644
--- a/packages/home-bridge/src/safety.js
+++ b/packages/home-bridge/src/safety.js
@@ -31,6 +31,26 @@ const UNSAFE_SERVICES = new Set([
'toggle',
]);
+/**
+ * Services that move a guarded entity toward locked, closed, or armed.
+ *
+ * This is the exact mirror of UNSAFE_SERVICES, and it is a separate set rather
+ * than "everything not unsafe" on purpose: `light.turn_on` is not unsafe and it
+ * is not a safety action either. Only the moves in here are the ones a quota,
+ * a plan limit, or any other commercial gate is forbidden to block.
+ */
+const SAFE_SERVICES = new Set([
+ 'lock',
+ 'close',
+ 'close_cover',
+ 'close_valve',
+ 'alarm_arm_away',
+ 'alarm_arm_home',
+ 'alarm_arm_night',
+ 'alarm_arm_vacation',
+ 'alarm_arm_custom_bypass',
+]);
+
/** Everything a read-only agent may do without ever prompting. */
export const READ_ONLY_SERVICES = new Set(['get_states', 'get_config', 'get_services']);
@@ -182,3 +202,74 @@ function toArray(value) {
if (value == null) return [];
return Array.isArray(value) ? value : [value];
}
+
+/**
+ * Does this call move the house toward safety?
+ *
+ * `classifyCall` answers the question the gate asks ("does this open the
+ * house"). This answers the opposite one, and the two are deliberately not
+ * complements: `light.turn_on` is neither. Locking a door, closing a garage,
+ * closing a water valve and arming an alarm are the four moves in the set, and
+ * they are the moves that must work when everything else about an account has
+ * been cut off.
+ *
+ * Why it lives here, beside the gate, rather than in the billing code: the list
+ * of things a lock can do is a fact about Home Assistant, not a fact about a
+ * price list. Anything that needs to know "may I refuse this" imports this
+ * function; nothing gets to keep its own copy of the list and drift from it.
+ *
+ * @param {object} call
+ * @param {string} call.domain
+ * @param {string} call.service
+ * @param {object} [call.attributes] the entity's current attributes, for device_class
+ * @returns {boolean}
+ */
+export function isSafetyAction({ domain, service, attributes = {} } = {}) {
+ const d = String(domain || '').toLowerCase();
+ const s = String(service || '').toLowerCase();
+
+ if (d === 'cover') {
+ const deviceClass = String(attributes.device_class || '').toLowerCase();
+ return GUARDED_COVER_CLASSES.has(deviceClass) && SAFE_SERVICES.has(s);
+ }
+ if (d === 'alarm_control_panel') return s.startsWith('alarm_arm') && SAFE_SERVICES.has(s);
+ if (GUARDED_DOMAINS.has(d)) return SAFE_SERVICES.has(s);
+ return false;
+}
+
+/**
+ * The same question, in front of the MCP channel.
+ *
+ * `HassTurnOn` on a lock is a lock, and `HassTurnOff` on a garage door is a
+ * close: the polymorphism that makes the gate necessary also means the safe
+ * direction arrives under a tool name that says nothing about doors. Resolve the
+ * targets the same way the gate does and ask `isSafetyAction` about each one.
+ *
+ * True only when the call touches at least one guarded entity and EVERY guarded
+ * entity it touches moves toward safety. A mixed call is not a safety action,
+ * because refusing it would still have refused a safety move, and allowing it
+ * would have allowed something else through on a safety exemption.
+ *
+ * @param {string} toolName
+ * @param {object} args
+ * @param {Array<object>} entities
+ * @returns {boolean}
+ */
+export function isSafetyMcpCall(toolName, args = {}, entities = []) {
+ const intent = String(toolName || '').split('__').pop();
+ const direction = MCP_INTENT_DIRECTION[intent];
+ if (!direction || direction === 'position') return false;
+
+ let sawSafety = false;
+ for (const entity of resolveMcpTargets(args, entities)) {
+ const service = serviceForDirection(entity.domain, direction);
+ if (!service) continue;
+ const call = { domain: entity.domain, service, entityId: entity.entityId, attributes: entity.attributes };
+ if (isSafetyAction(call)) {
+ sawSafety = true;
+ continue;
+ }
+ if (classifyCall(call).guarded) return false;
+ }
+ return sawSafety;
+}
diff --git a/scripts/home-test-instance.mjs b/scripts/home-test-instance.mjs
new file mode 100755
index 000000000..ef7bf2e39
--- /dev/null
+++ b/scripts/home-test-instance.mjs
@@ -0,0 +1,710 @@
+#!/usr/bin/env node
+/**
+ * A real Home Assistant, on demand, for the home lane's live tests.
+ *
+ * Every live test in this lane needs the same thing: an instance that is
+ * onboarded, holds a long-lived token, and contains a house worth asserting on
+ * (floors, areas, a lock, scenes, the MCP server). Before this script each test
+ * and each developer built that by hand from the README, which is how six
+ * slightly different instances came to exist and how a version difference could
+ * hide as "works on my machine".
+ *
+ * node scripts/home-test-instance.mjs --up --onboard --seed --json
+ * node scripts/home-test-instance.mjs --down
+ *
+ * Flags combine in that order, so one command takes you from nothing to a
+ * seeded house and prints the URL and token. Every step is idempotent: running
+ * it twice is a no-op that reprints the same connection details.
+ *
+ * Safety: this machine runs concurrent agents, several of which keep their own
+ * Home Assistant containers alive. The harness therefore stamps every container
+ * it creates with a label and REFUSES to stop, restart or remove a container
+ * that does not carry it. It also never touches a config directory outside the
+ * gitignored `.ha-config-*` prefix, because those directories hold real access
+ * tokens.
+ */
+
+import { spawn } from 'node:child_process';
+import fs from 'node:fs';
+import net from 'node:net';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+/** The label that marks a container as ours. Nothing without it is ever touched. */
+const LABEL = 'ws.three.home-test';
+const IMAGE = 'ghcr.io/home-assistant/home-assistant';
+const CLIENT_NAME = 'three.ws home lane';
+
+const USER = { name: 'Home Lane', username: 'threews', password: 'threews-home-lane' };
+
+/**
+ * The entry point lives at the bottom of this file, below every declaration it
+ * uses. A top-level call above a `class` declaration reads its binding in the
+ * temporal dead zone, which throws on every engine that checks it.
+ */
+async function main() {
+ const argv = process.argv.slice(2);
+ const opts = parseArgs(argv);
+
+ if (opts.help || !argv.length) {
+ usage();
+ process.exit(argv.length ? 0 : 1);
+ }
+
+ const instance = describeInstance(opts.name, opts.version);
+ log = opts.json ? () => {} : (...args) => console.error(...args);
+ emit = (payload) => {
+ if (opts.json) console.log(JSON.stringify({ ok: true, ...payload }, null, '\t'));
+ else if (payload.baseUrl) {
+ console.log(`HOME_ASSISTANT_URL=${payload.baseUrl}`);
+ if (payload.token) console.log(`HOME_ASSISTANT_TOKEN=${payload.token}`);
+ }
+ };
+
+ try {
+ let state = readState(instance);
+
+ if (opts.down) {
+ const removed = await down(instance, state);
+ emit({ action: 'down', name: instance.name, ...removed });
+ return;
+ }
+
+ if (opts.up) state = await up(instance, state, { seedNow: opts.seed });
+ if (!state) state = requireState(instance);
+
+ if (opts.onboard) state = await onboard(instance, state);
+ if (opts.seed) state = await seed(instance, state, { alreadyInConfig: Boolean(opts.up) });
+
+ emit({
+ action: 'ready',
+ name: instance.name,
+ version: state.version,
+ haVersion: state.haVersion || null,
+ container: instance.container,
+ port: state.port,
+ baseUrl: state.baseUrl,
+ token: state.token || null,
+ seeded: Boolean(state.seeded),
+ configDir: path.relative(ROOT, instance.configDir),
+ });
+ } catch (err) {
+ if (opts.json) console.log(JSON.stringify({ ok: false, error: err.message }, null, '\t'));
+ console.error(`home-test-instance: ${err.message}`);
+ process.exitCode = 1;
+ }
+}
+
+/** Progress goes to stderr so --json owns stdout. Bound by main(). */
+let log = () => {};
+let emit = () => {};
+
+// ---------------------------------------------------------------- lifecycle
+
+/**
+ * Start a container on a free port and wait until Home Assistant answers.
+ * Reuses a running instance rather than replacing it, so two tests that both
+ * ask for the same named instance share one house instead of racing.
+ */
+async function up(inst, state, { seedNow }) {
+ const existing = await inspect(inst.container);
+ if (existing?.running && state?.port) {
+ log(`[up] reusing ${inst.container} on :${state.port}`);
+ await waitForHomeAssistant(state.baseUrl);
+ return writeState(inst, { ...state, running: true });
+ }
+ if (existing && !existing.running) {
+ assertOurs(existing, inst.container);
+ await docker(['rm', '-f', inst.container]);
+ }
+
+ fs.mkdirSync(inst.configDir, { recursive: true });
+ // Writing configuration.yaml before the first boot is the difference between
+ // a 40s start and a 40s start plus a 40s restart. When --up and --seed are
+ // asked for together the demo house is therefore configured up front; a
+ // later standalone --seed appends and restarts instead.
+ writeConfiguration(inst, { demo: seedNow });
+
+ const port = await freePort();
+ log(`[up] starting ${inst.image} on :${port}`);
+ await docker([
+ 'run', '-d',
+ '--name', inst.container,
+ '--label', `${LABEL}=1`,
+ '--label', `${LABEL}.name=${inst.name}`,
+ '-p', `127.0.0.1:${port}:8123`,
+ '-v', `${inst.configDir}:/config`,
+ '-e', 'TZ=UTC',
+ inst.image,
+ ]);
+
+ const baseUrl = `http://127.0.0.1:${port}`;
+ const next = writeState(inst, { name: inst.name, version: inst.version, port, baseUrl, running: true, demoInConfig: Boolean(seedNow) });
+ const haVersion = await waitForHomeAssistant(baseUrl);
+ log(`[up] ${inst.container} is up, Home Assistant ${haVersion || 'unknown'}`);
+ return writeState(inst, { ...next, haVersion });
+}
+
+/**
+ * Remove the container and its config directory. Refuses anything it did not
+ * create, and reports honestly when there was nothing to remove.
+ */
+async function down(inst, state) {
+ const existing = await inspect(inst.container);
+ let removedContainer = false;
+ if (existing) {
+ assertOurs(existing, inst.container);
+ await docker(['rm', '-f', inst.container]);
+ removedContainer = true;
+ log(`[down] removed ${inst.container}`);
+ }
+
+ let removedConfig = false;
+ const dir = inst.configDir;
+ if (fs.existsSync(dir)) {
+ if (!path.basename(dir).startsWith('.ha-config-') || path.dirname(dir) !== ROOT) {
+ throw new Error(`refusing to delete ${dir}: not a harness config directory`);
+ }
+ fs.rmSync(dir, { recursive: true, force: true });
+ removedConfig = true;
+ log(`[down] removed ${path.relative(ROOT, dir)}`);
+ }
+ if (!removedContainer && !removedConfig) log(`[down] nothing to remove for "${inst.name}"`);
+ return { removedContainer, removedConfig };
+}
+
+// ---------------------------------------------------------------- onboarding
+
+/**
+ * Walk Home Assistant's real onboarding API and mint a long-lived token.
+ *
+ * This is the flow the browser performs on a fresh install: create the owner,
+ * exchange the returned auth code for a session, finish the remaining steps,
+ * then ask the WebSocket API for a long-lived token. No file is edited to fake
+ * a user into existence.
+ */
+async function onboard(inst, state) {
+ if (state.token && (await tokenWorks(state.baseUrl, state.token))) {
+ log('[onboard] already onboarded, token still valid');
+ return state;
+ }
+
+ const clientId = `${state.baseUrl}/`;
+ const steps = await json(`${state.baseUrl}/api/onboarding`);
+ const done = new Set(steps.filter((s) => s.done).map((s) => s.step));
+
+ if (done.has('user')) {
+ throw new Error(
+ `${inst.container} is already onboarded but the harness has no token for it. Run --down then --up --onboard to start clean.`,
+ );
+ }
+
+ log('[onboard] creating the owner account');
+ const { auth_code: userCode } = await json(`${state.baseUrl}/api/onboarding/users`, {
+ method: 'POST',
+ body: { client_id: clientId, ...USER, language: 'en' },
+ });
+
+ const session = await exchangeCode(state.baseUrl, clientId, userCode);
+
+ // core_config and analytics are separate steps and each has appeared and
+ // moved between releases, so a missing one is skipped rather than fatal.
+ for (const step of ['core_config', 'analytics']) {
+ if (done.has(step)) continue;
+ await json(`${state.baseUrl}/api/onboarding/${step}`, {
+ method: 'POST',
+ token: session.access_token,
+ body: step === 'analytics' ? { preferences: { base: false } } : {},
+ optional: true,
+ });
+ }
+ if (!done.has('integration')) {
+ await json(`${state.baseUrl}/api/onboarding/integration`, {
+ method: 'POST',
+ token: session.access_token,
+ body: { client_id: clientId, redirect_uri: clientId },
+ optional: true,
+ });
+ }
+
+ log('[onboard] minting a long-lived access token');
+ const ws = await WsSession.open(state.baseUrl, session.access_token);
+ let token;
+ try {
+ token = await ws.send({
+ type: 'auth/long_lived_access_token',
+ client_name: `${CLIENT_NAME} ${Date.now()}`,
+ lifespan: 30,
+ });
+ } finally {
+ ws.close();
+ }
+
+ return writeState(inst, { ...state, token, haVersion: ws.haVersion || state.haVersion });
+}
+
+async function exchangeCode(baseUrl, clientId, code) {
+ const res = await fetch(`${baseUrl}/auth/token`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({ grant_type: 'authorization_code', code, client_id: clientId }),
+ });
+ if (!res.ok) throw new Error(`token exchange returned ${res.status}: ${await res.text()}`);
+ return res.json();
+}
+
+// ---------------------------------------------------------------- seeding
+
+/**
+ * Turn a bare instance into a house: demo entities, a floor, three areas with
+ * entities assigned, two scenes, the MCP server, and a lock exposed to Assist.
+ *
+ * Everything is created through the real APIs and everything is idempotent, so
+ * a second --seed finds what the first one made and changes nothing.
+ */
+async function seed(inst, state, { alreadyInConfig }) {
+ if (!state.token) throw new Error('seed needs a token: run --onboard first.');
+
+ if (!state.demoInConfig && !alreadyInConfig) {
+ log('[seed] enabling the demo integration and restarting');
+ writeConfiguration(inst, { demo: true });
+ const existing = await inspect(inst.container);
+ assertOurs(existing, inst.container);
+ await docker(['restart', inst.container]);
+ await waitForHomeAssistant(state.baseUrl);
+ state = writeState(inst, { ...state, demoInConfig: true });
+ }
+
+ const ws = await WsSession.open(state.baseUrl, state.token);
+ const created = { floors: 0, areas: 0, assigned: 0, scenes: 0, exposed: 0, mcp: false };
+ try {
+ await waitFor(
+ async () => {
+ const states = await ws.send({ type: 'get_states' });
+ return states.some((s) => s.entity_id.startsWith('light.')) && states.some((s) => s.entity_id.startsWith('lock.'));
+ },
+ { timeout: 120_000, label: 'demo entities to appear' },
+ );
+
+ const floor = await ensureFloor(ws, 'Ground Floor');
+ created.floors = floor.created ? 1 : 0;
+
+ const states = await ws.send({ type: 'get_states' });
+ const byDomain = (domain) => states.filter((s) => s.entity_id.startsWith(`${domain}.`)).map((s) => s.entity_id);
+ const lights = byDomain('light');
+ const locks = byDomain('lock');
+ const climate = byDomain('climate');
+
+ // Three real rooms with real entities in them, which is the minimum the
+ // room graph, the 3D scene and the per-room rollups all need to mean
+ // anything. Entities are taken from whatever the demo actually provides
+ // rather than hardcoded, so a demo-integration change does not break this.
+ const plan = [
+ { name: 'Living Room', entities: [lights[0], climate[0]].filter(Boolean) },
+ { name: 'Bedroom', entities: [lights[1]].filter(Boolean) },
+ { name: 'Front Door', entities: [locks[0], lights[2]].filter(Boolean) },
+ ];
+
+ for (const room of plan) {
+ const area = await ensureArea(ws, room.name, floor.floor_id);
+ if (area.created) created.areas += 1;
+ for (const entityId of room.entities) {
+ await ws.send({ type: 'config/entity_registry/update', entity_id: entityId, area_id: area.area_id }).catch(() => {});
+ created.assigned += 1;
+ }
+ }
+
+ // The two scenes every intent test in the lane resolves against. Bedtime
+ // deliberately touches the lock, because "good night locks the door" is
+ // the case where the confirmation gate has to fire on a macro.
+ const scenes = [
+ { id: 'threews_bedtime', name: 'Bedtime', entities: sceneEntities({ lights: lights.slice(0, 2), off: true, lock: locks[0], lockState: 'locked' }) },
+ { id: 'threews_away_mode', name: 'Away Mode', entities: sceneEntities({ lights, off: true, lock: locks[0], lockState: 'locked' }) },
+ ];
+ for (const scene of scenes) {
+ const res = await fetch(`${state.baseUrl}/api/config/scene/config/${scene.id}`, {
+ method: 'POST',
+ headers: { authorization: `Bearer ${state.token}`, 'content-type': 'application/json' },
+ body: JSON.stringify({ id: scene.id, name: scene.name, entities: scene.entities }),
+ });
+ if (res.ok) created.scenes += 1;
+ else log(`[seed] scene ${scene.name} returned ${res.status}`);
+ }
+ await ws.send({ type: 'call_service', domain: 'scene', service: 'reload', service_data: {} }).catch(() => {});
+
+ // Expose the lock to Assist. This is the configuration that makes Home
+ // Assistant's own intent__HassTurnOff unlock a door, which is the finding
+ // the whole safety gate exists for: the lane must test against a house
+ // where that is actually reachable.
+ if (locks[0]) {
+ const ok = await ws
+ .send({
+ type: 'homeassistant/expose_entity/set',
+ assistants: ['conversation'],
+ entity_ids: [locks[0]],
+ should_expose: true,
+ })
+ .then(() => true)
+ .catch(() => false);
+ if (ok) created.exposed += 1;
+ }
+
+ created.mcp = await ensureMcpServer(state);
+ created.entities = { lights: lights.length, locks: locks.length, climate: climate.length };
+ created.lock = locks[0] || null;
+ created.light = lights[0] || null;
+ } finally {
+ ws.close();
+ }
+
+ log(
+ `[seed] ${created.areas} areas created, ${created.assigned} entities assigned, ${created.scenes} scenes, mcp_server ${created.mcp ? 'enabled' : 'unavailable'}`,
+ );
+ return writeState(inst, { ...state, seeded: true, seedResult: created });
+}
+
+function sceneEntities({ lights = [], off = true, lock, lockState = 'locked' }) {
+ const entities = {};
+ for (const id of lights) entities[id] = off ? 'off' : 'on';
+ if (lock) entities[lock] = lockState;
+ return entities;
+}
+
+async function ensureFloor(ws, name) {
+ const floors = await ws.send({ type: 'config/floor_registry/list' }).catch(() => []);
+ const found = floors.find((f) => f.name === name);
+ if (found) return { ...found, created: false };
+ const made = await ws.send({ type: 'config/floor_registry/create', name, level: 0 });
+ return { ...made, created: true };
+}
+
+async function ensureArea(ws, name, floorId) {
+ const areas = await ws.send({ type: 'config/area_registry/list' });
+ const found = areas.find((a) => a.name === name);
+ if (found) {
+ if (floorId && found.floor_id !== floorId) {
+ await ws.send({ type: 'config/area_registry/update', area_id: found.area_id, floor_id: floorId }).catch(() => {});
+ }
+ return { ...found, created: false };
+ }
+ const made = await ws.send({ type: 'config/area_registry/create', name, ...(floorId ? { floor_id: floorId } : {}) });
+ if (floorId && !made.floor_id) {
+ await ws.send({ type: 'config/area_registry/update', area_id: made.area_id, floor_id: floorId }).catch(() => {});
+ }
+ return { ...made, created: true };
+}
+
+/**
+ * Set up the `mcp_server` integration through its real config flow. It is a
+ * config-entry integration with no YAML form, so this drives the same HTTP flow
+ * the Settings UI drives. Returns false when the release does not ship it,
+ * which is a supported outcome: the MCP channel is an upgrade, not a
+ * requirement.
+ */
+async function ensureMcpServer(state) {
+ const headers = { authorization: `Bearer ${state.token}`, 'content-type': 'application/json' };
+ const entries = await fetch(`${state.baseUrl}/api/config/config_entries/entry`, { headers })
+ .then((r) => (r.ok ? r.json() : []))
+ .catch(() => []);
+ if (entries.some((e) => e.domain === 'mcp_server')) return true;
+
+ const start = await fetch(`${state.baseUrl}/api/config/config_entries/flow`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ handler: 'mcp_server', show_advanced_options: false }),
+ });
+ if (!start.ok) return false;
+ const flow = await start.json();
+ if (flow.type === 'create_entry') return true;
+ if (!flow.flow_id) return false;
+
+ // The single step asks which LLM API to expose. "assist" is the built-in one
+ // and the only value every release since the integration landed accepts.
+ const finish = await fetch(`${state.baseUrl}/api/config/config_entries/flow/${flow.flow_id}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ llm_hass_api: 'assist' }),
+ });
+ if (!finish.ok) return false;
+ const result = await finish.json();
+ return result.type === 'create_entry';
+}
+
+// ---------------------------------------------------------------- websocket
+
+/** A minimal authenticated Home Assistant WebSocket session. */
+class WsSession {
+ static async open(baseUrl, token) {
+ const url = `${baseUrl.replace(/^http/, 'ws')}/api/websocket`;
+ const socket = new WebSocket(url);
+ const session = new WsSession(socket);
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`websocket handshake to ${url} timed out`)), 30_000);
+ socket.onerror = () => {
+ clearTimeout(timer);
+ reject(new Error(`could not open ${url}`));
+ };
+ socket.onclose = () => {
+ clearTimeout(timer);
+ reject(new Error(`${url} closed during the handshake`));
+ };
+ socket.onmessage = (event) => {
+ const msg = JSON.parse(event.data);
+ if (msg.type === 'auth_required') {
+ session.haVersion = msg.ha_version || null;
+ socket.send(JSON.stringify({ type: 'auth', access_token: token }));
+ return;
+ }
+ if (msg.type === 'auth_ok') {
+ session.haVersion = msg.ha_version || session.haVersion;
+ clearTimeout(timer);
+ socket.onclose = null;
+ session.listen();
+ resolve();
+ return;
+ }
+ if (msg.type === 'auth_invalid') {
+ clearTimeout(timer);
+ reject(new Error('Home Assistant rejected the token.'));
+ }
+ };
+ });
+ return session;
+ }
+
+ constructor(socket) {
+ this.socket = socket;
+ this.nextId = 1;
+ this.pending = new Map();
+ this.haVersion = null;
+ }
+
+ listen() {
+ this.socket.onmessage = (event) => {
+ const msg = JSON.parse(event.data);
+ if (msg.type !== 'result') return;
+ const entry = this.pending.get(msg.id);
+ if (!entry) return;
+ this.pending.delete(msg.id);
+ if (msg.success) entry.resolve(msg.result);
+ else entry.reject(new Error(`${msg.error?.code || 'error'}: ${msg.error?.message || 'unknown'}`));
+ };
+ this.socket.onclose = () => {
+ for (const entry of this.pending.values()) entry.reject(new Error('websocket closed'));
+ this.pending.clear();
+ };
+ }
+
+ send(message) {
+ const id = this.nextId++;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`${message.type} timed out`));
+ }, 30_000);
+ this.pending.set(id, {
+ resolve: (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ reject: (err) => {
+ clearTimeout(timer);
+ reject(err);
+ },
+ });
+ this.socket.send(JSON.stringify({ ...message, id }));
+ });
+ }
+
+ close() {
+ try {
+ this.socket.close();
+ } catch {
+ // A socket that is already gone needs no closing.
+ }
+ }
+}
+
+// ---------------------------------------------------------------- helpers
+
+async function waitForHomeAssistant(baseUrl) {
+ let version = null;
+ await waitFor(
+ async () => {
+ const res = await fetch(`${baseUrl}/api/onboarding`, { signal: AbortSignal.timeout(4000) }).catch(() => null);
+ if (res && res.ok) return true;
+ // A fully onboarded instance answers /api/onboarding with 401 rather
+ // than 200, and that is just as good a readiness signal.
+ return Boolean(res && res.status === 401);
+ },
+ { timeout: 180_000, label: `${baseUrl} to answer` },
+ );
+ const cfg = await fetch(`${baseUrl}/manifest.json`, { signal: AbortSignal.timeout(4000) }).catch(() => null);
+ if (cfg?.ok) {
+ const body = await cfg.json().catch(() => null);
+ version = body?.version || null;
+ }
+ return version;
+}
+
+async function tokenWorks(baseUrl, token) {
+ const res = await fetch(`${baseUrl}/api/`, { headers: { authorization: `Bearer ${token}` } }).catch(() => null);
+ return Boolean(res?.ok);
+}
+
+/**
+ * Poll a condition to a deadline. Every wait in this harness is a wait for a
+ * condition, never a sleep for a guessed duration: a sleep is the seed of every
+ * flaky test this lane could grow.
+ */
+async function waitFor(condition, { timeout = 60_000, interval = 1000, label = 'condition' } = {}) {
+ const deadline = Date.now() + timeout;
+ let lastError = null;
+ while (Date.now() < deadline) {
+ try {
+ if (await condition()) return true;
+ lastError = null;
+ } catch (err) {
+ lastError = err;
+ }
+ await new Promise((r) => setTimeout(r, interval));
+ }
+ throw new Error(`timed out after ${Math.round(timeout / 1000)}s waiting for ${label}${lastError ? `: ${lastError.message}` : ''}`);
+}
+
+async function json(url, { method = 'GET', body, token, optional = false } = {}) {
+ const headers = {};
+ if (body) headers['content-type'] = 'application/json';
+ if (token) headers.authorization = `Bearer ${token}`;
+ const res = await fetch(url, { method, headers, body: body ? JSON.stringify(body) : undefined });
+ if (!res.ok) {
+ if (optional) return null;
+ throw new Error(`${method} ${new URL(url).pathname} returned ${res.status}: ${(await res.text()).slice(0, 200)}`);
+ }
+ const text = await res.text();
+ return text ? JSON.parse(text) : null;
+}
+
+function docker(args) {
+ return new Promise((resolve, reject) => {
+ const child = spawn('docker', args, { stdio: ['ignore', 'pipe', 'pipe'] });
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (d) => (out += d));
+ child.stderr.on('data', (d) => (err += d));
+ child.on('error', (e) => reject(new Error(`docker is not usable: ${e.message}`)));
+ child.on('close', (code) => {
+ if (code === 0) resolve(out.trim());
+ else reject(new Error(`docker ${args[0]} failed: ${(err || out).trim().split('\n').slice(-3).join(' ')}`));
+ });
+ });
+}
+
+async function inspect(container) {
+ const out = await docker(['inspect', container]).catch(() => null);
+ if (!out) return null;
+ const [info] = JSON.parse(out);
+ return { running: Boolean(info?.State?.Running), labels: info?.Config?.Labels || {} };
+}
+
+/**
+ * The guard that makes this safe to run on a machine full of other people's
+ * Home Assistant containers. Nothing without our label is ever acted on.
+ */
+function assertOurs(info, container) {
+ if (!info || info.labels?.[LABEL] !== '1') {
+ throw new Error(
+ `refusing to touch container "${container}": it was not created by this harness (missing ${LABEL} label). Pick another --name.`,
+ );
+ }
+}
+
+function freePort() {
+ return new Promise((resolve, reject) => {
+ const server = net.createServer();
+ server.unref();
+ server.on('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address();
+ server.close(() => resolve(port));
+ });
+ });
+}
+
+function writeConfiguration(inst, { demo }) {
+ const file = path.join(inst.configDir, 'configuration.yaml');
+ const lines = ['# Written by scripts/home-test-instance.mjs. Throwaway instance.', 'default_config:', 'logger:', ' default: warning'];
+ if (demo) lines.push('demo:');
+ fs.writeFileSync(file, `${lines.join('\n')}\n`);
+}
+
+function describeInstance(name, version) {
+ const slug = String(name).replace(/[^a-z0-9-]/gi, '-').toLowerCase();
+ return {
+ name: slug,
+ version,
+ image: `${IMAGE}:${version}`,
+ container: `three-ws-home-test-${slug}`,
+ configDir: path.join(ROOT, `.ha-config-test-${slug}`),
+ };
+}
+
+function statePath(inst) {
+ return path.join(inst.configDir, '.harness.json');
+}
+
+function readState(inst) {
+ try {
+ return JSON.parse(fs.readFileSync(statePath(inst), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function requireState(inst) {
+ const state = readState(inst);
+ if (!state) throw new Error(`no instance named "${inst.name}" is up. Run --up first.`);
+ return state;
+}
+
+function writeState(inst, state) {
+ fs.mkdirSync(inst.configDir, { recursive: true });
+ fs.writeFileSync(statePath(inst), `${JSON.stringify(state, null, '\t')}\n`);
+ return state;
+}
+
+function parseArgs(args) {
+ const out = { name: 'default', version: 'stable', json: false };
+ for (let i = 0; i < args.length; i += 1) {
+ const arg = args[i];
+ if (arg === '--up') out.up = true;
+ else if (arg === '--onboard') out.onboard = true;
+ else if (arg === '--seed') out.seed = true;
+ else if (arg === '--down') out.down = true;
+ else if (arg === '--json') out.json = true;
+ else if (arg === '--help' || arg === '-h') out.help = true;
+ else if (arg === '--name') out.name = args[++i];
+ else if (arg === '--version') out.version = args[++i];
+ else throw new Error(`unknown argument "${arg}"`);
+ }
+ return out;
+}
+
+function usage() {
+ console.log(`Usage: node scripts/home-test-instance.mjs [--up] [--onboard] [--seed] [--down] [options]
+
+ --up start a container on a free port and wait for readiness
+ --onboard complete onboarding and mint a long-lived access token
+ --seed demo entities, a floor, areas, scenes, mcp_server, an exposed lock
+ --down remove the container and its config directory
+ --name <slug> run more than one instance side by side (default: default)
+ --version <tag> Home Assistant image tag (default: stable)
+ --json machine-readable output for a test to consume
+
+Everything is idempotent. The usual call is:
+ node scripts/home-test-instance.mjs --up --onboard --seed --json`);
+}
+
+await main();
diff --git a/src/home/scene-model.js b/src/home/scene-model.js
new file mode 100644
index 000000000..901ce3318
--- /dev/null
+++ b/src/home/scene-model.js
@@ -0,0 +1,562 @@
+/**
+ * The room graph, turned into a scene.
+ *
+ * Everything geometric about /home/:id is decided here, as a pure function of
+ * the graph `packages/home-bridge` already builds. No Three.js, no DOM, no
+ * clock: the same model drives the WebGL renderer and the 2D fallback, and a
+ * test can assert the whole layout of a real house without a GPU.
+ *
+ * Two rules shape it:
+ *
+ * 1. A real house has no geometry in Home Assistant. Areas and floors are
+ * registries with names and levels, and nothing else, so the default
+ * arrangement here has to be good enough to use before anyone authors a
+ * floorplan. Rooms are packed per floor in name order, which is stable
+ * across reconnects and matches how the list beside the scene reads.
+ * 2. A room with sixty entities is not sixty objects. People care about
+ * lights, locks, doors and temperature; a humidity sensor is a number,
+ * not a thing you walk up to. Objects are ranked, capped and the rest are
+ * summarized, so a busy room stays legible instead of becoming gravel.
+ */
+
+import { summarizeClimate, summarizeLighting, summarizeSecurity } from '../../packages/home-bridge/src/rooms.js';
+
+/** Metres between floor slabs. Tall enough to read a room from the side. */
+export const FLOOR_HEIGHT = 4.6;
+
+/** One room occupies this cell; the room box sits inside it with a gap. */
+export const CELL = 7.2;
+const ROOM_GAP = 1.5;
+const WALL_HEIGHT = 2.7;
+
+/** Per room, before the rest is summarized into a readout. */
+const MAX_CEILING = 6;
+const MAX_WALL = 10;
+const MAX_FLOOR = 6;
+
+/**
+ * What a person cares about first, in order. Ranking is the whole reason a
+ * sixty-entity room is readable: the cap below cuts from the bottom of this
+ * list, never from the top, so the lights and the locks are always drawn.
+ */
+const RANK = {
+ light: 0,
+ lock: 1,
+ cover: 2,
+ climate: 3,
+ alarm_control_panel: 4,
+ media_player: 5,
+ fan: 6,
+ camera: 7,
+ vacuum: 8,
+ switch: 9,
+ binary_sensor: 10,
+ sensor: 11,
+};
+
+/** Binary sensors that are openings: they belong to the security story. */
+const OPENING_CLASSES = new Set(['door', 'window', 'garage_door', 'opening']);
+
+/**
+ * Where a domain lives in a room. Ceiling objects hang, wall objects mount on
+ * the perimeter, floor objects stand on the slab. This is the only place that
+ * decides it, so the renderer and the fallback legend cannot disagree.
+ */
+export function placementOf(entity) {
+ const domain = entity?.domain;
+ if (domain === 'light') return 'ceiling';
+ if (domain === 'fan') return entity.deviceClass === 'ceiling' || /ceiling/i.test(entity.name || '') ? 'ceiling' : 'floor';
+ if (domain === 'cover' || domain === 'lock' || domain === 'camera' || domain === 'switch') return 'wall';
+ if (domain === 'media_player' || domain === 'alarm_control_panel') return 'wall';
+ if (domain === 'binary_sensor') return OPENING_CLASSES.has(entity.deviceClass) ? 'wall' : null;
+ if (domain === 'climate' || domain === 'vacuum') return 'floor';
+ return null;
+}
+
+/**
+ * The visual kind the renderer draws. Deliberately coarser than the domain: a
+ * `switch` and a `media_player` are both panels on a wall, and giving each
+ * domain its own mesh would be a bestiary nobody can read at a glance.
+ */
+export function kindOf(entity) {
+ switch (entity.domain) {
+ case 'light':
+ return 'lamp';
+ case 'fan':
+ return 'fan';
+ case 'lock':
+ return 'lock';
+ case 'cover':
+ return entity.deviceClass === 'garage' || entity.deviceClass === 'door' ? 'door' : 'window';
+ case 'binary_sensor':
+ return entity.deviceClass === 'garage_door' || entity.deviceClass === 'door' ? 'door' : 'window';
+ case 'climate':
+ return 'thermostat';
+ case 'media_player':
+ return 'screen';
+ case 'camera':
+ return 'camera';
+ case 'alarm_control_panel':
+ return 'alarm';
+ case 'vacuum':
+ return 'puck';
+ case 'switch':
+ return 'plate';
+ default:
+ return 'plate';
+ }
+}
+
+/**
+ * Is this entity currently "active" in the way its kind means it?
+ *
+ * A light is on, a cover is open, a lock is UNLOCKED, a media player is
+ * playing. The lock inversion is deliberate and load-bearing: unlocked is the
+ * state a person needs to spot from across the room, so it is the one that
+ * lights up.
+ */
+export function activityOf(entity) {
+ const state = entity.state;
+ if (state === 'unavailable' || state === 'unknown') return 0;
+ switch (entity.domain) {
+ case 'light':
+ case 'switch':
+ case 'fan':
+ return state === 'on' ? 1 : 0;
+ case 'lock':
+ return state === 'unlocked' || state === 'open' || state === 'opening' ? 1 : 0;
+ case 'cover': {
+ const position = Number(entity.attributes?.current_position);
+ if (Number.isFinite(position)) return clamp01(position / 100);
+ return state === 'open' || state === 'opening' ? 1 : 0;
+ }
+ case 'binary_sensor':
+ return state === 'on' ? 1 : 0;
+ case 'media_player':
+ return state === 'playing' ? 1 : state === 'paused' || state === 'on' ? 0.5 : 0;
+ case 'climate':
+ return state && state !== 'off' ? 1 : 0;
+ case 'vacuum':
+ return state === 'cleaning' || state === 'returning' ? 1 : 0;
+ case 'alarm_control_panel':
+ return state && state !== 'disarmed' ? 1 : 0;
+ default:
+ return 0;
+ }
+}
+
+/** True when Home Assistant is telling us this device is not answering. */
+export function isUnavailable(entity) {
+ return entity.state === 'unavailable' || entity.state === 'unknown' || entity.state == null;
+}
+
+/**
+ * The room's own light: what colour it is and how bright, from the lights that
+ * are actually on. `summarizeLighting` already averages brightness and colour;
+ * this turns that into something a renderer and a CSS gradient can both use.
+ *
+ * Off means genuinely dark. A room whose lights are all off must not read as
+ * "dimmed": that is the difference between a model of a house and a picture of
+ * one.
+ */
+export function lightOf(room) {
+ const lighting = room.lighting || { total: 0, on: 0, brightness: 0, rgb: null };
+ const on = lighting.on > 0;
+ const brightness = on ? clamp01(lighting.brightness || 0.8) : 0;
+ const rgb = on ? lighting.rgb || [255, 236, 202] : [120, 132, 168];
+ return {
+ on,
+ total: lighting.total,
+ count: lighting.on,
+ brightness,
+ rgb,
+ hex: rgbToHex(rgb),
+ // A dark room still needs enough ambient to be readable, so the floor of
+ // the range is the moonlight a screen has to have, not zero.
+ intensity: on ? 0.35 + brightness * 1.5 : 0.06,
+ };
+}
+
+/**
+ * Warm or cool, from the room's own measured temperature. Neutral below the
+ * comfort band's width so an ordinary room is not permanently tinted.
+ */
+export function climateOf(room) {
+ const climate = room.climate;
+ if (!climate || !Number.isFinite(climate.temperature)) return null;
+ const t = climate.temperature;
+ const offset = clamp(-1, 1, (t - 21) / 6);
+ return {
+ temperature: t,
+ sources: climate.sources,
+ // -1 fully cool, +1 fully warm. The renderer and the 2D card both read it.
+ tint: Number(offset.toFixed(3)),
+ label: `${t.toFixed(1)}°`,
+ };
+}
+
+/** Sensors are numbers, not objects: they become one readout line per room. */
+export function readoutsOf(entities) {
+ const out = [];
+ for (const entity of entities) {
+ if (entity.domain !== 'sensor') continue;
+ const value = Number(entity.state);
+ if (!Number.isFinite(value)) continue;
+ out.push({
+ entityId: entity.entityId,
+ name: entity.name,
+ deviceClass: entity.deviceClass || null,
+ value,
+ unit: entity.attributes?.unit_of_measurement || '',
+ });
+ }
+ return out.sort((a, b) => String(a.name).localeCompare(String(b.name))).slice(0, 6);
+}
+
+/**
+ * Build the scene.
+ *
+ * @param {object} graph the room graph from buildHomeGraph()
+ * @param {object} [options]
+ * @param {string} [options.focusRoomId] the room the camera and the agent are on
+ * @param {Record<string, {x:number,z:number,w?:number,d?:number}>} [options.layout]
+ * an authored floorplan (order 07). Absent, rooms pack by floor in name order.
+ * @returns {object} the scene model
+ */
+export function buildSceneModel(graph, options = {}) {
+ const source = graph && typeof graph === 'object' ? graph : {};
+ const rawRooms = Array.isArray(source.rooms) ? source.rooms : [];
+ const unassigned = Array.isArray(source.unassigned) ? source.unassigned : [];
+ const layout = options.layout || null;
+
+ // Every entity the house has that nobody put in an area is still somebody's
+ // device. A house with zero assigned areas is the common case, not an edge
+ // case, so it renders as one honest room rather than a blank floor.
+ const rooms = [...rawRooms];
+ if (unassigned.length) {
+ rooms.push({
+ id: '__unassigned__',
+ name: rawRooms.length ? 'Not in a room' : 'Everything',
+ floorId: null,
+ icon: null,
+ synthetic: true,
+ entities: unassigned,
+ // The rollups a real area gets, applied to the bucket nobody filed.
+ // Same functions the graph builder uses, so one shape flows through.
+ lighting: summarizeLighting(unassigned),
+ climate: summarizeClimate(unassigned),
+ secured: summarizeSecurity(unassigned),
+ });
+ }
+
+ const floors = planFloors(source.floors, rooms);
+ const placed = [];
+ for (const floor of floors) {
+ const cells = packCells(floor.rooms.length);
+ floor.rooms.forEach((room, index) => {
+ const authored = layout?.[room.id];
+ const cell = cells[index];
+ const x = Number.isFinite(authored?.x) ? authored.x : cell.x * CELL;
+ const z = Number.isFinite(authored?.z) ? authored.z : cell.z * CELL;
+ placed.push(buildRoom(room, floor, { x, z, w: authored?.w, d: authored?.d }));
+ });
+ }
+
+ const bounds = boundsOf(placed);
+ const focusRoomId = pickFocusRoom(placed, options.focusRoomId);
+ const drawn = placed.reduce((n, r) => n + r.objects.length, 0);
+ const total = placed.reduce((n, r) => n + r.entityCount, 0);
+
+ return {
+ floors: floors.map((f) => ({ id: f.id, name: f.name, level: f.level, y: f.y, roomIds: f.rooms.map((r) => r.id) })),
+ rooms: placed,
+ bounds,
+ focusRoomId,
+ agent: agentStand(placed, focusRoomId),
+ // A house where nothing is assigned to an area is a designed state, not a
+ // failure, and the page has to be able to tell the two apart.
+ needsLayout: rawRooms.length === 0 && unassigned.length > 0,
+ empty: total === 0,
+ stats: { floors: floors.length, rooms: placed.length, entities: total, drawn, summarized: total - drawn },
+ };
+}
+
+/** Floors, with every room slotted onto one, ordered by level then by name. */
+function planFloors(rawFloors, rooms) {
+ const declared = (Array.isArray(rawFloors) ? rawFloors : []).map((f) => ({
+ id: f.id,
+ name: f.name,
+ level: Number.isFinite(f.level) ? f.level : 0,
+ rooms: [],
+ }));
+ const byId = new Map(declared.map((f) => [f.id, f]));
+ let loose = null;
+
+ for (const room of [...rooms].sort(byName)) {
+ const floor = room.floorId && byId.get(room.floorId);
+ if (floor) {
+ floor.rooms.push(room);
+ continue;
+ }
+ // A house with no floor registry, or a room nobody placed on a floor.
+ // It joins the lowest declared floor rather than getting a phantom one
+ // beneath the house: a floor labelled "Unplaced" hanging under the ground
+ // floor reads as a basement the user does not have, and it dragged the
+ // default camera and the agent down into it.
+ if (!loose) {
+ loose = lowestFloor(declared) || { id: '__ground__', name: 'Home', level: 0, rooms: [] };
+ if (!byId.has(loose.id)) {
+ declared.push(loose);
+ byId.set(loose.id, loose);
+ }
+ }
+ loose.rooms.push(room);
+ }
+
+ const used = declared.filter((f) => f.rooms.length).sort((a, b) => a.level - b.level || String(a.name).localeCompare(String(b.name)));
+ used.forEach((floor, index) => {
+ floor.y = index * FLOOR_HEIGHT;
+ });
+ return used;
+}
+
+function lowestFloor(floors) {
+ return floors.reduce((low, f) => (!low || f.level < low.level ? f : low), null);
+}
+
+/**
+ * Pack n rooms into a grid centred on the origin. Wider than tall, because a
+ * screen is, and a house read from a 3/4 camera reads better in rows.
+ */
+export function packCells(n) {
+ const cols = Math.max(1, Math.ceil(Math.sqrt(n * 1.35)));
+ const rows = Math.max(1, Math.ceil(n / cols));
+ const out = [];
+ for (let i = 0; i < n; i += 1) {
+ const col = i % cols;
+ const row = Math.floor(i / cols);
+ out.push({ x: col - (cols - 1) / 2, z: row - (rows - 1) / 2 });
+ }
+ return out;
+}
+
+function buildRoom(room, floor, cell) {
+ const entities = Array.isArray(room.entities) ? room.entities : [];
+ const w = Number.isFinite(cell.w) ? cell.w : CELL - ROOM_GAP;
+ const d = Number.isFinite(cell.d) ? cell.d : CELL - ROOM_GAP;
+
+ const ranked = [...entities].sort(
+ (a, b) => (RANK[a.domain] ?? 99) - (RANK[b.domain] ?? 99) || String(a.name).localeCompare(String(b.name)),
+ );
+
+ const slots = { ceiling: [], wall: [], floor: [] };
+ const caps = { ceiling: MAX_CEILING, wall: MAX_WALL, floor: MAX_FLOOR };
+ const overflow = [];
+ for (const entity of ranked) {
+ const where = placementOf(entity);
+ if (!where) continue;
+ if (slots[where].length >= caps[where]) {
+ overflow.push(entity);
+ continue;
+ }
+ slots[where].push(entity);
+ }
+
+ const objects = [];
+ slots.ceiling.forEach((entity, i) => objects.push(placeObject(entity, ceilingSlot(i, slots.ceiling.length, w, d))));
+ slots.wall.forEach((entity, i) => objects.push(placeObject(entity, wallSlot(i, slots.wall.length, w, d))));
+ slots.floor.forEach((entity, i) => objects.push(placeObject(entity, floorSlot(i, slots.floor.length, w, d))));
+
+ const secured = room.secured || null;
+ return {
+ id: room.id,
+ name: room.name,
+ floorId: floor.id,
+ level: floor.level,
+ synthetic: Boolean(room.synthetic),
+ x: cell.x,
+ y: floor.y,
+ z: cell.z,
+ w,
+ d,
+ h: WALL_HEIGHT,
+ light: lightOf(room),
+ climate: climateOf(room),
+ security: secured
+ ? { ...secured, unlocked: secured.unlocked || [], open: secured.open || [] }
+ : null,
+ objects,
+ readouts: readoutsOf(entities),
+ entityCount: entities.length,
+ hiddenCount: overflow.length,
+ unavailableCount: entities.filter(isUnavailable).length,
+ };
+}
+
+function placeObject(entity, slot) {
+ return {
+ entityId: entity.entityId,
+ name: entity.name,
+ domain: entity.domain,
+ deviceClass: entity.deviceClass || null,
+ kind: kindOf(entity),
+ placement: slot.placement,
+ x: round(slot.x),
+ y: round(slot.y),
+ z: round(slot.z),
+ rotation: round(slot.rotation),
+ state: entity.state,
+ activity: activityOf(entity),
+ available: !isUnavailable(entity),
+ attributes: entity.attributes || {},
+ };
+}
+
+/** Ceiling objects hang in a row across the room, just under the slab. */
+function ceilingSlot(i, n, w, d) {
+ const span = w * 0.62;
+ const x = n === 1 ? 0 : -span / 2 + (span * i) / (n - 1);
+ return { placement: 'ceiling', x, y: WALL_HEIGHT - 0.42, z: n > 3 && i % 2 ? d * 0.16 : -d * 0.12, rotation: 0 };
+}
+
+/**
+ * Wall objects walk the perimeter clockwise from the front-left corner, so two
+ * doors never land on the same spot and a room reads the same way every time
+ * it rebuilds.
+ */
+function wallSlot(i, n, w, d) {
+ const perimeter = 2 * (w + d);
+ const t = ((i + 0.5) / Math.max(1, n)) * perimeter;
+ const halfW = w / 2 - 0.12;
+ const halfD = d / 2 - 0.12;
+ const y = 1.15;
+ if (t < w) return { placement: 'wall', x: -halfW + (t / w) * (w - 0.24), y, z: -halfD, rotation: 0 };
+ if (t < w + d) return { placement: 'wall', x: halfW, y, z: -halfD + ((t - w) / d) * (d - 0.24), rotation: -Math.PI / 2 };
+ if (t < 2 * w + d) return { placement: 'wall', x: halfW - ((t - w - d) / w) * (w - 0.24), y, z: halfD, rotation: Math.PI };
+ return { placement: 'wall', x: -halfW, y, z: halfD - ((t - 2 * w - d) / d) * (d - 0.24), rotation: Math.PI / 2 };
+}
+
+/** Floor objects stand in a shallow arc toward the front of the room. */
+function floorSlot(i, n, w, d) {
+ const span = w * 0.5;
+ const x = n === 1 ? 0 : -span / 2 + (span * i) / (n - 1);
+ return { placement: 'floor', x, y: 0, z: d * 0.24, rotation: 0 };
+}
+
+function boundsOf(rooms) {
+ if (!rooms.length) return { minX: -CELL, maxX: CELL, minZ: -CELL, maxZ: CELL, minY: 0, maxY: FLOOR_HEIGHT, width: CELL * 2, depth: CELL * 2 };
+ let minX = Infinity;
+ let maxX = -Infinity;
+ let minZ = Infinity;
+ let maxZ = -Infinity;
+ let maxY = 0;
+ for (const room of rooms) {
+ minX = Math.min(minX, room.x - room.w / 2);
+ maxX = Math.max(maxX, room.x + room.w / 2);
+ minZ = Math.min(minZ, room.z - room.d / 2);
+ maxZ = Math.max(maxZ, room.z + room.d / 2);
+ maxY = Math.max(maxY, room.y + room.h);
+ }
+ return { minX, maxX, minZ, maxZ, minY: 0, maxY, width: maxX - minX, depth: maxZ - minZ };
+}
+
+function pickFocusRoom(rooms, requested) {
+ if (requested && rooms.some((r) => r.id === requested)) return requested;
+ if (!rooms.length) return null;
+ // Default to the busiest real room on the lowest floor: it is where a person
+ // walks in, and it is the room most likely to make the first frame legible.
+ // The unassigned bucket is never the default focus while a real room exists,
+ // however many entities it holds, because it is a filing cabinet and not a
+ // place in the house.
+ const real = rooms.filter((r) => !r.synthetic);
+ const pool0 = real.length ? real : rooms;
+ const lowest = Math.min(...pool0.map((r) => r.level));
+ const candidates = pool0.filter((r) => r.level === lowest);
+ const pool = candidates.length ? candidates : pool0;
+ return pool.reduce((best, room) => (room.objects.length > best.objects.length ? room : best), pool[0]).id;
+}
+
+/** Where the agent's body stands, and which way it faces. */
+function agentStand(rooms, focusRoomId) {
+ const room = rooms.find((r) => r.id === focusRoomId) || rooms[0];
+ if (!room) return { roomId: null, x: 0, y: 0, z: 0, facing: 0 };
+ return {
+ roomId: room.id,
+ x: round(room.x - room.w * 0.22),
+ y: room.y,
+ z: round(room.z + room.d * 0.2),
+ // Facing out of the room toward the default camera, so it reads as
+ // standing in the house and looking at you rather than at a wall.
+ facing: 0,
+ };
+}
+
+/**
+ * Diff two scene models by entity id. The renderer uses it to touch only what
+ * changed: a burst of a hundred state updates must not rebuild a hundred
+ * meshes, and a ten-minute session must not grow the heap by one object.
+ */
+export function diffScene(previous, next) {
+ const before = objectIndex(previous);
+ const after = objectIndex(next);
+ const changed = [];
+ const added = [];
+ const removed = [];
+ for (const [id, object] of after) {
+ const old = before.get(id);
+ if (!old) {
+ added.push(object);
+ continue;
+ }
+ if (old.activity !== object.activity || old.state !== object.state || old.available !== object.available) changed.push(object);
+ }
+ for (const [id, object] of before) if (!after.has(id)) removed.push(object);
+
+ const roomsChanged = [];
+ const beforeRooms = new Map((previous?.rooms || []).map((r) => [r.id, r]));
+ for (const room of next?.rooms || []) {
+ const old = beforeRooms.get(room.id);
+ if (!old) {
+ roomsChanged.push(room.id);
+ continue;
+ }
+ if (
+ old.light.intensity !== room.light.intensity ||
+ old.light.hex !== room.light.hex ||
+ old.climate?.temperature !== room.climate?.temperature ||
+ old.security?.secure !== room.security?.secure
+ ) {
+ roomsChanged.push(room.id);
+ }
+ }
+ return { added, changed, removed, roomsChanged };
+}
+
+function objectIndex(model) {
+ const map = new Map();
+ for (const room of model?.rooms || []) for (const object of room.objects) map.set(object.entityId, object);
+ return map;
+}
+
+// ── small helpers ────────────────────────────────────────────────────────────
+
+function byName(a, b) {
+ return String(a.name).localeCompare(String(b.name));
+}
+
+function clamp01(n) {
+ return clamp(0, 1, n);
+}
+
+function clamp(min, max, n) {
+ return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : min;
+}
+
+function round(n) {
+ return Math.round(n * 1000) / 1000;
+}
+
+export function rgbToHex(rgb) {
+ const [r, g, b] = rgb;
+ return `#${[r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('')}`;
+}