Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(home): meter what a connected house costs and price it per plan
nirholas38e6b6c4d537
diff --git a/api/_lib/home/entitlements.js b/api/_lib/home/entitlements.jsnew file mode 100644index 000000000..a2a32ec47--- /dev/null+++ b/api/_lib/home/entitlements.js@@ -0,0 +1,890 @@+/**+ * What a plan lets a house do, and the one thing no plan may ever stop it doing.+ *+ * ── The cost model, because it decides the shape of everything below ─────────+ *+ * The expensive thing in this lane is not an action. It is a HELD SOCKET. A+ * house that is connected and idle occupies heap on a Cloud Run instance for+ * the entire month whether or not anybody speaks to it, so a plan metered only+ * on actions would charge nothing for the dominant cost. That is why `homes`+ * is the first dimension here and why it is the one enforced at acquisition.+ *+ * Measured, not assumed (scripts/measure-home-entitlement-cost.mjs, 2026-09-03,+ * 16 real WebSocket connections against a real Home Assistant with 125+ * entities, priced against the production service shape and the live Cloud Run+ * SKUs from Google's own billing catalog):+ *+ * 302 KB heap / 262 KB RSS per live connection → $0.0155 per home per month+ * 23,036-byte room graph per stream event → $0.0066 per open stream per month+ * an agent turn on the default free LLM chain → $0+ * the same turn on Claude Sonnet 5 → $0.0228+ *+ * The finding that number produces is worth stating plainly: **one agent turn on+ * a paid model costs more than a year of holding that house's socket.** The free+ * tier can therefore carry a genuinely connected home, and the limits below are+ * generous on connections and careful on paid-model turns, which is the opposite+ * of what the cost model looked like before it was measured.+ *+ * ── The five commitments ─────────────────────────────────────────────────────+ *+ * These are product commitments, not implementation details, and the first and+ * last are the ones to fight for if anybody pushes back:+ *+ * 1. A LIMIT NEVER BLOCKS A SAFETY ACTION. Over quota, past due, downgraded,+ * suspended: a user can still lock their door, close their garage, close a+ * water valve and arm their alarm. The safe direction is always free. A+ * product that will not let someone lock up because they hit a quota is+ * indefensible, and `isQuotaExempt` below is where that is enforced rather+ * than promised. It delegates to the home-bridge package's own+ * `isSafetyAction`, so the list of safe moves is a fact about Home+ * Assistant kept in one place, never a copy in the billing code.+ *+ * 2. DOWNGRADING NEVER SILENTLY DISCONNECTS A HOUSE. Connections over the new+ * limit are marked inactive with a written explanation and the user picks+ * which to keep. Nothing is deleted, no credential is scrubbed, no action+ * log loses its lineage. See `planDowngrade` and `applyDowngrade`.+ *+ * 3. A QUOTA IS SHOWN BEFORE IT IS HIT, on the manage surface, with the reset+ * date. `describeEntitlements` returns exactly what that surface renders.+ *+ * 4. ENTERPRISE LIMITS ARE CONFIGURABLE PER ACCOUNT, not hardcoded, because+ * that is what the sales conversation is. `home_plan_overrides` carries+ * them and raising one is a row, never a deploy.+ *+ * 5. NOTHING ABOUT THE GATE IS A PAID FEATURE. Confirmations, the audit log's+ * integrity and the role system's safety properties exist on every tier.+ * Selling safety would be wrong and it would also make the free tier a+ * liability. There is deliberately no dimension below for any of them, and+ * there must never be one.+ *+ * ── Where the numbers come from ──────────────────────────────────────────────+ *+ * This module does NOT invent a fourth entitlement system. It reads the two that+ * already exist:+ *+ * api/_lib/account-tier.js the membership modes (user, beta, pro, holder,+ * three-dimensional) and the resolver over them.+ * api/_lib/three-tier.js the $THREE holder ladder and its `rateMultiplier`,+ * which is already defined as "scales free quotas".+ *+ * A member wears several badges at once, so a limit is the MAX across every+ * active badge, never the primary badge's alone: a Pro subscriber who also holds+ * $THREE must not lose Pro's connection limit because `holder` outranks `pro`.+ *+ * Every number is env-overridable (`HOME_LIMIT_<TIER>_<DIMENSION>`), so applying+ * an owner-approved price is a config change on a running service and not a+ * deploy. The defaults below are a PROPOSAL: see docs/home-plans.md.+ */++import { isSafetyAction, isSafetyMcpCall } from '@three-ws/home-bridge';++import { ACCOUNT_TIERS, detectHolder, resolveAccountTier } from '../account-tier.js';+import { sql } from '../db.js';+import { withDbRetry } from '../db-retry.js';+import { tierForUsd } from '../three-tier.js';++/** No limit. Chosen over `null` so a comparison never silently passes on a typo. */+export const UNLIMITED = Number.POSITIVE_INFINITY;++/**+ * The dimensions we meter, each with the measured cost that justifies metering+ * it at all. A dimension without a cost behind it is a dimension we should not+ * be charging for, so `costPerUnitUsd` is required and `costBasis` says how it+ * was read.+ *+ * `scalesWithHolding` marks the dimensions the $THREE ladder's `rateMultiplier`+ * applies to. Structural, sold-not-held dimensions (household members) are+ * deliberately excluded: holding a bag is not the same purchase as buying seats+ * for a hotel, and multiplying one by the other prices neither correctly.+ */+export const HOME_DIMENSIONS = Object.freeze({+ homes: Object.freeze({+ id: 'homes',+ label: 'Connected homes',+ unit: 'home',+ scope: 'account',+ period: 'concurrent',+ scalesWithHolding: true,+ costPerUnitUsd: 0.0155,+ costBasis: 'per month; 302 KB heap / 262 KB RSS per live WebSocket, 16 connections against a real Home Assistant, priced on the production 4 GiB / 2 vCPU shape at the live us-central1 Cloud Run rate',+ why: 'A connected house holds a socket for the whole month whether or not anyone speaks to it. This is the lane’s primary cost.',+ }),+ members: Object.freeze({+ id: 'members',+ label: 'Household members per home',+ unit: 'member',+ scope: 'home',+ period: 'concurrent',+ scalesWithHolding: false,+ costPerUnitUsd: 0,+ costBasis: 'no marginal infrastructure cost; a member is a row in home_members and shares the home’s single pooled socket',+ why: 'The enterprise dimension. A hotel or an office buys seats, and seats are the sales conversation, not a compute cost.',+ }),+ streams: Object.freeze({+ id: 'streams',+ label: 'Live streams per home',+ unit: 'stream',+ scope: 'home',+ period: 'concurrent',+ scalesWithHolding: true,+ costPerUnitUsd: 0.0066,+ costBasis: 'per month; a 23,036-byte room graph serialized once per 10 s, priced at the live us-central1 Cloud Run CPU and memory rates',+ why: 'A wall display left open all month is a subscriber we serialize the house to on every state change.',+ }),+ voiceMinutes: Object.freeze({+ id: 'voiceMinutes',+ label: 'Voice minutes',+ unit: 'minute',+ scope: 'account',+ period: 'month',+ scalesWithHolding: true,+ costPerUnitUsd: 0,+ costBasis: 'the default lanes are keyless: Edge Read Aloud TTS (api/_lib/tts-edge.js) and NVIDIA Riva ASR (api/_lib/asr-nvidia.js) both cost the platform nothing per utterance',+ why: 'Metered because a paid speech lane can be selected and because an unbounded always-listening satellite is an abuse surface, not because the default lane costs money.',+ }),+ agentTurns: Object.freeze({+ id: 'agentTurns',+ label: 'Agent turns',+ unit: 'turn',+ scope: 'account',+ period: 'month',+ scalesWithHolding: true,+ costPerUnitUsd: 0,+ costBasis: 'the default provider chain leads with platform-held free lanes (isFreeLane in api/_lib/llm-pricing.js); the same 6,359-token home prompt costs $0.0025 on Vertex Gemini 2.5 Flash and $0.0228 on Claude Sonnet 5 when a paid model is chosen',+ why: 'The room graph makes a home prompt large. On a paid model one turn costs more than a year of holding that house’s socket, so the turn is the dimension that actually needs a ceiling.',+ }),+ logRetentionDays: Object.freeze({+ id: 'logRetentionDays',+ label: 'Action-log retention',+ unit: 'day',+ scope: 'account',+ period: 'retention',+ scalesWithHolding: true,+ costPerUnitUsd: 0,+ costBasis: 'Neon row storage; a busy evening of voice control is a few dozen rows of a few hundred bytes each',+ why: 'A natural enterprise upsell: a hotel needs a year of attribution, a household needs last Tuesday. Length is the product, never the log’s integrity.',+ // A CEILING on what a user may set, never a value of its own. Order 15+ // (api/_lib/home/privacy.js) owns the per-home retention setting, its+ // default of 90 days and the purge that enforces it; this only caps how+ // high that setting may go. It is checked when the user changes the+ // setting and NEVER applied retroactively: shortening somebody's existing+ // audit trail for a billing reason would destroy their evidence, which is+ // the log's integrity, which commitment 5 puts out of reach of a plan.+ ceilingOnly: true,+ }),+ relayConnections: Object.freeze({+ id: 'relayConnections',+ label: 'Relay connections',+ unit: 'relay',+ scope: 'account',+ period: 'concurrent',+ scalesWithHolding: true,+ costPerUnitUsd: 0.0155,+ costBasis: 'the same held-socket cost as a direct home; a relay is an inbound socket instead of an outbound one',+ why: 'A LAN-only house reaches us through a sustained dial-out tunnel, which costs what a direct connection costs.',+ }),+});++/** Dimension ids, in the order the manage surface renders them. */+export const HOME_DIMENSION_IDS = Object.freeze(Object.keys(HOME_DIMENSIONS));++/**+ * The proposed defaults, per account-tier badge.+ *+ * PROPOSAL, not a decision. The mechanism is complete and every number here is+ * a config value: `HOME_LIMIT_PRO_HOMES=25` on the running service raises Pro's+ * connection limit with no deploy and no code change. See docs/home-plans.md for+ * the table put to the owner and the measured cost behind each row.+ *+ * The shape follows the cost: connections are cheap so the free tier gets a real+ * one, and turns are the dimension where a paid model can actually spend money+ * so that is where the tiers separate.+ */+const DEFAULT_LIMITS = Object.freeze({+ user: Object.freeze({+ homes: 1,+ members: 3,+ streams: 2,+ voiceMinutes: 300,+ agentTurns: 1000,+ logRetentionDays: 90,+ relayConnections: 1,+ }),+ beta: Object.freeze({+ homes: 2,+ members: 5,+ streams: 3,+ voiceMinutes: 600,+ agentTurns: 2500,+ logRetentionDays: 90,+ relayConnections: 1,+ }),+ pro: Object.freeze({+ homes: 5,+ members: 15,+ streams: 10,+ voiceMinutes: 3000,+ agentTurns: 15000,+ logRetentionDays: 365,+ relayConnections: 5,+ }),+ holder: Object.freeze({+ homes: 1,+ members: 3,+ streams: 2,+ voiceMinutes: 300,+ agentTurns: 1000,+ logRetentionDays: 90,+ relayConnections: 1,+ }),+ 'three-dimensional': Object.freeze({+ homes: UNLIMITED,+ members: UNLIMITED,+ streams: UNLIMITED,+ voiceMinutes: UNLIMITED,+ agentTurns: UNLIMITED,+ // Not UNLIMITED: home_connections_retention_days_chk caps the stored value+ // at ten years, so an "unlimited" ceiling here would offer a number the+ // database refuses. A limit the schema cannot honour is a broken promise.+ logRetentionDays: 3650,+ relayConnections: UNLIMITED,+ }),+});++const TIER_IDS = Object.freeze(ACCOUNT_TIERS.map((t) => t.id));++/**+ * `HOME_LIMIT_<TIER>_<DIMENSION>`, upper snake case, e.g.+ * `HOME_LIMIT_THREE_DIMENSIONAL_AGENT_TURNS`. `unlimited` and `-1` both mean no+ * limit; anything unparseable is ignored so a typo degrades to the default+ * rather than to zero, which would lock an account out of its own house.+ */+function envLimit(tierId, dimensionId) {+ const key = `HOME_LIMIT_${screamingSnake(tierId)}_${screamingSnake(dimensionId)}`;+ const raw = process.env[key];+ if (raw == null || String(raw).trim() === '') return null;+ return parseLimit(raw);+}++function parseLimit(raw) {+ const s = String(raw).trim().toLowerCase();+ if (s === 'unlimited' || s === 'infinity' || s === '-1') return UNLIMITED;+ const n = Number.parseInt(s, 10);+ return Number.isFinite(n) && n >= 0 ? n : null;+}++function screamingSnake(id) {+ return String(id)+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')+ .replace(/[^A-Za-z0-9]+/g, '_')+ .toUpperCase();+}++/**+ * The configured limits for one badge, env overrides applied.+ * @param {string} tierId+ * @returns {Record<string, number>}+ */+export function limitsForTier(tierId) {+ const base = DEFAULT_LIMITS[tierId] || DEFAULT_LIMITS.user;+ const out = {};+ for (const dimension of HOME_DIMENSION_IDS) {+ const override = envLimit(tierId, dimension);+ out[dimension] = override == null ? base[dimension] : override;+ }+ return out;+}++/**+ * Merge a set of badges into one limit set by taking the max per dimension.+ *+ * Max, not the primary badge's value, because badges are additive: `holder`+ * outranks `pro` on the display ladder, and a Pro subscriber who also holds+ * $THREE must not lose Pro's connection limit by buying some of the coin.+ */+function mergeBadgeLimits(badgeIds) {+ const merged = {};+ for (const dimension of HOME_DIMENSION_IDS) merged[dimension] = 0;+ for (const id of badgeIds) {+ const limits = limitsForTier(id);+ for (const dimension of HOME_DIMENSION_IDS) {+ if (limits[dimension] > merged[dimension]) merged[dimension] = limits[dimension];+ }+ }+ return merged;+}++/**+ * One account's effective limits, and everything the manage surface needs to+ * explain them.+ *+ * Pure over its inputs so it unit-tests without a wallet RPC or a database:+ * `resolveHomeEntitlements` does the I/O and calls this.+ *+ * @param {{ account_tier?: string|null, plan?: string|null }} user+ * @param {object} [opts]+ * @param {{ isHolder: boolean, amount: number, usd: number }} [opts.holder]+ * @param {Record<string, number>|null} [opts.override] per-account overrides+ * @returns {{+ * tier: object, badges: object[], holderTier: object, multiplier: number,+ * limits: Record<string, number>, sources: Record<string, string>,+ * dimensions: object,+ * }}+ */+export function computeEntitlements(user, { holder = { isHolder: false, amount: 0, usd: 0 }, override = null } = {}) {+ const account = resolveAccountTier(user, { holder });+ const badgeIds = account.badges.map((b) => b.id);+ const base = mergeBadgeLimits(badgeIds);++ // The $THREE ladder already models holding. Read its multiplier; never model+ // holding a second time with thresholds of our own.+ const holderTier = tierForUsd(holder.usd);+ const multiplier = Math.max(1, Number(holderTier.rateMultiplier) || 1);++ const limits = {};+ const sources = {};+ for (const dimension of HOME_DIMENSION_IDS) {+ let value = base[dimension];+ sources[dimension] = 'plan';+ if (HOME_DIMENSIONS[dimension].scalesWithHolding && multiplier > 1 && Number.isFinite(value)) {+ value = value * multiplier;+ sources[dimension] = 'holder-multiplier';+ }+ if (override && Object.prototype.hasOwnProperty.call(override, dimension)) {+ const parsed = typeof override[dimension] === 'number' ? override[dimension] : parseLimit(override[dimension]);+ // An override is the sales conversation, so it wins in both directions:+ // an enterprise deal can raise a limit and a fair-use agreement can cap+ // one. It is never silently ignored.+ if (parsed != null) {+ value = parsed;+ sources[dimension] = 'account-override';+ }+ }+ limits[dimension] = value;+ }++ return {+ tier: account.primary,+ badges: account.badges,+ plan: account.plan,+ holder,+ holderTier,+ multiplier,+ limits,+ sources,+ dimensions: HOME_DIMENSIONS,+ };+}++/**+ * The same thing, with the reads. Resolves the caller's on-chain $THREE standing+ * and their per-account override row.+ *+ * Fails toward the user on every read: an unreachable price oracle resolves a+ * holder to the Member floor rather than throwing, and an unreadable override+ * row falls back to the plan's limits rather than to zero.+ *+ * @param {{ id: string, account_tier?: string|null, plan?: string|null }} user+ * @param {object} [opts]+ * @param {string[]} [opts.walletAddresses]+ * @returns {Promise<object>}+ */+export async function resolveHomeEntitlements(user, { walletAddresses = [] } = {}) {+ const wallets = walletAddresses.length ? walletAddresses : [user?.wallet_address].filter(Boolean);+ const [holder, override] = await Promise.all([+ detectHolder(wallets).catch(() => ({ isHolder: false, amount: 0, usd: 0 })),+ getAccountOverride(user?.id).catch(() => null),+ ]);+ const resolved = computeEntitlements(user, { holder, override: override?.limits || null });+ return { ...resolved, override };+}++/**+ * The same thing, from a user id alone, which is what every route actually has.+ *+ * Reads the account exactly the way /api/users/me/tier already does: the plan+ * and grant columns from `users`, plus every Solana wallet the account controls+ * (the login wallet and any linked ones), because $THREE may be held in any of+ * them and a holder who is only credited for one wallet is a holder we have+ * under-served.+ *+ * @param {string} userId+ * @returns {Promise<object>}+ */+export async function resolveHomeEntitlementsForUser(userId) {+ const rows = await withDbRetry(() => sql`+ select id, plan, account_tier, wallet_address+ from users+ where id = ${userId} and deleted_at is null+ limit 1+ `);+ const user = rows[0];+ if (!user) throw new Error('resolveHomeEntitlementsForUser: no such account');++ const linked = await withDbRetry(() => sql`+ select address from user_wallets+ where user_id = ${userId} and chain_type = 'solana'+ `).catch(() => []);++ const wallets = [user.wallet_address, ...linked.map((w) => w.address)].filter(Boolean);+ return resolveHomeEntitlements(user, { walletAddresses: wallets });+}++// ── Per-account overrides ────────────────────────────────────────────────────++/**+ * The enterprise row. One per account, set by an admin, with the reason on it,+ * because "why does this account have 400 homes" is a question somebody asks six+ * months later and the answer has to be in the row rather than in a memory.+ *+ * @param {string} userId+ * @returns {Promise<{ limits: Record<string, number>, note: string|null, setBy: string|null, updatedAt: string }|null>}+ */+export async function getAccountOverride(userId) {+ if (!userId) return null;+ const rows = await withDbRetry(() => sql`+ select limits, note, set_by, updated_at+ from home_plan_overrides+ where user_id = ${userId}+ `);+ if (!rows.length) return null;+ return {+ limits: rows[0].limits || {},+ note: rows[0].note || null,+ setBy: rows[0].set_by || null,+ updatedAt: rows[0].updated_at,+ };+}++/**+ * Write or replace an account's override. Only known dimensions survive, so a+ * typo in an admin form cannot install a limit nothing reads.+ *+ * @param {object} input+ * @param {string} input.userId+ * @param {Record<string, number|string>} input.limits+ * @param {string|null} [input.note] why this account has these limits+ * @param {string|null} [input.setBy] the admin's user id+ */+export async function setAccountOverride({ userId, limits, note = null, setBy = null }) {+ if (!userId) throw new Error('setAccountOverride: userId is required');+ const clean = {};+ for (const [key, value] of Object.entries(limits || {})) {+ if (!HOME_DIMENSIONS[key]) continue;+ const parsed = typeof value === 'number' && Number.isFinite(value) ? value : parseLimit(value);+ if (parsed != null) clean[key] = parsed === UNLIMITED ? 'unlimited' : parsed;+ }+ const rows = await withDbRetry(() => sql`+ insert into home_plan_overrides (user_id, limits, note, set_by)+ values (${userId}, ${JSON.stringify(clean)}::jsonb, ${note}, ${setBy})+ on conflict (user_id) do update set+ limits = excluded.limits,+ note = excluded.note,+ set_by = excluded.set_by,+ updated_at = now()+ returning limits, note, set_by, updated_at+ `);+ return rows[0];+}++/** Remove an account's override, returning it to its plan's limits. */+export async function clearAccountOverride(userId) {+ if (!userId) return false;+ const rows = await withDbRetry(() => sql`+ delete from home_plan_overrides where user_id = ${userId} returning user_id+ `);+ return rows.length > 0;+}++// ── The safety exemption ─────────────────────────────────────────────────────++/**+ * Is this call one no commercial limit may ever refuse?+ *+ * COMMITMENT 1 LIVES HERE. Every enforcement point in the lane calls this first+ * and returns without consulting a counter when it answers true. There is no+ * tier, no override, no past-due state and no suspension in which locking a+ * door, closing a garage, closing a water valve or arming an alarm is refused+ * by this platform.+ *+ * The list of safe moves is NOT duplicated here. It comes from+ * `@three-ws/home-bridge`'s `isSafetyAction`, beside the gate it mirrors,+ * because what a lock can do is a fact about Home Assistant and not a fact about+ * a price list.+ *+ * @param {object} call+ * @param {string} [call.domain]+ * @param {string} [call.service]+ * @param {object} [call.attributes]+ * @param {string} [call.tool] an MCP tool name, when the call arrives on that channel+ * @param {object} [call.arguments] the MCP tool's arguments+ * @param {Array<object>} [call.entities] the live entity list, for MCP target resolution+ * @returns {boolean}+ */+export function isQuotaExempt(call = {}) {+ if (call.tool) return isSafetyMcpCall(call.tool, call.arguments || {}, call.entities || []);+ return isSafetyAction({ domain: call.domain, service: call.service, attributes: call.attributes || {} });+}++// ── Enforcement ──────────────────────────────────────────────────────────────++/**+ * A refusal a user can act on. Never a 500, never a bare "quota exceeded": it+ * names the limit, what they are using, when it resets, and what to do next.+ */+export class HomeQuotaError extends Error {+ /**+ * @param {object} input+ * @param {string} input.dimension+ * @param {number} input.limit+ * @param {number} input.used+ * @param {string|null} [input.resetAt]+ * @param {object} [input.tier]+ * @param {string} [input.message]+ */+ constructor({ dimension, limit, used, resetAt = null, tier = null, message = null }) {+ const meta = HOME_DIMENSIONS[dimension];+ super(message || defaultQuotaMessage({ dimension, limit, used, resetAt, tier }));+ this.name = 'HomeQuotaError';+ this.code = 'quota_exceeded';+ this.status = 402;+ this.dimension = dimension;+ this.dimensionLabel = meta?.label || dimension;+ this.limit = limit;+ this.used = used;+ this.resetAt = resetAt;+ this.tierId = tier?.id || null;+ this.upgradePath = '/pricing';+ }+}++function defaultQuotaMessage({ dimension, limit, used, resetAt, tier }) {+ const meta = HOME_DIMENSIONS[dimension];+ const label = (meta?.label || dimension).toLowerCase();+ const plan = tier?.label ? `Your ${tier.label} plan` : 'Your plan';+ const head = `${plan} covers ${limit} ${limit === 1 ? meta?.unit || label : plural(meta?.unit || label)}, and you are using ${used}.`;+ const tail = resetAt+ ? `This resets on ${formatResetDate(resetAt)}. You can upgrade at three.ws/pricing to raise it now.`+ : 'Upgrade at three.ws/pricing to raise it, or free one up on your homes page.';+ const safe = 'Locking up, closing a garage or valve and arming an alarm are never affected by a limit.';+ return `${head} ${tail} ${safe}`;+}++function plural(unit) {+ return /s$/.test(unit) ? unit : `${unit}s`;+}++function formatResetDate(iso) {+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return 'the start of next month';+ return d.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' });+}++/**+ * The one enforcement primitive. Every call site in the lane goes through it so+ * the safety exemption cannot be forgotten at one of them.+ *+ * @param {object} input+ * @param {object} input.entitlements from resolveHomeEntitlements+ * @param {string} input.dimension+ * @param {number} input.used current usage, exclusive of the request being made+ * @param {number} [input.cost] how many units this request consumes+ * @param {string|null} [input.resetAt]+ * @param {object|null} [input.call] the physical call, when there is one+ * @returns {{ allowed: true, exempt: boolean, remaining: number }}+ * @throws {HomeQuotaError}+ */+export function assertWithinLimit({ entitlements, dimension, used, cost = 1, resetAt = null, call = null }) {+ if (call && isQuotaExempt(call)) {+ return { allowed: true, exempt: true, remaining: Number.POSITIVE_INFINITY };+ }+ const limit = entitlements?.limits?.[dimension];+ if (limit == null) throw new Error(`assertWithinLimit: unknown dimension "${dimension}"`);+ if (!Number.isFinite(limit)) return { allowed: true, exempt: false, remaining: Number.POSITIVE_INFINITY };+ if (used + cost > limit) {+ throw new HomeQuotaError({ dimension, limit, used, resetAt, tier: entitlements.tier });+ }+ return { allowed: true, exempt: false, remaining: limit - used - cost };+}++/**+ * A paused home is not a broken home. It is a home the account's plan does not+ * currently cover, and the distinction is the whole of commitment 2: the row is+ * intact, the credential is intact, the log is intact, and the user can bring it+ * back by upgrading, by pausing a different house, or by changing their mind.+ */+export class HomePausedError extends Error {+ /**+ * @param {object} input+ * @param {string} input.label+ * @param {string|null} [input.reason]+ */+ constructor({ label, reason = null }) {+ super(+ `"${label}" is paused because your plan covers fewer connected homes than you have. ` ++ `${reason ? `${reason} ` : ''}` ++ 'Nothing was deleted and nothing was disconnected: bring it back from your homes page, or pause a different home to make room. ' ++ 'Locking up, closing a garage or valve and arming an alarm keep working on a paused home.',+ );+ this.name = 'HomePausedError';+ this.code = 'home_paused';+ this.status = 402;+ this.label = label;+ this.reason = reason;+ this.upgradePath = '/pricing';+ }+}++/**+ * The guard every action goes through, and the one place commitment 1 is+ * enforced on the write path.+ *+ * Order matters and it is the point: the safety exemption is checked FIRST, so+ * there is no plan state, no pause, no quota and no override in which locking a+ * door, closing a garage or a valve, or arming an alarm is refused. It is+ * checked before the home's state is even looked at, so a bug in the pause logic+ * cannot reach it.+ *+ * The exemption does not need a live socket. `isSafetyAction` classifies from+ * the domain and service alone, which is what makes this usable in exactly the+ * degraded states where a person most needs to lock up.+ *+ * @param {object} input+ * @param {{ label: string, deactivated_at?: string|null, deactivated_reason?: string|null }} input.home+ * @param {{ domain?: string, service?: string, tool?: string, arguments?: object, entities?: object[] }} input.call+ * @returns {{ allowed: true, exempt: boolean }}+ * @throws {HomePausedError}+ */+export function assertHomeActionAllowed({ home, call }) {+ if (isQuotaExempt(call)) return { allowed: true, exempt: true };+ if (home?.deactivated_at) {+ throw new HomePausedError({ label: home.label || 'This home', reason: home.deactivated_reason });+ }+ return { allowed: true, exempt: false };+}++/**+ * Can this home take another household member?+ *+ * Billed to the HOME'S OWNER, never to the person sending the invitation. An+ * admin inviting a house sitter is spending the owner's seats, and charging the+ * admin's own plan for them would mean a household's capacity changed depending+ * on which member happened to click the button.+ *+ * Counts the seats already taken plus the invitations already outstanding,+ * because an unspent invite is a seat that is about to be occupied and letting+ * ten of them through to a five-seat home just moves the refusal to the moment+ * somebody accepts, which is the worst possible time to discover it.+ *+ * @param {string} homeId+ * @returns {Promise<{ allowed: true, remaining: number }>}+ * @throws {HomeQuotaError}+ */+export async function assertMemberCapacity(homeId) {+ const rows = await withDbRetry(() => sql`+ select+ c.user_id as owner_id,+ (select count(*)::int from home_members m where m.home_id = c.id) as members,+ (select count(*)::int from home_invites i+ where i.home_id = c.id and i.accepted_at is null and i.revoked_at is null and i.expires_at > now())+ as pending+ from home_connections c+ where c.id = ${homeId}+ `);+ const row = rows[0];+ if (!row) throw new Error('assertMemberCapacity: no such home');++ const entitlements = await resolveHomeEntitlementsForUser(row.owner_id);+ return assertWithinLimit({+ entitlements,+ dimension: 'members',+ used: (row.members ?? 0) + (row.pending ?? 0),+ });+}++// ── The downgrade path ───────────────────────────────────────────────────────++/**+ * What a downgrade would do, without doing it.+ *+ * COMMITMENT 2 LIVES HERE. A downgrade never picks for the user and never+ * deletes: it names which homes exceed the new limit, keeps the oldest ones+ * active by default because they are the ones most likely to be the real house,+ * and hands the choice back.+ *+ * @param {Array<{ id: string, label: string, created_at: string, deactivated_at?: string|null }>} connections+ * @param {number} limit the new connection limit+ * @returns {{ overBy: number, limit: number, keep: object[], deactivate: object[], explanation: string }}+ */+export function planDowngrade(connections, limit) {+ const live = connections.filter((c) => !c.deactivated_at);+ if (!Number.isFinite(limit) || live.length <= limit) {+ return { overBy: 0, limit, keep: live, deactivate: [], explanation: '' };+ }+ const ordered = [...live].sort((a, b) => new Date(a.created_at) - new Date(b.created_at));+ const keep = ordered.slice(0, Math.max(0, limit));+ const deactivate = ordered.slice(Math.max(0, limit));+ const explanation =+ `Your plan now covers ${limit} connected ${limit === 1 ? 'home' : 'homes'} and you have ${live.length}. ` ++ `We have paused ${deactivate.map((c) => `"${c.label}"`).join(', ')} rather than disconnecting ${deactivate.length === 1 ? 'it' : 'them'}: ` ++ 'nothing was deleted, your access tokens and your action logs are untouched, and you can swap which homes are active at any time. ' ++ 'A paused home still answers safety actions: locking up, closing a garage or valve and arming an alarm keep working.';+ return { overBy: deactivate.length, limit, keep, deactivate, explanation };+}++/**+ * Carry out a downgrade plan. Marks rows inactive; deletes nothing, revokes+ * nothing, scrubs no credential.+ *+ * @param {object} input+ * @param {string} input.userId+ * @param {string[]} input.deactivateIds+ * @param {string} input.reason+ * @returns {Promise<object[]>} the paused rows+ */+export async function applyDowngrade({ userId, deactivateIds, reason }) {+ if (!userId || !deactivateIds?.length) return [];+ return withDbRetry(() => sql`+ update home_connections+ set deactivated_at = now(),+ deactivated_reason = ${String(reason || 'Paused by a plan change.')},+ updated_at = now()+ where user_id = ${userId}+ and id = any(${deactivateIds}::uuid[])+ and revoked_at is null+ and deactivated_at is null+ returning id, label, deactivated_at, deactivated_reason+ `);+}++/**+ * Bring a paused home back, refusing when doing so would exceed the limit. The+ * user swapping which houses are active is the whole point of pausing rather+ * than disconnecting, so this is the other half of commitment 2.+ *+ * @param {object} input+ * @param {string} input.userId+ * @param {string} input.homeId+ * @param {object} input.entitlements+ * @returns {Promise<object>}+ */+export async function reactivateConnection({ userId, homeId, entitlements }) {+ const active = await countActiveConnections(userId);+ assertWithinLimit({ entitlements, dimension: 'homes', used: active });+ const rows = await withDbRetry(() => sql`+ update home_connections+ set deactivated_at = null, deactivated_reason = null, updated_at = now()+ where user_id = ${userId} and id = ${homeId} and revoked_at is null+ returning id, label, deactivated_at+ `);+ if (!rows.length) throw new Error('reactivateConnection: no such home for this account');+ return rows[0];+}++/** How many of this account's homes are live right now. The `homes` gauge. */+export async function countActiveConnections(userId) {+ if (!userId) return 0;+ const rows = await withDbRetry(() => sql`+ select count(*)::int as n+ from home_connections+ where user_id = ${userId} and revoked_at is null and deactivated_at is null+ `);+ return rows[0]?.n ?? 0;+}++// ── The manage surface's view ────────────────────────────────────────────────++/**+ * The quota period. A UTC calendar month.+ *+ * The platform has no per-user plan billing period to key off (`users.plan` is a+ * column, not a subscription with a cycle), and inventing one here would be a+ * second billing clock that drifts from whatever the real one turns out to be.+ * A calendar month resets on a date every user can predict, it is the same+ * choice the per-IP image quota already made one rung down (a UTC day), and when+ * a real billing cycle lands this is one function to change.+ *+ * @param {Date} [now]+ * @returns {{ start: Date, end: Date, startIso: string, endIso: string, key: string }}+ */+export function quotaPeriod(now = new Date()) {+ const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0, 0));+ const end = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0, 0));+ return {+ start,+ end,+ startIso: start.toISOString(),+ endIso: end.toISOString(),+ key: start.toISOString().slice(0, 7),+ };+}++/**+ * Everything the manage surface renders, in one object.+ *+ * COMMITMENT 3 LIVES HERE: a quota is shown before it is hit. Every dimension+ * comes back whether or not it is close to its ceiling, each with its usage, its+ * limit, the percentage, the reset date, and the measured cost that justifies+ * metering it, so the page can explain the limit rather than merely enforce it.+ *+ * Pure: it takes the usage rather than reading it, so the page's numbers and the+ * enforcement path's numbers come from one function and cannot disagree.+ *+ * @param {object} entitlements from resolveHomeEntitlements+ * @param {Record<string, number>} usage per-dimension current usage+ * @param {object} [opts]+ * @param {Date} [opts.now]+ * @returns {object}+ */+export function describeEntitlements(entitlements, usage = {}, { now = new Date() } = {}) {+ const period = quotaPeriod(now);+ const dimensions = HOME_DIMENSION_IDS.map((id) => {+ const meta = HOME_DIMENSIONS[id];+ const limit = entitlements.limits[id];+ const used = Number(usage[id]) || 0;+ const unlimited = !Number.isFinite(limit);+ return {+ id,+ label: meta.label,+ unit: meta.unit,+ scope: meta.scope,+ period: meta.period,+ why: meta.why,+ used,+ limit: unlimited ? null : limit,+ unlimited,+ remaining: unlimited ? null : Math.max(0, limit - used),+ percent: unlimited ? 0 : limit === 0 ? 100 : Math.min(100, Math.round((used / limit) * 100)),+ exceeded: !unlimited && used > limit,+ source: entitlements.sources[id],+ resetsAt: meta.period === 'month' ? period.endIso : null,+ costPerUnitUsd: meta.costPerUnitUsd,+ costBasis: meta.costBasis,+ };+ });++ return {+ tier: { id: entitlements.tier.id, label: entitlements.tier.label, color: entitlements.tier.color },+ badges: entitlements.badges.map((b) => ({ id: b.id, label: b.label, color: b.color })),+ plan: entitlements.plan,+ holder: {+ isHolder: entitlements.holder.isHolder,+ usd: entitlements.holder.usd,+ tier: entitlements.holderTier.label,+ multiplier: entitlements.multiplier,+ },+ override: entitlements.override+ ? { note: entitlements.override.note, updatedAt: entitlements.override.updatedAt, dimensions: Object.keys(entitlements.override.limits || {}) }+ : null,+ period: { startsAt: period.startIso, resetsAt: period.endIso },+ dimensions,+ // Stated on the surface itself, not only in this file, because a user+ // reading their limits is exactly the person who needs to know which of+ // them can never apply to them.+ alwaysFree: [+ 'Locking a door, closing a garage or gate, closing a water valve and arming an alarm are never refused by a limit, on any plan.',+ 'Confirmation prompts, the action log and every role safety property are on every plan. Safety is not an upgrade.',+ ],+ upgradePath: '/pricing',+ };+}diff --git a/api/_lib/home/usage.js b/api/_lib/home/usage.jsnew file mode 100644index 000000000..f16cc4690--- /dev/null+++ b/api/_lib/home/usage.js@@ -0,0 +1,262 @@+/**+ * What an account has used this month, counted once.+ *+ * There is exactly one authoritative number per dimension and it lives in+ * `usage_events`, the platform's existing counter (api/_lib/usage.js). This+ * module does NOT introduce a second one. Two counters means two numbers that+ * disagree, and the one on the invoice is the one that will be wrong.+ *+ * What it does add is a read path fast enough to gate a request with, because+ * `recordEvent` is deliberately eventually consistent: it buffers into Redis and+ * a job drains the buffer into Postgres. Gating on a `select count(*)` alone+ * would let a burst through before the first row landed, and gating on a+ * separate tally would be the second counter we just refused. So:+ *+ * * `usage_events` is the source of truth. The invoice reads it. `readUsage`+ * reads it.+ * * A Redis key per (account, dimension, month) CACHES that number and is+ * incremented in lockstep with each `recordEvent`, so the very next gate+ * check sees the event that was just recorded.+ * * When the cache is cold it is SEEDED from `usage_events`, so it converges+ * on the authoritative number rather than starting a private tally.+ *+ * The one place the two can disagree is a cache eviction while events are still+ * in the buffer: the re-seed misses them and the account is under-counted for+ * the rest of the month. That bias is deliberate and it is the same bias the+ * per-IP image quota already takes: a quota that errs must err toward serving+ * the user. Over-counting would refuse a person access to their own house over+ * a Redis hiccup, which is not a trade this lane is willing to make.+ *+ * Without Redis (local dev, tests) every read goes straight to `usage_events`.+ * Correct, just slower, and there is no cross-instance state to protect.+ */++import { sql } from '../db.js';+import { withDbRetry } from '../db-retry.js';+import { getRedis } from '../redis.js';+import { recordEvent } from '../usage.js';++import { quotaPeriod } from './entitlements.js';++/**+ * Which `usage_events` rows each metered dimension is made of.+ *+ * `agentTurns` deliberately has NO kind of its own. A conversation with the+ * agent already writes exactly one `kind: 'chat'` row carrying the provider, the+ * model, the token counts and the priced cost (api/chat.js), and that row is+ * what an invoice would charge for. Minting a `home.turn` row beside it would be+ * the second counter this module exists to refuse: two numbers, disagreeing, and+ * the one on the invoice wrong. So the home turn is the same row, distinguished+ * by the `home_id` api/chat.js stamps into its meta when a home tool ran.+ *+ * `voiceMinutes` does get its own kind, because nothing counts voice today: the+ * TTS and ASR lanes write no usage events at all. That is a new fact, not a+ * duplicated one.+ */+export const USAGE_SOURCES = Object.freeze({+ agentTurns: Object.freeze({+ kind: 'chat',+ // Only the turns that actually touched a house. A conversation about+ // nothing in particular is not a home turn and must not be billed as one.+ requiresMetaKey: 'home_id',+ }),+ voiceMinutes: Object.freeze({ kind: 'home.voice', requiresMetaKey: null }),+});++/** The dimension whose events this module mints itself. */+const OWN_KINDS = Object.freeze({ voiceMinutes: 'home.voice' });++/** Dimensions this module counts. The rest are live gauges, not accumulations. */+export const METERED_DIMENSIONS = Object.freeze(Object.keys(USAGE_SOURCES));++const CACHE_PREFIX = 'home:usage';++function cacheKey(userId, dimension, periodKey) {+ return `${CACHE_PREFIX}:${userId}:${dimension}:${periodKey}`;+}++/** Seconds from now to the end of the quota period, plus a day of clock slack. */+function ttlSeconds(period, now = new Date()) {+ return Math.max(60, Math.ceil((period.end.getTime() - now.getTime()) / 1000) + 86_400);+}++/**+ * Count one unit of usage, in both places, in that order.+ *+ * The durable write goes first (it is fire-and-forget and cannot fail the+ * caller) and the cache bump second, so a cache that is unreachable costs+ * accuracy on the next gate check and never costs a billing row.+ *+ * @param {object} input+ * @param {string} input.userId+ * @param {'agentTurns'|'voiceMinutes'} input.dimension+ * @param {number} [input.amount] units consumed; voice is counted in minutes,+ * fractional, and rounded up only at the gate so a 20 second utterance is not+ * billed as a minute.+ * @param {string|null} [input.homeId]+ * @param {object} [input.meta] anything worth answering a support question with.+ * Never a credential, never a full state dump.+ */+export async function recordHomeUsage({ userId, dimension, amount = 1, homeId = null, meta = {} }) {+ if (!userId) return;+ const kind = OWN_KINDS[dimension];+ if (!kind) {+ throw new Error(+ `recordHomeUsage: "${dimension}" is not a dimension this module mints. ` ++ 'Agent turns are counted from the chat row api/chat.js already writes; do not mint a second one.',+ );+ }++ recordEvent({+ userId,+ kind,+ tool: homeId ? `home:${homeId}` : null,+ meta: { ...meta, amount, dimension },+ provider: meta.provider ?? null,+ model: meta.model ?? null,+ inputTokens: meta.inputTokens ?? null,+ outputTokens: meta.outputTokens ?? null,+ costMicroUsd: meta.costMicroUsd ?? null,+ });++ const redis = getRedis();+ if (!redis) return;+ const period = quotaPeriod();+ const key = cacheKey(userId, dimension, period.key);+ try {+ // Seed before the increment, or the increment starts a private tally from+ // zero and the cache never converges on the authoritative number.+ await ensureSeeded(redis, key, userId, dimension, period);+ await redis.incrbyfloat(key, amount);+ } catch {+ // The durable row is already written. A cache miss costs precision on the+ // next gate check, which the module's header accepts by design.+ }+}++/**+ * The authoritative count for one dimension this period, straight from+ * `usage_events`. This is the number the invoice would use.+ *+ * @param {string} userId+ * @param {string} dimension+ * @param {{ start: Date, end: Date }} period+ * @returns {Promise<number>}+ */+export async function readUsageFromEvents(userId, dimension, period = quotaPeriod()) {+ const source = USAGE_SOURCES[dimension];+ if (!source) return 0;+ // `amount` is how a fractional unit (a 20 second utterance is a third of a+ // voice minute) survives into the sum; a row without one is one unit, which is+ // what every chat row is.+ const rows = await withDbRetry(() => sql`+ select coalesce(sum(coalesce((meta->>'amount')::numeric, 1)), 0)::float8 as total+ from usage_events+ where user_id = ${userId}+ and kind = ${source.kind}+ and (${source.requiresMetaKey}::text is null or meta ? ${source.requiresMetaKey}::text)+ and created_at >= ${period.start.toISOString()}+ and created_at < ${period.end.toISOString()}+ `);+ return Number(rows[0]?.total) || 0;+}++async function ensureSeeded(redis, key, userId, dimension, period) {+ const existing = await redis.get(key);+ if (existing != null) return Number(existing) || 0;+ const seed = await readUsageFromEvents(userId, dimension, period);+ // SET NX so two instances seeding the same cold key at once cannot double it.+ await redis.set(key, seed, { nx: true, ex: ttlSeconds(period) });+ const settled = await redis.get(key);+ return Number(settled ?? seed) || 0;+}++/**+ * One dimension's usage for the gate: the cache when it is warm, the+ * authoritative table when it is not.+ *+ * @param {string} userId+ * @param {string} dimension+ * @param {{ start: Date, end: Date, key: string }} [period]+ * @returns {Promise<number>}+ */+export async function readUsage(userId, dimension, period = quotaPeriod()) {+ if (!userId) return 0;+ const redis = getRedis();+ if (!redis) return readUsageFromEvents(userId, dimension, period);+ try {+ return await ensureSeeded(redis, cacheKey(userId, dimension, period.key), userId, dimension, period);+ } catch {+ return readUsageFromEvents(userId, dimension, period);+ }+}++/**+ * Every dimension at once, for the manage surface and for the gate.+ *+ * The live gauges (`homes`, `streams`, `members`, `relayConnections`) are counted+ * from their own tables rather than from an event stream, because a gauge that is+ * reconstructed from a log of opens and closes is a gauge that drifts the first+ * time a process dies holding a socket.+ *+ * @param {string} userId+ * @param {object} [opts]+ * @param {number|null} [opts.streams] live SSE subscribers for this account, from+ * the runtime, when the caller has it. Omitted rather than guessed.+ * @returns {Promise<Record<string, number>>}+ */+export async function readHomeUsage(userId, { streams = null } = {}) {+ const period = quotaPeriod();+ const [agentTurns, voiceMinutes, gauges] = await Promise.all([+ readUsage(userId, 'agentTurns', period),+ readUsage(userId, 'voiceMinutes', period),+ readGauges(userId),+ ]);+ return {+ agentTurns,+ voiceMinutes: Math.round(voiceMinutes * 100) / 100,+ ...gauges,+ streams: streams == null ? 0 : streams,+ };+}++/**+ * The concurrent counts, read from the tables that own them.+ * @param {string} userId+ */+async function readGauges(userId) {+ const rows = await withDbRetry(() => sql`+ select+ count(*) filter (where c.revoked_at is null and c.deactivated_at is null)::int as homes,+ count(*) filter (where c.revoked_at is null and c.deactivated_at is null and c.transport = 'relay')::int as relay_connections,+ coalesce(max(m.members), 0)::int as members+ from home_connections c+ left join lateral (+ select count(*)::int as members from home_members hm where hm.home_id = c.id+ ) m on true+ where c.user_id = ${userId}+ `);+ const row = rows[0] || {};+ return {+ homes: row.homes ?? 0,+ relayConnections: row.relay_connections ?? 0,+ // The members limit is per home, so the account-level figure the manage+ // surface shows is the fullest household: that is the one that would be+ // refused an invite, and therefore the one worth showing.+ members: row.members ?? 0,+ logRetentionDays: 0,+ };+}++/**+ * Reset a cached counter so the next read re-seeds from `usage_events`.+ * Used by the tests and by an admin correcting a miscount; never on a hot path.+ * @param {string} userId+ * @param {string} dimension+ */+export async function invalidateUsageCache(userId, dimension) {+ const redis = getRedis();+ if (!redis) return;+ const period = quotaPeriod();+ await redis.del(cacheKey(userId, dimension, period.key)).catch(() => {});+}diff --git a/api/_lib/migrations/20260903160000_home_plan_overrides.sql b/api/_lib/migrations/20260903160000_home_plan_overrides.sqlnew file mode 100644index 000000000..90c79713c--- /dev/null+++ b/api/_lib/migrations/20260903160000_home_plan_overrides.sql@@ -0,0 +1,87 @@+begin;++-- Plans, entitlements and quotas for the Home lane.+--+-- Two changes, both of which exist because of a commitment the product makes+-- rather than because of a schema convenience.+--+-- ── 1. home_plan_overrides: the enterprise row ───────────────────────────────+--+-- Enterprise limits are configurable per account, not hardcoded, because that is+-- what the sales conversation is. A hotel does not buy "Pro", it buys 400 rooms+-- and a year of attribution, and the shape of that deal is known on the call and+-- not at deploy time. Encoding it as a tier constant means every new customer is+-- a code change; encoding it as a row means it is an admin action.+--+-- The note column is not decoration. "Why does this account have 400 homes" is a+-- question somebody asks six months after the person who agreed it has moved on,+-- and the answer has to be in the row rather than in a memory.+--+-- Considered and rejected:+--+-- * Columns per dimension. The dimension list is a product decision that will+-- move (relay connections did not exist two orders ago), and a migration per+-- pricing experiment is how a pricing experiment stops happening. jsonb,+-- validated in api/_lib/home/entitlements.js against the known dimension+-- set, so an unknown key cannot install a limit nothing reads.+--+-- * Storing the resolved limits rather than the deltas. A stored resolution+-- goes stale the moment a plan default moves, and then the enterprise+-- account is the ONE account that silently keeps the old defaults. Only the+-- agreed overrides live here; everything else resolves live.+--+-- * A tier row instead of an account row. Inventing a sixth account tier per+-- customer pollutes a display ladder that users see with rows only a+-- salesperson understands.++create table if not exists home_plan_overrides (+ user_id uuid primary key references users(id) on delete cascade,++ -- { "homes": 400, "members": "unlimited", "logRetentionDays": 365 }. Only+ -- keys in HOME_DIMENSIONS survive the writer; the string "unlimited" is the+ -- only non-numeric value accepted, and it means no limit.+ limits jsonb not null default '{}'::jsonb,++ -- Why this account has these numbers, in a sentence, for the person who asks+ -- in six months. Nullable only because a correction of a miscount is a valid+ -- write with nothing to say.+ note text,++ -- The admin who agreed it. Kept when they leave (set null), because the fact+ -- that a human authorised it survives the human's account.+ set_by uuid references users(id) on delete set null,++ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- ── 2. Pausing a home, which is what a downgrade does instead of disconnecting ─+--+-- Downgrading never silently disconnects a house. When an account drops below+-- the number of homes it has connected, the excess are marked inactive here with+-- a written explanation and the user chooses which to keep. Nothing is deleted,+-- the credential is NOT scrubbed (that is what revoke does and it is+-- irreversible), and the action log keeps its lineage.+--+-- This is a different state from `revoked_at`, and conflating them would be the+-- bug: revoke is the user saying "take my house off this platform" and it throws+-- the key away. A pause is the platform saying "your plan covers fewer of these+-- right now", and it must be reversible by paying, by cancelling another home,+-- or by the user changing their mind. Two columns, because "why is this paused"+-- has to be answerable on the page without a second lookup.+--+-- A paused home still answers safety actions. Locking up, closing a garage or a+-- valve and arming an alarm are never refused by a commercial limit, on any+-- plan, in any state. See api/_lib/home/entitlements.js `isQuotaExempt`.++alter table home_connections add column if not exists deactivated_at timestamptz;+alter table home_connections add column if not exists deactivated_reason text;++-- The list view's real working set: an account's homes that are actually live.+-- The existing user index does not carry the pause state, so a fleet with many+-- paused homes would scan them on every quota check.+create index if not exists home_connections_user_active_idx+ on home_connections(user_id, created_at desc)+ where revoked_at is null and deactivated_at is null;++commit;diff --git a/api/home/plan.js b/api/home/plan.jsnew file mode 100644index 000000000..9250aec77--- /dev/null+++ b/api/home/plan.js@@ -0,0 +1,179 @@+// GET /api/home/plan what this account's plan covers, what it is using, when it resets+// POST /api/home/plan the two things a user does about it, and the one thing an admin does+//+// This is the surface behind commitment 3: a quota is SHOWN before it is hit.+// The GET returns every dimension whether or not it is anywhere near its+// ceiling, each with the measured cost that justifies metering it, so the page+// can explain a limit rather than merely enforce one.+//+// The POST carries commitment 2. When a plan change leaves an account with more+// connected homes than it covers, nothing is disconnected and nothing is+// deleted: the excess are PAUSED, and the user swaps which of their houses are+// live whenever they like. `pause` and `resume` are that swap. Both are+// reversible, neither touches a credential, and neither removes a row.+//+// { action: 'preview' } what a downgrade to the current limit would pause+// { action: 'pause', home_id } pause one home+// { action: 'resume', home_id } bring one back, refused if it would exceed the limit+// { action: 'override', user_id, limits, note } admin only: the enterprise row+//+// A paused home still answers safety actions. Locking up, closing a garage or a+// valve and arming an alarm are never refused by a commercial limit, on any+// plan, in any state, and the response says so in words on the page.++import { requireAdmin } from '../_lib/admin.js';+import { requireCsrf } from '../_lib/csrf.js';+import { resolveCaller } from '../_lib/home/access.js';+import {+ applyDowngrade,+ clearAccountOverride,+ describeEntitlements,+ HomeQuotaError,+ planDowngrade,+ reactivateConnection,+ resolveHomeEntitlementsForUser,+ setAccountOverride,+} from '../_lib/home/entitlements.js';+import { readHomeUsage } from '../_lib/home/usage.js';+import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { limits as rateLimits } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const caller = await resolveCaller(req, res);+ if (!caller) return error(res, 401, 'unauthorized', 'Sign in to see your home plan.');++ if (req.method === 'GET') return handleGet(req, res, caller);+ return handlePost(req, res, caller);+});++async function handleGet(req, res, caller) {+ const rl = await rateLimits.homeRead(caller.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many plan reads, slow down');++ const [entitlements, usage] = await Promise.all([+ resolveHomeEntitlementsForUser(caller.userId),+ readHomeUsage(caller.userId),+ ]);++ const homes = await listHomesForPlan(caller.userId);+ const view = describeEntitlements(entitlements, usage);++ return json(res, 200, {+ ...view,+ homes,+ // What a downgrade to the CURRENT limit would pause. Zero on a healthy+ // account, and the whole explanation when a plan has just changed under+ // somebody, which is exactly when they open this page.+ downgrade: summarizeDowngrade(homes, entitlements.limits.homes),+ });+}++async function handlePost(req, res, caller) {+ if (!(await requireCsrf(req, res, caller.userId))) return;++ const rl = await rateLimits.homeAct(caller.userId);+ if (!rl.success) return rateLimited(res, rl, 'too many plan changes, slow down');++ const body = await readJson(req, 8_000).catch(() => null);+ const action = String(body?.action || '').toLowerCase();++ if (action === 'override') return handleOverride(req, res, body);++ if (action === 'preview') {+ const entitlements = await resolveHomeEntitlementsForUser(caller.userId);+ const homes = await listHomesForPlan(caller.userId);+ return json(res, 200, { downgrade: summarizeDowngrade(homes, entitlements.limits.homes), homes });+ }++ const homeId = String(body?.home_id || body?.homeId || '');+ if (!isUuid(homeId)) return error(res, 400, 'bad_request', 'home_id must be the id of one of your homes.');++ if (action === 'pause') {+ const paused = await applyDowngrade({+ userId: caller.userId,+ deactivateIds: [homeId],+ // Written in the user's own terms: they did this, and the page has to be+ // able to say so rather than blaming a plan for a choice they made.+ reason: 'You paused this home to make room for another one.',+ });+ if (!paused.length) return error(res, 404, 'not_found', 'No such home, or it is already paused.');+ return json(res, 200, { home: paused[0], homes: await listHomesForPlan(caller.userId) });+ }++ if (action === 'resume') {+ const entitlements = await resolveHomeEntitlementsForUser(caller.userId);+ try {+ const home = await reactivateConnection({ userId: caller.userId, homeId, entitlements });+ return json(res, 200, { home, homes: await listHomesForPlan(caller.userId) });+ } catch (err) {+ if (err instanceof HomeQuotaError) {+ return error(res, err.status, err.code, err.message, {+ code: err.code,+ quota: { dimension: err.dimension, label: err.dimensionLabel, limit: err.limit, used: err.used, upgrade: err.upgradePath },+ });+ }+ if (/no such home/.test(err?.message || '')) return error(res, 404, 'not_found', 'No such home.');+ throw err;+ }+ }++ return error(res, 400, 'bad_request', "action must be 'preview', 'pause', 'resume' or 'override'.");+}++/**+ * The enterprise row, set by an admin.+ *+ * Enterprise limits are configurable per account rather than hardcoded because+ * that is what the sales conversation is: a hotel buys 400 rooms and a year of+ * attribution, and the shape of that deal is known on the call and not at deploy+ * time. Sending `limits: {}` clears the override and returns the account to its+ * plan.+ */+async function handleOverride(req, res, body) {+ const admin = await requireAdmin(req, res);+ if (!admin) return;++ const userId = String(body?.user_id || body?.userId || '');+ if (!isUuid(userId)) return error(res, 400, 'bad_request', 'user_id is required.');++ const incoming = body?.limits && typeof body.limits === 'object' && !Array.isArray(body.limits) ? body.limits : null;+ if (!incoming) return error(res, 400, 'bad_request', 'limits must be an object of dimension to number or "unlimited".');++ if (Object.keys(incoming).length === 0) {+ await clearAccountOverride(userId);+ return json(res, 200, { cleared: true, entitlements: await resolveHomeEntitlementsForUser(userId) });+ }++ const note = typeof body.note === 'string' ? body.note.trim().slice(0, 500) : null;+ const row = await setAccountOverride({ userId, limits: incoming, note, setBy: admin.id });+ const entitlements = await resolveHomeEntitlementsForUser(userId);+ return json(res, 200, { override: row, entitlements: { limits: entitlements.limits, sources: entitlements.sources } });+}++/**+ * The account's homes as the plan page needs them: label, when it was added, and+ * whether it is live or paused (and why). No credential, no capability dump.+ */+async function listHomesForPlan(userId) {+ return sql`+ select id, label, base_url, status, created_at, deactivated_at, deactivated_reason+ from home_connections+ where user_id = ${userId} and revoked_at is null+ order by created_at asc+ `;+}++function summarizeDowngrade(homes, limit) {+ const plan = planDowngrade(homes, limit);+ return {+ overBy: plan.overBy,+ limit: Number.isFinite(plan.limit) ? plan.limit : null,+ explanation: plan.explanation,+ wouldPause: plan.deactivate.map((h) => ({ id: h.id, label: h.label })),+ };+}diff --git a/src/home/plan.css b/src/home/plan.cssnew file mode 100644index 000000000..4e47685f9--- /dev/null+++ b/src/home/plan.css@@ -0,0 +1,154 @@+/*+ * The plan page.+ *+ * Built on the tokens src/home/home.css already establishes, so the plan+ * surface and the connect surface are visibly one product rather than two pages+ * that happen to share a nav. Nothing here redefines a colour: --hm-live,+ * --hm-stale and --hm-down carry the same meanings they do everywhere else in+ * the lane (fine, nearly out, over), which is why a bar going amber reads the+ * same way a house going amber does.+ */++/* ── The plan header ─────────────────────────────────────────────────────── */++.hm-plan-badges {+ display: flex;+ flex-wrap: wrap;+ gap: 0.4rem;+ align-items: center;+}++.hm-plan-badge {+ --badge: var(--hm-ink-3);+ display: inline-flex;+ align-items: center;+ padding: 0.2rem 0.6rem;+ border-radius: var(--radius-pill);+ border: 1px solid color-mix(in srgb, var(--badge) 45%, transparent);+ background: color-mix(in srgb, var(--badge) 14%, transparent);+ color: var(--ink);+ font-size: 0.76rem;+ font-weight: 600;+ letter-spacing: 0.01em;+ white-space: nowrap;+}++.hm-panel-quiet { background: var(--hm-panel-2); }++/* ── The quota bars ──────────────────────────────────────────────────────── */++.hm-quotas {+ display: grid;+ gap: 1.1rem;+ margin-top: var(--space-md);+}++.hm-quota {+ display: grid;+ gap: 0.42rem;+ /* The state colour every bar inherits. Overridden by .is-warn / .is-over. */+ --quota: var(--hm-live);+}++.hm-quota.is-warn { --quota: var(--hm-stale); }+.hm-quota.is-over { --quota: var(--hm-down); }++.hm-quota-head {+ display: flex;+ align-items: baseline;+ justify-content: space-between;+ gap: var(--space-md);+}++.hm-quota-label {+ font-weight: 600;+ color: var(--ink);+ font-size: 0.95rem;+}++.hm-quota-count {+ font-family: var(--font-mono);+ font-size: 0.82rem;+ color: var(--hm-ink-2);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.hm-quota-track {+ height: 0.42rem;+ border-radius: var(--radius-pill);+ background: var(--hm-line);+ overflow: hidden;+}++.hm-quota-fill {+ height: 100%;+ border-radius: var(--radius-pill);+ background: var(--quota);+ /* Animated so a bar that moved after an action is visibly the thing that+ moved, rather than a number that was different the next time you looked. */+ transition: width 320ms cubic-bezier(0.22, 1, 0.36, 1), background-color 200ms ease;+}++.hm-quota-why {+ margin: 0;+ font-size: 0.82rem;+ line-height: var(--leading-normal);+ color: var(--hm-ink-3);+}++.hm-quota-note {+ margin: 0;+ font-size: 0.78rem;+ font-weight: 600;+ color: var(--hm-live);+}++/* ── A paused home ───────────────────────────────────────────────────────── */++.hm-card.is-paused {+ /* Dimmed, never hidden. A paused home is still your house and it still+ answers safety actions, so it stays legible rather than being greyed into+ the background as though it were gone. */+ border-style: dashed;+ background: var(--hm-panel-2);+}++.hm-card.is-paused .hm-card-label { color: var(--hm-ink-2); }++.hm-pill {+ display: inline-block;+ margin-left: 0.5rem;+ padding: 0.1rem 0.5rem;+ border-radius: var(--radius-pill);+ border: 1px solid color-mix(in srgb, var(--hm-stale) 45%, transparent);+ background: color-mix(in srgb, var(--hm-stale) 16%, transparent);+ color: var(--hm-stale);+ font-size: 0.7rem;+ font-weight: 700;+ letter-spacing: 0.03em;+ text-transform: uppercase;+ vertical-align: middle;+}++.hm-card-reason {+ margin: 0.4rem 0 0;+ font-size: 0.82rem;+ line-height: var(--leading-normal);+ color: var(--hm-ink-3);+}++.hm-btn.is-disabled {+ opacity: 0.45;+ pointer-events: none;+}++/* ── Responsive ──────────────────────────────────────────────────────────── */++@media (max-width: 520px) {+ .hm-quota-head { flex-direction: column; align-items: flex-start; gap: 0.15rem; }+}++@media (prefers-reduced-motion: reduce) {+ .hm-quota-fill { transition: none; }+}diff --git a/src/home/plan.js b/src/home/plan.jsnew file mode 100644index 000000000..8c4614f9b--- /dev/null+++ b/src/home/plan.js@@ -0,0 +1,328 @@+/**+ * The plan page: what your homes cost you, before it costs you anything.+ *+ * The point of this surface is commitment 3 from api/_lib/home/entitlements.js:+ * a quota is SHOWN before it is hit. So every dimension renders whether or not+ * it is anywhere near its ceiling, each with its reset date and the reason it is+ * metered at all, and the two lines that can never apply to a limit are on the+ * page in words rather than buried in a policy nobody opens.+ *+ * The other thing this page exists for is the moment a plan changes under+ * somebody. When that leaves an account with more connected homes than it+ * covers, nothing is disconnected: the excess are PAUSED, and this is where the+ * user swaps which of their houses are live. Every state of that swap is+ * designed here, including the one where the swap is refused because there is no+ * room, because that refusal is the whole reason the pause is reversible.+ */++import { changePlanState, getPlan, HomeApiError } from './api.js';+import { clear, el, noticeEl } from './connect.js';++const root = document.getElementById('hm-plan-root');++/** Bars go amber here and red at the ceiling, so "nearly out" is visible early. */+const WARN_AT = 80;++let busy = false;++boot();++async function boot() {+ try {+ render(await getPlan());+ } catch (err) {+ renderFailure(err);+ }+}++function render(plan) {+ const frag = document.createDocumentFragment();++ if (plan.downgrade?.overBy > 0) frag.append(downgradeNotice(plan.downgrade));+ frag.append(planPanel(plan));+ frag.append(quotaPanel(plan));+ frag.append(homesPanel(plan));+ frag.append(alwaysFreePanel(plan));++ clear(root);+ root.append(frag);+ root.setAttribute('aria-busy', 'false');+}++// ── The plan you are on ──────────────────────────────────────────────────────++function planPanel(plan) {+ const panel = el('section', 'hm-panel');+ const head = el('div', 'hm-panel-head');+ const left = el('div');+ left.append(el('h2', 'hm-panel-title', `You are on ${plan.tier.label}`));++ const sub = el('p', 'hm-panel-sub');+ sub.textContent = plan.holder.isHolder+ ? `Your $THREE holding puts you at ${plan.holder.tier}, which multiplies your free quotas by ${plan.holder.multiplier}.`+ : 'Holding $THREE multiplies your free quotas. Every limit below already accounts for what you hold.';+ left.append(sub);+ head.append(left);++ const badges = el('div', 'hm-plan-badges');+ for (const badge of plan.badges) {+ const chip = el('span', 'hm-plan-badge', badge.label);+ chip.style.setProperty('--badge', badge.color);+ badges.append(chip);+ }+ head.append(badges);+ panel.append(head);++ if (plan.override) {+ panel.append(+ noticeEl({+ tone: 'info',+ title: 'This account has agreed limits',+ body: plan.override.note || 'An administrator set custom limits on this account.',+ bullets: plan.override.dimensions.map((d) => `${labelFor(plan, d)} is set for this account specifically.`),+ }),+ );+ }++ const upgrade = el('div', 'hm-actions');+ const link = el('a', 'hm-btn hm-btn-primary', 'See plans');+ link.href = plan.upgradePath || '/pricing';+ upgrade.append(link);+ const back = el('a', 'hm-btn hm-btn-ghost', 'Back to your homes');+ back.href = '/smart-home';+ upgrade.append(back);+ panel.append(upgrade);++ return panel;+}++// ── What you are using ───────────────────────────────────────────────────────++function quotaPanel(plan) {+ const panel = el('section', 'hm-panel');+ const head = el('div', 'hm-panel-head');+ const left = el('div');+ left.append(el('h2', 'hm-panel-title', 'What you are using'));+ left.append(+ el(+ 'p',+ 'hm-panel-sub',+ `Monthly allowances reset on ${formatDate(plan.period.resetsAt)}. Connected homes, seats and live screens are counted as they are, right now.`,+ ),+ );+ head.append(left);+ panel.append(head);++ const list = el('div', 'hm-quotas');+ for (const dimension of plan.dimensions) list.append(quotaRow(dimension));+ panel.append(list);+ return panel;+}++function quotaRow(d) {+ const row = el('div', 'hm-quota');+ if (d.exceeded) row.classList.add('is-over');+ else if (!d.unlimited && d.percent >= WARN_AT) row.classList.add('is-warn');++ const head = el('div', 'hm-quota-head');+ head.append(el('span', 'hm-quota-label', d.label));+ head.append(el('span', 'hm-quota-count', d.unlimited ? `${formatNumber(d.used)} used · unlimited` : `${formatNumber(d.used)} of ${formatNumber(d.limit)}`));+ row.append(head);++ const track = el('div', 'hm-quota-track');+ track.setAttribute('role', 'progressbar');+ track.setAttribute('aria-valuemin', '0');+ track.setAttribute('aria-valuemax', '100');+ track.setAttribute('aria-valuenow', String(d.unlimited ? 0 : d.percent));+ track.setAttribute('aria-label', `${d.label}: ${d.unlimited ? 'unlimited' : `${d.percent}% used`}`);+ const fill = el('div', 'hm-quota-fill');+ fill.style.width = d.unlimited ? '0%' : `${Math.max(2, d.percent)}%`;+ track.append(fill);+ row.append(track);++ const foot = el('p', 'hm-quota-why');+ foot.textContent = d.resetsAt ? `${d.why} Resets ${formatDate(d.resetsAt)}.` : d.why;+ row.append(foot);++ if (d.source === 'holder-multiplier') row.append(el('p', 'hm-quota-note', 'Raised by your $THREE holding.'));+ if (d.source === 'account-override') row.append(el('p', 'hm-quota-note', 'Set for this account specifically.'));++ return row;+}++// ── Which homes are live ─────────────────────────────────────────────────────++function homesPanel(plan) {+ const panel = el('section', 'hm-panel');+ const head = el('div', 'hm-panel-head');+ const left = el('div');+ left.append(el('h2', 'hm-panel-title', 'Which homes are live'));+ left.append(+ el(+ 'p',+ 'hm-panel-sub',+ 'Pausing a home never disconnects it. Its access token, its settings and its whole action log stay exactly where they are, and you can swap which homes are live whenever you like.',+ ),+ );+ head.append(left);+ panel.append(head);++ if (!plan.homes.length) {+ const empty = el('div', 'hm-empty');+ empty.append(el('p', 'hm-empty-title', 'No homes connected yet'));+ empty.append(el('p', 'hm-empty-body', 'Connect a Home Assistant instance and it will appear here with everything it counts against.'));+ const cta = el('a', 'hm-btn hm-btn-primary', 'Connect a home');+ cta.href = '/smart-home';+ empty.append(cta);+ panel.append(empty);+ return panel;+ }++ const list = el('div', 'hm-list');+ for (const home of plan.homes) list.append(homeRow(home, plan));+ panel.append(list);+ return panel;+}++function homeRow(home, plan) {+ const card = el('div', 'hm-card');+ if (home.deactivated_at) card.classList.add('is-paused');++ const main = el('div', 'hm-card-main');+ const title = el('div', 'hm-card-label');+ title.textContent = home.label;+ if (home.deactivated_at) title.append(el('span', 'hm-pill', 'Paused'));+ main.append(title);+ main.append(el('div', 'hm-card-url', hostOf(home.base_url)));+ if (home.deactivated_at && home.deactivated_reason) {+ main.append(el('p', 'hm-card-reason', home.deactivated_reason));+ }+ card.append(main);++ const actions = el('div', 'hm-card-actions');+ const paused = Boolean(home.deactivated_at);+ const button = el('button', `hm-btn ${paused ? 'hm-btn-primary' : 'hm-btn-ghost'}`, paused ? 'Make live' : 'Pause');+ button.type = 'button';+ button.addEventListener('click', () => swap(paused ? 'resume' : 'pause', home, button));+ actions.append(button);++ const open = el('a', 'hm-btn hm-btn-ghost', 'Open');+ open.href = `/smart-home/${home.id}`;+ if (paused) {+ open.setAttribute('aria-disabled', 'true');+ open.classList.add('is-disabled');+ }+ actions.append(open);+ card.append(actions);++ void plan;+ return card;+}++async function swap(action, home, button) {+ if (busy) return;+ busy = true;+ const original = button.textContent;+ button.disabled = true;+ button.textContent = action === 'resume' ? 'Making live…' : 'Pausing…';+ try {+ await changePlanState(action, home.id);+ render(await getPlan());+ } catch (err) {+ button.disabled = false;+ button.textContent = original;+ const message =+ err instanceof HomeApiError+ ? err.message+ : 'Something went wrong changing which homes are live. Nothing was changed; try again.';+ const notice = noticeEl({ tone: 'error', title: action === 'resume' ? 'Could not make that home live' : 'Could not pause that home', body: message });+ root.prepend(notice);+ notice.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ } finally {+ busy = false;+ }+}++// ── The two things a limit can never do ──────────────────────────────────────++function alwaysFreePanel(plan) {+ const panel = el('section', 'hm-panel hm-panel-quiet');+ panel.append(el('h2', 'hm-panel-title', 'What a limit can never do'));+ const ul = el('ul', 'hm-ol');+ for (const line of plan.alwaysFree) {+ ul.append(el('li', null, line));+ }+ panel.append(ul);+ return panel;+}++// ── The downgrade moment ─────────────────────────────────────────────────────++function downgradeNotice(downgrade) {+ return noticeEl({+ tone: 'warn',+ title: `${downgrade.overBy} of your homes ${downgrade.overBy === 1 ? 'is' : 'are'} over your plan`,+ body: downgrade.explanation,+ bullets: downgrade.wouldPause.map((h) => `${h.label} would be paused, not disconnected.`),+ });+}++// ── Failure ──────────────────────────────────────────────────────────────────++function renderFailure(err) {+ const signedOut = err instanceof HomeApiError && (err.status === 401 || err.code === 'unauthorized');+ clear(root);+ root.setAttribute('aria-busy', 'false');+ root.append(+ noticeEl({+ tone: 'error',+ title: signedOut ? 'Sign in to see your plan' : 'Could not load your plan',+ body: signedOut+ ? 'Your home plan is tied to your three.ws account, so this page needs you signed in.'+ : err?.message || 'We could not read your plan just now. Your homes and your limits are unaffected.',+ }),+ );+ const actions = el('div', 'hm-actions');+ if (signedOut) {+ const login = el('a', 'hm-btn hm-btn-primary', 'Sign in');+ login.href = `/login?next=${encodeURIComponent('/smart-home/plan')}`;+ actions.append(login);+ } else {+ const retry = el('button', 'hm-btn hm-btn-primary', 'Try again');+ retry.type = 'button';+ retry.addEventListener('click', () => {+ root.setAttribute('aria-busy', 'true');+ boot();+ });+ actions.append(retry);+ }+ const back = el('a', 'hm-btn hm-btn-ghost', 'Back to your homes');+ back.href = '/smart-home';+ actions.append(back);+ root.append(actions);+}++// ── Formatting ───────────────────────────────────────────────────────────────++function labelFor(plan, dimensionId) {+ return plan.dimensions.find((d) => d.id === dimensionId)?.label || dimensionId;+}++function formatNumber(n) {+ if (n == null) return '0';+ return Number.isInteger(n) ? n.toLocaleString() : n.toLocaleString(undefined, { maximumFractionDigits: 2 });+}++function formatDate(iso) {+ const d = new Date(iso);+ if (Number.isNaN(d.getTime())) return 'the first of next month';+ return d.toLocaleDateString(undefined, { month: 'long', day: 'numeric', timeZone: 'UTC' });+}++function hostOf(url) {+ try {+ return new URL(url).host;+ } catch {+ return url;+ }+}diff --git a/tests/home-entitlements.test.js b/tests/home-entitlements.test.jsnew file mode 100644index 000000000..fd7411890--- /dev/null+++ b/tests/home-entitlements.test.js@@ -0,0 +1,538 @@+// Plans, entitlements and quotas for the Home lane.+//+// The first describe block is the one that matters most and it is deliberately+// first in the file: NO COMMERCIAL LIMIT MAY EVER REFUSE A SAFETY ACTION. If a+// future change makes locking a door depend on a plan, that is the block that+// fails, and it fails before anything about pricing is even loaded.+//+// The rest hold the other four commitments: a downgrade pauses and never+// deletes, a counter matches the table an invoice would read, an override raises+// a limit without a deploy, and the gate itself is free on every tier.+//+// The live blocks run against the real database and are skipped, loudly, when+// DATABASE_URL is absent. They are never replaced by a mock: a quota a mock+// "verifies" is a quota nobody verified.++import { afterAll, describe, expect, it } from 'vitest';++import { isSafetyAction, isSafetyMcpCall } from '../packages/home-bridge/src/safety.js';+import {+ assertHomeActionAllowed,+ assertWithinLimit,+ computeEntitlements,+ describeEntitlements,+ HOME_DIMENSION_IDS,+ HOME_DIMENSIONS,+ HomePausedError,+ HomeQuotaError,+ isQuotaExempt,+ limitsForTier,+ planDowngrade,+ quotaPeriod,+ UNLIMITED,+} from '../api/_lib/home/entitlements.js';++/** An account with the tightest limits the platform issues. */+const FREE = { id: 'u-free', account_tier: null, plan: 'free' };++/** Entitlements for a free account with every dimension already exhausted. */+function exhausted() {+ const e = computeEntitlements(FREE);+ const limits = {};+ for (const id of HOME_DIMENSION_IDS) limits[id] = 0;+ return { ...e, limits };+}++// ── Commitment 1: safety is never refused ────────────────────────────────────++describe('a limit never blocks a safety action', () => {+ const SAFE = [+ { domain: 'lock', service: 'lock' },+ { domain: 'cover', service: 'close_cover' },+ { domain: 'alarm_control_panel', service: 'alarm_arm_away' },+ { domain: 'alarm_control_panel', service: 'alarm_arm_home' },+ { domain: 'alarm_control_panel', service: 'alarm_arm_night' },+ { domain: 'valve', service: 'close_valve' },+ ];++ it.each(SAFE)('$domain.$service is exempt from every quota', (call) => {+ expect(isSafetyAction(call)).toBe(true);+ expect(isQuotaExempt(call)).toBe(true);+ });++ it.each(SAFE)('$domain.$service passes assertWithinLimit at a limit of zero', (call) => {+ const result = assertWithinLimit({+ entitlements: exhausted(),+ dimension: 'agentTurns',+ used: 9_999,+ call,+ });+ expect(result).toEqual({ allowed: true, exempt: true, remaining: Number.POSITIVE_INFINITY });+ });++ it.each(SAFE)('$domain.$service executes on a home the plan has paused', (call) => {+ const paused = { label: 'Home', deactivated_at: '2026-09-01T00:00:00.000Z', deactivated_reason: 'Plan change.' };+ expect(assertHomeActionAllowed({ home: paused, call })).toEqual({ allowed: true, exempt: true });+ });++ it('the unsafe direction is NOT exempt, or the exemption would be a hole in the gate', () => {+ for (const call of [+ { domain: 'lock', service: 'unlock' },+ { domain: 'cover', service: 'open_cover' },+ { domain: 'alarm_control_panel', service: 'alarm_disarm' },+ { domain: 'valve', service: 'open_valve' },+ ]) {+ expect(isQuotaExempt(call)).toBe(false);+ }+ });++ it('an ordinary action is not a safety action either', () => {+ expect(isQuotaExempt({ domain: 'light', service: 'turn_on' })).toBe(false);+ expect(isQuotaExempt({ domain: 'light', service: 'turn_off' })).toBe(false);+ });++ it('the exemption needs no live socket, so it survives a degraded connection', () => {+ // No `attributes` anywhere: the classification is from the domain and the+ // service alone. The states where somebody most needs to lock up are the+ // states where the entity attributes are not in hand.+ expect(isQuotaExempt({ domain: 'cover', service: 'close_cover' })).toBe(true);+ });++ it('an ordinary action on a paused home IS refused, with an explanation', () => {+ const paused = { label: 'The office', deactivated_at: '2026-09-01T00:00:00.000Z', deactivated_reason: 'Plan change.' };+ let thrown;+ try {+ assertHomeActionAllowed({ home: paused, call: { domain: 'light', service: 'turn_on' } });+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(HomePausedError);+ expect(thrown.message).toContain('The office');+ expect(thrown.message).toContain('Nothing was deleted');+ expect(thrown.message).toContain('Locking up');+ expect(thrown.status).toBe(402);+ });++ it('the MCP channel gets the same exemption, through the same predicate', () => {+ const entities = [+ { entityId: 'lock.front_door', name: 'Front Door', domain: 'lock', deviceClass: null, areaId: null, attributes: {} },+ ];+ expect(isSafetyMcpCall('intent__HassTurnOn', { name: 'Front Door' }, entities)).toBe(true);+ expect(isQuotaExempt({ tool: 'intent__HassTurnOn', arguments: { name: 'Front Door' }, entities })).toBe(true);+ // The polymorphic direction that unlocks is not exempt.+ expect(isQuotaExempt({ tool: 'intent__HassTurnOff', arguments: { name: 'Front Door' }, entities })).toBe(false);+ });++ it('a mixed MCP call is not exempt: it would carry something else through', () => {+ const entities = [+ { entityId: 'lock.front_door', name: 'Front Door', domain: 'lock', deviceClass: null, areaId: null, attributes: {} },+ { entityId: 'cover.garage', name: 'Garage', domain: 'cover', deviceClass: 'garage', areaId: null, attributes: { device_class: 'garage' } },+ ];+ // HassTurnOn locks the lock (safe) and opens the garage (not safe).+ expect(isQuotaExempt({ tool: 'intent__HassTurnOn', arguments: {}, entities })).toBe(false);+ });+});++// ── Commitment 5: the gate is not a paid feature ─────────────────────────────++describe('nothing about the gate is sold', () => {+ it('no dimension meters confirmations, the audit log, or a role', () => {+ const forbidden = /confirm|audit|gate|role|guard|safety/i;+ for (const id of HOME_DIMENSION_IDS) {+ expect(id, `"${id}" looks like it meters a safety property`).not.toMatch(forbidden);+ expect(HOME_DIMENSIONS[id].label).not.toMatch(/confirmation|audit|role/i);+ }+ });++ it('the free tier gets every dimension the top tier gets, only smaller', () => {+ const free = limitsForTier('user');+ const top = limitsForTier('three-dimensional');+ expect(Object.keys(free).sort()).toEqual(Object.keys(top).sort());+ for (const id of HOME_DIMENSION_IDS) {+ expect(free[id], `free tier has no ${id} at all`).toBeGreaterThan(0);+ }+ });++ it('every dimension carries the measured cost that justifies metering it', () => {+ for (const id of HOME_DIMENSION_IDS) {+ const d = HOME_DIMENSIONS[id];+ expect(typeof d.costPerUnitUsd).toBe('number');+ expect(d.costBasis, `${id} has no stated cost basis`).toBeTruthy();+ expect(d.why, `${id} has no stated reason`).toBeTruthy();+ }+ });+});++// ── Resolution: one entitlement system, not a fourth ─────────────────────────++describe('entitlements resolve from the tier systems that already exist', () => {+ it('a free account gets the floor', () => {+ const e = computeEntitlements(FREE);+ expect(e.tier.id).toBe('user');+ expect(e.limits.homes).toBe(limitsForTier('user').homes);+ });++ it('a Pro subscriber gets Pro limits', () => {+ const e = computeEntitlements({ plan: 'pro' });+ expect(e.limits.homes).toBe(limitsForTier('pro').homes);+ expect(e.limits.agentTurns).toBe(limitsForTier('pro').agentTurns);+ });++ it('badges are merged by MAX, so holding $THREE never costs a Pro their Pro limits', () => {+ // `holder` outranks `pro` on the display ladder. If the resolver took the+ // primary badge's limits, buying some of the coin would DOWNGRADE a paying+ // customer, which is the bug this test exists to prevent.+ const proOnly = computeEntitlements({ plan: 'pro' });+ const proAndHolder = computeEntitlements({ plan: 'pro' }, { holder: { isHolder: true, amount: 1, usd: 1 } });+ expect(proAndHolder.tier.id).toBe('holder');+ expect(proAndHolder.limits.homes).toBeGreaterThanOrEqual(proOnly.limits.homes);+ expect(proAndHolder.limits.agentTurns).toBeGreaterThanOrEqual(proOnly.limits.agentTurns);+ });++ it('the $THREE ladder is read, never re-modelled: its multiplier scales the free quotas', () => {+ const member = computeEntitlements(FREE, { holder: { isHolder: true, amount: 1, usd: 1 } });+ const gold = computeEntitlements(FREE, { holder: { isHolder: true, amount: 1, usd: 600 } });+ expect(member.multiplier).toBe(1);+ expect(gold.multiplier).toBe(5); // three-tier.js Gold, minUsd 500+ expect(gold.limits.agentTurns).toBe(member.limits.agentTurns * 5);+ expect(gold.sources.agentTurns).toBe('holder-multiplier');+ });++ it('the seat count does NOT scale with holding: seats are sold, not held', () => {+ const gold = computeEntitlements(FREE, { holder: { isHolder: true, amount: 1, usd: 600 } });+ expect(gold.limits.members).toBe(limitsForTier('holder').members);+ expect(gold.sources.members).toBe('plan');+ });++ it('the retention ceiling never promises more than the schema will store', () => {+ // home_connections_retention_days_chk caps the stored value at ten years.+ for (const tier of ['user', 'beta', 'pro', 'holder', 'three-dimensional']) {+ expect(limitsForTier(tier).logRetentionDays).toBeLessThanOrEqual(3650);+ }+ });++ it('the free retention ceiling is at least the default, so no existing home is retroactively over it', () => {+ expect(limitsForTier('user').logRetentionDays).toBeGreaterThanOrEqual(90);+ });+});++// ── Enforcement ──────────────────────────────────────────────────────────────++describe('enforcement', () => {+ it('refuses past the limit with a message naming the limit and the way out', () => {+ const e = computeEntitlements(FREE);+ let thrown;+ try {+ assertWithinLimit({ entitlements: e, dimension: 'homes', used: e.limits.homes });+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(HomeQuotaError);+ expect(thrown.status).toBe(402);+ expect(thrown.dimension).toBe('homes');+ expect(thrown.message).toContain('three.ws/pricing');+ expect(thrown.message).toContain('never affected by a limit');+ });++ it('allows right up to the limit', () => {+ const e = computeEntitlements(FREE);+ const r = assertWithinLimit({ entitlements: e, dimension: 'homes', used: e.limits.homes - 1 });+ expect(r.allowed).toBe(true);+ expect(r.remaining).toBe(0);+ });++ it('an unlimited dimension never refuses', () => {+ const e = computeEntitlements({ account_tier: 'three-dimensional' });+ expect(e.limits.homes).toBe(UNLIMITED);+ expect(assertWithinLimit({ entitlements: e, dimension: 'homes', used: 10_000 }).allowed).toBe(true);+ });++ it('an unknown dimension is a programming error, not a silent pass', () => {+ expect(() =>+ assertWithinLimit({ entitlements: computeEntitlements(FREE), dimension: 'nonsense', used: 0 }),+ ).toThrow(/unknown dimension/);+ });+});++// ── Commitment 2: the downgrade path ─────────────────────────────────────────++describe('a downgrade pauses and explains, it never disconnects', () => {+ const homes = [+ { id: 'a', label: 'Home', created_at: '2026-01-01T00:00:00.000Z' },+ { id: 'b', label: 'The office', created_at: '2026-02-01T00:00:00.000Z' },+ { id: 'c', label: "Mum's house", created_at: '2026-03-01T00:00:00.000Z' },+ ];++ it('names exactly the excess and keeps the oldest', () => {+ const plan = planDowngrade(homes, 1);+ expect(plan.overBy).toBe(2);+ expect(plan.keep.map((h) => h.id)).toEqual(['a']);+ expect(plan.deactivate.map((h) => h.id)).toEqual(['b', 'c']);+ });++ it('explains in words a person can act on, and promises nothing was deleted', () => {+ const plan = planDowngrade(homes, 1);+ expect(plan.explanation).toContain('The office');+ expect(plan.explanation).toContain('nothing was deleted');+ expect(plan.explanation).toContain('swap which homes are active');+ expect(plan.explanation).toContain('safety actions');+ });++ it('does nothing when the account is inside its limit', () => {+ expect(planDowngrade(homes, 5).overBy).toBe(0);+ expect(planDowngrade(homes, 5).deactivate).toEqual([]);+ });++ it('does nothing on an unlimited plan', () => {+ expect(planDowngrade(homes, UNLIMITED).overBy).toBe(0);+ });++ it('never counts an already-paused home against the new limit', () => {+ const withPaused = [...homes, { id: 'd', label: 'Cabin', created_at: '2026-04-01T00:00:00.000Z', deactivated_at: '2026-05-01T00:00:00.000Z' }];+ const plan = planDowngrade(withPaused, 3);+ expect(plan.overBy).toBe(0);+ });+});++// ── Commitment 3: the quota is shown before it is hit ────────────────────────++describe('the manage surface view', () => {+ const usage = { homes: 1, members: 2, streams: 0, voiceMinutes: 42.5, agentTurns: 900, logRetentionDays: 90, relayConnections: 0 };++ it('returns every dimension, not only the ones near their ceiling', () => {+ const view = describeEntitlements(computeEntitlements(FREE), usage);+ expect(view.dimensions.map((d) => d.id).sort()).toEqual([...HOME_DIMENSION_IDS].sort());+ });++ it('carries a real reset date for the monthly dimensions and none for the gauges', () => {+ const now = new Date('2026-09-03T12:00:00.000Z');+ const view = describeEntitlements(computeEntitlements(FREE), usage, { now });+ const turns = view.dimensions.find((d) => d.id === 'agentTurns');+ const homes = view.dimensions.find((d) => d.id === 'homes');+ expect(turns.resetsAt).toBe('2026-10-01T00:00:00.000Z');+ expect(homes.resetsAt).toBeNull();+ expect(view.period.resetsAt).toBe('2026-10-01T00:00:00.000Z');+ });++ it('shows the percentage used before the ceiling is reached', () => {+ const view = describeEntitlements(computeEntitlements(FREE), usage);+ const turns = view.dimensions.find((d) => d.id === 'agentTurns');+ expect(turns.used).toBe(900);+ expect(turns.limit).toBe(1000);+ expect(turns.percent).toBe(90);+ expect(turns.exceeded).toBe(false);+ });++ it('states on the surface itself which actions a limit can never touch', () => {+ const view = describeEntitlements(computeEntitlements(FREE), usage);+ expect(view.alwaysFree.join(' ')).toMatch(/Locking a door/);+ expect(view.alwaysFree.join(' ')).toMatch(/Safety is not an upgrade/);+ });++ it('an unlimited dimension reports null rather than Infinity, which does not survive JSON', () => {+ const view = describeEntitlements(computeEntitlements({ account_tier: 'three-dimensional' }), usage);+ const homes = view.dimensions.find((d) => d.id === 'homes');+ expect(homes.unlimited).toBe(true);+ expect(homes.limit).toBeNull();+ expect(JSON.parse(JSON.stringify(view)).dimensions[0].limit).toBeNull();+ });+});++describe('the quota period', () => {+ it('is the UTC calendar month', () => {+ const p = quotaPeriod(new Date('2026-09-17T23:59:59.000Z'));+ expect(p.startIso).toBe('2026-09-01T00:00:00.000Z');+ expect(p.endIso).toBe('2026-10-01T00:00:00.000Z');+ expect(p.key).toBe('2026-09');+ });++ it('rolls over December correctly', () => {+ const p = quotaPeriod(new Date('2026-12-31T23:00:00.000Z'));+ expect(p.endIso).toBe('2027-01-01T00:00:00.000Z');+ });+});++// ── Commitments 2 and 4, against the real database ───────────────────────────++const LIVE = Boolean(process.env.DATABASE_URL);++describe.skipIf(!LIVE)('entitlements against the real database', () => {+ /** @type {any} */ let sql;+ /** @type {any} */ let ent;+ /** @type {any} */ let usageMod;+ const created = { users: [], homes: [] };++ async function setup() {+ if (sql) return;+ ({ sql } = await import('../api/_lib/db.js'));+ ent = await import('../api/_lib/home/entitlements.js');+ usageMod = await import('../api/_lib/home/usage.js');+ }++ async function makeUser(tag, patch = {}) {+ const email = `home-ent-${tag}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}@test.invalid`;+ const [row] = await sql`+ insert into users (email, display_name, plan)+ values (${email}, ${'home entitlements test'}, ${patch.plan || 'free'})+ returning id, email, plan, account_tier, wallet_address+ `;+ created.users.push(row.id);+ return row;+ }++ async function makeHome(userId, label) {+ const [row] = await sql`+ insert into home_connections (user_id, label, base_url, access_token_enc, token_fingerprint)+ values (${userId}, ${label}, ${'https://ha-' + Math.random().toString(36).slice(2, 10) + '.test.invalid'},+ ${'enc'}, ${Math.random().toString(36).slice(2)})+ returning id, label, created_at, deactivated_at+ `;+ created.homes.push(row.id);+ return row;+ }++ afterAll(async () => {+ if (!sql) return;+ for (const id of created.homes) await sql`delete from home_connections where id = ${id}`;+ for (const id of created.users) {+ await sql`delete from usage_events where user_id = ${id}`;+ await sql`delete from home_plan_overrides where user_id = ${id}`;+ await sql`delete from users where id = ${id}`;+ }+ });++ it('an override raises a limit with no code change and no deploy', async () => {+ await setup();+ const user = await makeUser('override');++ const before = await ent.resolveHomeEntitlementsForUser(user.id);+ expect(before.limits.homes).toBe(limitsForTier('user').homes);+ expect(before.sources.homes).toBe('plan');++ await ent.setAccountOverride({+ userId: user.id,+ limits: { homes: 400, logRetentionDays: 730 },+ note: 'Hotel group, 400 rooms, one year of attribution. Agreed on the call.',+ });++ const after = await ent.resolveHomeEntitlementsForUser(user.id);+ expect(after.limits.homes).toBe(400);+ expect(after.limits.logRetentionDays).toBe(730);+ expect(after.sources.homes).toBe('account-override');+ expect(after.override.note).toContain('Hotel group');+ // A dimension the deal did not mention keeps its plan value.+ expect(after.limits.streams).toBe(limitsForTier('user').streams);++ expect(await ent.clearAccountOverride(user.id)).toBe(true);+ const cleared = await ent.resolveHomeEntitlementsForUser(user.id);+ expect(cleared.limits.homes).toBe(limitsForTier('user').homes);+ });++ it('an unknown dimension in an override is dropped, not stored', async () => {+ await setup();+ const user = await makeUser('badkey');+ await ent.setAccountOverride({ userId: user.id, limits: { homes: 9, nonsense: 5 }, note: null });+ const row = await ent.getAccountOverride(user.id);+ expect(row.limits.homes).toBe(9);+ expect(row.limits.nonsense).toBeUndefined();+ });++ it('a downgrade pauses the excess, deletes nothing, and keeps the credential', async () => {+ await setup();+ const user = await makeUser('downgrade');+ const a = await makeHome(user.id, 'Home');+ const b = await makeHome(user.id, 'The office');+ const c = await makeHome(user.id, "Mum's house");++ expect(await ent.countActiveConnections(user.id)).toBe(3);++ const rows = await sql`+ select id, label, created_at, deactivated_at from home_connections where user_id = ${user.id}+ `;+ const plan = ent.planDowngrade(rows, 1);+ expect(plan.deactivate).toHaveLength(2);++ const paused = await ent.applyDowngrade({+ userId: user.id,+ deactivateIds: plan.deactivate.map((h) => h.id),+ reason: 'Plan changed to Free.',+ });+ expect(paused).toHaveLength(2);++ // Nothing deleted, nothing revoked, the credential still there.+ const after = await sql`+ select id, revoked_at, deactivated_at, deactivated_reason, access_token_enc+ from home_connections where user_id = ${user.id} order by created_at+ `;+ expect(after).toHaveLength(3);+ expect(after.every((r) => r.revoked_at === null)).toBe(true);+ expect(after.every((r) => r.access_token_enc === 'enc')).toBe(true);+ expect(after.filter((r) => r.deactivated_at !== null)).toHaveLength(2);+ expect(after.find((r) => r.id === a.id).deactivated_at).toBeNull();+ expect(after.find((r) => r.id === b.id).deactivated_reason).toBe('Plan changed to Free.');++ expect(await ent.countActiveConnections(user.id)).toBe(1);++ // The user picks: swap which one is live. Bringing one back while at the+ // limit is refused, and it succeeds once room is made.+ const free = ent.computeEntitlements({ plan: 'free' });+ const oneHome = { ...free, limits: { ...free.limits, homes: 1 } };+ await expect(+ ent.reactivateConnection({ userId: user.id, homeId: b.id, entitlements: oneHome }),+ ).rejects.toBeInstanceOf(HomeQuotaError);++ await ent.applyDowngrade({ userId: user.id, deactivateIds: [a.id], reason: 'Swapped by the user.' });+ const back = await ent.reactivateConnection({ userId: user.id, homeId: b.id, entitlements: oneHome });+ expect(back.deactivated_at).toBeNull();+ expect(await ent.countActiveConnections(user.id)).toBe(1);+ void c;+ });++ it('the agent-turn counter reads the same rows an invoice would', async () => {+ await setup();+ const user = await makeUser('counter');+ const home = await makeHome(user.id, 'Counted');++ // Exactly the row api/chat.js writes for a turn that touched a house.+ for (let i = 0; i < 20; i += 1) {+ await sql`+ insert into usage_events (user_id, kind, tool, provider, model, input_tokens, output_tokens, cost_micro_usd, meta)+ values (${user.id}, ${'chat'}, ${'claude-haiku-4-5'}, ${'anthropic'}, ${'claude-haiku-4-5'},+ ${6359}, ${250}, ${7609}, ${JSON.stringify({ home_id: home.id, provider: 'anthropic' })}::jsonb)+ `;+ }+ // A conversation about nothing in particular: same kind, no home. Must NOT count.+ for (let i = 0; i < 5; i += 1) {+ await sql`+ insert into usage_events (user_id, kind, tool, meta)+ values (${user.id}, ${'chat'}, ${'claude-haiku-4-5'}, ${JSON.stringify({ provider: 'anthropic' })}::jsonb)+ `;+ }+ // Three voice turns, counted in fractional minutes.+ for (const minutes of [0.5, 0.25, 1.5]) {+ await sql`+ insert into usage_events (user_id, kind, tool, meta)+ values (${user.id}, ${'home.voice'}, ${'home:' + home.id}, ${JSON.stringify({ amount: minutes, dimension: 'voiceMinutes' })}::jsonb)+ `;+ }++ const period = ent.quotaPeriod();+ expect(await usageMod.readUsageFromEvents(user.id, 'agentTurns', period)).toBe(20);+ expect(await usageMod.readUsageFromEvents(user.id, 'voiceMinutes', period)).toBe(2.25);++ // And the same numbers the manage surface shows.+ await usageMod.invalidateUsageCache(user.id, 'agentTurns');+ await usageMod.invalidateUsageCache(user.id, 'voiceMinutes');+ const usage = await usageMod.readHomeUsage(user.id);+ expect(usage.agentTurns).toBe(20);+ expect(usage.voiceMinutes).toBe(2.25);+ expect(usage.homes).toBe(1);+ });++ it('refuses to mint a second counter for agent turns', async () => {+ await setup();+ await expect(+ usageMod.recordHomeUsage({ userId: created.users[0], dimension: 'agentTurns' }),+ ).rejects.toThrow(/do not mint a second one/);+ });+});