Skip to content

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

6.0 KB
Raw Blame
// Skill-access gate primitives for the agent runtime.
//
// The Runtime calls `skillAccess(toolName)` before invoking any skill tool.
// If the call returns `{ allowed: false, ...paymentInfo }`, the runtime
// emits a `skill:payment-required` event and feeds a structured 402 result
// back to the LLM so it can react (ask the user to purchase, or — once track 2
// is wired — let an autonomous agent invoke its own purchase flow).
//
// Built-in tools (BUILTIN_HANDLERS) and stage tools are always allowed; the
// gate only applies to skill-provided tools.

export class PaymentRequiredError extends Error {
	/**
	 * @param {{ skill: string, price?: object, reference?: string, message?: string, recipient?: string }} payload
	 */
	constructor(payload) {
		super(payload?.message || `payment required to use skill: ${payload?.skill}`);
		this.name = 'PaymentRequiredError';
		this.code = 'payment_required';
		this.payload = payload || {};
	}
}

/**
 * Default no-op gate: every skill is allowed. Used when the runtime is not
 * wired to a marketplace context (local dev, embedded agent without monetization).
 */
export function alwaysAllow() {
	return async () => ({ allowed: true });
}

/**
 * Build a `skillAccess` checker from a marketplace agent detail payload.
 *
 * @param {{
 *   skill_prices?: Record<string, { amount: string|number, currency_mint: string, chain?: string }>,
 *   purchased_skills?: string[],
 * }} agent
 * @returns {(toolName: string) => Promise<{allowed: boolean, price?: object, message?: string}>}
 */
export function fromAgentDetail(agent) {
	const prices = agent?.skill_prices || {};
	const purchased = new Set(agent?.purchased_skills || []);

	return async (toolName) => {
		const price = prices[toolName];
		if (!price) return { allowed: true }; // free skill

		// `purchased_skills` folds in NFT gates the viewer currently holds, so a
		// holder of the gating collection is allowed here just like a buyer.
		if (purchased.has(toolName)) return { allowed: true };

		// NFT-gated and not held: payment cannot unlock it, so don't surface a
		// price challenge — tell the caller which collection they need.
		if (price.gate_type === 'nft') {
			return {
				allowed: false,
				skill: toolName,
				gate: { type: 'nft', collection: price.nft_collection_mint },
				message: price.nft_collection_mint
					? `This skill requires holding an NFT from collection ${price.nft_collection_mint}`
					: `This skill is restricted to NFT holders`,
			};
		}

		return {
			allowed: false,
			skill: toolName,
			price: {
				amount: String(price.amount),
				currency_mint: price.currency_mint,
				chain: price.chain || 'solana',
			},
			message: `This skill requires a purchase: ${toolName}`,
		};
	};
}

/**
 * Build a `skillAccess` checker that re-fetches purchase status against the
 * server on every check. More authoritative than the snapshot built from
 * agent detail, but adds a network round-trip per call.
 *
 * @param {{ agentId: string, fetchImpl?: typeof fetch }} opts
 */
export function remoteCheck({ agentId, fetchImpl = fetch }) {
	return async (toolName) => {
		try {
			const url = `/api/marketplace/check-skill-access?agent_id=${encodeURIComponent(agentId)}&skill=${encodeURIComponent(toolName)}`;
			const r = await fetchImpl(url, { credentials: 'include' });
			if (!r.ok) {
				// Anonymous or skill not for sale → treat as allowed (free).
				return { allowed: true };
			}
			const j = await r.json();
			if (j?.has_access) return { allowed: true };
			return {
				allowed: false,
				skill: toolName,
				message: `This skill requires a purchase: ${toolName}`,
			};
		} catch {
			// Network error: fail open so transient issues don't block use.
			return { allowed: true };
		}
	};
}

/**
 * Build a `skillAccess` checker that auto-purchases unowned skills using a
 * buyer-agent's server-stored Solana wallet via /api/marketplace/purchase-as-agent.
 *
 * Useful for autonomous agents (cron jobs, headless agent-to-agent flows) where
 * a human-in-the-loop purchase modal isn't possible.
 *
 * Order of operations on each call:
 *   1. Check if the buyer already owns the skill — if so, allow.
 *   2. Try to auto-purchase via the server endpoint.
 *   3. If purchase confirms, allow.
 *   4. Otherwise deny with the original 402-style payload so the runtime can
 *      surface a `skill:payment-required` event.
 *
 * @param {{
 *   buyerAgentId: string,    // the agent whose wallet pays
 *   sellerAgentId: string,   // the agent whose skill is being purchased
 *   fetchImpl?: typeof fetch,
 * }} opts
 */
export function autoBuying({ buyerAgentId, sellerAgentId, fetchImpl = fetch }) {
	return async (toolName) => {
		// 1. Already-owned check
		try {
			const url =
				`/api/marketplace/check-skill-access?agent_id=${encodeURIComponent(sellerAgentId)}` +
				`&skill=${encodeURIComponent(toolName)}`;
			const r = await fetchImpl(url, { credentials: 'include' });
			if (r.ok) {
				const j = await r.json();
				if (j?.has_access) return { allowed: true };
			} else if (r.status === 400) {
				return { allowed: true };
			}
		} catch {
			return { allowed: true };
		}

		// 2. Attempt auto-purchase
		try {
			const r = await fetchImpl('/api/marketplace/purchase-as-agent', {
				method: 'POST',
				credentials: 'include',
				headers: { 'content-type': 'application/json' },
				body: JSON.stringify({
					buyer_agent_id:  buyerAgentId,
					seller_agent_id: sellerAgentId,
					skill:           toolName,
				}),
			});
			if (r.ok) {
				const j = await r.json();
				const status = j?.data?.status;
				if (status === 'confirmed' || j?.data?.already_owned) {
					return { allowed: true, autoPurchased: !j?.data?.already_owned };
				}
			}
			let reason;
			try {
				const j = await r.json();
				reason = j?.error_description || j?.error;
			} catch {
				reason = `purchase failed (HTTP ${r.status})`;
			}
			return {
				allowed: false,
				skill: toolName,
				message: `Auto-purchase failed: ${reason}`,
			};
		} catch (e) {
			return {
				allowed: false,
				skill: toolName,
				message: `Auto-purchase error: ${e.message}`,
			};
		}
	};
}