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(cards): agents buy gift and prepaid cards through Bitrefill, with recorded API fixtures
nirholasf790dbd8aaba
diff --git a/api/_lib/cards/bitrefill.js b/api/_lib/cards/bitrefill.jsnew file mode 100644index 000000000..7015dd158--- /dev/null+++ b/api/_lib/cards/bitrefill.js@@ -0,0 +1,466 @@+// Bitrefill card adapter: gift cards for major merchants and prepaid Visa and+// Mastercard cards, settled in USDC on Solana.+//+// Why this provider: API-first (REST v2 at api.bitrefill.com), a price-locked+// USDC-on-Solana invoice per purchase (payment method `usdc_solana`, so an+// agent wallet pays with a plain SPL transfer to the invoice address), a real+// catalog of gift cards plus the `payment-cards` category of prepaid cards,+// and free test products for a sandbox that runs against the real API.+//+// Modes+// sandbox Bitrefill's own test products (ids starting `test-`). Paid from+// the account balance with auto-pay, which the provider does not+// charge for test products. No agent funds move.+// live any real product. The quote creates an unpaid `usdc_solana`+// invoice; the service pays it from the agent wallet.+//+// Credential: BITREFILL_API_KEY (Personal API key, Bearer auth).+// Docs: https://docs.bitrefill.com/docs/api-overview++import { CardProviderError } from './provider.js';++const BASE_URL = 'https://api.bitrefill.com/v2';+const IMAGE_BASE = 'https://res.cloudinary.com/bitrefill/image/upload/c_pad,h_160,w_240,f_auto/';+const TIMEOUT_MS = 20_000;+const USDC_DECIMALS = 6;+const PREPAID_CATEGORY = 'payment-cards';++// Bitrefill order status -> the adapter contract's normalized status.+const ORDER_STATUS = {+ created: 'awaiting_payment',+ payment_detected: 'processing',+ payment_confirmed: 'processing',+ processing: 'processing',+ pending: 'processing',+ delivered: 'delivered',+ failed: 'failed',+ permanent_failure: 'failed',+ refunded: 'refunded',+ blocked: 'needs_verification',+ denied: 'failed',+ payment_error: 'failed',+};++const SECRET_FIELDS = ['code', 'pin', 'link', 'barcode_value'];++export function isSandboxProductId(id) {+ return typeof id === 'string' && id.startsWith('test-');+}++function imageUrl(image) {+ if (!image || typeof image !== 'string') return null;+ if (/^https?:\/\//.test(image)) return image;+ return `${IMAGE_BASE}${encodeURIComponent(image).replace(/%2F/g, '/')}`;+}++function kindOf(p) {+ return Array.isArray(p?.categories) && p.categories.includes(PREPAID_CATEGORY) ? 'prepaid_card' : 'gift_card';+}++/** Normalize one Bitrefill product into the adapter's product shape. */+export function normalizeProduct(p) {+ const packages = (Array.isArray(p.packages) ? p.packages : [])+ .map((pk) => ({+ id: String(pk.id ?? pk.package_id ?? ''),+ value: Number(pk.amount ?? pk.value),+ }))+ .filter((pk) => pk.id && Number.isFinite(pk.value) && pk.value > 0)+ .sort((a, b) => a.value - b.value);+ const r = p.range && typeof p.range === 'object' ? p.range : null;+ return {+ id: String(p.id),+ name: String(p.name || p.id),+ merchant: String(p.base_name || p.name || p.id),+ kind: kindOf(p),+ country_code: p.country_code || null,+ country_name: p.country_name || null,+ currency: String(p.currency || 'USD'),+ categories: Array.isArray(p.categories) ? p.categories : [],+ redemption_methods: Array.isArray(p.redemption_methods) ? p.redemption_methods : [],+ image_url: imageUrl(p.image),+ in_stock: p.in_stock !== false,+ sandbox: isSandboxProductId(p.id),+ packages,+ range: r && Number.isFinite(Number(r.min)) && Number.isFinite(Number(r.max))+ ? { min: Number(r.min), max: Number(r.max), step: Number(r.step) || 0.01 }+ : null,+ terms: typeof p.termsAndConditions === 'string' ? p.termsAndConditions.slice(0, 2000) : null,+ };+}++/**+ * Resolve a requested face value against a product's packages and range.+ * Returns `{ value, packageId }` or throws invalid_amount naming what is allowed.+ */+export function resolveDenomination(product, amount) {+ const v = Number(amount);+ if (!Number.isFinite(v) || v <= 0) {+ throw new CardProviderError('invalid_amount', 'amount must be a positive number');+ }+ const pkg = product.packages.find((pk) => Math.abs(pk.value - v) < 1e-9);+ if (pkg) return { value: pkg.value, packageId: pkg.id };+ const r = product.range;+ if (r && v >= r.min - 1e-9 && v <= r.max + 1e-9) {+ const steps = (v - r.min) / r.step;+ if (Math.abs(steps - Math.round(steps)) < 1e-6) return { value: v, packageId: null };+ }+ const allowed = product.packages.map((pk) => pk.value);+ const rangeText = r ? `any value from ${r.min} to ${r.max} in steps of ${r.step}` : null;+ throw new CardProviderError(+ 'invalid_amount',+ `${product.name} does not sell a ${v} ${product.currency} card. Choose ${[+ allowed.length ? `one of ${allowed.join(', ')}` : null,+ rangeText,+ ].filter(Boolean).join(', or ')}.`,+ { detail: { packages: allowed, range: r } },+ );+}++function firstOrder(invoice) {+ return Array.isArray(invoice?.orders) && invoice.orders.length ? invoice.orders[0] : null;+}++function normalizeStatus(invoice, order) {+ const s = order?.status ? ORDER_STATUS[order.status] : null;+ if (s) return s;+ const inv = invoice?.status ? ORDER_STATUS[invoice.status] : null;+ return inv || 'processing';+}++/** Mask a redemption value: keep only its last four characters. */+export function maskSecret(value) {+ const s = String(value ?? '').replace(/\s+/g, '');+ if (!s) return null;+ if (/^https?:\/\//i.test(s)) return 'Redemption link';+ const tail = s.slice(-4);+ return `•••• ${tail}`;+}++/** Split Bitrefill redemption_info into the secret part and the public part. */+export function splitRedemption(info) {+ const r = info && typeof info === 'object' ? info : {};+ const secret = {};+ for (const k of SECRET_FIELDS) {+ if (r[k] != null && String(r[k]).trim() !== '') secret[k] = String(r[k]);+ }+ const extra = r.extra_fields && typeof r.extra_fields === 'object' ? r.extra_fields : {};+ for (const [k, v] of Object.entries(extra)) {+ if (v != null && String(v).trim() !== '') secret[`extra_${k}`] = String(v);+ }+ const primary = secret.code ?? secret.link ?? secret.barcode_value ?? null;+ return {+ secret,+ fields: Object.keys(secret),+ masked: maskSecret(primary),+ instructions: typeof r.instructions === 'string' ? r.instructions.slice(0, 2000) : null,+ expires_on: r.expiration_date ? String(r.expiration_date) : null,+ };+}++/**+ * @param {object} [opts]+ * @param {string} [opts.apiKey] defaults to BITREFILL_API_KEY+ * @param {typeof fetch} [opts.fetchImpl]+ * @param {string} [opts.baseUrl]+ */+export function createBitrefillProvider({ apiKey, fetchImpl, baseUrl = BASE_URL } = {}) {+ const doFetch = fetchImpl || ((...a) => fetch(...a));+ const key = () => apiKey ?? process.env.BITREFILL_API_KEY ?? '';++ async function call(path, { method = 'GET', body, query } = {}) {+ const k = key();+ if (!k) {+ throw new CardProviderError('not_configured', 'Card purchases are not configured on this server (BITREFILL_API_KEY is missing).');+ }+ const url = new URL(baseUrl + path);+ for (const [q, v] of Object.entries(query || {})) {+ if (v !== undefined && v !== null && v !== '') url.searchParams.set(q, String(v));+ }+ let res;+ try {+ res = await doFetch(url.toString(), {+ method,+ headers: {+ authorization: `Bearer ${k}`,+ accept: 'application/json',+ ...(body ? { 'content-type': 'application/json' } : {}),+ },+ body: body ? JSON.stringify(body) : undefined,+ signal: AbortSignal.timeout(TIMEOUT_MS),+ });+ } catch (e) {+ throw new CardProviderError('upstream', 'The card provider did not respond. Try again in a moment.', {+ detail: { reason: e?.name === 'TimeoutError' ? 'timeout' : 'network' },+ });+ }+ let payload = null;+ try {+ payload = await res.json();+ } catch {+ payload = null;+ }+ if (res.status === 429) {+ throw new CardProviderError('rate_limited', 'The card provider is rate limiting requests. Try again in a minute.');+ }+ if (res.status === 401 || res.status === 403) {+ throw new CardProviderError('not_configured', 'The card provider rejected this server\'s credential.', { status: 503 });+ }+ const code = payload?.error_code;+ if (!res.ok || code) {+ const message = typeof payload?.message === 'string' ? payload.message.slice(0, 300) : `card provider error (HTTP ${res.status})`;+ if (code === 'not_found' || res.status === 404) throw new CardProviderError('not_found', message);+ if (code === 'out_of_stock') throw new CardProviderError('out_of_stock', message);+ if (['wrong_value', 'invalid_value', 'invalid_package_id', 'invalid_param', 'missing_param'].includes(code)) {+ throw new CardProviderError('invalid_amount', message);+ }+ throw new CardProviderError('upstream', message, { detail: { provider_code: code || null, http: res.status } });+ }+ return payload;+ }++ async function getProduct(productId) {+ const id = String(productId || '').trim();+ if (!id || id.length > 200) throw new CardProviderError('not_found', 'product id is required');+ const payload = await call(`/products/${encodeURIComponent(id)}`);+ if (!payload?.data) throw new CardProviderError('not_found', 'product not found');+ return normalizeProduct(payload.data);+ }++ async function searchProducts({ q, country, category, merchant, kind, sandbox = false, limit = 24, start = 0 } = {}) {+ const lim = Math.min(50, Math.max(1, Number(limit) || 24));+ const query = typeof q === 'string' ? q.trim().slice(0, 100) : '';+ const cat = kind === 'prepaid_card' ? PREPAID_CATEGORY : (category || undefined);+ let payload;+ if (query || sandbox) {+ payload = await call('/products/search', {+ query: {+ q: query || 'test',+ limit: sandbox ? 50 : lim,+ start: Number(start) || 0,+ include_test_products: sandbox ? 'true' : undefined,+ },+ });+ } else {+ payload = await call('/products', {+ query: { country: country || undefined, category: cat, limit: lim, start: Number(start) || 0 },+ });+ }+ let items = (Array.isArray(payload?.data) ? payload.data : []).map(normalizeProduct);+ if (sandbox) items = items.filter((p) => p.sandbox && !p.id.endsWith('-fail') && !p.categories.includes('esim'));+ if (country) items = items.filter((p) => !p.country_code || p.country_code === country.toUpperCase());+ if (cat && (query || sandbox)) items = items.filter((p) => p.categories.includes(cat));+ if (kind === 'gift_card') items = items.filter((p) => p.kind === 'gift_card');+ if (merchant) {+ const m = String(merchant).toLowerCase();+ items = items.filter((p) => p.merchant.toLowerCase() === m);+ }+ const total = Number(payload?.meta?.total_results ?? payload?.meta?.total ?? items.length);+ return {+ items: items.slice(0, lim),+ total,+ has_more: Boolean(payload?.meta?._next),+ next_start: payload?.meta?._next ? (Number(start) || 0) + lim : null,+ };+ }++ async function searchMerchants(opts = {}) {+ const { items, total, has_more } = await searchProducts({ ...opts, limit: 50 });+ const byMerchant = new Map();+ for (const p of items) {+ const k = p.merchant.toLowerCase();+ const m = byMerchant.get(k) || {+ name: p.merchant,+ kind: p.kind,+ image_url: p.image_url,+ categories: new Set(),+ countries: new Set(),+ product_count: 0,+ sandbox: p.sandbox,+ };+ m.product_count += 1;+ p.categories.forEach((c) => m.categories.add(c));+ if (p.country_code) m.countries.add(p.country_code);+ byMerchant.set(k, m);+ }+ const lim = Math.min(50, Math.max(1, Number(opts.limit) || 24));+ return {+ items: [...byMerchant.values()].slice(0, lim).map((m) => ({+ ...m,+ categories: [...m.categories],+ countries: [...m.countries].sort(),+ })),+ total_products: total,+ has_more,+ };+ }++ /**+ * Create the provider invoice that locks the price.+ * @returns normalized quote with the exact USDC amount (atomic) and address.+ */+ async function quote({ product, value, packageId, mode, refundAddress }) {+ const item = { product_id: product.id, quantity: 1 };+ if (packageId) item.package_id = packageId;+ else item.value = value;+ const body = mode === 'sandbox'+ ? { products: [item], payment_method: 'balance', auto_pay: false }+ : {+ products: [item],+ payment_method: 'usdc_solana',+ ...(refundAddress ? { refund_address: refundAddress } : {}),+ };+ const payload = await call('/invoices', { method: 'POST', body });+ const inv = payload?.data;+ const order = firstOrder(inv);+ if (!inv?.id || !order?.id) throw new CardProviderError('upstream', 'the card provider returned an incomplete invoice');+ if (mode === 'sandbox') {+ return {+ provider_invoice_id: String(inv.id),+ provider_order_id: String(order.id),+ pay_address: null,+ total_atomic: 0n,+ total_usdc: 0,+ fee_usdc: 0,+ provider_status: order.status || inv.status || null,+ };+ }+ const pay = inv.payment || {};+ if (pay.currency !== 'USDC' || !pay.address || !Number.isFinite(Number(pay.price))) {+ throw new CardProviderError('upstream', 'the card provider did not return a USDC payment request');+ }+ const totalAtomic = BigInt(Math.round(Number(pay.price)));+ const totalUsdc = Number(totalAtomic) / 10 ** USDC_DECIMALS;+ return {+ provider_invoice_id: String(inv.id),+ provider_order_id: String(order.id),+ pay_address: String(pay.address),+ total_atomic: totalAtomic,+ total_usdc: totalUsdc,+ fee_usdc: Math.max(0, Number((totalUsdc - Number(value)).toFixed(6))),+ provider_status: order.status || inv.status || null,+ };+ }++ /** Read an invoice's payment request so the service can re-verify it before paying. */+ async function paymentRequest(invoiceId) {+ const payload = await call(`/invoices/${encodeURIComponent(invoiceId)}`);+ const pay = payload?.data?.payment || {};+ return {+ status: pay.status || null,+ address: pay.address || null,+ currency: pay.currency || null,+ total_atomic: Number.isFinite(Number(pay.price)) ? BigInt(Math.round(Number(pay.price))) : null,+ };+ }++ /**+ * Start fulfillment. Sandbox pays the invoice from the account balance+ * (free for test products). Live invoices are paid by the agent's on-chain+ * transfer, so there is nothing to call here.+ */+ async function create({ card }) {+ if (card.mode === 'sandbox') {+ await call(`/invoices/${encodeURIComponent(card.provider_invoice_id)}/pay`, { method: 'POST' });+ }+ return status({ card });+ }++ async function status({ card }) {+ if (!card.provider_invoice_id) throw new CardProviderError('not_found', 'this card has no provider invoice');+ const payload = await call(`/invoices/${encodeURIComponent(card.provider_invoice_id)}`);+ const inv = payload?.data;+ const order = (inv?.orders || []).find((o) => String(o.id) === String(card.provider_order_id)) || firstOrder(inv);+ const normalized = normalizeStatus(inv, order);+ // The invoice read carries redemption_info once delivered. Only its+ // non-secret shape leaves this function; the secret goes through reveal().+ const split = order?.redemption_info ? splitRedemption(order.redemption_info) : null;+ return {+ status: normalized,+ provider_status: order?.status || inv?.status || null,+ payment_status: inv?.payment?.status || null,+ delivered_at: order?.delivered_time || null,+ error: normalized === 'failed' ? (order?.error || 'The provider could not deliver this card.') : null,+ card_data: split ? { masked: split.masked, fields: split.fields, instructions: split.instructions, expires_on: split.expires_on } : null,+ };+ }++ async function fetchRedemption(card) {+ if (!card.provider_order_id) throw new CardProviderError('not_found', 'this card has no provider order');+ const payload = await call(`/orders/${encodeURIComponent(card.provider_order_id)}`);+ const order = payload?.data;+ if (!order) throw new CardProviderError('not_found', 'order not found');+ if (order.status !== 'delivered') {+ throw new CardProviderError('unsupported', 'This card has not been delivered yet, so there is nothing to reveal.', { status: 409 });+ }+ return splitRedemption(order.redemption_info);+ }++ async function cardData({ card }) {+ const r = await fetchRedemption(card);+ return { masked: r.masked, fields: r.fields, instructions: r.instructions, expires_on: r.expires_on };+ }++ async function reveal({ card }) {+ const r = await fetchRedemption(card);+ return r.secret;+ }++ async function balance() {+ throw new CardProviderError(+ 'unsupported',+ 'This provider does not report a remaining balance. A gift card holds its face value until it is redeemed at the merchant.',+ );+ }++ async function cancel({ card }) {+ if (card.status !== 'quoted') {+ throw new CardProviderError(+ 'unsupported',+ 'This provider cannot cancel a card once it has been paid for. Delivered cards are final; failed ones are refunded automatically.',+ );+ }+ // An unpaid provider invoice simply lapses. Nothing to call.+ return { cancelled: true };+ }++ async function withdraw() {+ throw new CardProviderError('unsupported', 'This provider does not support moving a card balance back to USDC.');+ }++ async function connectLink() {+ // Bitrefill is the merchant of record for the platform account: no+ // per-owner identity step exists, so there is never a link to open.+ return { required: false, status: 'ready', url: null };+ }++ return {+ name: 'bitrefill',+ label: 'Bitrefill',+ capabilities: {+ settlement: ['usdc_solana'],+ sandbox: true,+ gift_cards: true,+ prepaid_cards: true,+ balance: false,+ cancel: 'unpaid_only',+ withdraw: false,+ connect: false,+ },+ configured: () => Boolean(key()),+ isSandboxProduct: isSandboxProductId,+ searchMerchants,+ searchProducts,+ getProduct,+ quote,+ paymentRequest,+ create,+ status,+ cardData,+ balance,+ reveal,+ cancel,+ refresh: status,+ withdraw,+ connectLink,+ };+}diff --git a/api/_lib/cards/provider.js b/api/_lib/cards/provider.jsnew file mode 100644index 000000000..a03d51840--- /dev/null+++ b/api/_lib/cards/provider.js@@ -0,0 +1,109 @@+// Card provider adapter contract.+//+// Every gift-card or prepaid-card issuer the platform integrates is one adapter+// module that returns an object with exactly these methods. The card service+// (api/_lib/cards/service.js) talks only to this contract, so adding a second+// issuer is one new file plus one line in PROVIDERS below.+//+// Adapters never persist anything and never touch an agent wallet: they turn+// provider HTTP into normalized shapes. Settlement, spend limits, the audit+// trail and secret encryption all live in the service.+//+// Normalized card statuses an adapter may report:+// awaiting_payment the provider invoice exists and is unpaid+// processing paid, being fulfilled+// delivered redemption data is available+// failed fulfillment failed permanently+// refunded the provider returned the payment+// needs_verification the provider wants the account holder to complete+// identity steps (see connectLink)++import { createBitrefillProvider } from './bitrefill.js';++export const PROVIDER_METHODS = Object.freeze([+ 'searchMerchants',+ 'searchProducts',+ 'getProduct',+ 'quote',+ 'create',+ 'status',+ 'cardData',+ 'balance',+ 'reveal',+ 'cancel',+ 'refresh',+ 'withdraw',+ 'connectLink',+]);++export const CARD_STATUSES = Object.freeze([+ 'awaiting_payment', 'processing', 'delivered', 'failed', 'refunded', 'needs_verification',+]);++/**+ * A provider-side failure with a machine-readable code and an HTTP-ish status,+ * so the REST and MCP boundaries can surface it verbatim.+ * unsupported the provider has no such capability (withdraw, balance)+ * not_configured the provider credential is missing+ * invalid_amount the value is not a package or is outside the range+ * not_found unknown product / order+ * out_of_stock product unavailable right now+ * rate_limited provider throttled us+ * upstream any other provider failure+ */+export class CardProviderError extends Error {+ constructor(code, message, { status, detail } = {}) {+ super(message);+ this.name = 'CardProviderError';+ this.code = code;+ this.status = status ?? STATUS_BY_CODE[code] ?? 502;+ this.detail = detail || {};+ }+}++const STATUS_BY_CODE = {+ unsupported: 409,+ not_configured: 503,+ invalid_amount: 400,+ not_found: 404,+ out_of_stock: 409,+ rate_limited: 429,+ upstream: 502,+};++/** Throws when an adapter object is missing part of the contract. */+export function assertProvider(adapter) {+ if (!adapter || typeof adapter !== 'object') throw new TypeError('card provider must be an object');+ if (typeof adapter.name !== 'string' || !adapter.name) throw new TypeError('card provider needs a name');+ if (!adapter.capabilities || typeof adapter.capabilities !== 'object') {+ throw new TypeError(`card provider ${adapter.name} needs a capabilities object`);+ }+ for (const m of PROVIDER_METHODS) {+ if (typeof adapter[m] !== 'function') throw new TypeError(`card provider ${adapter.name} is missing ${m}()`);+ }+ return adapter;+}++const PROVIDERS = {+ bitrefill: createBitrefillProvider,+};++export const DEFAULT_PROVIDER = 'bitrefill';++const cache = new Map();++/**+ * The adapter for `name` (default provider when omitted). Instances are cached+ * per process; pass `opts` (tests) to build a fresh, uncached one.+ */+export function getCardProvider(name = DEFAULT_PROVIDER, opts = null) {+ const factory = Object.hasOwn(PROVIDERS, name) ? PROVIDERS[name] : null;+ if (!factory) throw new CardProviderError('not_found', `unknown card provider: ${name}`);+ if (opts) return assertProvider(factory(opts));+ if (!cache.has(name)) cache.set(name, assertProvider(factory()));+ return cache.get(name);+}++export function listCardProviders() {+ return Object.keys(PROVIDERS);+}diff --git a/api/_lib/cards/service.js b/api/_lib/cards/service.jsnew file mode 100644index 000000000..dfd6f008f--- /dev/null+++ b/api/_lib/cards/service.js@@ -0,0 +1,759 @@+// Agent cards service: the one place card purchases, status, reveals and+// withdrawals happen. The REST routes (api/v1/agent-cards.js) and the MCP tools+// (api/_mcp/tools/cards.js) are thin boundaries over these functions.+//+// Money path (live mode)+// quote creates the provider's price-locked USDC invoice and stores it as a+// card row in status 'quoted' for QUOTE_TTL_MS.+// create requires confirm_spend === true and that fresh quote id. It claims+// the quote atomically (so it settles at most once), re-reads the+// provider invoice to prove the address and exact amount are+// unchanged, then pays through transferUsdcGuarded: the custody+// reserve under the agent's spend limits, natural-language policy,+// capability scope and the anomaly freeze, all before any key is+// touched, with the spend recorded in agent_custody_events.+//+// Secret path+// On delivery the redemption data is fetched once, secret-box encrypted+// (the custodial-wallet scheme) and stored; only a masked form and the list+// of field names are kept in the clear. `data` issues a single-use reveal+// grant; `reveal` requires confirm_reveal === true plus that grant, returns+// the secret, clears the ciphertext in the same statement, and logs who+// revealed what (field names, never values) in agent_card_events.++import { createHash, randomBytes } from 'node:crypto';+import { sql } from '../db.js';+import { encryptSecret, decryptSecret } from '../agent-wallet.js';+import { transferUsdcGuarded } from '../agent-usdc-transfer.js';+import { currentSignatureFor, agreementRequirement } from '../real-funds-agreement.js';+import { logAudit } from '../audit.js';+import { getCardProvider, CardProviderError, DEFAULT_PROVIDER } from './provider.js';+import { resolveDenomination } from './bitrefill.js';++export const QUOTE_TTL_MS = 10 * 60 * 1000;+export const REVEAL_GRANT_TTL_MS = 5 * 60 * 1000;+const MAX_QUOTES_PER_HOUR = 30;+const OPEN_STATUSES = ['paying', 'processing', 'needs_verification'];+const TERMINAL = new Set(['delivered', 'failed', 'refunded', 'cancelled', 'expired']);+const POLL_ATTEMPTS = 4;+const POLL_GAP_MS = 2500;++/** Live purchases are enabled per deploy; sandbox always works. */+export function liveCardsEnabled() {+ return process.env.AGENT_CARDS_LIVE === '1';+}++export class CardError extends Error {+ constructor(status, code, message, details = null) {+ super(message);+ this.name = 'CardError';+ this.status = status;+ this.code = code;+ this.details = details;+ }+}++/** Map an adapter error onto the service error shape. */+function fromProvider(e) {+ if (e instanceof CardProviderError) return new CardError(e.status, e.code, e.message, e.detail || null);+ return e;+}++async function withProvider(fn) {+ try {+ return await fn();+ } catch (e) {+ throw fromProvider(e);+ }+}++function actorKind(principal) {+ if (!principal) return 'system';+ if (principal.source === 'session') return 'owner_session';+ if (principal.source === 'apikey') return 'api_key';+ if (principal.source === 'oauth') return 'oauth';+ if (principal.source === 'mcp') return 'mcp';+ return String(principal.source || 'owner');+}++/** Load an agent the principal owns, or throw a designed 401/403/404. */+export async function loadOwnedAgent(agentId, principal) {+ if (!principal?.userId) throw new CardError(401, 'unauthorized', 'Sign in to manage agent cards.');+ if (!/^[0-9a-f-]{36}$/i.test(String(agentId || ''))) {+ throw new CardError(400, 'invalid_agent_id', 'agent id must be a UUID');+ }+ const [agent] = await sql`+ SELECT id, user_id, name, meta+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) throw new CardError(404, 'agent_not_found', 'Agent not found.');+ if (agent.user_id !== principal.userId) {+ throw new CardError(403, 'forbidden', 'Only the owner of this agent can manage its cards.');+ }+ return agent;+}++async function recordCardEvent(card, principal, event, { from = null, to = null, detail = {}, grantHash = null, grantExpiresAt = null } = {}) {+ const [row] = await sql`+ INSERT INTO agent_card_events+ (card_id, agent_id, actor_user_id, actor_kind, event, from_status, to_status,+ grant_hash, grant_expires_at, ip, detail)+ VALUES (+ ${card.id}, ${card.agent_id}, ${principal?.userId ?? null}, ${actorKind(principal)}, ${event},+ ${from}, ${to}, ${grantHash}, ${grantExpiresAt}, ${principal?.ip ?? null},+ ${JSON.stringify(detail)}::jsonb+ )+ RETURNING id, created_at+ `;+ return row;+}++/** The owner-facing shape of a card. Never includes the ciphertext. */+export function cardView(row) {+ if (!row) return null;+ return {+ id: row.id,+ agent_id: row.agent_id,+ provider: row.provider,+ mode: row.mode,+ kind: row.kind,+ product_id: row.product_id,+ product_name: row.product_name,+ merchant: row.merchant,+ country_code: row.country_code,+ image_url: row.image_url,+ face_value: Number(row.face_value),+ currency: row.currency,+ status: row.status,+ provider_status: row.provider_status,+ total_usdc: Number(row.quote_total_usdc),+ fee_usdc: Number(row.quote_fee_usdc),+ quote_expires_at: row.quote_expires_at,+ pay_address: row.pay_address,+ pay_network: row.pay_network,+ pay_signature: row.pay_signature,+ pay_explorer: row.pay_signature ? `https://solscan.io/tx/${row.pay_signature}` : null,+ masked_number: row.masked_number,+ secret_fields: row.secret_fields || [],+ redeem_instructions: row.redeem_instructions,+ expires_on: row.expires_on,+ revealed_at: row.revealed_at,+ reveal_count: Number(row.reveal_count || 0),+ error_code: row.error_code,+ error_message: row.error_message,+ created_at: row.created_at,+ updated_at: row.updated_at,+ delivered_at: row.delivered_at,+ };+}++function quoteView(row, product) {+ const card = cardView(row);+ const live = row.mode === 'live';+ return {+ quote_id: row.id,+ mode: row.mode,+ product: product ? {+ id: product.id, name: product.name, merchant: product.merchant, kind: product.kind,+ country_code: product.country_code, image_url: product.image_url,+ } : { id: row.product_id, name: row.product_name, merchant: row.merchant, kind: row.kind },+ face_value: card.face_value,+ currency: card.currency,+ total_usdc: card.total_usdc,+ fee_usdc: card.fee_usdc,+ expires_at: row.quote_expires_at,+ // The exact table an owner must see before saying yes (stop-and-ask gate 1).+ confirm: {+ recipient: live ? row.pay_address : `${row.provider} sandbox (test product, no funds move)`,+ amount: live ? card.total_usdc.toFixed(6).replace(/0+$/, '').replace(/\.$/, '') : '0',+ token: 'USDC',+ chain: 'Solana',+ buys: `${card.merchant} ${row.kind === 'prepaid_card' ? 'prepaid card' : 'gift card'}, ${card.face_value} ${card.currency}`,+ provider: row.provider,+ },+ next: {+ tool: 'agent_card_create',+ args: { agent_id: row.agent_id, quote_id: row.id, confirm_spend: true },+ note: 'Show the confirm table to the owner and wait for an explicit yes before calling agent_card_create.',+ },+ };+}++// ── catalog ──────────────────────────────────────────────────────────────────++function providerFor(name) {+ try {+ return getCardProvider(name || DEFAULT_PROVIDER);+ } catch (e) {+ throw fromProvider(e);+ }+}++export function providerInfo(name) {+ const p = providerFor(name);+ return {+ name: p.name,+ label: p.label,+ capabilities: p.capabilities,+ configured: p.configured(),+ live_enabled: liveCardsEnabled(),+ };+}++export async function searchMerchants({ q, country, kind, sandbox, limit, provider } = {}) {+ const p = providerFor(provider);+ return withProvider(() => p.searchMerchants({ q, country, kind, sandbox, limit }));+}++export async function searchProducts({ q, country, category, merchant, kind, sandbox, limit, start, provider } = {}) {+ const p = providerFor(provider);+ return withProvider(() => p.searchProducts({ q, country, category, merchant, kind, sandbox, limit, start }));+}++export async function getProduct({ productId, provider } = {}) {+ const p = providerFor(provider);+ return withProvider(() => p.getProduct(productId));+}++// ── quote ────────────────────────────────────────────────────────────────────++async function requireAgreement(userId) {+ let sig;+ try {+ sig = await currentSignatureFor(userId);+ } catch {+ throw new CardError(503, 'agreement_check_failed', 'Could not verify your real-funds agreement. No funds moved; try again.');+ }+ if (!sig) {+ throw new CardError(403, 'agreement_required',+ 'Buying a live card spends real USDC. Sign the real-funds agreements first, then try again.',+ agreementRequirement());+ }+}++export async function quoteCard({ agentId, principal, productId, amount, provider }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const p = providerFor(provider);+ const product = await withProvider(() => p.getProduct(productId));+ if (!product.in_stock) throw new CardError(409, 'out_of_stock', `${product.name} is out of stock right now. Pick another merchant or try later.`);+ const denom = await withProvider(async () => resolveDenomination(product, amount));++ const mode = p.isSandboxProduct(product.id) ? 'sandbox' : 'live';+ const meta = agent.meta || {};+ if (mode === 'live') {+ if (!liveCardsEnabled()) {+ throw new CardError(409, 'live_cards_disabled',+ 'Live card purchases are not switched on for this deployment yet. Sandbox test products work today; search with sandbox: true to try the full flow.');+ }+ if (!meta.solana_address || !meta.encrypted_solana_secret) {+ throw new CardError(409, 'wallet_preparing', 'This agent has no Solana wallet yet, so it cannot pay for a card. Open its wallet page to provision one.');+ }+ }++ const [{ n }] = await sql`+ SELECT count(*)::int AS n FROM agent_cards+ WHERE agent_id = ${agent.id} AND created_at > now() - interval '1 hour'+ `;+ if (n >= MAX_QUOTES_PER_HOUR) {+ throw new CardError(429, 'quote_rate_limited', `This agent has requested ${n} card quotes in the last hour. Wait a while before quoting again.`);+ }++ const q = await withProvider(() => p.quote({+ product, value: denom.value, packageId: denom.packageId, mode,+ refundAddress: mode === 'live' ? meta.solana_address : null,+ }));++ const expiresAt = new Date(Date.now() + QUOTE_TTL_MS);+ const [row] = await sql`+ INSERT INTO agent_cards+ (agent_id, user_id, provider, mode, kind, product_id, product_name, merchant, country_code,+ image_url, face_value, currency, status, quote_total_usdc, quote_total_atomic, quote_fee_usdc,+ quote_expires_at, pay_address, provider_invoice_id, provider_order_id, provider_status, meta)+ VALUES (+ ${agent.id}, ${agent.user_id}, ${p.name}, ${mode}, ${product.kind}, ${product.id}, ${product.name},+ ${product.merchant}, ${product.country_code}, ${product.image_url}, ${denom.value}, ${product.currency},+ 'quoted', ${q.total_usdc}, ${q.total_atomic.toString()}, ${q.fee_usdc}, ${expiresAt.toISOString()},+ ${q.pay_address}, ${q.provider_invoice_id}, ${q.provider_order_id}, ${q.provider_status},+ ${JSON.stringify({ package_id: denom.packageId })}::jsonb+ )+ RETURNING *+ `;+ await recordCardEvent(row, principal, 'quoted', {+ to: 'quoted',+ detail: { total_usdc: q.total_usdc, face_value: denom.value, currency: product.currency, mode },+ });+ return quoteView(row, product);+}++// ── create ───────────────────────────────────────────────────────────────────++async function claimQuote(agentId, quoteId) {+ const [row] = await sql`+ UPDATE agent_cards SET status = 'paying', updated_at = now()+ WHERE id = ${quoteId} AND agent_id = ${agentId} AND status = 'quoted' AND quote_expires_at > now()+ RETURNING *+ `;+ if (row) return row;+ const [existing] = await sql`SELECT * FROM agent_cards WHERE id = ${quoteId} AND agent_id = ${agentId}`;+ if (!existing) throw new CardError(404, 'quote_not_found', 'No quote with that id for this agent. Call agent_card_quote first.');+ if (existing.status === 'quoted') {+ await sql`UPDATE agent_cards SET status = 'expired', updated_at = now() WHERE id = ${quoteId} AND status = 'quoted'`;+ throw new CardError(409, 'quote_expired', 'That quote is more than ten minutes old. Call agent_card_quote again for a fresh price.');+ }+ throw new CardError(409, 'quote_used', `That quote was already used (card status: ${existing.status}). Call agent_card_quote for a new card.`);+}++async function setStatus(card, principal, patch, event = 'status') {+ const [row] = await sql`+ UPDATE agent_cards SET+ status = COALESCE(${patch.status ?? null}, status),+ provider_status = COALESCE(${patch.provider_status ?? null}, provider_status),+ pay_signature = COALESCE(${patch.pay_signature ?? null}, pay_signature),+ custody_event_id = COALESCE(${patch.custody_event_id ?? null}, custody_event_id),+ error_code = ${patch.error_code !== undefined ? patch.error_code : card.error_code ?? null},+ error_message = ${patch.error_message !== undefined ? patch.error_message : card.error_message ?? null},+ delivered_at = COALESCE(${patch.delivered_at ?? null}, delivered_at),+ updated_at = now()+ WHERE id = ${card.id}+ RETURNING *+ `;+ if (patch.status && patch.status !== card.status) {+ await recordCardEvent(row, principal, event, {+ from: card.status, to: patch.status,+ detail: patch.error_code ? { error_code: patch.error_code } : {},+ });+ }+ return row;+}++/**+ * Store the redemption data encrypted, once, right after delivery. Only runs+ * while the card has never been revealed, so a revealed secret is never+ * written back.+ */+async function sealSecret(card, p) {+ if (card.secret_enc || card.revealed_at) return card;+ const secret = await withProvider(() => p.reveal({ card }));+ const data = await withProvider(() => p.cardData({ card }));+ const fields = Object.keys(secret || {});+ if (!fields.length) return card;+ const sealed = await encryptSecret(JSON.stringify(secret));+ const [row] = await sql`+ UPDATE agent_cards SET+ secret_enc = ${sealed}, secret_fields = ${fields}, masked_number = ${data.masked},+ redeem_instructions = ${data.instructions}, expires_on = ${data.expires_on}, updated_at = now()+ WHERE id = ${card.id} AND secret_enc IS NULL AND revealed_at IS NULL+ RETURNING *+ `;+ return row || card;+}++/** Pull the provider's status onto the row; seals the secret on delivery. */+async function syncCard(card, principal) {+ const p = providerFor(card.provider);+ if (card.status === 'quoted') {+ if (new Date(card.quote_expires_at).getTime() <= Date.now()) {+ return setStatus(card, principal, { status: 'expired' });+ }+ return card;+ }+ if (TERMINAL.has(card.status) && card.status !== 'delivered') return card;+ if (card.status === 'delivered' && (card.secret_enc || card.revealed_at)) return card;+ // A live card whose payment never broadcast has nothing to ask the provider.+ if (card.status === 'paying' && card.mode === 'live' && !card.pay_signature) return card;++ const s = await withProvider(() => p.status({ card }));+ let next = card.status;+ if (s.status === 'delivered') next = 'delivered';+ else if (s.status === 'failed') next = 'failed';+ else if (s.status === 'refunded') next = 'refunded';+ else if (s.status === 'needs_verification') next = 'needs_verification';+ else if (s.status === 'processing' || (s.status === 'awaiting_payment' && card.pay_signature)) next = 'processing';++ let row = await setStatus(card, principal, {+ status: next,+ provider_status: s.provider_status,+ delivered_at: next === 'delivered' ? (s.delivered_at || new Date().toISOString()) : null,+ error_code: next === 'failed' ? 'provider_failed' : undefined,+ error_message: next === 'failed' ? s.error : undefined,+ });+ if (row.status === 'delivered') row = await sealSecret(row, p);+ return row;+}++const pause = (ms) => new Promise((r) => setTimeout(r, ms));++async function pollUntilSettled(card, principal) {+ let row = card;+ for (let i = 0; i < POLL_ATTEMPTS; i++) {+ row = await syncCard(row, principal);+ if (TERMINAL.has(row.status) || row.status === 'needs_verification') return row;+ await pause(POLL_GAP_MS);+ }+ return row;+}++export async function createCard({ agentId, principal, quoteId, confirmSpend }) {+ const agent = await loadOwnedAgent(agentId, principal);+ if (confirmSpend !== true) {+ throw new CardError(400, 'confirm_required',+ 'agent_card_create moves funds. Call agent_card_quote first, show the owner its confirm table, and pass confirm_spend: true only after they say yes.',+ { preview_tool: 'agent_card_quote', confirm_flag: 'confirm_spend' });+ }+ if (typeof quoteId !== 'string' || !/^[0-9a-f-]{36}$/i.test(quoteId)) {+ throw new CardError(400, 'quote_required', 'quote_id from agent_card_quote is required.', { preview_tool: 'agent_card_quote' });+ }++ const [peek] = await sql`SELECT mode FROM agent_cards WHERE id = ${quoteId} AND agent_id = ${agent.id}`;+ if (peek?.mode === 'live') {+ if (!liveCardsEnabled()) throw new CardError(409, 'live_cards_disabled', 'Live card purchases are not switched on for this deployment.');+ await requireAgreement(principal.userId);+ }++ let card = await claimQuote(agent.id, quoteId);+ await recordCardEvent(card, principal, 'purchase_confirmed', { from: 'quoted', to: 'paying', detail: { total_usdc: Number(card.quote_total_usdc) } });+ const p = providerFor(card.provider);++ if (card.mode === 'sandbox') {+ try {+ await p.create({ card });+ } catch (e) {+ const err = fromProvider(e);+ await setStatus(card, principal, { status: 'failed', error_code: err.code || 'provider_error', error_message: err.message });+ throw err;+ }+ card = await setStatus(card, principal, { status: 'processing' }, 'paid');+ return cardView(await pollUntilSettled(card, principal));+ }++ // Live: prove the provider invoice still asks for exactly what the owner confirmed.+ let pr;+ try {+ pr = await p.paymentRequest(card.provider_invoice_id);+ } catch (e) {+ await setStatus(card, principal, { status: 'failed', error_code: 'invoice_unreadable', error_message: 'Could not re-read the provider invoice. No funds moved.' });+ throw fromProvider(e);+ }+ const expected = BigInt(card.quote_total_atomic);+ if (pr.status !== 'unpaid' || pr.currency !== 'USDC' || pr.address !== card.pay_address || pr.total_atomic !== expected) {+ await setStatus(card, principal, { status: 'failed', error_code: 'invoice_changed', error_message: 'The provider invoice no longer matches the quote. No funds moved; request a new quote.' });+ throw new CardError(409, 'invoice_changed', 'The provider invoice no longer matches the quote you confirmed. No funds moved; request a new quote.');+ }++ const pay = await transferUsdcGuarded({+ fromAgentId: agent.id,+ fromUserId: agent.user_id,+ fromMeta: agent.meta || {},+ toAddress: card.pay_address,+ usdc: Number(card.quote_total_usdc),+ amountAtomics: expected,+ network: 'mainnet',+ category: 'card',+ idempotencyKey: `card:${card.id}`,+ rowMeta: { card_id: card.id, provider: card.provider, product_id: card.product_id, invoice_id: card.provider_invoice_id },+ });++ if (pay.status === 'blocked') {+ await setStatus(card, principal, { status: 'failed', error_code: pay.code, error_message: pay.message });+ throw new CardError(403, pay.code, pay.message || 'The agent spend policy blocked this purchase. No funds moved.');+ }+ if (pay.status === 'failed' && pay.code === 'unconfirmed') {+ card = await setStatus(card, principal, { pay_signature: pay.signature, custody_event_id: pay.custodyEventId });+ logAudit({ userId: agent.user_id, action: 'cards.purchase_unconfirmed', resourceId: agent.id, meta: { card_id: card.id, signature: pay.signature } });+ return cardView(card);+ }+ if (pay.status !== 'paid' && pay.status !== 'replayed') {+ const message = pay.code === 'wallet_preparing'+ ? 'This agent has no Solana wallet yet.'+ : `The USDC payment did not go through (${pay.code}). No card was bought.`;+ await setStatus(card, principal, { status: 'failed', error_code: pay.code, error_message: message });+ throw new CardError(502, pay.code || 'payment_failed', message);+ }++ card = await setStatus(card, principal, {+ status: 'processing', pay_signature: pay.signature, custody_event_id: pay.custodyEventId,+ }, 'paid');+ logAudit({+ userId: agent.user_id, action: 'cards.purchase', resourceId: agent.id,+ meta: { card_id: card.id, usdc: Number(card.quote_total_usdc), signature: pay.signature, provider: card.provider },+ });+ return cardView(await pollUntilSettled(card, principal));+}++// ── read ─────────────────────────────────────────────────────────────────────++async function loadCard(agentId, cardId) {+ if (typeof cardId !== 'string' || !/^[0-9a-f-]{36}$/i.test(cardId)) {+ throw new CardError(400, 'invalid_card_id', 'card id must be a UUID');+ }+ const [row] = await sql`SELECT * FROM agent_cards WHERE id = ${cardId} AND agent_id = ${agentId}`;+ if (!row) throw new CardError(404, 'card_not_found', 'No card with that id for this agent.');+ return row;+}++export async function listCards({ agentId, principal, status = null, limit = 25, cursor = null }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const lim = Math.min(100, Math.max(1, Number(limit) || 25));+ let before = null;+ if (cursor) {+ const d = new Date(String(cursor));+ if (!Number.isNaN(d.getTime())) before = d.toISOString();+ }+ const rows = await sql`+ SELECT * FROM agent_cards+ WHERE agent_id = ${agent.id}+ AND (${status}::text IS NULL OR status = ${status})+ AND (${before}::timestamptz IS NULL OR created_at < ${before}::timestamptz)+ AND NOT (status IN ('expired', 'cancelled') AND created_at < now() - interval '1 day')+ ORDER BY created_at DESC+ LIMIT ${lim + 1}+ `;+ const pageRows = rows.slice(0, lim);+ // Bring in-flight cards up to date so a list read reflects delivery.+ const synced = [];+ let budget = 5;+ for (const r of pageRows) {+ const stale = OPEN_STATUSES.includes(r.status) || (r.status === 'quoted' && new Date(r.quote_expires_at) <= new Date());+ if (stale && budget > 0) {+ budget -= 1;+ try {+ synced.push(await syncCard(r, principal));+ continue;+ } catch {+ // Provider unreachable: show the stored state rather than failing the list.+ }+ }+ synced.push(r);+ }+ const [totals] = await sql`+ SELECT+ count(*) FILTER (WHERE status = 'delivered')::int AS delivered,+ COALESCE(sum(quote_total_usdc) FILTER (WHERE status IN ('delivered', 'processing') AND mode = 'live'), 0)::float8 AS spent_usdc+ FROM agent_cards WHERE agent_id = ${agent.id}+ `;+ return {+ items: synced.map(cardView),+ has_more: rows.length > lim,+ next_cursor: rows.length > lim ? new Date(pageRows[pageRows.length - 1].created_at).toISOString() : null,+ totals: { delivered: totals.delivered, spent_usdc: Number(totals.spent_usdc) },+ };+}++export async function getCard({ agentId, principal, cardId }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ const events = await sql`+ SELECT id, actor_kind, event, from_status, to_status, detail, created_at+ FROM agent_card_events+ WHERE card_id = ${row.id} AND event <> 'reveal_preview'+ ORDER BY id DESC LIMIT 30+ `;+ return { card: cardView(row), events };+}++export async function refreshCard({ agentId, principal, cardId }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ return cardView(await syncCard(row, principal));+}++export async function cardBalance({ agentId, principal, cardId }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ const p = providerFor(row.provider);+ if (p.capabilities.balance) {+ const b = await withProvider(() => p.balance({ card: row }));+ return { card_id: row.id, balance: b.balance, currency: b.currency, source: 'provider' };+ }+ const live = row.status === 'delivered';+ return {+ card_id: row.id,+ balance: live ? Number(row.face_value) : 0,+ currency: row.currency,+ source: 'face_value',+ note: live+ ? `${p.label} does not report balances. A delivered gift card holds its face value until it is redeemed at ${row.merchant}.`+ : `This card is ${row.status}, so it holds no balance.`,+ };+}++// ── reveal ───────────────────────────────────────────────────────────────────++const hashGrant = (id) => createHash('sha256').update(String(id)).digest('hex');++/**+ * Card data without the secret, plus a single-use reveal grant (`preview_id`)+ * that agent_card_reveal must present with confirm_reveal: true.+ */+export async function cardData({ agentId, principal, cardId }) {+ const agent = await loadOwnedAgent(agentId, principal);+ let row = await loadCard(agent.id, cardId);+ if (row.status !== 'delivered') row = await syncCard(row, principal);+ if (row.status !== 'delivered') {+ throw new CardError(409, 'not_delivered', `This card is ${row.status}; its data is available once it is delivered.`);+ }+ const previewId = randomBytes(24).toString('base64url');+ const expiresAt = new Date(Date.now() + REVEAL_GRANT_TTL_MS);+ await recordCardEvent(row, principal, 'reveal_preview', {+ grantHash: hashGrant(previewId), grantExpiresAt: expiresAt.toISOString(),+ detail: { fields: row.secret_fields || [] },+ });+ return {+ card: cardView(row),+ fields: row.secret_fields || [],+ masked_number: row.masked_number,+ instructions: row.redeem_instructions,+ expires_on: row.expires_on,+ preview_id: previewId,+ preview_expires_at: expiresAt.toISOString(),+ next: {+ tool: 'agent_card_reveal',+ args: { agent_id: agent.id, card_id: row.id, preview_id: previewId, confirm_reveal: true },+ note: 'Revealing exposes the redemption secret. Confirm with the owner first. The preview id works once.',+ },+ };+}++export async function revealCard({ agentId, principal, cardId, previewId, confirmReveal }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ const refuse = async (code, message, status = 400) => {+ await recordCardEvent(row, principal, 'reveal_refused', { detail: { reason: code } });+ throw new CardError(status, code, message, { preview_tool: 'agent_card_data', confirm_flag: 'confirm_reveal' });+ };+ if (confirmReveal !== true) {+ await refuse('confirm_required', 'agent_card_reveal exposes the card secret. Call agent_card_data, confirm with the owner, then pass its preview_id with confirm_reveal: true.');+ }+ if (typeof previewId !== 'string' || previewId.length < 16 || previewId.length > 128) {+ await refuse('preview_required', 'preview_id from agent_card_data is required.');+ }+ if (row.status !== 'delivered') {+ await refuse('not_delivered', `This card is ${row.status}; there is nothing to reveal.`, 409);+ }+ const [grant] = await sql`+ UPDATE agent_card_events SET grant_consumed_at = now()+ WHERE grant_hash = ${hashGrant(previewId)} AND card_id = ${row.id}+ AND grant_consumed_at IS NULL AND grant_expires_at > now()+ RETURNING id+ `;+ if (!grant) {+ await refuse('preview_invalid', 'That preview id was already used or has expired. Call agent_card_data for a new one and confirm again.', 409);+ }++ // Take the ciphertext and clear it in one statement.+ const [taken] = await sql`+ UPDATE agent_cards c SET secret_enc = NULL, revealed_at = now(), reveal_count = c.reveal_count + 1, updated_at = now()+ FROM (SELECT id, secret_enc FROM agent_cards WHERE id = ${row.id} FOR UPDATE) o+ WHERE c.id = o.id+ RETURNING o.secret_enc AS sealed, c.reveal_count+ `;+ let secret;+ let source;+ if (taken?.sealed) {+ secret = JSON.parse(await decryptSecret(taken.sealed));+ source = 'sealed';+ } else {+ const p = providerFor(row.provider);+ secret = await withProvider(() => p.reveal({ card: row }));+ source = 'provider';+ }+ const fields = Object.keys(secret || {});+ await recordCardEvent(row, principal, 'revealed', { detail: { fields, source, reveal_count: taken?.reveal_count ?? null } });+ logAudit({ userId: agent.user_id, action: 'cards.reveal', resourceId: agent.id, meta: { card_id: row.id, fields } });+ return {+ card_id: row.id,+ merchant: row.merchant,+ face_value: Number(row.face_value),+ currency: row.currency,+ secret,+ fields,+ instructions: row.redeem_instructions,+ notice: 'Shown once. three.ws no longer stores this secret; save it somewhere safe now.',+ };+}++// ── cancel / withdraw / connect ─────────────────────────────────────────────++export async function cancelCard({ agentId, principal, cardId, confirmCancel }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ if (confirmCancel !== true) {+ throw new CardError(400, 'confirm_required', 'Cancelling is irreversible. Show the card to the owner and pass confirm_cancel: true after they agree.',+ { preview_tool: 'agent_card_get', confirm_flag: 'confirm_cancel' });+ }+ const p = providerFor(row.provider);+ await withProvider(() => p.cancel({ card: row }));+ const [updated] = await sql`+ UPDATE agent_cards SET status = 'cancelled', updated_at = now()+ WHERE id = ${row.id} AND status = 'quoted'+ RETURNING *+ `;+ if (!updated) throw new CardError(409, 'not_cancellable', 'This card can no longer be cancelled.');+ await recordCardEvent(updated, principal, 'cancelled', { from: row.status, to: 'cancelled' });+ return cardView(updated);+}++export async function withdrawCard({ agentId, principal, cardId, amount, confirmWithdraw }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ const p = providerFor(row.provider);+ if (!p.capabilities.withdraw) {+ await withProvider(() => p.withdraw({ card: row }));+ }+ if (confirmWithdraw !== true) {+ throw new CardError(400, 'confirm_required', 'Withdrawing moves the card balance. Check agent_card_balance, confirm with the owner, then pass confirm_withdraw: true.',+ { preview_tool: 'agent_card_balance', confirm_flag: 'confirm_withdraw' });+ }+ if (row.status !== 'delivered') throw new CardError(409, 'not_delivered', 'Only a delivered card has a balance to withdraw.');+ const amt = Number(amount);+ if (!(amt > 0)) throw new CardError(400, 'invalid_amount', 'amount must be a positive number');+ const destination = agent.meta?.solana_address;+ if (!destination) throw new CardError(409, 'wallet_preparing', 'This agent has no Solana wallet to receive the withdrawal.');+ const [w] = await sql`+ INSERT INTO agent_card_withdrawals (card_id, agent_id, user_id, provider, amount, currency, destination)+ VALUES (${row.id}, ${agent.id}, ${agent.user_id}, ${row.provider}, ${amt}, ${row.currency}, ${destination})+ RETURNING *+ `;+ try {+ const r = await p.withdraw({ card: row, amount: amt, destination });+ const [done] = await sql`+ UPDATE agent_card_withdrawals SET status = ${r.status || 'processing'}, provider_ref = ${r.provider_ref || null},+ usdc_amount = ${r.usdc_amount ?? null}, signature = ${r.signature || null}, updated_at = now()+ WHERE id = ${w.id} RETURNING *+ `;+ await recordCardEvent(row, principal, 'withdraw_requested', { detail: { withdrawal_id: w.id, amount: amt } });+ return done;+ } catch (e) {+ const err = fromProvider(e);+ await sql`UPDATE agent_card_withdrawals SET status = 'failed', error_message = ${err.message}, updated_at = now() WHERE id = ${w.id}`;+ throw err;+ }+}++export async function listWithdrawals({ agentId, principal, cardId }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const row = await loadCard(agent.id, cardId);+ const items = await sql`+ SELECT id, amount, currency, usdc_amount, destination, status, signature, error_message, created_at, updated_at+ FROM agent_card_withdrawals WHERE card_id = ${row.id} ORDER BY created_at DESC LIMIT 50+ `;+ return { items, supported: Boolean(providerFor(row.provider).capabilities.withdraw) };+}++export async function connectStatus({ agentId, principal, provider }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const p = providerFor(provider);+ const c = await withProvider(() => p.connectLink({ agent }));+ return { provider: p.name, required: Boolean(c.required), status: c.status, has_link: Boolean(c.url) };+}++export async function connectLink({ agentId, principal, provider }) {+ const agent = await loadOwnedAgent(agentId, principal);+ const p = providerFor(provider);+ const c = await withProvider(() => p.connectLink({ agent }));+ if (!c.required || !c.url) {+ throw new CardError(409, 'connect_not_required', `${p.label} needs no identity steps for this account. Cards can be bought right away.`);+ }+ return { provider: p.name, url: c.url, status: c.status };+}diff --git a/api/_lib/migrations/20260922161000_agent_cards.sql b/api/_lib/migrations/20260922161000_agent_cards.sqlnew file mode 100644index 000000000..12ff68185--- /dev/null+++ b/api/_lib/migrations/20260922161000_agent_cards.sql@@ -0,0 +1,115 @@+-- Agent cards: gift cards and prepaid cards an agent buys from its own wallet.+--+-- One row per card, from the quote through delivery. A quote IS a card row in+-- status 'quoted' so the confirm step can only ever settle the exact price and+-- address the owner was shown, and only while the quote is fresh.+--+-- quoted -> paying -> processing -> delivered+-- \-> expired | cancelled \-> failed | refunded+-- any live state -> needs_verification (provider wants identity steps)+--+-- The redemption secret (card number, PIN, code, link) is never stored in+-- plaintext. It is secret-box encrypted (WALLET_ENCRYPTION_KEY, the same scheme+-- as custodial wallet keys) from delivery until the first confirmed reveal, and+-- the ciphertext is cleared by that reveal. Service layer: api/_lib/cards/.++CREATE TABLE IF NOT EXISTS agent_cards (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ provider text NOT NULL,+ mode text NOT NULL CHECK (mode IN ('sandbox', 'live')),+ kind text NOT NULL DEFAULT 'gift_card' CHECK (kind IN ('gift_card', 'prepaid_card')),+ product_id text NOT NULL,+ product_name text NOT NULL,+ merchant text NOT NULL,+ country_code text,+ image_url text,+ face_value numeric(20, 6) NOT NULL CHECK (face_value > 0),+ currency text NOT NULL,+ status text NOT NULL DEFAULT 'quoted'+ CHECK (status IN ('quoted', 'paying', 'processing', 'delivered', 'failed', 'refunded',+ 'cancelled', 'expired', 'needs_verification')),+ -- The price-locked quote the owner confirmed.+ quote_total_usdc numeric(20, 6) NOT NULL DEFAULT 0,+ quote_total_atomic bigint NOT NULL DEFAULT 0,+ quote_fee_usdc numeric(20, 6) NOT NULL DEFAULT 0,+ quote_expires_at timestamptz NOT NULL,+ pay_network text NOT NULL DEFAULT 'mainnet',+ pay_address text,+ -- Provider handles.+ provider_invoice_id text,+ provider_order_id text,+ provider_status text,+ -- Settlement.+ custody_event_id bigint,+ pay_signature text,+ -- Card data. Only the masked form and the list of secret fields are kept.+ masked_number text,+ secret_fields text[] NOT NULL DEFAULT '{}',+ secret_enc text,+ redeem_instructions text,+ expires_on text,+ revealed_at timestamptz,+ reveal_count int NOT NULL DEFAULT 0,+ error_code text,+ error_message text,+ meta jsonb NOT NULL DEFAULT '{}'::jsonb,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ delivered_at timestamptz+);++CREATE INDEX IF NOT EXISTS agent_cards_agent_idx ON agent_cards (agent_id, created_at DESC);+CREATE INDEX IF NOT EXISTS agent_cards_open_idx ON agent_cards (status, updated_at)+ WHERE status IN ('paying', 'processing', 'needs_verification');+CREATE UNIQUE INDEX IF NOT EXISTS agent_cards_provider_invoice_uq ON agent_cards (provider, provider_invoice_id)+ WHERE provider_invoice_id IS NOT NULL;++-- Append-only audit of everything that happens to a card: status changes, the+-- reveal previews (single-use grants), reveals and refused reveals, each with+-- the actor and time. Never holds a secret.+CREATE TABLE IF NOT EXISTS agent_card_events (+ id bigserial PRIMARY KEY,+ card_id uuid NOT NULL REFERENCES agent_cards(id) ON DELETE CASCADE,+ agent_id uuid NOT NULL,+ actor_user_id uuid,+ actor_kind text NOT NULL DEFAULT 'system',+ event text NOT NULL,+ from_status text,+ to_status text,+ -- Reveal grants: sha256 of the single-use preview id, its expiry, and when it+ -- was spent. A grant can be consumed exactly once.+ grant_hash text,+ grant_expires_at timestamptz,+ grant_consumed_at timestamptz,+ ip text,+ detail jsonb NOT NULL DEFAULT '{}'::jsonb,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS agent_card_events_card_idx ON agent_card_events (card_id, id DESC);+CREATE UNIQUE INDEX IF NOT EXISTS agent_card_events_grant_uq ON agent_card_events (grant_hash)+ WHERE grant_hash IS NOT NULL;++-- Prepaid balances moved back to USDC, for providers that support it.+CREATE TABLE IF NOT EXISTS agent_card_withdrawals (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ card_id uuid NOT NULL REFERENCES agent_cards(id) ON DELETE CASCADE,+ agent_id uuid NOT NULL,+ user_id uuid NOT NULL,+ provider text NOT NULL,+ amount numeric(20, 6) NOT NULL CHECK (amount > 0),+ currency text NOT NULL,+ usdc_amount numeric(20, 6),+ destination text NOT NULL,+ status text NOT NULL DEFAULT 'requested'+ CHECK (status IN ('requested', 'processing', 'completed', 'failed')),+ provider_ref text,+ signature text,+ error_message text,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS agent_card_withdrawals_card_idx ON agent_card_withdrawals (card_id, created_at DESC);diff --git a/api/_mcp/tools/cards.js b/api/_mcp/tools/cards.jsnew file mode 100644index 000000000..7e05d92ab--- /dev/null+++ b/api/_mcp/tools/cards.js@@ -0,0 +1,296 @@+// Agent cards MCP tools: search, quote, buy, check and reveal gift cards and+// prepaid cards paid for from an agent's own wallet.+//+// Every tool calls the same service the REST API uses (api/_lib/cards/service.js),+// so limits, the audit trail and secret handling are identical on both surfaces.+//+// Policy fields (group / tier / confirmFlag / previewTool) follow the shared+// MCP tool policy: `financial` tools refuse without their confirm flag and the+// id their preview tool returned (quote_id for a purchase, preview_id for a+// reveal). The catalog strips these fields from tools/list and republishes them+// under `_meta`.++import * as cards from '../../_lib/cards/service.js';++const READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };+const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };+const MONEY = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true };++const AGENT_ID = { type: 'string', format: 'uuid', description: 'Agent UUID (from list_my_agents).' };+const CARD_ID = { type: 'string', format: 'uuid', description: 'Card UUID (from agent_card_list or agent_card_create).' };++function ok(structured) {+ return {+ content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }],+ structuredContent: structured,+ };+}++function fail(e) {+ if (e instanceof cards.CardError) {+ const structured = { error: e.code, message: e.message, ...(e.details ? { details: e.details } : {}) };+ return { content: [{ type: 'text', text: `Error (${e.code}): ${e.message}` }], structuredContent: structured, isError: true };+ }+ throw e;+}++const principalOf = (auth) => ({ userId: auth?.userId ?? null, source: 'mcp', ip: null });++function tool(def, run) {+ return {+ group: 'cards',+ ...def,+ async handler(args, auth) {+ if (!auth?.userId) {+ return fail(new cards.CardError(401, 'unauthorized', 'Connect a three.ws account (OAuth or API key) to use agent cards.'));+ }+ try {+ return ok(await run(args || {}, principalOf(auth)));+ } catch (e) {+ return fail(e);+ }+ },+ };+}++export const toolDefs = [+ tool({+ name: 'agent_card_search_merchants',+ title: 'Search card merchants',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description:+ 'Search merchants an agent can buy a gift card or prepaid card from (for example a game store, a marketplace, food delivery, or a prepaid Visa). Returns merchant names with the countries and categories they sell in. Pass sandbox: true to list the provider\'s free test products, which run the whole purchase flow without moving funds.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ q: { type: 'string', maxLength: 100, description: 'Merchant or brand name to search for.' },+ country: { type: 'string', pattern: '^[A-Za-z]{2}$', description: 'ISO country code, e.g. US.' },+ kind: { type: 'string', enum: ['gift_card', 'prepaid_card'], description: 'Only gift cards or only prepaid cards.' },+ sandbox: { type: 'boolean', default: false },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 24 },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ }, async (a, p) => {+ await cards.loadOwnedAgent(a.agent_id, p);+ return cards.searchMerchants({ q: a.q, country: a.country, kind: a.kind, sandbox: a.sandbox, limit: a.limit });+ }),++ tool({+ name: 'agent_card_search_gift_cards',+ title: 'Search gift and prepaid card products',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description:+ 'Search card products with their denominations: fixed packages and/or an allowed range, currency, country and stock. Use a product id and one allowed amount with agent_card_quote.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ q: { type: 'string', maxLength: 100 },+ country: { type: 'string', pattern: '^[A-Za-z]{2}$' },+ merchant: { type: 'string', maxLength: 120, description: 'Exact merchant name from agent_card_search_merchants.' },+ kind: { type: 'string', enum: ['gift_card', 'prepaid_card'] },+ sandbox: { type: 'boolean', default: false },+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 24 },+ start: { type: 'integer', minimum: 0, default: 0 },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ }, async (a, p) => {+ await cards.loadOwnedAgent(a.agent_id, p);+ return cards.searchProducts({+ q: a.q, country: a.country, merchant: a.merchant, kind: a.kind, sandbox: a.sandbox, limit: a.limit, start: a.start,+ });+ }),++ tool({+ name: 'agent_card_quote',+ title: 'Quote a card purchase',+ tier: 'write',+ scope: 'wallet:write',+ annotations: WRITE,+ description:+ 'Lock a price for one card: returns the total in USDC including fees, the Solana address it would be paid to, a quote_id valid for ten minutes, and a confirm table (recipient, amount, token, chain). Moves no funds. Show the confirm table to the owner before calling agent_card_create.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ product_id: { type: 'string', minLength: 1, maxLength: 200 },+ amount: { type: 'number', exclusiveMinimum: 0, description: 'Face value in the product currency; must be a package value or inside the range.' },+ },+ required: ['agent_id', 'product_id', 'amount'],+ additionalProperties: false,+ },+ }, (a, p) => cards.quoteCard({ agentId: a.agent_id, principal: p, productId: a.product_id, amount: a.amount })),++ tool({+ name: 'agent_card_create',+ title: 'Buy a card from the agent wallet',+ tier: 'financial',+ confirmFlag: 'confirm_spend',+ previewTool: 'agent_card_quote',+ scope: 'wallet:write',+ annotations: MONEY,+ description:+ 'Buy the card a quote describes, paying the quoted USDC from the agent wallet on Solana under the agent\'s spend limits and anomaly freeze. Requires a quote_id from agent_card_quote that is under ten minutes old and confirm_spend: true, which you may only send after the owner explicitly approved the quote\'s confirm table. Returns the card with its status and the payment signature.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ quote_id: { type: 'string', format: 'uuid' },+ confirm_spend: { type: 'boolean', description: 'Must be true, and only after the owner said yes to the quote.' },+ },+ required: ['agent_id', 'quote_id', 'confirm_spend'],+ additionalProperties: false,+ },+ }, (a, p) => cards.createCard({ agentId: a.agent_id, principal: p, quoteId: a.quote_id, confirmSpend: a.confirm_spend })),++ tool({+ name: 'agent_card_list',+ title: 'List agent cards',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description: 'List the agent\'s cards, newest first, with masked numbers, status and what each cost. In-flight cards are refreshed from the provider.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ status: { type: 'string', enum: ['quoted', 'paying', 'processing', 'delivered', 'failed', 'refunded', 'cancelled', 'expired', 'needs_verification'] },+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 25 },+ cursor: { type: 'string', maxLength: 40 },+ },+ required: ['agent_id'],+ additionalProperties: false,+ },+ }, (a, p) => cards.listCards({ agentId: a.agent_id, principal: p, status: a.status, limit: a.limit, cursor: a.cursor })),++ tool({+ name: 'agent_card_get',+ title: 'Get one agent card',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description: 'One card with its audit trail (quotes, payment, status changes, reveals with who and when). Never includes the secret.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID, card_id: CARD_ID }, required: ['agent_id', 'card_id'], additionalProperties: false },+ }, (a, p) => cards.getCard({ agentId: a.agent_id, principal: p, cardId: a.card_id })),++ tool({+ name: 'agent_card_status',+ title: 'Refresh a card from the provider',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description: 'Ask the provider for the card\'s current status (processing, delivered, failed, refunded) and update the record.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID, card_id: CARD_ID }, required: ['agent_id', 'card_id'], additionalProperties: false },+ }, (a, p) => cards.refreshCard({ agentId: a.agent_id, principal: p, cardId: a.card_id })),++ tool({+ name: 'agent_card_balance',+ title: 'Card balance',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description: 'The card\'s remaining balance. When the provider does not report balances the answer is the face value of a delivered card, and says so.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID, card_id: CARD_ID }, required: ['agent_id', 'card_id'], additionalProperties: false },+ }, (a, p) => cards.cardBalance({ agentId: a.agent_id, principal: p, cardId: a.card_id })),++ tool({+ name: 'agent_card_data',+ title: 'Card data and reveal preview',+ tier: 'write',+ scope: 'wallet:write',+ annotations: WRITE,+ description:+ 'The masked card number, which secret fields exist (code, PIN, link) and redemption instructions, plus a single-use preview_id valid for five minutes. Required before agent_card_reveal. Does not expose the secret.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID, card_id: CARD_ID }, required: ['agent_id', 'card_id'], additionalProperties: false },+ }, (a, p) => cards.cardData({ agentId: a.agent_id, principal: p, cardId: a.card_id })),++ tool({+ name: 'agent_card_reveal',+ title: 'Reveal a card secret once',+ tier: 'financial',+ confirmFlag: 'confirm_reveal',+ previewTool: 'agent_card_data',+ scope: 'wallet:write',+ annotations: MONEY,+ description:+ 'Return the card number, PIN or redemption code. Requires the preview_id from agent_card_data and confirm_reveal: true after the owner agreed. The preview id works once; the stored encrypted copy is deleted by this call, and the reveal is logged with the actor and time. Treat the result as a secret: give it to the owner only, never post it anywhere.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID,+ card_id: CARD_ID,+ preview_id: { type: 'string', minLength: 16, maxLength: 128 },+ confirm_reveal: { type: 'boolean' },+ },+ required: ['agent_id', 'card_id', 'preview_id', 'confirm_reveal'],+ additionalProperties: false,+ },+ }, (a, p) => cards.revealCard({ agentId: a.agent_id, principal: p, cardId: a.card_id, previewId: a.preview_id, confirmReveal: a.confirm_reveal })),++ tool({+ name: 'agent_card_cancel',+ title: 'Cancel a card',+ tier: 'financial',+ confirmFlag: 'confirm_cancel',+ previewTool: 'agent_card_get',+ scope: 'wallet:write',+ annotations: MONEY,+ description: 'Cancel a card. Unpaid quotes can always be cancelled; whether a paid card can be depends on the provider, and the error says so when it cannot. Requires confirm_cancel: true.',+ inputSchema: {+ type: 'object',+ properties: { agent_id: AGENT_ID, card_id: CARD_ID, confirm_cancel: { type: 'boolean' } },+ required: ['agent_id', 'card_id', 'confirm_cancel'],+ additionalProperties: false,+ },+ }, (a, p) => cards.cancelCard({ agentId: a.agent_id, principal: p, cardId: a.card_id, confirmCancel: a.confirm_cancel })),++ tool({+ name: 'agent_card_withdraw',+ title: 'Withdraw a prepaid balance to USDC',+ tier: 'financial',+ confirmFlag: 'confirm_withdraw',+ previewTool: 'agent_card_balance',+ scope: 'wallet:write',+ annotations: MONEY,+ description: 'Move a prepaid card balance back to the agent wallet as USDC, where the provider supports it. Check agent_card_balance first and pass confirm_withdraw: true after the owner agreed.',+ inputSchema: {+ type: 'object',+ properties: {+ agent_id: AGENT_ID, card_id: CARD_ID,+ amount: { type: 'number', exclusiveMinimum: 0 },+ confirm_withdraw: { type: 'boolean' },+ },+ required: ['agent_id', 'card_id', 'amount', 'confirm_withdraw'],+ additionalProperties: false,+ },+ }, (a, p) => cards.withdrawCard({ agentId: a.agent_id, principal: p, cardId: a.card_id, amount: a.amount, confirmWithdraw: a.confirm_withdraw })),++ tool({+ name: 'agent_card_connect',+ title: 'Card provider verification status',+ tier: 'read',+ scope: 'wallet:read',+ annotations: READ,+ description: 'Whether the card provider needs the account holder to complete identity steps before cards can be bought.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID }, required: ['agent_id'], additionalProperties: false },+ }, (a, p) => cards.connectStatus({ agentId: a.agent_id, principal: p })),++ tool({+ name: 'agent_card_connect_link',+ title: 'Card provider verification link',+ tier: 'write',+ scope: 'wallet:write',+ annotations: WRITE,+ description: 'A browser link where the account holder completes the provider\'s identity steps. Give it to the owner; do not open it yourself.',+ inputSchema: { type: 'object', properties: { agent_id: AGENT_ID }, required: ['agent_id'], additionalProperties: false },+ }, (a, p) => cards.connectLink({ agentId: a.agent_id, principal: p })),+];diff --git a/api/v1/agent-cards.js b/api/v1/agent-cards.jsnew file mode 100644index 000000000..a52f8ade1--- /dev/null+++ b/api/v1/agent-cards.js@@ -0,0 +1,205 @@+/**+ * Agent cards REST API: gift cards and prepaid cards bought from an agent's+ * own wallet. Service layer: api/_lib/cards/service.js. Docs: docs/agent-cards.md.+ *+ * vercel.json maps /api/v1/agents/:id/cards[/...] here.+ *+ * GET /api/v1/agents/:id/cards list (alias: /cards/list)+ * GET /api/v1/agents/:id/cards/provider provider capabilities+ * GET /api/v1/agents/:id/cards/merchants/search ?q&country&kind&sandbox+ * GET /api/v1/agents/:id/cards/products/search ?q&country&category&merchant&kind&sandbox&limit&start+ * GET /api/v1/agents/:id/cards/products/:productId+ * POST /api/v1/agents/:id/cards/quote { product_id, amount }+ * POST /api/v1/agents/:id/cards/create { quote_id, confirm_spend: true }+ * GET /api/v1/agents/:id/cards/connect+ * GET /api/v1/agents/:id/cards/connect-link+ * GET /api/v1/agents/:id/cards/:cardId card + audit events+ * GET /api/v1/agents/:id/cards/:cardId/status sync from the provider+ * POST /api/v1/agents/:id/cards/:cardId/refresh same, as a write+ * GET /api/v1/agents/:id/cards/:cardId/balance+ * POST /api/v1/agents/:id/cards/:cardId/data masked data + single-use preview_id+ * POST /api/v1/agents/:id/cards/:cardId/reveal { preview_id, confirm_reveal: true }+ * POST /api/v1/agents/:id/cards/:cardId/cancel { confirm_cancel: true }+ * POST /api/v1/agents/:id/cards/:cardId/withdraw { amount, confirm_withdraw: true }+ * GET /api/v1/agents/:id/cards/:cardId/withdrawals+ *+ * Envelope (the v1 contract): success { data, meta: { requestId, timestamp } },+ * failure { error: { code, message, details }, meta }.+ *+ * Auth: a signed-in session (writes need X-CSRF-Token), or a three.ws API key+ * / OAuth token. Bearer callers need `wallet:read` for reads and `wallet:write`+ * for anything that quotes, buys, reveals, cancels or withdraws.+ */++import { randomUUID } from 'node:crypto';+import { cors, readJson, setRateLimitHeaders } from '../_lib/http.js';+import { authenticateBearer, extractBearer, getSessionUser, hasScope } from '../_lib/auth.js';+import { checkCsrf } from '../_lib/csrf.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import * as cards from '../_lib/cards/service.js';++const READ_SCOPE = 'wallet:read';+const WRITE_SCOPE = 'wallet:write';++function send(res, status, body) {+ if (res.headersSent || res.writableEnded) return;+ res.statusCode = status;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('cache-control', 'no-store');+ res.end(JSON.stringify(body));+}++const meta = (ctx) => ({ requestId: ctx.requestId, timestamp: new Date().toISOString() });++function sendError(res, ctx, status, code, message, details = null) {+ res.setHeader('x-request-id', ctx.requestId);+ send(res, status, { error: { code, message, details }, meta: meta(ctx) });+}++async function resolvePrincipal(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, source: 'session', scope: null, ip: clientIp(req) };+ const bearer = await authenticateBearer(extractBearer(req));+ if (!bearer) return null;+ return { userId: bearer.userId, source: bearer.source, scope: bearer.scope || '', ip: clientIp(req) };+}++/** Split the request into the agent id and the path segments after /cards. */+function parseTarget(req) {+ const url = new URL(req.url, 'http://x');+ const m = url.pathname.match(/^\/api\/v1\/agents\/([^/]+)\/cards(?:\/(.*))?$/);+ const agentId = m ? decodeURIComponent(m[1]) : url.searchParams.get('id');+ const rest = m ? (m[2] || '') : (url.searchParams.get('path') || '');+ const segments = rest.split('/').filter(Boolean).map((s) => decodeURIComponent(s));+ return { url, agentId, segments };+}++const bool = (v) => v === true || v === 'true' || v === '1';++/** Route table: [method, pattern, scope, handler(ctx)]. `:card` is a card id. */+const ROUTES = [+ ['GET', '', READ_SCOPE, (c) => cards.listCards({ ...c.base, status: c.q('status'), limit: c.q('limit'), cursor: c.q('cursor') })],+ ['GET', 'list', READ_SCOPE, (c) => cards.listCards({ ...c.base, status: c.q('status'), limit: c.q('limit'), cursor: c.q('cursor') })],+ ['GET', 'provider', READ_SCOPE, async (c) => {+ await cards.loadOwnedAgent(c.agentId, c.principal);+ return cards.providerInfo(c.q('provider'));+ }],+ ['GET', 'merchants/search', READ_SCOPE, async (c) => {+ await cards.loadOwnedAgent(c.agentId, c.principal);+ return cards.searchMerchants({ q: c.q('q'), country: c.q('country'), kind: c.q('kind'), sandbox: bool(c.q('sandbox')), limit: c.q('limit') });+ }],+ ['GET', 'products/search', READ_SCOPE, async (c) => {+ await cards.loadOwnedAgent(c.agentId, c.principal);+ return cards.searchProducts({+ q: c.q('q'), country: c.q('country'), category: c.q('category'), merchant: c.q('merchant'),+ kind: c.q('kind'), sandbox: bool(c.q('sandbox')), limit: c.q('limit'), start: c.q('start'),+ });+ }],+ ['GET', 'products/:product', READ_SCOPE, async (c) => {+ await cards.loadOwnedAgent(c.agentId, c.principal);+ return cards.getProduct({ productId: c.params.product });+ }],+ ['POST', 'quote', WRITE_SCOPE, (c) => cards.quoteCard({ ...c.base, productId: c.body.product_id, amount: c.body.amount })],+ ['POST', 'create', WRITE_SCOPE, (c) => cards.createCard({ ...c.base, quoteId: c.body.quote_id, confirmSpend: c.body.confirm_spend })],+ ['GET', 'connect', READ_SCOPE, (c) => cards.connectStatus({ ...c.base, provider: c.q('provider') })],+ ['GET', 'connect-link', WRITE_SCOPE, (c) => cards.connectLink({ ...c.base, provider: c.q('provider') })],+ ['GET', ':card', READ_SCOPE, (c) => cards.getCard({ ...c.base, cardId: c.params.card })],+ ['GET', ':card/status', READ_SCOPE, (c) => cards.refreshCard({ ...c.base, cardId: c.params.card })],+ ['POST', ':card/refresh', READ_SCOPE, (c) => cards.refreshCard({ ...c.base, cardId: c.params.card })],+ ['GET', ':card/balance', READ_SCOPE, (c) => cards.cardBalance({ ...c.base, cardId: c.params.card })],+ ['POST', ':card/data', WRITE_SCOPE, (c) => cards.cardData({ ...c.base, cardId: c.params.card })],+ ['POST', ':card/reveal', WRITE_SCOPE, (c) => cards.revealCard({+ ...c.base, cardId: c.params.card, previewId: c.body.preview_id, confirmReveal: c.body.confirm_reveal,+ })],+ ['POST', ':card/cancel', WRITE_SCOPE, (c) => cards.cancelCard({ ...c.base, cardId: c.params.card, confirmCancel: c.body.confirm_cancel })],+ ['POST', ':card/withdraw', WRITE_SCOPE, (c) => cards.withdrawCard({+ ...c.base, cardId: c.params.card, amount: c.body.amount, confirmWithdraw: c.body.confirm_withdraw,+ })],+ ['GET', ':card/withdrawals', READ_SCOPE, (c) => cards.listWithdrawals({ ...c.base, cardId: c.params.card })],+].map(([m, pattern, scope, handler]) => ({ method: m, parts: pattern.split('/').filter(Boolean), scope, handler }));++// Literal segments win over `:card`, so /cards/list never reads as a card id.+function match(method, segments) {+ let literalPathSeen = false;+ let anyPathSeen = false;+ let paramHit = null;+ for (const r of ROUTES) {+ if (r.parts.length !== segments.length) continue;+ const params = {};+ let ok = true;+ let literal = true;+ for (let i = 0; i < r.parts.length; i++) {+ const p = r.parts[i];+ if (p.startsWith(':')) {+ params[p.slice(1)] = segments[i];+ if (i === 0) literal = false;+ } else if (p !== segments[i]) {+ ok = false;+ break;+ }+ }+ if (!ok) continue;+ anyPathSeen = true;+ if (literal) literalPathSeen = true;+ if (r.method !== method) continue;+ if (literal) return { route: r, params };+ paramHit = paramHit || { route: r, params };+ }+ if (literalPathSeen || (!paramHit && anyPathSeen)) return { methodMismatch: true };+ return paramHit;+}++export default async function handler(req, res) {+ const ctx = { requestId: randomUUID() };+ res.setHeader('x-request-id', ctx.requestId);+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ const { url, agentId, segments } = parseTarget(req);+ const hit = match(req.method, segments);+ if (!hit?.route) {+ if (hit?.methodMismatch) return sendError(res, ctx, 405, 'method_not_allowed', `${req.method} is not supported on this path`);+ return sendError(res, ctx, 404, 'not_found', 'unknown agent cards route');+ }++ try {+ const principal = await resolvePrincipal(req);+ if (!principal) return sendError(res, ctx, 401, 'unauthorized', 'Sign in or send a three.ws API key.');+ if (principal.source !== 'session' && !hasScope(principal.scope, hit.route.scope)) {+ return sendError(res, ctx, 403, 'insufficient_scope', `This key needs the ${hit.route.scope} scope.`, { required: hit.route.scope });+ }++ const rl = await limits.apiV1(`cards:${principal.userId}`);+ setRateLimitHeaders(res, rl);+ if (!rl.success) return sendError(res, ctx, 429, 'rate_limited', 'Too many requests. Slow down and retry shortly.');++ let body = {};+ if (req.method === 'POST') {+ if (principal.source === 'session') {+ const v = await checkCsrf(req, principal.userId);+ if (!v.ok) return sendError(res, ctx, 403, v.code, v.message);+ }+ try {+ body = (await readJson(req)) || {};+ } catch (e) {+ return sendError(res, ctx, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid JSON body');+ }+ if (typeof body !== 'object' || Array.isArray(body)) body = {};+ }++ const c = {+ agentId,+ principal,+ params: hit.params,+ body,+ q: (k) => url.searchParams.get(k),+ base: { agentId, principal },+ };+ const data = await hit.route.handler(c);+ const status = hit.route.parts[0] === 'quote' ? 201 : 200;+ return send(res, status, { data, meta: meta(ctx) });+ } catch (e) {+ if (e instanceof cards.CardError) return sendError(res, ctx, e.status, e.code, e.message, e.details);+ console.error('[agent-cards]', ctx.requestId, e?.message);+ return sendError(res, ctx, 500, 'internal_error', 'Something went wrong on our side. No funds moved unless the card shows a payment signature.');+ }+}diff --git a/tests/fixtures/bitrefill/invoice-create-balance.json b/tests/fixtures/bitrefill/invoice-create-balance.jsonnew file mode 100644index 000000000..b50b7f121--- /dev/null+++ b/tests/fixtures/bitrefill/invoice-create-balance.json@@ -0,0 +1,47 @@+{+ "meta": {+ "products": [+ {+ "product_id": "test-gift-card-code",+ "value": 20,+ "quantity": 1+ }+ ],+ "payment_method": "balance",+ "auto_pay": false,+ "_endpoint": "/invoices"+ },+ "data": {+ "id": "e6661ab3-1438-40d5-94bd-db6c51e123e7",+ "created_time": "2026-09-22T05:03:34.715Z",+ "status": "not_delivered",+ "user": {+ "id": "000000000000000000000001",+ "email": "[email protected]"+ },+ "payment": {+ "method": "balance",+ "currency": "BTC",+ "price": 24583,+ "status": "unpaid",+ "commission": 0+ },+ "orders": [+ {+ "id": "6ab20c26196a68dc6a682002",+ "status": "created",+ "product": {+ "id": "test-gift-card-code",+ "name": "Test Gift Card Code",+ "value": "20",+ "currency": "USD",+ "image": "us",+ "_href": "https://api-bitrefill.com/v2/products/test-gift-card-code"+ },+ "created_time": "2026-09-22T05:03:34.698Z",+ "delivered_time": null,+ "commission": 0+ }+ ]+ }+}diff --git a/tests/fixtures/bitrefill/invoice-create-usdc-solana.json b/tests/fixtures/bitrefill/invoice-create-usdc-solana.jsonnew file mode 100644index 000000000..d003663e6--- /dev/null+++ b/tests/fixtures/bitrefill/invoice-create-usdc-solana.json@@ -0,0 +1,48 @@+{+ "meta": {+ "products": [+ {+ "product_id": "test-gift-card-code",+ "value": 10,+ "quantity": 1+ }+ ],+ "payment_method": "usdc_solana",+ "auto_pay": false,+ "_endpoint": "/invoices"+ },+ "data": {+ "id": "c2b05566-fbb6-4a02-85f0-bc5153bfb090",+ "created_time": "2026-09-22T04:57:24.164Z",+ "status": "not_delivered",+ "user": {+ "id": "000000000000000000000001",+ "email": "[email protected]"+ },+ "payment": {+ "method": "usdc_solana",+ "address": "DZLnpA4gNTMDCBC3uWJWuUpytm5Erim8nPeRnABzpo5b",+ "currency": "USDC",+ "price": 10500000,+ "status": "unpaid",+ "commission": 0+ },+ "orders": [+ {+ "id": "6ab20ab466ad71725fd301e3",+ "status": "created",+ "product": {+ "id": "test-gift-card-code",+ "name": "Test Gift Card Code",+ "value": "10",+ "currency": "USD",+ "image": "us",+ "_href": "https://api-bitrefill.com/v2/products/test-gift-card-code"+ },+ "created_time": "2026-09-22T04:57:24.137Z",+ "delivered_time": null,+ "commission": 0+ }+ ]+ }+}diff --git a/tests/fixtures/bitrefill/invoice-get-delivered.json b/tests/fixtures/bitrefill/invoice-get-delivered.jsonnew file mode 100644index 000000000..ac3d2c55e--- /dev/null+++ b/tests/fixtures/bitrefill/invoice-get-delivered.json@@ -0,0 +1,45 @@+{+ "meta": {+ "id": "e6661ab3-1438-40d5-94bd-db6c51e123e7",+ "_endpoint": "/invoices/e6661ab3-1438-40d5-94bd-db6c51e123e7"+ },+ "data": {+ "id": "e6661ab3-1438-40d5-94bd-db6c51e123e7",+ "created_time": "2026-09-22T05:03:34.715Z",+ "status": "not_delivered",+ "user": {+ "id": "000000000000000000000001",+ "email": "[email protected]"+ },+ "payment": {+ "method": "balance",+ "currency": "BTC",+ "price": 24583,+ "status": "payment_confirmed",+ "commission": 0+ },+ "orders": [+ {+ "id": "6ab20c26196a68dc6a682002",+ "status": "delivered",+ "product": {+ "id": "test-gift-card-code",+ "name": "Test Gift Card Code",+ "value": "20",+ "currency": "USD",+ "image": "us",+ "_href": "https://api-bitrefill.com/v2/products/test-gift-card-code"+ },+ "created_time": "2026-09-22T05:03:34.698Z",+ "delivered_time": "2026-09-22T05:03:42.063Z",+ "redemption_info": {+ "code": "3270583975372575",+ "instructions": "This field will contain instructions on how to redeem the voucher.",+ "other": "This field will contain other relevant information like expiration date.",+ "extra_fields": {}+ },+ "commission": 0+ }+ ]+ }+}diff --git a/tests/fixtures/bitrefill/invoice-pay.json b/tests/fixtures/bitrefill/invoice-pay.jsonnew file mode 100644index 000000000..4ef901abd--- /dev/null+++ b/tests/fixtures/bitrefill/invoice-pay.json@@ -0,0 +1,39 @@+{+ "meta": {+ "id": "e6661ab3-1438-40d5-94bd-db6c51e123e7",+ "_endpoint": "/invoices/e6661ab3-1438-40d5-94bd-db6c51e123e7/pay"+ },+ "data": {+ "id": "e6661ab3-1438-40d5-94bd-db6c51e123e7",+ "created_time": "2026-09-22T05:03:34.715Z",+ "status": "not_delivered",+ "user": {+ "id": "000000000000000000000001",+ "email": "[email protected]"+ },+ "payment": {+ "method": "balance",+ "currency": "BTC",+ "price": 24583,+ "status": "unpaid",+ "commission": 0+ },+ "orders": [+ {+ "id": "6ab20c26196a68dc6a682002",+ "status": "created",+ "product": {+ "id": "test-gift-card-code",+ "name": "Test Gift Card Code",+ "value": "20",+ "currency": "USD",+ "image": "us",+ "_href": "https://api-bitrefill.com/v2/products/test-gift-card-code"+ },+ "created_time": "2026-09-22T05:03:34.698Z",+ "delivered_time": null,+ "commission": 0+ }+ ]+ }+}diff --git a/tests/fixtures/bitrefill/invoice-wrong-value.json b/tests/fixtures/bitrefill/invoice-wrong-value.jsonnew file mode 100644index 000000000..71e53d61c--- /dev/null+++ b/tests/fixtures/bitrefill/invoice-wrong-value.json@@ -0,0 +1,7 @@+{+ "meta": {+ "_endpoint": "/invoices"+ },+ "message": "Provided value or package does not exist for product",+ "error_code": "wrong_value"+}diff --git a/tests/fixtures/bitrefill/order-delivered.json b/tests/fixtures/bitrefill/order-delivered.jsonnew file mode 100644index 000000000..0be51794f--- /dev/null+++ b/tests/fixtures/bitrefill/order-delivered.json@@ -0,0 +1,35 @@+{+ "meta": {+ "id": "6ab20c26196a68dc6a682002",+ "_endpoint": "/orders/6ab20c26196a68dc6a682002"+ },+ "data": {+ "id": "6ab20c26196a68dc6a682002",+ "status": "delivered",+ "product": {+ "id": "test-gift-card-code",+ "name": "Test Gift Card Code",+ "value": "20",+ "currency": "USD",+ "image": "us",+ "_href": "https://api-bitrefill.com/v2/products/test-gift-card-code"+ },+ "created_time": "2026-09-22T05:03:34.698Z",+ "delivered_time": "2026-09-22T05:03:42.063Z",+ "redemption_info": {+ "code": "3270583975372575",+ "instructions": "This field will contain instructions on how to redeem the voucher.",+ "other": "This field will contain other relevant information like expiration date.",+ "extra_fields": {}+ },+ "commission": 0,+ "user": {+ "id": "000000000000000000000001",+ "email": "[email protected]"+ },+ "invoice": {+ "id": "e6661ab3-1438-40d5-94bd-db6c51e123e7",+ "_href": "https://api-bitrefill.com/v2/invoices/e6661ab3-1438-40d5-94bd-db6c51e123e7"+ }+ }+}diff --git a/tests/fixtures/bitrefill/order-failed.json b/tests/fixtures/bitrefill/order-failed.jsonnew file mode 100644index 000000000..81b3ae361--- /dev/null+++ b/tests/fixtures/bitrefill/order-failed.json@@ -0,0 +1,29 @@+{+ "meta": {+ "id": "6ab20c36196a68dc6a6820a6",+ "_endpoint": "/orders/6ab20c36196a68dc6a6820a6"+ },+ "data": {+ "id": "6ab20c36196a68dc6a6820a6",+ "status": "permanent_failure",+ "product": {+ "id": "test-gift-card-code-fail",+ "name": "Test Gift Card Code (Fail)",+ "value": "10",+ "currency": "USD",+ "image": "this_is_a_test",+ "_href": "https://api-bitrefill.com/v2/products/test-gift-card-code-fail"+ },+ "created_time": "2026-09-22T05:03:50.738Z",+ "delivered_time": null,+ "commission": 0,+ "user": {+ "id": "000000000000000000000001",+ "email": "[email protected]"+ },+ "invoice": {+ "id": "0a239d49-5086-440d-ab87-329344cb63bb",+ "_href": "https://api-bitrefill.com/v2/invoices/0a239d49-5086-440d-ab87-329344cb63bb"+ }+ }+}diff --git a/tests/fixtures/bitrefill/product-not-found.json b/tests/fixtures/bitrefill/product-not-found.jsonnew file mode 100644index 000000000..0a95d638b--- /dev/null+++ b/tests/fixtures/bitrefill/product-not-found.json@@ -0,0 +1,8 @@+{+ "meta": {+ "id": "amazon-us",+ "_endpoint": "/products/amazon-us"+ },+ "message": "Product not found",+ "error_code": "not_found"+}diff --git a/tests/fixtures/bitrefill/product-test-gift-card-code.json b/tests/fixtures/bitrefill/product-test-gift-card-code.jsonnew file mode 100644index 000000000..4cd077b07--- /dev/null+++ b/tests/fixtures/bitrefill/product-test-gift-card-code.json@@ -0,0 +1,63 @@+{+ "meta": {+ "id": "test-gift-card-code",+ "_endpoint": "/products/test-gift-card-code"+ },+ "data": {+ "id": "test-gift-card-code",+ "name": "Test Gift Card Code",+ "base_name": "Test Gift Card Code",+ "country_code": "KN",+ "country_name": "St Kitts and Nevis",+ "currency": "USD",+ "categories": [+ "gifts"+ ],+ "redemption_methods": [+ "online"+ ],+ "created_time": "2021-10-21T12:04:11.677Z",+ "recipient_type": "none",+ "image": "us",+ "termsAndConditions": "You must comply, otherwise...",+ "in_stock": true,+ "range": {+ "min": 10,+ "max": 100,+ "step": 10,+ "price_rate": 1229.4097931219776+ },+ "packages": [+ {+ "id": "test-gift-card-code<&>10",+ "value": "10",+ "price": 12295,+ "amount": 10+ },+ {+ "id": "test-gift-card-code<&>20",+ "value": "20",+ "price": 24589,+ "amount": 20+ },+ {+ "id": "test-gift-card-code<&>30",+ "value": "30",+ "price": 36883,+ "amount": 30+ },+ {+ "id": "test-gift-card-code<&>50",+ "value": "50",+ "price": 61471,+ "amount": 50+ },+ {+ "id": "test-gift-card-code<&>100",+ "value": "100",+ "price": 122941,+ "amount": 100+ }+ ]+ }+}diff --git a/tests/fixtures/bitrefill/products-search-prepaid.json b/tests/fixtures/bitrefill/products-search-prepaid.jsonnew file mode 100644index 000000000..d5c6d1890--- /dev/null+++ b/tests/fixtures/bitrefill/products-search-prepaid.json@@ -0,0 +1,104 @@+{+ "meta": {+ "q": "visa",+ "include_test_products": false,+ "_endpoint": "/products/search",+ "limit": 5,+ "start": 0,+ "total_results": 8,+ "_next": "https://api-bitrefill.com/products/search?q=visa&limit=5&start=5"+ },+ "data": [+ {+ "id": "the-visa-digital-gift-card-australia",+ "name": "Digital Prepaid Visa Australia",+ "base_name": "Digital Prepaid Visa",+ "country_code": "AU",+ "country_name": "Australia",+ "currency": "AUD",+ "categories": [+ "payment-cards"+ ],+ "redemption_methods": [+ "instore",+ "online"+ ],+ "created_time": "2024-07-26T15:08:07.868Z",+ "recipient_type": "none",+ "image": "TheVisaDigitalGiftCardAUD_twpukv",+ "termsAndConditions": "The Card is a prepaid Visa card that can be used for purchasing goods and services where prepaid Visa cards are accepted",+ "in_stock": true,+ "packages": [+ {+ "id": "the-visa-digital-gift-card-australia<&>250",+ "value": "250",+ "price": 214734,+ "amount": 250+ },+ {+ "id": "the-visa-digital-gift-card-australia<&>100",+ "value": "100",+ "price": 85894,+ "amount": 100+ },+ {+ "id": "the-visa-digital-gift-card-australia<&>50",+ "value": "50",+ "price": 42947,+ "amount": 50+ },+ {+ "id": "the-visa-digital-gift-card-australia<&>10",+ "value": "10",+ "price": 8590,+ "amount": 10+ }+ ]+ },+ {+ "id": "v-preca-gift_visa-gift-card_-japan",+ "name": "V-preca Visa card Japan",+ "base_name": "V-preca Visa card",+ "country_code": "JP",+ "country_name": "Japan",+ "currency": "JPY",+ "categories": [+ "payment-cards"+ ],+ "redemption_methods": [+ "online"+ ],+ "created_time": "2026-03-24T14:53:46.522Z",+ "recipient_type": "none",+ "image": "v-preca-gift_visa-gift-card_-japan",+ "logo_background": "#f5f5f5",+ "in_stock": true,+ "packages": [+ {+ "id": "v-preca-gift_visa-gift-card_-japan<&>50000",+ "value": "50000",+ "price": 373553,+ "amount": 50000+ },+ {+ "id": "v-preca-gift_visa-gift-card_-japan<&>10000",+ "value": "10000",+ "price": 74711,+ "amount": 10000+ },+ {+ "id": "v-preca-gift_visa-gift-card_-japan<&>5000",+ "value": "5000",+ "price": 37356,+ "amount": 5000+ },+ {+ "id": "v-preca-gift_visa-gift-card_-japan<&>1000",+ "value": "1000",+ "price": 7472,+ "amount": 1000+ }+ ]+ }+ ]+}diff --git a/tests/fixtures/bitrefill/products-search.json b/tests/fixtures/bitrefill/products-search.jsonnew file mode 100644index 000000000..36ec8d308--- /dev/null+++ b/tests/fixtures/bitrefill/products-search.json@@ -0,0 +1,129 @@+{+ "meta": {+ "q": "amazon",+ "include_test_products": false,+ "_endpoint": "/products/search",+ "limit": 3,+ "start": 0,+ "total_results": 14,+ "_next": "https://api-bitrefill.com/products/search?q=amazon&limit=3&start=3"+ },+ "data": [+ {+ "id": "amazon-south-africa",+ "name": "Amazon South Africa",+ "base_name": "Amazon",+ "country_code": "ZA",+ "country_name": "South Africa",+ "currency": "ZAR",+ "categories": [+ "online-marketplaces"+ ],+ "redemption_methods": [+ "online"+ ],+ "created_time": "2024-09-04T15:47:40.689Z",+ "recipient_type": "none",+ "image": "amazon-south-africa",+ "termsAndConditions": "Restrictions apply, see amazon.co.za/gc-legal\r\n\r\n<P>\r\n\r\nBeperkings geld, sien amazon.co.za/gc-legal",+ "in_stock": true,+ "packages": [+ {+ "id": "amazon-south-africa<&>5000",+ "value": "5000",+ "price": 367398,+ "amount": 5000+ },+ {+ "id": "amazon-south-africa<&>2000",+ "value": "2000",+ "price": 146960,+ "amount": 2000+ },+ {+ "id": "amazon-south-africa<&>1000",+ "value": "1000",+ "price": 73480,+ "amount": 1000+ },+ {+ "id": "amazon-south-africa<&>500",+ "value": "500",+ "price": 36740,+ "amount": 500+ },+ {+ "id": "amazon-south-africa<&>100",+ "value": "100",+ "price": 7348,+ "amount": 100+ },+ {+ "id": "amazon-south-africa<&>10",+ "value": "10",+ "price": 735,+ "amount": 10+ }+ ]+ },+ {+ "id": "amazon-fresh-india",+ "name": "Amazon Fresh India",+ "base_name": "Amazon Fresh",+ "country_code": "IN",+ "country_name": "India",+ "currency": "INR",+ "categories": [+ "food",+ "food-delivery"+ ],+ "redemption_methods": [+ "online",+ "phone"+ ],+ "created_time": "2026-08-26T14:25:10.733Z",+ "recipient_type": "none",+ "image": "2024_logos/1490328-fresh",+ "logo_background": "#022900",+ "in_stock": true,+ "packages": [+ {+ "id": "amazon-fresh-india<&>50",+ "value": "50",+ "price": 643,+ "amount": 50+ },+ {+ "id": "amazon-fresh-india<&>100",+ "value": "100",+ "price": 1272,+ "amount": 100+ },+ {+ "id": "amazon-fresh-india<&>500",+ "value": "500",+ "price": 6358,+ "amount": 500+ },+ {+ "id": "amazon-fresh-india<&>1000",+ "value": "1000",+ "price": 12716,+ "amount": 1000+ },+ {+ "id": "amazon-fresh-india<&>2000",+ "value": "2000",+ "price": 25431,+ "amount": 2000+ },+ {+ "id": "amazon-fresh-india<&>10000",+ "value": "10000",+ "price": 127153,+ "amount": 10000+ }+ ]+ }+ ]+}