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): refuse another agent's top-up preview before funds move and share provisioning between REST and MCP

nirholasf5496e564298
diff --git a/api/_lib/inference-provision.js b/api/_lib/inference-provision.js
new file mode 100644
index 000000000..7da05c381
--- /dev/null
+++ b/api/_lib/inference-provision.js
@@ -0,0 +1,98 @@
+// Inference provisioning: fund a new inference-only API key from an agent
+// wallet in one confirmed move, and return the key exactly once.
+//
+// Two steps, shared by POST /api/me/inference/provision{,/preview}
+// (api/inference/[action].js) and the provision_inference MCP tools
+// (api/_mcpagent/inference-tools.js), so both surfaces are held to the same
+// preview, confirm flag and one-key-per-top-up rule:
+//
+// previewProvision() the wallet top-up preview (source 'provision') plus the
+// key it will mint. Nothing moves.
+// executeProvision() settles that top-up through the self-facilitator, then
+// mints an API key scoped to `inference` alone, binds it
+// to the funding agent (inference_keys) and returns the
+// secret once. A retry of a provision that already
+// minted reports the key's prefix, never the secret.
+
+import { sql } from './db.js';
+import { mintApiKey } from './api-keys.js';
+import { inferencePricing } from './inference-billing.js';
+import { previewTopup, executeTopup, TopupError } from './inference-topup.js';
+import { isUuid } from './validate.js';
+
+export const INFERENCE_BASE_URL = 'https://three.ws/api/v1';
+const MAX_KEY_NAME = 80;
+
+/**
+ * Preview funding a new inference key from an agent wallet.
+ * @returns {Promise<object>} the top-up confirmation table plus `key`
+ */
+export async function previewProvision({ userId, agentId, amountUsdc }) {
+ const id = String(agentId || '');
+ if (!isUuid(id)) throw new TopupError(400, 'bad_request', 'agent_id is required: the agent whose wallet funds the key');
+ const preview = await previewTopup({ userId, agentId: id, amountUsdc, source: 'provision' });
+ return {
+ ...preview,
+ key: { scope: 'inference', bound_agent_id: id, base_url: INFERENCE_BASE_URL, model: inferencePricing().model },
+ };
+}
+
+function keyName(raw) {
+ return typeof raw === 'string' && raw.trim() ? raw.trim().slice(0, MAX_KEY_NAME) : 'Inference key';
+}
+
+/**
+ * Settle a provision preview and mint its key.
+ * @returns {Promise<{ status: number, body: object }>} HTTP status and body:
+ * 202 while Solana confirms, 200 on a replay (no secret), 201 with the key
+ * @throws {TopupError} on a missing confirm flag, a stale preview, or a refused settlement
+ */
+export async function executeProvision({ userId, previewId, confirmDeposit, name = null, req = null }) {
+ const topup = await executeTopup({ userId, previewId, confirmDeposit, sources: ['provision'] });
+ if (topup.status === 'pending') return { status: 202, body: topup };
+ if (topup.status !== 'settled') {
+ throw new TopupError(502, 'topup_failed', 'The top-up did not settle, so no key was minted.', topup);
+ }
+
+ if (topup.api_key_id) {
+ const [k] = await sql`SELECT id, prefix, scope FROM api_keys WHERE id = ${topup.api_key_id}`;
+ return {
+ status: 200,
+ body: {
+ ...topup,
+ key: { id: k?.id, prefix: k?.prefix, scope: k?.scope, token: null, base_url: INFERENCE_BASE_URL },
+ note: 'This top-up already minted its key; the secret is only shown once. Revoke it at /dashboard/api and provision again if it was lost.',
+ },
+ };
+ }
+
+ const minted = await mintApiKey({ userId, name: keyName(name), scopes: ['inference'], req, via: 'inference_provision' });
+ const [claimed] = await sql`
+ UPDATE inference_topups SET api_key_id = ${minted.row.id}
+ WHERE id = ${topup.topup_id} AND api_key_id IS NULL
+ RETURNING id
+ `;
+ if (!claimed) {
+ await sql`UPDATE api_keys SET revoked_at = now() WHERE id = ${minted.row.id}`;
+ throw new TopupError(409, 'already_provisioned', 'A concurrent request already minted the key for this top-up.');
+ }
+ await sql`
+ INSERT INTO inference_keys (api_key_id, user_id, agent_id, topup_id)
+ VALUES (${minted.row.id}, ${userId}, ${topup.agent_id}, ${topup.topup_id})
+ `;
+ return {
+ status: 201,
+ body: {
+ ...topup,
+ api_key_id: minted.row.id,
+ key: {
+ id: minted.row.id,
+ prefix: minted.row.prefix,
+ scope: minted.row.scope,
+ token: minted.secret,
+ base_url: INFERENCE_BASE_URL,
+ model: inferencePricing().model,
+ },
+ },
+ };
+}
diff --git a/api/_lib/inference-topup.js b/api/_lib/inference-topup.js
index 140dbffe3..ae742e4f3 100644
--- a/api/_lib/inference-topup.js
+++ b/api/_lib/inference-topup.js
@@ -244,10 +244,11 @@ function rowResult(row, extra = {}) {
/**
* Execute a previewed top-up. Requires `confirmDeposit === true` and a fresh,
- * unused preview owned by the caller. Retrying a settled or pending preview is
+ * unused preview owned by the caller (and, when `agentId` is given, previewed
+ * for that agent). Retrying a settled or pending preview is
* safe: it returns the recorded result or reconciles the recorded signature.
*/
-export async function executeTopup({ userId, previewId, confirmDeposit, sources = ['owner'] }) {
+export async function executeTopup({ userId, previewId, confirmDeposit, sources = ['owner'], agentId = null }) {
if (confirmDeposit !== true) {
throw new TopupError(400, 'confirm_required', 'Moving funds needs confirm_deposit: true together with a preview_id from the matching /preview call. Show the preview to the owner first.');
}
@@ -258,6 +259,11 @@ export async function executeTopup({ userId, previewId, confirmDeposit, sources
if (!row || !sources.includes(row.source)) {
throw new TopupError(404, 'preview_not_found', 'No preview with that id belongs to this account. Create a new one with /preview.');
}
+ // A route scoped to one agent refuses another agent's preview before
+ // anything moves, never after.
+ if (agentId && String(row.agent_id) !== String(agentId)) {
+ throw new TopupError(409, 'agent_mismatch', 'That preview belongs to a different agent. Create a new one for this agent with /preview.');
+ }
if (row.status === 'settled') return rowResult(row, { replay: true });
if (row.status === 'pending') return reconcileTopup(row);
if (row.status === 'failed' || row.status === 'expired') {
diff --git a/api/agents/_id/credits.js b/api/agents/_id/credits.js
index b1662b62b..e36f1a9b2 100644
--- a/api/agents/_id/credits.js
+++ b/api/agents/_id/credits.js
@@ -105,10 +105,8 @@ export const handleCredits = wrap(async (req, res, agentId, action, sub) => {
previewId: body.preview_id,
confirmDeposit: body.confirm_deposit,
sources: ['owner'],
+ agentId: agent.id,
});
- if (result.agent_id && result.agent_id !== agent.id) {
- return error(res, 409, 'agent_mismatch', 'that preview belongs to a different agent');
- }
return json(res, result.status === 'pending' ? 202 : 200, result);
} catch (err) {
return sendTyped(res, err);
diff --git a/api/inference/[action].js b/api/inference/[action].js
index 0e55f15c3..d935f0b48 100644
--- a/api/inference/[action].js
+++ b/api/inference/[action].js
@@ -11,7 +11,8 @@
// POST /api/me/inference/provision { preview_id, confirm_deposit: true, name? }
// → settles the top-up, then mints an API key
// scoped to `inference` alone, bound to the
-// agent, and returns it ONCE.
+// agent, and returns it ONCE
+// (api/_lib/inference-provision.js).
//
// vercel.json maps the /api/me/* paths here (?action=usage | provision-preview |
// provision). Reads accept a session or any Bearer key carrying `inference`,
@@ -23,13 +24,11 @@ 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 { limits, clientIp } from '../_lib/rate-limit.js';
-import { mintApiKey } from '../_lib/api-keys.js';
-import { inferenceUsage, inferencePricing } from '../_lib/inference-billing.js';
-import { previewTopup, executeTopup, reconcilePendingTopups } from '../_lib/inference-topup.js';
+import { inferenceUsage } from '../_lib/inference-billing.js';
+import { reconcilePendingTopups } from '../_lib/inference-topup.js';
+import { previewProvision, executeProvision, INFERENCE_BASE_URL } from '../_lib/inference-provision.js';
import { isUuid } from '../_lib/validate.js';
-const BASE_URL = 'https://three.ws/api/v1';
-
async function resolveCaller(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, scope: null };
@@ -80,7 +79,7 @@ async function handleUsage(req, res, caller) {
}
await reconcilePendingTopups(caller.userId);
const usage = await inferenceUsage({ userId: caller.userId, agent });
- return json(res, 200, { ...usage, base_url: BASE_URL });
+ return json(res, 200, { ...usage, base_url: INFERENCE_BASE_URL });
}
async function handleProvision(req, res, caller, action) {
@@ -95,72 +94,21 @@ async function handleProvision(req, res, caller, action) {
const body = (await readJson(req).catch(() => null)) || {};
try {
if (action === 'provision-preview') {
- const agentId = String(body.agent_id || '');
- if (!isUuid(agentId)) return error(res, 400, 'bad_request', 'agent_id is required: the agent whose wallet funds the key');
- const preview = await previewTopup({
+ const preview = await previewProvision({
userId: caller.userId,
- agentId,
+ agentId: body.agent_id,
amountUsdc: body.amount_usdc ?? body.amount,
- source: 'provision',
- });
- return json(res, 200, {
- ...preview,
- key: { scope: 'inference', bound_agent_id: agentId, base_url: BASE_URL },
});
+ return json(res, 200, preview);
}
-
- const topup = await executeTopup({
+ const out = await executeProvision({
userId: caller.userId,
previewId: body.preview_id,
confirmDeposit: body.confirm_deposit,
- sources: ['provision'],
- });
- if (topup.status === 'pending') return json(res, 202, topup);
- if (topup.status !== 'settled') return error(res, 502, 'topup_failed', 'the top-up did not settle, so no key was minted', topup);
-
- // The key is minted once per settled top-up. A retry of a provision that
- // already minted reports the key's prefix; the secret was shown once.
- if (topup.api_key_id) {
- const [k] = await sql`SELECT id, prefix, scope FROM api_keys WHERE id = ${topup.api_key_id}`;
- return json(res, 200, {
- ...topup,
- key: { id: k?.id, prefix: k?.prefix, scope: k?.scope, token: null, base_url: BASE_URL },
- note: 'This top-up already minted its key; the secret is only shown once. Revoke it at /dashboard/api and provision again if it was lost.',
- });
- }
- const name = typeof body.name === 'string' && body.name.trim() ? body.name.trim().slice(0, 80) : 'Inference key';
- const minted = await mintApiKey({
- userId: caller.userId,
- name,
- scopes: ['inference'],
+ name: body.name,
req,
- via: 'inference_provision',
- });
- const [claimed] = await sql`
- UPDATE inference_topups SET api_key_id = ${minted.row.id}
- WHERE id = ${topup.topup_id} AND api_key_id IS NULL
- RETURNING id
- `;
- if (!claimed) {
- await sql`UPDATE api_keys SET revoked_at = now() WHERE id = ${minted.row.id}`;
- return error(res, 409, 'already_provisioned', 'A concurrent request already minted the key for this top-up.');
- }
- await sql`
- INSERT INTO inference_keys (api_key_id, user_id, agent_id, topup_id)
- VALUES (${minted.row.id}, ${caller.userId}, ${topup.agent_id}, ${topup.topup_id})
- `;
- return json(res, 201, {
- ...topup,
- api_key_id: minted.row.id,
- key: {
- id: minted.row.id,
- prefix: minted.row.prefix,
- scope: minted.row.scope,
- token: minted.secret,
- base_url: BASE_URL,
- model: inferencePricing().model,
- },
});
+ return json(res, out.status, out.body);
} catch (err) {
return sendTyped(res, err);
}