Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

refactor(chat): lift the home turn gate into its own module

nirholas14dffe935324
diff --git a/api/_lib/home/turn-gate.js b/api/_lib/home/turn-gate.js
new file mode 100644
index 000000000..cac416254
--- /dev/null
+++ b/api/_lib/home/turn-gate.js
@@ -0,0 +1,137 @@
+/**
+ * May this account spend another home agent turn, and if not, what is refused.
+ *
+ * The chat lane is where an agent turn is actually spent, and `api/chat.js` is
+ * a large file about routing models rather than about billing. This module
+ * holds the entitlement half so it can be reasoned about, and tested, on its
+ * own.
+ *
+ * The one rule that shapes everything here is commitment 1 from
+ * `api/_lib/home/entitlements.js`: a limit never blocks a safety action. Over
+ * quota, an agent asked to lock up, close a garage or a valve, or arm an alarm
+ * still does it. Two things make that true rather than merely stated:
+ *
+ * * the exemption is checked per call, not per round, so one refused call in
+ * a round cannot take a safe one down with it, and
+ * * read-only tools are never gated at all (see `isGatedHomeTool`).
+ */
+
+import { HOME_TOOLS_BY_NAME } from './tools.js';
+import {
+ assertWithinLimit,
+ HomeQuotaError,
+ isQuotaExempt,
+ quotaPeriod,
+ resolveHomeEntitlementsForUser,
+} from './entitlements.js';
+import { readUsage } from './usage.js';
+
+/**
+ * Which home tools a monthly turn quota may refuse.
+ *
+ * Read-only tools are never gated, and that is a deliberate product decision
+ * rather than an oversight. Commitment 1 says a limit never blocks a safety
+ * action, and in an agent lane that promise is only real if the agent can still
+ * find the door: the model reads the house with `home_status` and then targets
+ * the lock. Gate the read and the exemption survives in a unit test and nowhere
+ * else, because the conversation a person is actually having ends one step
+ * earlier. A read also spends nothing the turn had not already spent by the
+ * time the model emitted the call.
+ *
+ * @param {string} name
+ * @returns {boolean}
+ */
+export function isGatedHomeTool(name) {
+ return HOME_TOOLS_BY_NAME[name]?.readOnly !== true;
+}
+
+/**
+ * The shape `isQuotaExempt` reads, from a chat tool call.
+ *
+ * `home_call` carries the domain and the service on its input, which is exactly
+ * what the safety classifier wants, so a lock, a close or an arm is recognised
+ * with no live entity list and therefore in precisely the degraded states where
+ * somebody most needs to lock up.
+ *
+ * @param {{ name: string, input?: object }} call
+ * @returns {object}
+ */
+export function homeCallShape(call) {
+ const input = call?.input || {};
+ if (call?.name === 'home_call') {
+ return { domain: input.domain, service: input.service, attributes: input.data || {} };
+ }
+ return { tool: call?.name, arguments: input, entities: [] };
+}
+
+/**
+ * Resolve the account's agent-turn standing once, for a whole round.
+ *
+ * FAILS OPEN. An unreadable entitlement row or an unreachable usage counter
+ * resolves to "allowed", never to "refused". Refusing a person access to their
+ * own house because a billing read hiccuped is the failure this lane is least
+ * willing to ship, and it is the same bias `usage.js` already takes on a cold
+ * cache: a quota that errs must err toward serving the user.
+ *
+ * @param {string} userId
+ * @param {object} [deps] injection seam for tests; production passes nothing
+ * @returns {Promise<{ allowed: boolean, error: HomeQuotaError|null }>}
+ */
+export async function homeTurnGate(userId, deps = {}) {
+ const resolve = deps.resolveHomeEntitlementsForUser || resolveHomeEntitlementsForUser;
+ const read = deps.readUsage || readUsage;
+ try {
+ const [entitlements, used] = await Promise.all([resolve(userId), read(userId, 'agentTurns')]);
+ assertWithinLimit({
+ entitlements,
+ dimension: 'agentTurns',
+ used,
+ resetAt: quotaPeriod().endIso,
+ });
+ return { allowed: true, error: null };
+ } catch (err) {
+ if (err instanceof HomeQuotaError) return { allowed: false, error: err };
+ deps.onError?.(err);
+ return { allowed: true, error: null };
+ }
+}
+
+/**
+ * Should this one call be refused, given the round's verdict?
+ *
+ * The safety exemption is consulted here and only here, so no call site can
+ * apply a quota verdict without it.
+ *
+ * @param {{ allowed: boolean }} gate
+ * @param {{ name: string, input?: object }} call
+ * @returns {boolean}
+ */
+export function shouldRefuseHomeCall(gate, call) {
+ if (gate?.allowed) return false;
+ if (!isGatedHomeTool(call?.name)) return false;
+ return !isQuotaExempt(homeCallShape(call));
+}
+
+/**
+ * The refusal the model speaks. A tool result the agent can turn into a
+ * sentence, never a bare error and never a 500.
+ *
+ * @param {HomeQuotaError} err
+ * @returns {object}
+ */
+export function quotaRefusalResult(err) {
+ return {
+ ok: false,
+ kind: 'error',
+ code: 'quota_exceeded',
+ text: err.message,
+ structured: {
+ error: 'quota_exceeded',
+ dimension: err.dimension,
+ limit: err.limit,
+ used: err.used,
+ resets_at: err.resetAt,
+ upgrade: err.upgradePath,
+ },
+ };
+}
diff --git a/api/chat.js b/api/chat.js
index 525d11c97..6e4a4043a 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -58,15 +58,13 @@ import {
PER_CALL_TIMEOUT_MS,
} from './_lib/chat-models.js';
import { computeContext, searchMemories } from './_lib/memory-store.js';
-import { HOME_TOOL_DEFS, isHomeTool, runHomeTool, HOME_TOOLS_BY_NAME } from './_lib/home/tools.js';
+import { HOME_TOOL_DEFS, isHomeTool, runHomeTool } from './_lib/home/tools.js';
import {
- assertWithinLimit,
- HomeQuotaError,
- isQuotaExempt,
- quotaPeriod,
- resolveHomeEntitlementsForUser,
-} from './_lib/home/entitlements.js';
-import { readUsage } from './_lib/home/usage.js';
+ homeTurnGate,
+ isGatedHomeTool,
+ quotaRefusalResult,
+ shouldRefuseHomeCall,
+} from './_lib/home/turn-gate.js';
import { listMembershipHomes } from './_lib/home/members.js';
import { loadInstalledSkills, skillsPromptBlock } from './_lib/installed-skills.js';
import {
@@ -1245,99 +1243,13 @@ export default wrap(async (req, res) => {
* conversation is the product and a house that did not answer is something the
* agent should be able to say out loud.
*/
-/**
- * May this account spend another home agent turn this month?
- *
- * Resolved once per round rather than once per call, because the answer cannot
- * change inside a round and a house with four tool calls should not pay for four
- * entitlement resolutions.
- *
- * FAILS OPEN. An unreadable entitlement row or an unreachable usage counter
- * resolves to "allowed", never to "refused". Refusing a person access to their
- * own house because our billing read hiccuped is the failure this lane is least
- * willing to ship, and it is the same bias api/_lib/home/usage.js already takes
- * on a cold cache.
- *
- * @param {string} userId
- * @returns {Promise<{ allowed: boolean, error: HomeQuotaError|null }>}
- */
-async function homeTurnGate(userId) {
- try {
- const [entitlements, used] = await Promise.all([
- resolveHomeEntitlementsForUser(userId),
- readUsage(userId, 'agentTurns'),
- ]);
- assertWithinLimit({
- entitlements,
- dimension: 'agentTurns',
- used,
- resetAt: quotaPeriod().endIso,
- });
- return { allowed: true, error: null };
- } catch (err) {
- if (err instanceof HomeQuotaError) return { allowed: false, error: err };
- captureException(err, { route: 'chat', stage: 'home-turn-gate' });
- return { allowed: true, error: null };
- }
-}
-
-/**
- * The shape `isQuotaExempt` needs, from a chat tool call.
- *
- * `home_call` carries the domain and service on the input, which is exactly what
- * the safety classifier reads, so a lock, a close or an arm is recognised here
- * with no live entity list and therefore works in precisely the degraded states
- * where somebody most needs to lock up.
- */
-function homeCallShape(call) {
- const input = call.input || {};
- if (call.name === 'home_call') {
- return { domain: input.domain, service: input.service, attributes: input.data || {} };
- }
- return { tool: call.name, arguments: input, entities: [] };
-}
-
-/**
- * Which home tools a monthly turn quota may refuse.
- *
- * Read-only tools are never gated, and that is a deliberate product decision
- * rather than an oversight. Commitment 1 says a limit never blocks a safety
- * action, and in an agent lane that promise is only real if the agent can still
- * find the door: the model reads the house with `home_status` and then targets
- * the lock. Gate the read and the exemption survives only in a unit test, never
- * in the conversation a person is actually having. A read also adds nothing to
- * the account's spend that the turn had not already spent by the time the model
- * emitted the call.
- */
-function isGatedHomeTool(name) {
- return HOME_TOOLS_BY_NAME[name]?.readOnly !== true;
-}
-
-/** The refusal the model speaks when a turn is over quota. Never a bare error. */
-function quotaRefusalResult(err) {
- return {
- ok: false,
- kind: 'error',
- code: 'quota_exceeded',
- text: err.message,
- structured: {
- error: 'quota_exceeded',
- dimension: err.dimension,
- limit: err.limit,
- used: err.used,
- resets_at: err.resetAt,
- upgrade: err.upgradePath,
- },
- };
-}
-
async function runHomeRound(calls, userId) {
const out = [];
// One resolution for the round, and only when a gated tool is actually
// present: a conversation that only reads the house never pays for a
// database round trip it cannot be refused by.
const gate = calls.slice(0, 4).some((c) => isGatedHomeTool(c.name))
- ? await homeTurnGate(userId)
+ ? await homeTurnGate(userId, { onError: (err) => captureException(err, { route: 'chat', stage: 'home-turn-gate' }) })
: { allowed: true, error: null };
for (const call of calls.slice(0, 4)) {
@@ -1346,7 +1258,7 @@ async function runHomeRound(calls, userId) {
// checked before the quota verdict is applied, so there is no plan state
// in which asking the agent to lock up, close a garage or a valve, or arm
// an alarm is refused for a commercial reason.
- if (!gate.allowed && isGatedHomeTool(call.name) && !isQuotaExempt(homeCallShape(call))) {
+ if (shouldRefuseHomeCall(gate, call)) {
out.push({ call, result: quotaRefusalResult(gate.error) });
continue;
}
diff --git a/tests/home-turn-gate.test.js b/tests/home-turn-gate.test.js
new file mode 100644
index 000000000..3d3451317
--- /dev/null
+++ b/tests/home-turn-gate.test.js
@@ -0,0 +1,154 @@
+// The agent-turn gate: what a monthly quota may refuse in the chat lane, and
+// the two things it may never refuse.
+//
+// The load-bearing assertions here are the ones that keep commitment 1 true in
+// the lane where a person actually talks to their house: over quota, asking the
+// agent to lock up, close a garage or a valve, or arm an alarm still runs, and
+// asking it what the house is doing still answers.
+
+import { describe, expect, it, vi } from 'vitest';
+
+import { HomeQuotaError, UNLIMITED } from '../api/_lib/home/entitlements.js';
+import {
+ homeCallShape,
+ homeTurnGate,
+ isGatedHomeTool,
+ quotaRefusalResult,
+ shouldRefuseHomeCall,
+} from '../api/_lib/home/turn-gate.js';
+
+const OVER = { allowed: false, error: new HomeQuotaError({ dimension: 'agentTurns', limit: 1000, used: 1000, resetAt: '2026-10-01T00:00:00.000Z' }) };
+const UNDER = { allowed: true, error: null };
+
+const callOf = (domain, service, data = {}) => ({ name: 'home_call', input: { domain, service, data } });
+
+describe('over quota, a safety action is still run', () => {
+ const safe = [
+ ['lock', 'lock'],
+ ['cover', 'close_cover'],
+ ['alarm_control_panel', 'alarm_arm_away'],
+ ['valve', 'close_valve'],
+ ];
+
+ for (const [domain, service] of safe) {
+ it(`${domain}.${service} is never refused`, () => {
+ expect(shouldRefuseHomeCall(OVER, callOf(domain, service))).toBe(false);
+ });
+ }
+
+ it('the unsafe direction of the same domain IS refused', () => {
+ expect(shouldRefuseHomeCall(OVER, callOf('lock', 'unlock'))).toBe(true);
+ expect(shouldRefuseHomeCall(OVER, callOf('cover', 'open_cover'))).toBe(true);
+ expect(shouldRefuseHomeCall(OVER, callOf('alarm_control_panel', 'alarm_disarm'))).toBe(true);
+ });
+
+ it('a safety action needs no live entity list, which is what makes it work when degraded', () => {
+ // Classified from the domain and service alone: no socket, no state, no
+ // registry read. That is the property that matters, because the states in
+ // which somebody most needs to lock up are the degraded ones.
+ expect(homeCallShape(callOf('lock', 'lock'))).toEqual({ domain: 'lock', service: 'lock', attributes: {} });
+ expect(shouldRefuseHomeCall(OVER, callOf('lock', 'lock'))).toBe(false);
+ });
+});
+
+describe('reading the house is never gated', () => {
+ it('the read-only tools stay open over quota', () => {
+ for (const name of ['home_status', 'home_list_macros', 'home_grants']) {
+ expect(isGatedHomeTool(name)).toBe(false);
+ expect(shouldRefuseHomeCall(OVER, { name, input: {} })).toBe(false);
+ }
+ });
+
+ it('the acting tools are gated', () => {
+ expect(isGatedHomeTool('home_call')).toBe(true);
+ expect(isGatedHomeTool('home_activate')).toBe(true);
+ expect(shouldRefuseHomeCall(OVER, { name: 'home_activate', input: { macro: 'movie night' } })).toBe(true);
+ });
+
+ it('an unknown tool is treated as gated rather than waved through', () => {
+ expect(isGatedHomeTool('home_not_a_tool')).toBe(true);
+ });
+});
+
+describe('under quota nothing is refused at all', () => {
+ it('every tool runs', () => {
+ for (const name of ['home_status', 'home_call', 'home_activate']) {
+ expect(shouldRefuseHomeCall(UNDER, { name, input: { domain: 'light', service: 'turn_on' } })).toBe(false);
+ }
+ });
+});
+
+describe('the gate resolves a verdict', () => {
+ const entitlements = (agentTurns) => ({
+ tier: { id: 'user', label: 'User' },
+ limits: { agentTurns },
+ sources: { agentTurns: 'plan' },
+ });
+
+ it('allows an account inside its limit', async () => {
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsForUser: async () => entitlements(1000),
+ readUsage: async () => 999,
+ });
+ expect(gate).toEqual({ allowed: true, error: null });
+ });
+
+ it('refuses the turn that would cross the limit, and says how to fix it', async () => {
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsForUser: async () => entitlements(1000),
+ readUsage: async () => 1000,
+ });
+ expect(gate.allowed).toBe(false);
+ expect(gate.error).toBeInstanceOf(HomeQuotaError);
+ expect(gate.error.status).toBe(402);
+ expect(gate.error.upgradePath).toBe('/pricing');
+ // It tells the user the one thing a quota message must never omit here.
+ expect(gate.error.message).toContain('Locking up');
+ });
+
+ it('never refuses an unlimited plan', async () => {
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsForUser: async () => entitlements(UNLIMITED),
+ readUsage: async () => 10_000_000,
+ });
+ expect(gate.allowed).toBe(true);
+ });
+
+ it('FAILS OPEN when the entitlement read throws', async () => {
+ const onError = vi.fn();
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsForUser: async () => { throw new Error('neon is down'); },
+ readUsage: async () => 0,
+ onError,
+ });
+ expect(gate.allowed).toBe(true);
+ expect(onError).toHaveBeenCalledOnce();
+ });
+
+ it('FAILS OPEN when the usage counter is unreachable', async () => {
+ const gate = await homeTurnGate('u1', {
+ resolveHomeEntitlementsForUser: async () => entitlements(10),
+ readUsage: async () => { throw new Error('redis and postgres both refused'); },
+ onError: () => {},
+ });
+ expect(gate.allowed).toBe(true);
+ });
+});
+
+describe('the refusal the model speaks', () => {
+ it('is a tool result the agent can turn into a sentence, not a bare error', () => {
+ const r = quotaRefusalResult(OVER.error);
+ expect(r.ok).toBe(false);
+ expect(r.kind).toBe('error');
+ expect(r.code).toBe('quota_exceeded');
+ expect(r.text).toContain('three.ws/pricing');
+ expect(r.structured).toMatchObject({
+ error: 'quota_exceeded',
+ dimension: 'agentTurns',
+ limit: 1000,
+ used: 1000,
+ upgrade: '/pricing',
+ });
+ expect(r.structured.resets_at).toBe('2026-10-01T00:00:00.000Z');
+ });
+});