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.

fix(inference): require the real-funds agreements before a credit top-up moves agent-wallet USDC

nirholasf8af368cb3b4
diff --git a/api/agents/_id/credits.js b/api/agents/_id/credits.js
index e36f1a9b2..8b12ad02a 100644
--- a/api/agents/_id/credits.js
+++ b/api/agents/_id/credits.js
@@ -22,6 +22,7 @@ import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../
import { sql } from '../../_lib/db.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../../_lib/real-funds-agreement.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { inferenceUsage, autoFundIntent } from '../../_lib/inference-billing.js';
import { previewTopup, executeTopup, reconcilePendingTopups } from '../../_lib/inference-topup.js';
@@ -85,6 +86,9 @@ export const handleCredits = wrap(async (req, res, agentId, action, sub) => {
if (!scopeOk(caller, 'wallet:write')) {
return error(res, 403, 'insufficient_scope', 'moving funds from an agent wallet needs the wallet:write scope');
}
+ // The top-up sends mainnet USDC out of the agent wallet; the preview moves
+ // nothing. Checked before CSRF so a refusal does not burn the single-use token.
+ if (sub !== 'preview' && !(await requireRealFundsAgreement(req, res, { userId: caller.userId, context: 'inference-topup' }))) return;
if (!(await requireCsrf(req, res, caller.userId))) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -125,13 +129,17 @@ async function handleAutoFund(req, res, caller, agent) {
if (!scopeOk(caller, 'wallet:write')) {
return error(res, 403, 'insufficient_scope', 'changing the auto-fund rule needs the wallet:write scope');
}
+ const body = (await readJson(req).catch(() => null)) || {};
+ const enabled = body.enabled !== false;
+ // An enabled rule arms autonomous USDC top-ups from the agent wallet;
+ // switching it off never needs the agreement. Checked before CSRF so a
+ // refusal does not burn the single-use token.
+ if (enabled && !(await requireRealFundsAgreement(req, res, { userId: caller.userId, context: 'inference-auto-fund' }))) return;
if (!(await requireCsrf(req, res, caller.userId))) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const body = (await readJson(req).catch(() => null)) || {};
const current = await autoFundIntent(agent.id);
- const enabled = body.enabled !== false;
// Turning an absent rule off is a no-op, not an error.
if (!current && !enabled) return json(res, 200, { auto_fund: null });
diff --git a/api/inference/[action].js b/api/inference/[action].js
index d935f0b48..68b45d90f 100644
--- a/api/inference/[action].js
+++ b/api/inference/[action].js
@@ -23,6 +23,7 @@ import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../
import { sql } from '../_lib/db.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
import { requireCsrf } from '../_lib/csrf.js';
+import { requireRealFundsAgreement } from '../_lib/real-funds-agreement.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { inferenceUsage } from '../_lib/inference-billing.js';
import { reconcilePendingTopups } from '../_lib/inference-topup.js';
@@ -87,6 +88,9 @@ async function handleProvision(req, res, caller, action) {
if (!scopeOk(caller, 'wallet:write')) {
return error(res, 403, 'insufficient_scope', 'funding an inference key from an agent wallet needs the wallet:write scope');
}
+ // Provisioning sends mainnet USDC out of the agent wallet; the preview moves
+ // nothing. Checked before CSRF so a refusal does not burn the single-use token.
+ if (action === 'provision' && !(await requireRealFundsAgreement(req, res, { userId: caller.userId, context: 'inference-provision' }))) return;
if (!(await requireCsrf(req, res, caller.userId))) return;
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
diff --git a/data/changelog.json b/data/changelog.json
index e24855b85..b368f7d75 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-10-08",
+ "title": "Topping up an agent's inference credits now asks for the real-funds agreements first",
+ "summary": "Moving USDC from an agent wallet into model credits is a real-funds action, so it now follows the same rule as withdrawals, trades and vaults. A one-off credit top-up, turning on the automatic top-up rule, and funding a new inference key from the command line all require the signed real-funds agreements (Terms of Service, Risk Disclosure and Agent Wallet Agreement). On the credits panel the signing dialog opens before the first top-up; from the CLI or an API key you get a link to sign once. Previews still work without signing, and switching the automatic top-up off never needs it.",
+ "tags": ["security"],
+ "link": "/legal/agreements"
+ },
{
"date": "2026-10-08",
"title": "Agent Wallet MCP: quote an x402 service before your assistant pays it",
diff --git a/docs/risk-acknowledgment.md b/docs/risk-acknowledgment.md
index 97b12c5c8..c2d138ea2 100644
--- a/docs/risk-acknowledgment.md
+++ b/docs/risk-acknowledgment.md
@@ -98,6 +98,15 @@ redeeming from, owner-trading and fee-claiming a [USDC vault](./vaults.md)
(`a2a-hire`). Pausing an order, like every other way of turning spending off,
is not gated.
+Self-funded inference moves USDC out of the agent wallet into model credits, so
+it is gated at both ends: a credit top-up (`inference-topup`, `POST
+/api/agents/:id/credits/topup`), enabling the automatic top-up rule
+(`inference-auto-fund`, `PUT /api/agents/:id/credits/auto-fund`), and funding a
+new inference key (`inference-provision`, `POST /api/me/inference/provision`).
+The credits panel opens the signing dialog before the first two; the CLI prints
+the server's refusal with the signing link. Their previews, and switching the
+automatic rule off, are not gated.
+
Positive lookups are cached in-process for 10 minutes (signatures are append-only
and the required version only changes on deploy); negative results are never
cached, so a fresh signature takes effect on the next request.
diff --git a/src/inference-credits.js b/src/inference-credits.js
index 14f897fa2..128a3e404 100644
--- a/src/inference-credits.js
+++ b/src/inference-credits.js
@@ -17,6 +17,7 @@
*/
import { consumeCsrfToken } from './api.js';
+import { ensureRiskAck } from './shared/risk-ack.js';
const STYLE_ID = 'ic-style';
const AMOUNTS = [1, 5, 20];
@@ -466,6 +467,9 @@ export function mountInferenceCredits(root, { agentId, compact = false, walletHr
const amount = Number(field('auto-amount')?.value);
if (!(threshold > 0)) return set({ flash: 'Set a floor above $0 for the automatic top-up.' });
if (!(amount >= 0.1)) return set({ flash: 'The automatic top-up must be at least 0.1 USDC.' });
+ // An enabled rule spends real USDC on its own; the server refuses it
+ // until the real-funds agreements are signed, so ask for them first.
+ if (enabled && !(await ensureRiskAck({ context: 'inference-auto-fund' }))) return undefined;
set({ busy: true, flash: null });
const r = await call(`${base}/credits/auto-fund`, {
method: 'PUT',
@@ -525,6 +529,7 @@ export function mountInferenceCredits(root, { agentId, compact = false, walletHr
return set({ busy: false, preview: r.data });
}
case 'confirm': {
+ if (!(await ensureRiskAck({ context: 'inference-topup' }))) return undefined;
set({ busy: true });
const r = await call(`${base}/credits/topup`, {
method: 'POST',
diff --git a/tests/api/inference-topup-agreement-gate.test.js b/tests/api/inference-topup-agreement-gate.test.js
new file mode 100644
index 000000000..157af1921
--- /dev/null
+++ b/tests/api/inference-topup-agreement-gate.test.js
@@ -0,0 +1,199 @@
+// The real-funds agreement gate on the inference money paths.
+//
+// Three requests send mainnet USDC out of an agent's custodial wallet into
+// inference credits:
+// POST /api/agents/:id/credits/topup (api/agents/_id/credits.js)
+// PUT /api/agents/:id/credits/auto-fund arms an autonomous top-up rule
+// POST /api/me/inference/provision (api/inference/[action].js)
+// Each must refuse an account that has not signed the current real-funds
+// agreements before anything moves and before the single-use CSRF token is
+// spent. The previews and switching the rule off move nothing and stay open.
+//
+// The gate itself is the real requireRealFundsAgreement; only the database
+// rows behind it, the session, and the money modules are doubles, so the
+// assertions read what the handler actually decides.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
+
+const USER_ID = 'ab2aabd2-39f7-493b-8191-c9f174af62ab';
+const AGENT_ID = '5e05f68f-eead-4ef9-b6b4-fc85ea73bbe9';
+
+const state = { signed: false };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings) => {
+ const query = strings.join('?');
+ if (query.includes('legal_signatures')) {
+ return state.signed ? [{ created_at: new Date(), signature_name: 'Ada', context: 'inference-topup' }] : [];
+ }
+ if (query.includes('agent_identities')) {
+ return [{ id: AGENT_ID, user_id: USER_ID, name: 'Topup Agent', meta: {} }];
+ }
+ return [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => ({ id: USER_ID }),
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+ hasScope: () => true,
+}));
+
+vi.mock('../../api/_lib/http.js', async () => {
+ const actual = await vi.importActual('../../api/_lib/http.js');
+ return { ...actual, wrap: (fn) => fn, readJson: async (req) => JSON.parse(req._rawBody || '{}') };
+});
+
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: async () => ({ success: true }), authedReadIp: async () => ({ success: true }) },
+ clientIp: () => '1.2.3.4',
+}));
+
+vi.mock('../../api/_lib/inference-billing.js', () => ({
+ inferenceUsage: async () => ({}),
+ autoFundIntent: vi.fn(async () => null),
+}));
+
+vi.mock('../../api/_lib/inference-topup.js', () => ({
+ previewTopup: vi.fn(async () => ({ preview_id: 'p1', amount_usdc: 5 })),
+ executeTopup: vi.fn(async () => ({ status: 'settled' })),
+ reconcilePendingTopups: vi.fn(async () => {}),
+}));
+
+vi.mock('../../api/_lib/wallet-intents.js', () => ({
+ normalizeIntent: () => ({ ok: true, intent: {} }),
+ createIntent: vi.fn(async () => ({})),
+ updateIntent: vi.fn(async () => ({})),
+ describeIntent: () => 'Top up 5 USDC when credits fall below 1 USD',
+}));
+
+vi.mock('../../api/_lib/inference-provision.js', () => ({
+ previewProvision: vi.fn(async () => ({ preview_id: 'p2' })),
+ executeProvision: vi.fn(async () => ({ status: 201, body: { key: 'sk_test' } })),
+ INFERENCE_BASE_URL: 'https://three.ws/api/inference/v1',
+}));
+
+const { handleCredits } = await import('../../api/agents/_id/credits.js');
+const inferenceHandler = (await import('../../api/inference/[action].js')).default;
+const { requireCsrf } = await import('../../api/_lib/csrf.js');
+const { previewTopup, executeTopup } = await import('../../api/_lib/inference-topup.js');
+const { createIntent } = await import('../../api/_lib/wallet-intents.js');
+const { previewProvision, executeProvision } = await import('../../api/_lib/inference-provision.js');
+const { resetRealFundsAgreementCache } = await import('../../api/_lib/real-funds-agreement.js');
+
+function makeReq(httpMethod, body, query = {}) {
+ return { method: httpMethod, headers: { host: 'three.ws' }, query, _rawBody: JSON.stringify(body), on() {} };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+const bodyOf = (res) => JSON.parse(res.body);
+
+beforeEach(() => {
+ state.signed = false;
+ resetRealFundsAgreementCache();
+ vi.clearAllMocks();
+});
+
+describe('POST /api/agents/:id/credits/topup', () => {
+ it('refuses an unsigned account before any USDC moves or the CSRF token is spent', async () => {
+ const res = makeRes();
+ await handleCredits(makeReq('POST', { preview_id: 'p1', confirm_deposit: true }), res, AGENT_ID, 'topup', undefined);
+ expect(res.statusCode).toBe(403);
+ expect(bodyOf(res).error).toBe('risk_ack_required');
+ expect(bodyOf(res).context).toBe('inference-topup');
+ expect(executeTopup).not.toHaveBeenCalled();
+ expect(requireCsrf).not.toHaveBeenCalled();
+ });
+
+ it('settles the top-up once the account has signed', async () => {
+ state.signed = true;
+ const res = makeRes();
+ await handleCredits(makeReq('POST', { preview_id: 'p1', confirm_deposit: true }), res, AGENT_ID, 'topup', undefined);
+ expect(res.statusCode).toBe(200);
+ expect(executeTopup).toHaveBeenCalledOnce();
+ });
+
+ it('still quotes a preview for an unsigned account, since nothing moves', async () => {
+ const res = makeRes();
+ await handleCredits(makeReq('POST', { amount_usdc: 5 }), res, AGENT_ID, 'topup', 'preview');
+ expect(res.statusCode).toBe(200);
+ expect(previewTopup).toHaveBeenCalledOnce();
+ expect(executeTopup).not.toHaveBeenCalled();
+ });
+});
+
+describe('PUT /api/agents/:id/credits/auto-fund', () => {
+ it('refuses to arm an autonomous top-up rule for an unsigned account', async () => {
+ const res = makeRes();
+ await handleCredits(makeReq('PUT', { enabled: true, threshold_usd: 1, amount_usdc: 5 }), res, AGENT_ID, 'auto-fund');
+ expect(res.statusCode).toBe(403);
+ expect(bodyOf(res).error).toBe('risk_ack_required');
+ expect(bodyOf(res).context).toBe('inference-auto-fund');
+ expect(createIntent).not.toHaveBeenCalled();
+ expect(requireCsrf).not.toHaveBeenCalled();
+ });
+
+ it('arms the rule once the account has signed', async () => {
+ state.signed = true;
+ const res = makeRes();
+ await handleCredits(makeReq('PUT', { enabled: true, threshold_usd: 1, amount_usdc: 5 }), res, AGENT_ID, 'auto-fund');
+ expect(res.statusCode).toBe(200);
+ expect(createIntent).toHaveBeenCalledOnce();
+ });
+
+ it('lets an unsigned account switch the rule off, since that never spends', async () => {
+ const res = makeRes();
+ await handleCredits(makeReq('PUT', { enabled: false }), res, AGENT_ID, 'auto-fund');
+ expect(res.statusCode).toBe(200);
+ expect(bodyOf(res).auto_fund).toBeNull();
+ });
+});
+
+describe('POST /api/me/inference/provision', () => {
+ it('refuses an unsigned account before the funding top-up runs', async () => {
+ const res = makeRes();
+ await inferenceHandler(makeReq('POST', { preview_id: 'p2', confirm_deposit: true }, { action: 'provision' }), res);
+ expect(res.statusCode).toBe(403);
+ expect(bodyOf(res).error).toBe('risk_ack_required');
+ expect(bodyOf(res).context).toBe('inference-provision');
+ expect(executeProvision).not.toHaveBeenCalled();
+ expect(requireCsrf).not.toHaveBeenCalled();
+ });
+
+ it('provisions once the account has signed', async () => {
+ state.signed = true;
+ const res = makeRes();
+ await inferenceHandler(makeReq('POST', { preview_id: 'p2', confirm_deposit: true }, { action: 'provision' }), res);
+ expect(res.statusCode).toBe(201);
+ expect(executeProvision).toHaveBeenCalledOnce();
+ });
+
+ it('still previews for an unsigned account, since nothing moves', async () => {
+ const res = makeRes();
+ await inferenceHandler(makeReq('POST', { agent_id: AGENT_ID, amount_usdc: 5 }, { action: 'provision-preview' }), res);
+ expect(res.statusCode).toBe(200);
+ expect(previewProvision).toHaveBeenCalledOnce();
+ });
+});
diff --git a/tests/real-funds-agreement-coverage.test.js b/tests/real-funds-agreement-coverage.test.js
index b65fa53f8..4567f748f 100644
--- a/tests/real-funds-agreement-coverage.test.js
+++ b/tests/real-funds-agreement-coverage.test.js
@@ -26,11 +26,12 @@ const EXEMPT = {
'api/launcher/me.js': 'reads wallet balances only',
'api/stage/index.js': 'ensures a wallet exists for a stage; no funds move',
'api/user/wallet/index.js': 'creates the master wallet and reads balances; sends go through the gated send.js',
+ 'api/_mcp/resources.js': 'MCP resources are reads: a wallet signature lookup and the intent list; nothing signs or moves funds',
+ 'api/cli/[action].js': 'device-link sign-in and whoami; reads the wallet address and balances only',
'api/agent-memory.js': 'signs memory records with the agent key; no transfer',
'api/agents/_id/_sub.js': 'config, reads, and message signing; no transfer',
'api/agents/_id/brain.js': 'agent key signs a digest; anchor gas is paid by the platform validator key',
'api/agents/alpha.js': 'read-only candidates and analysis',
- 'api/agents/copilot.js': 'renders proposal cards; execution happens on gated endpoints',
'api/autopilot/activity.js': 'read-only activity feed',
'api/avatars/fork.js': 'creates a fresh empty wallet for the fork; no funds move',
'api/irl/world-lines.js': 'agent key signs a proof-of-presence message; no transfer',