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(forge): public cost-preview API and an off-by-default pay-to-keep gate
nirholas73fbc917812d
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 789b66b15..07e22a6d4 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -58,6 +58,7 @@ packages, a generated standalone GitHub mirror). See| Guided site tour | [tour-sdk/](tour-sdk) | Published as `@three-ws/tour` | 3D guide walks a live site, spotlights sections, narrates each. One-tag CDN build + free roam || Concierge (embeddable AI support chat) | [concierge-sdk/](concierge-sdk), backend [api/concierge.js](api/concierge.js) `→ /api/concierge`, landing [pages/concierge.html](pages/concierge.html) `→ /concierge`, first-party CDN copy `→ /concierge/concierge.global.js` (mirrored by [concierge-sdk/build.mjs](concierge-sdk/build.mjs)) | Published as `@three-ws/concierge` | An AI concierge for ANY website: floating launcher, chat panel with a rigged 3D avatar bust (blink/idle/viseme lipsync via the page-agent stage lineage), SSE-streamed answers grounded in the live page (ask-time DOM harvest + host `knowledge`, no crawler), speaks while streaming (sentence-level TTS handoff), push-to-talk mic, themes/accent/position, avatar picker or custom GLB. Backend is anonymous + CORS-`*` (third-party origins by design) with its own rate buckets (`limits.conciergeIp`/`conciergeGlobal`), no platform-side content filter on the visitor question, and streaming failover over the shared free-first chain (api/_lib/llm.js). Shopping mode (Shopify): when embedded on a Shopify storefront it auto-detects the store (`window.Shopify` / `shop` config) and becomes a shopping assistant, reading the store's public `/products.json` + `/collections.json` + `/policies/*` at ask-time (no key, no crawler, same-origin), retrieving the relevant products per question via keyword+intent search ([concierge-sdk/src/shopify.js](concierge-sdk/src/shopify.js)), grounding the answer in them, and rendering real product cards (image/live price/link + on-store `/cart/add.js` add-to-cart). The endpoint accepts a bounded `shopping` payload and swaps the system prompt to a store assistant. `<three-concierge>` element, `data-concierge` one-tag auto-init, or `new Concierge({...})`. Also reachable from any AI agent via the MCP server [packages/concierge-mcp/](packages/concierge-mcp) (`@three-ws/concierge-mcp`, registry `io.github.nirholas/concierge-mcp`): `concierge_ask` (ask any site's concierge, grounded in the fetched page), `concierge_embed` (generate the embed), `concierge_avatars`. Examples: [concierge-sdk/examples/](concierge-sdk/examples) (one-tag, web component, imperative, custom avatar, React, self-hosted backend). Docs: [docs/concierge.md](docs/concierge.md), tutorial [docs/tutorials/build-a-site-concierge.md](docs/tutorials/build-a-site-concierge.md). Tests: [concierge-sdk/test/](concierge-sdk/test), [tests/api-concierge.test.js](tests/api-concierge.test.js), [packages/concierge-mcp/test/](packages/concierge-mcp/test) || Assistant widget (3D avatar assistant for any website) | Loader [public/assistant/v1.js](public/assistant/v1.js) `-> /assistant/v1.js`, iframe app [pages/assistant-frame.html](pages/assistant-frame.html) + [src/assistant-frame.js](src/assistant-frame.js) `-> /assistant-frame`, builder [pages/assistant.html](pages/assistant.html) + [src/assistant-page.js](src/assistant-page.js) `-> /assistant`, shared validators [src/assistant-widget-core.js](src/assistant-widget-core.js). npm SDK [assistant-sdk/](assistant-sdk) (`@three-ws/assistant`) is the single source for the loader; its [build.mjs](assistant-sdk/build.mjs) emits the npm ESM + the mirrored one-tag build at `public/assistant/v1.js`. MCP server [packages/assistant-mcp/](packages/assistant-mcp) (`@three-ws/assistant-mcp`, registry `io.github.nirholas/assistant-widget`): `build_assistant_widget` (config -> paste-ready snippet + frame URL + JS-API call), `list_assistant_options` (avatars, backgrounds, modes, attributes). | Published as `@three-ws/assistant` | One script tag adds a floating launcher to any site; clicking it pops up a full-body animated avatar against the host page (transparent) or a color/gradient. Two modes: chatbot (free chain via POST /api/chat, or the visitor's own Groq/OpenRouter key sent browser-to-provider, stored in the frame's localStorage only) and speak mode (avatar repeats typed text out loud via Web Speech + head-anchored speech bubble + talking clip). All params re-validated in-frame (CSS/URL injection safe). Sibling of Concierge (chat panel) - this one is the full-body, avatar-first widget. Install three ways: one-tag CDN, `npm i @three-ws/assistant`, or the MCP server for AI agents. Examples: [assistant-sdk/examples/](assistant-sdk/examples). Docs: [docs/assistant-widget.md](docs/assistant-widget.md) `-> /docs/assistant-widget`, tutorial [docs/tutorials/add-a-3d-assistant.md](docs/tutorials/add-a-3d-assistant.md). Tests: [tests/assistant-widget.test.js](tests/assistant-widget.test.js), [assistant-sdk/test/](assistant-sdk/test), [packages/assistant-mcp/test/](packages/assistant-mcp/test) |+| Forge cost preview + pay-to-keep | [api/forge-quote.js](api/forge-quote.js), [api/forge-keep.js](api/forge-keep.js), [api/_lib/forge-quote.js](api/_lib/forge-quote.js), [api/_lib/forge-keep.js](api/_lib/forge-keep.js), [src/forge-keep.js](src/forge-keep.js), [scripts/forge-pay-to-keep.mjs](scripts/forge-pay-to-keep.mjs) | Live (pay-to-keep off by default) | Public no-spend `GET /api/forge-quote` priced from the real tier and catalog code, shown on `/forge`. Pay-to-keep is gated by `FORGE_PAY_TO_KEEP` (`npm run forge:pay-to-keep -- on`) and reuses the single-use consumption ledger and $THREE hold-or-pay rail. Docs: [docs/forge.md](docs/forge.md#cost-preview-and-pay-to-keep). Tests: [tests/api/forge-quote.test.js](tests/api/forge-quote.test.js), [tests/api/forge-keep.test.js](tests/api/forge-keep.test.js) || Chat (conversational surface) | [chat/](chat) `→ /chat` | Live | Svelte 4 + Vite client, fork of eplus, built by `build:chat` inside `build:gcp` into `public/chat` → `dist/chat`. Free Built-in lane via `/api/chat/proxy` plus BYOK providers; inline 3D forge tools + ModelViewer3D; shares the platform wallet via [src/shared/](src/shared). Sign-in is wallet (SIWE/SIWS) or email+password against the platform's own `/api/auth/*`, on the same cookie session as the rest of the site ([chat/src/passwordAuth.js](chat/src/passwordAuth.js)). The app is the chat and only the chat: marketing lives at the site root, and the hash routes that once rendered in-app copies of it resolve to the real page and redirect ([chat/src/three-ui/site-routes.js](chat/src/three-ui/site-routes.js)). Docs: [chat/README.md](chat/README.md). Tests: [tests/chat-app-core.test.js](tests/chat-app-core.test.js) || three.ws's own guided tour + onboarding | [src/feature-tour/](src/feature-tour) `→ /feature-tour.js`, entry [src/feature-tour.js](src/feature-tour.js), curriculum [public/tour/curriculum.json](public/tour/curriculum.json) generated by [scripts/build-tour.mjs](scripts/build-tour.mjs), landing [pages/tour.html](pages/tour.html) `→ /tour` | Live | A hardened, site-native fork of the [tour-sdk/](tour-sdk) engine (same curriculum schema — stops/sections/tracks/highlight/narration/targets), lazy-injected only when a tour is starting/active (`feature-tour-boot` Vite plugin) so pages that never tour pay no Three.js cost. Three tracks share one curriculum: `full` (every feature, chapter by chapter), `quick` (highlighted heroes), and `onboarding` (added 2026-07-12) — a 6-stop, hand-authored new-account walkthrough chaining `/start` → make an avatar (`/create/selfie`) → build a world (`/diorama`) → live `/markets` data → an optional coin launch (`/create-agent`, clearly skippable) → the new creator's own `/profile`. Auto-offered once to a signed-in account with zero creations across avatars/agents/forged models/worlds (`GET /api/me` → `show_onboarding_tour`, backed by `users.onboarding_tour_seen_at`/`onboarding_tour_completed_at`, migration [api/_lib/migrations/20260712030000_onboarding_tour_state.sql](api/_lib/migrations/20260712030000_onboarding_tour_state.sql)); always reachable afterward via "🎬 Replay guided tour" in the [public/getting-started.js](public/getting-started.js) checklist panel. Tests: [tests/feature-tour-curriculum.test.js](tests/feature-tour-curriculum.test.js), [tests/api-me-onboarding-tour.test.js](tests/api-me-onboarding-tour.test.js) || Tour Atlas (visual index + tour health board) | Page [pages/tour-atlas.html](pages/tour-atlas.html) `-> /tour/atlas` + [src/tour-atlas.js](src/tour-atlas.js), manifest source [data/tour-atlas.json](data/tour-atlas.json) published to [public/tour/atlas.json](public/tour/atlas.json) by [scripts/build-tour-atlas.mjs](scripts/build-tour-atlas.mjs), capture [scripts/capture-tour-atlas.mjs](scripts/capture-tour-atlas.mjs) `npm run tour:atlas`, screenshots [public/media/tour/](public/media/tour) | Live | Every stop of the guided tour above, photographed on the live site with the tour's own spotlight ring painted over the feature it is talking about. Searchable by feature, path or narration, filterable by chapter, track, and anchor health; each card is one click from the live tour via `/<path>?tour=start&stop=<id>`. It doubles as the tour's health board: a stop whose CSS anchor rotted, whose page stopped answering, or whose screenshot is missing shows up here and fails `npm run audit:tour-atlas`, which also holds the page's advertised stop count to the manifest's real total. Tests: [tests/tour-atlas.test.js](tests/tour-atlas.test.js) |diff --git a/api/_lib/forge-keep.js b/api/_lib/forge-keep.jsnew file mode 100644index 000000000..413ed7cc0--- /dev/null+++ b/api/_lib/forge-keep.js@@ -0,0 +1,30 @@+// Pay-to-keep ledger reads for Forge (api/forge-keep.js). A generation is "kept"+// when a settled $THREE payment for forge.keep.<tier> was redeemed against its+// creation id in forge_consumption_redemptions (the single-use ledger Game-Ready+// already uses), so no new table is needed and one payment still funds exactly one+// keep. Holders keep for free and leave no row: their entitlement is re-derived+// from the holding on every read.++import { sql } from './db.js';++/** The creation a keep applies to: a finished row with a durable file, or null. */+export async function loadKeepableCreation(creationId) {+ const [row] = await sql`+ select id, tier, glb_url, status+ from forge_creations+ where id = ${creationId} and status = 'done' and glb_url is not null+ limit 1+ `;+ return row || null;+}++/** True when a keep payment was already redeemed for this creation. */+export async function isCreationKept(creationId) {+ const [row] = await sql`+ select payment_id+ from forge_consumption_redemptions+ where job_id = ${creationId} and action like 'forge.keep.%'+ limit 1+ `;+ return Boolean(row);+}diff --git a/api/_lib/forge-quote.js b/api/_lib/forge-quote.jsnew file mode 100644index 000000000..78e77eae2--- /dev/null+++ b/api/_lib/forge-quote.js@@ -0,0 +1,162 @@+// Forge cost preview: what one generation would cost, per lane and options,+// computed from the same tables the generation endpoint enforces. Nothing here+// is a second copy of a price: tier and export prices come from forge-tiers.js+// through the pricing catalog (pricing/catalog.js), the gate rule mirrors the+// High-tier gate in api/forge.js, and the lane choice is the real resolver.+// Pure and spend-free: no database, no network, no wallet. The one env read is+// the lane-configured flags the resolver already depends on.+//+// Pay-to-keep (api/forge-keep.js) is OFF unless FORGE_PAY_TO_KEEP is on. With it+// off the quote reports `keep.enabled: false` and behaviour is unchanged.++import {+ BACKENDS,+ OUTPUTS,+ PATHS,+ DEFAULT_PATH,+ TIER_IDS,+ DEFAULT_TIER,+ resolveTier,+ resolveBackendId,+ backendIsConfigured,+ estimateEtaSeconds,+ estimateCredits,+ outputIsConfigured,+} from './forge-tiers.js';+import { laneAllowedInTerritory } from './forge-territory.js';+import { priceForAction } from './pricing/catalog.js';+import { requiredTierFor } from './three-access.js';++const ON = new Set(['1', 'on', 'true', 'yes', 'enabled']);++/** True when the owner has switched pay-to-keep on (FORGE_PAY_TO_KEEP). */+export function payToKeepEnabled(env = process.env) {+ return ON.has(String(env?.FORGE_PAY_TO_KEEP ?? '').trim().toLowerCase());+}++/**+ * The catalog action a non-holder pays to keep a generation of this tier, or null+ * when the tier needs none: High is already paid for or held at generation time.+ */+export function keepActionForTier(tierId) {+ return tierId === 'draft' || tierId === 'standard' ? `forge.keep.${tierId}` : null;+}++function usdFor(action) {+ const n = Number(priceForAction(action).usd);+ return Number.isFinite(n) ? n : null;+}++function round2(n) {+ return Math.round(n * 100) / 100;+}++/**+ * @param {object} p+ * @param {string} [p.path] image | geometry | sketch+ * @param {string} [p.tier] draft | standard | high+ * @param {string} [p.backend] explicit lane id (otherwise the default router)+ * @param {boolean} [p.userImages] the request carries reference photos+ * @param {boolean} [p.ownKey] the caller supplies their own vendor key+ * @param {boolean} [p.gameready] include the Game-Ready export add-on+ * @param {string|null} [p.country] requester country (edge geo), for territory routing+ * @param {object} [p.env]+ */+export function buildForgeQuote({+ path,+ tier,+ backend,+ userImages = false,+ ownKey = false,+ gameready = false,+ country = null,+ env = process.env,+} = {}) {+ const p = PATHS.includes(path) ? path : DEFAULT_PATH;+ const t = resolveTier(TIER_IDS.includes(tier) ? tier : DEFAULT_TIER);+ const backendId = resolveBackendId({ path: p, tier: t, backend, userImages, country });+ const b = BACKENDS[backendId];+ const notes = [];++ const houseKey = Boolean(b?.houseKeyEnv && env?.[b.houseKeyEnv]);+ const usesCallerKey = Boolean(b?.byok) && (ownKey || !houseKey);+ const gated = t.id === 'high' && (b?.byok === false || (Boolean(b?.byok) && houseKey && !ownKey));++ let model = 'free';+ let generationUsd = 0;+ let gateFeature = null;+ if (usesCallerKey) {+ model = 'byok';+ notes.push('This engine bills your own vendor key. three.ws charges nothing for it.');+ } else if (gated) {+ model = 'hold_or_pay';+ generationUsd = usdFor('forge.high') ?? 0;+ const req = requiredTierFor('forge.high');+ gateFeature = { id: 'forge.high', holder_tier: req.id, holder_tier_label: req.label, holder_min_usd: req.minUsd };+ notes.push(`$THREE holders (${req.label} and above) generate High for free. Everyone else pays once per generation.`);+ } else {+ notes.push('Free on this engine. No payment is requested.');+ }++ if (b && country !== null && !laneAllowedInTerritory(backendId, country)) {+ notes.push('This engine is not available in your region; the router picks another lane.');+ }++ const keepEnabled = payToKeepEnabled(env);+ const keepAction = keepActionForTier(t.id);+ const keepApplies = keepEnabled && keepAction !== null && model !== 'byok';+ const keepUsd = keepApplies ? usdFor(keepAction) : null;+ if (keepApplies) {+ notes.push('Previewing is free. Keeping the original file is a one-time $THREE payment, free for holders.');+ }++ const gr = OUTPUTS.gameready;+ const grUsd = gameready ? usdFor('forge.gameready') : null;++ const parts = [generationUsd, keepUsd ?? 0, grUsd ?? 0];+ const totalUsd = round2(parts.reduce((a, n) => a + n, 0));++ return {+ path: p,+ tier: { id: t.id, label: t.label, polycount: t.polycount, pbr: t.pbr, hd: t.hd },+ backend: b+ ? {+ id: b.id,+ label: b.label,+ vendor: b.vendor,+ free: Boolean(b.free),+ byok: b.byok || null,+ configured: backendIsConfigured(b.id),+ territory_ok: country === null ? null : laneAllowedInTerritory(b.id, country),+ }+ : null,+ eta_seconds: b ? estimateEtaSeconds({ backendId: b.id, tier: t }) : null,+ generation: {+ model,+ usd: generationUsd,+ action: model === 'hold_or_pay' ? 'forge.high' : null,+ gate: gateFeature,+ vendor_credits: usesCallerKey ? estimateCredits({ backendId, path: p, tier: t }) : null,+ x402_usdc: round2(t.priceUsdcAtomics / 1_000_000),+ },+ keep: {+ enabled: keepEnabled,+ applies: keepApplies,+ action: keepApplies ? keepAction : null,+ usd: keepUsd,+ },+ gameready: gameready+ ? { usd: grUsd, action: 'forge.gameready', configured: outputIsConfigured('gameready'), eta_seconds: gr.baseEta }+ : null,+ total_usd: totalUsd,+ currency: 'USD',+ settles_in: '$THREE',+ holders_pay_usd: 0,+ notes,+ };+}++/** Every tier quoted for one lane choice: the table the Forge composer renders. */+export function buildForgeQuoteTable(opts = {}) {+ return TIER_IDS.map((id) => buildForgeQuote({ ...opts, tier: id }));+}diff --git a/api/_lib/pricing/catalog.js b/api/_lib/pricing/catalog.jsindex 3c37ab91a..274d197f2 100644--- a/api/_lib/pricing/catalog.js+++ b/api/_lib/pricing/catalog.js@@ -34,6 +34,10 @@ export const POLICY = Object.freeze({// Prices come from forge-tiers.js so they're never duplicated.const FORGE_STANDARD_USD = Number(priceUsdcForTier(TIERS.standard)); // 0.15const FORGE_HIGH_USD = Number(priceUsdcForTier(TIERS.high)); // 0.50+// Pay-to-keep (api/forge-keep.js, off unless FORGE_PAY_TO_KEEP is on): generating on+// a free lane stays free, keeping the original file costs the tier's published+// price. Read from forge-tiers.js like every other Forge price.+const FORGE_KEEP_DRAFT_USD = Number(priceUsdcForTier(TIERS.draft)); // 0.05// Game-Ready export price, read from OUTPUTS.gameready (its source of truth) so// it isn't duplicated. The export drives the remesh worker (real GPU cost) to turn// any model into an engine-ready asset — a deliverable, billed per export.@@ -81,6 +85,18 @@ export const CATALOG = Object.freeze({policy: POLICY.CONSUMPTION,usd: FORGE_HIGH_USD,},+ 'forge.keep.draft': {+ label: 'Forge: keep a Draft generation',+ category: 'generation',+ policy: POLICY.CONSUMPTION,+ usd: FORGE_KEEP_DRAFT_USD,+ },+ 'forge.keep.standard': {+ label: 'Forge: keep a Standard generation',+ category: 'generation',+ policy: POLICY.CONSUMPTION,+ usd: FORGE_STANDARD_USD,+ },'forge.gameready': {label: 'Forge: Game-Ready export (Unity/Unreal)',category: 'generation',diff --git a/api/_lib/require-three.js b/api/_lib/require-three.jsindex 16a66f4dd..6adff0f63 100644--- a/api/_lib/require-three.js+++ b/api/_lib/require-three.js@@ -130,6 +130,19 @@ function reasonFor(caller) {return 'insufficient_tier';}+/**+ * Read-only holder check: resolves the caller (comp, tier pass, on-chain tier) and+ * reports whether they are eligible for a registered gated feature. Writes nothing+ * to `res` beyond what comp resolution may set, so a handler that owns its own 402+ * (a per-tier pay-per-use action, say) can branch on it.+ * @returns {Promise<{ eligible: boolean, level: number, wallet: string|null }>}+ */+export async function checkFeatureAccess(req, res, featureId, { body = null } = {}) {+ const caller = await resolveCaller(req, res, body);+ const access = accessFromTierLevel(caller.level, featureId);+ return { eligible: access.eligible, level: caller.level, wallet: caller.wallet };+}+/*** Require a minimum $THREE holder tier for a feature.* @param {object} reqdiff --git a/api/_lib/three-access.js b/api/_lib/three-access.jsindex b7cd08fb9..c96400aa1 100644--- a/api/_lib/three-access.js+++ b/api/_lib/three-access.js@@ -59,6 +59,13 @@ export const GATED_FEATURES = Object.freeze({why: 'Retopology + PBR re-bake runs the remesh GPU worker — holders fund it by holding, or pay per export.',payPerUse: 'forge.gameready',}),+ 'forge.keep': Object.freeze({+ minLevel: 1,+ enforced: false, // live only when FORGE_PAY_TO_KEEP is on (api/forge-keep.js); off by default+ label: 'Keep a Forge generation (original file)',+ why: 'Generating on the free lanes costs nothing; keeping the original file is a holder perk, or a one-time $THREE payment.',+ payPerUse: null, // the price depends on the generation tier: forge.keep.<tier>+ }),'worlds.private': Object.freeze({minLevel: 2,enforced: false,diff --git a/api/forge-keep.js b/api/forge-keep.jsnew file mode 100644index 000000000..37743a8dc--- /dev/null+++ b/api/forge-keep.js@@ -0,0 +1,132 @@+/**+ * /api/forge-keep: pay-to-keep for Forge generations. OFF unless the owner sets+ * FORGE_PAY_TO_KEEP=on (npm run forge:pay-to-keep -- on). With it off every+ * generation is keepable and these endpoints answer `enabled:false, kept:true`, so+ * default behaviour is exactly what shipped before.+ *+ * When on, generating and previewing on a free lane stays free. The original file+ * is released once per creation to a $THREE holder (Bronze and above), or against+ * one settled $THREE payment for forge.keep.<tier> (the same quote, sign, settle+ * rail High and Game-Ready use: src/forge-pay.js payForConsumption). High needs no+ * keep payment because it is already held or paid for at generation time.+ *+ * GET /api/forge-keep?creation_id=<uuid>+ * -> { enabled, kept, reason, price?: { action, usd }, holder_free?, tier }+ * POST /api/forge-keep { creation_id, payment_id?, ref_id?, tier_pass? }+ * -> 200 { enabled, kept:true, reason, download_url }+ * 402 { error:'three_hold_required', pay_per_use:{ action, usd } }+ * 402/409 payment errors (payment_invalid, payment_expired, payment_already_used)+ *+ * Settlement is $THREE on Solana (api/_lib/token). Nothing here signs or spends:+ * the caller pays through the token rail first and presents the settled proof.+ */++import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { isUuid } from './_lib/validate.js';+import { priceForAction } from './_lib/pricing/catalog.js';+import { checkFeatureAccess } from './_lib/require-three.js';+import { payToKeepEnabled, keepActionForTier } from './_lib/forge-quote.js';+import { loadKeepableCreation, isCreationKept } from './_lib/forge-keep.js';+import { assertForgePurchase, redeemForgePurchase } from './_lib/forge-consumption-payment.js';++const PAYMENT_ERROR_CODES = new Set(['bad_request', 'payment_invalid', 'payment_expired', 'payment_already_used']);++function priceOf(action) {+ try {+ const usd = Number(priceForAction(action).usd);+ return Number.isFinite(usd) && usd > 0 ? { action, usd } : null;+ } catch {+ return null;+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const isPost = req.method === 'POST';+ const body = isPost ? await readJson(req, 4_000).catch(() => null) : null;+ const creationId = isPost+ ? typeof body?.creation_id === 'string' ? body.creation_id.trim() : ''+ : (new URL(req.url, 'http://localhost').searchParams.get('creation_id') || '').trim();+ if (!isUuid(creationId)) {+ return json(res, 400, { error: 'invalid_creation', message: 'Pass creation_id as a valid creation id.' });+ }++ const creation = await loadKeepableCreation(creationId);+ if (!creation) {+ return json(res, 404, { error: 'creation_not_found', message: 'That generation is not finished or no longer exists.' });+ }++ const enabled = payToKeepEnabled();+ const action = keepActionForTier(creation.tier);+ const released = (reason) =>+ json(res, 200, { enabled, kept: true, reason, tier: creation.tier, download_url: creation.glb_url });++ if (!enabled) return released('pay_to_keep_off');+ if (!action) return released('included');+ if (await isCreationKept(creationId)) return released('paid');++ const price = priceOf(action);+ if (!price) return released('unpriced');++ if (!isPost) {+ const access = await checkFeatureAccess(req, res, 'forge.keep').catch(() => ({ eligible: false }));+ return json(res, 200, {+ enabled,+ kept: access.eligible,+ reason: access.eligible ? 'holder' : 'payment_required',+ tier: creation.tier,+ price,+ holder_free: access.eligible,+ ...(access.eligible ? { download_url: creation.glb_url } : {}),+ });+ }++ const paymentId = typeof body?.payment_id === 'string' ? body.payment_id.trim() : '';+ const refId = typeof body?.ref_id === 'string' ? body.ref_id.trim() : '';+ if (paymentId && refId) {+ let proof;+ try {+ proof = await assertForgePurchase({ action, paymentId, refId });+ } catch (err) {+ if (!PAYMENT_ERROR_CODES.has(err?.code)) throw err;+ return json(res, err.status || 402, {+ error: err.code,+ feature: action,+ pay_per_use: price,+ message: err.message || 'That $THREE payment could not be verified.',+ });+ }+ const claim = await redeemForgePurchase({+ action,+ paymentId,+ refId,+ jobId: creationId,+ settledAt: proof.payment.settledAt,+ });+ if (!claim.redeemed) {+ return json(res, 409, {+ error: 'payment_already_used',+ feature: action,+ pay_per_use: price,+ message: 'That payment was already used. Pay again to keep this model.',+ });+ }+ return released('paid');+ }++ const access = await checkFeatureAccess(req, res, 'forge.keep', { body });+ if (access.eligible) return released('holder');+ return json(res, 402, {+ error: 'three_hold_required',+ feature: action,+ message: `Keeping this ${creation.tier} model costs $${price.usd.toFixed(2)} in $THREE, free for holders.`,+ pay_per_use: price,+ get_three_url: '/three-token',+ });+});diff --git a/api/forge-quote.js b/api/forge-quote.jsnew file mode 100644index 000000000..a8b15a848--- /dev/null+++ b/api/forge-quote.js@@ -0,0 +1,68 @@+/**+ * /api/forge-quote: what a Forge generation would cost, before any spend.+ *+ * GET /api/forge-quote?tier=high&path=image&backend=trellis2&images=1&gameready=1+ * -> one quote (see api/_lib/forge-quote.js)+ * GET /api/forge-quote?table=1&path=image+ * -> { quotes: [draft, standard, high] } for the composer's tier picker+ *+ * Public, read-only and spend-free: it signs nothing, charges nothing and touches+ * no wallet. Every price is read from the tables the generation endpoint enforces+ * (forge-tiers.js, pricing/catalog.js), so a quote cannot drift from the charge.+ * `keep.enabled` reports whether pay-to-keep (api/forge-keep.js) is switched on.+ */++import { cors, json, method, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { requestTerritory } from './_lib/forge-territory.js';+import { buildForgeQuote, buildForgeQuoteTable } from './_lib/forge-quote.js';+import { PATHS, TIER_IDS, BACKENDS } from './_lib/forge-tiers.js';++const FLAG = new Set(['1', 'true', 'yes', 'on']);++function flag(sp, name) {+ return FLAG.has((sp.get(name) || '').toLowerCase());+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const sp = new URL(req.url, 'http://localhost').searchParams;+ const path = sp.get('path') || undefined;+ const tier = sp.get('tier') || undefined;+ const backend = sp.get('backend') || undefined;++ if (path && !PATHS.includes(path)) {+ return json(res, 400, { error: 'invalid_path', message: `path must be one of ${PATHS.join(', ')}.` });+ }+ if (tier && !TIER_IDS.includes(tier)) {+ return json(res, 400, { error: 'invalid_tier', message: `tier must be one of ${TIER_IDS.join(', ')}.` });+ }+ if (backend && !BACKENDS[backend]) {+ return json(res, 400, {+ error: 'invalid_backend',+ message: 'Unknown engine. GET /api/forge?catalog lists the engine ids.',+ });+ }++ const opts = {+ path,+ backend,+ userImages: flag(sp, 'images'),+ ownKey: flag(sp, 'own_key'),+ gameready: flag(sp, 'gameready'),+ country: requestTerritory(req),+ };++ // The answer depends on the caller's region (territory routing) and on live env,+ // so it is cacheable by the browser only, never by a shared edge.+ const headers = { 'cache-control': 'private, max-age=30' };+ if (flag(sp, 'table')) {+ return json(res, 200, { quotes: buildForgeQuoteTable(opts) }, headers);+ }+ return json(res, 200, buildForgeQuote({ ...opts, tier }), headers);+});diff --git a/data/changelog.json b/data/changelog.jsonindex 0e344f8d0..830966a59 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-24",+ "title": "See what a Forge generation costs before you press Generate",+ "summary": "The Forge page now shows a live cost line for the tier, engine and options you picked, read from the same pricing code that bills you, with nothing spent. A pay-to-keep mode (free preview, pay in $THREE to download, holders keep free) is built and switched off, so downloads stay free until it is turned on.",+ "tags": ["feature", "docs"],+ "link": "/docs/forge"+ },{"date": "2026-10-24","title": "Agents join the open Solana agent registry and hires read trust tiers",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 799238632..a926b1944 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -10650,3 +10650,13 @@ for verification code. A failed delivery retries after 30s, 2m, 10m, 30m, 1h, 3hand 8h (8 attempts total) and every attempt is kept in the delivery log; replaya delivery from the log or the `/dashboard/developers` page. The signing secret(`whsec_…`) is shown once at creation and on `rotate-secret`.++## Forge cost preview and pay-to-keep++| Method and path | Auth | Purpose |+| --- | --- | --- |+| `GET /api/forge-quote?path=text&tier=standard` | none | What a generation would cost. Optional `backend`, `images`, `own_key`, `gameready`; `table=1` returns every tier. No spend, `cache-control: private, max-age=30`. |+| `GET /api/forge-keep?id=<creation>` | none | Whether the creation is kept, and whether pay-to-keep is enabled. |+| `POST /api/forge-keep` | optional $THREE wallet or payment | Release a creation for download. With `FORGE_PAY_TO_KEEP` off it always returns `kept: true`. Non-holders get `402 three_hold_required` with the `pay_per_use` action. A reused payment returns `409 payment_already_used`. |++Details and the enable command: [forge.md](./forge.md#cost-preview-and-pay-to-keep).diff --git a/docs/forge.md b/docs/forge.mdindex 910a60f7f..f00fea939 100644--- a/docs/forge.md+++ b/docs/forge.md@@ -612,6 +612,24 @@ with the Generate node's current engine, quality and controls.- **Photo input** accepts up to six views of one object (front, back, left, right, top, three-quarter); text-only engines are filtered out of the photo modes automatically.- Rate limits are per client IP on the shared 3D generation buckets.+## Cost preview and pay-to-keep++`GET /api/forge-quote` is a public, no-spend preview of what a generation costs before you press Generate. Query: `path` (`text`, `image`, `multi`), `tier` (`draft`, `standard`, `high`), optional `backend`, `images`, `own_key`, `gameready`, or `table=1` for every tier at once. Every figure comes from the same tier and catalog code the generator charges from ([api/_lib/forge-tiers.js](../api/_lib/forge-tiers.js), [api/_lib/pricing/catalog.js](../api/_lib/pricing/catalog.js)), so the preview cannot drift from the bill. The `/forge` page shows it as a line under the estimate and refreshes it as you change tier, engine or options.++The response splits the cost into `generation` (free lane, your own key, or the High tier hold-or-pay gate), `keep` (the pay-to-keep step), the optional `gameready` export, and `total_usd`. Payments settle in $THREE on Solana.++**Pay-to-keep** is off by default, and while it is off nothing changes: every download is free exactly as before. When the owner turns it on, a Draft or Standard result is generated free and previewed, and the Download button first calls `POST /api/forge-keep` for that creation. $THREE holders keep for free, High results are already paid or held at generation time, and everyone else pays the `forge.keep.<tier>` price through the existing single-use consumption ledger (a payment can release one creation, once). `GET /api/forge-keep?id=<creation>` reports whether a creation is already kept. The keep step fails open on server faults so an outage never blocks a download. In this release the flag gates the Forge download flow, not the secrecy of the stored GLB URL on the CDN.++Enable or disable it with one command (it only updates the one env var, never the rest of the service env):++```+npm run forge:pay-to-keep -- status+npm run forge:pay-to-keep -- on+npm run forge:pay-to-keep -- off+```++Price points are derived from the tier prices (`forge.keep.draft` follows the Draft tier price, `forge.keep.standard` the Standard tier price) and are changed in the pricing catalog, not hardcoded in the UI.+## Measuring realismAny change that could affect output quality (a tier's sampler budget, a newdiff --git a/package.json b/package.jsonindex 1b1368f78..7dc69c2b6 100644--- a/package.json+++ b/package.json@@ -580,7 +580,8 @@"awesome:standalone": "node scripts/build-awesome.mjs --standalone","verify:three-gate": "node scripts/verify-three-gate.mjs","check:mcp-catalog": "node scripts/check-mcp-catalog.mjs",- "vet:mcp-catalog": "node scripts/vet-mcp-integrations.mjs"+ "vet:mcp-catalog": "node scripts/vet-mcp-integrations.mjs",+ "forge:pay-to-keep": "node scripts/forge-pay-to-keep.mjs"},"dependencies": {"8004-solana": "^0.8.5",diff --git a/pages/forge.html b/pages/forge.htmlindex 7397b4691..dd86515be 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -4091,6 +4091,7 @@<span class="byok-hint" id="byok-hint"></span></div><p class="fq-estimate" id="estimate" aria-live="polite"></p>+ <p class="fq-estimate fq-quote" id="forge-quote" aria-live="polite" hidden></p></div><div class="composer-row">diff --git a/scripts/forge-pay-to-keep.mjs b/scripts/forge-pay-to-keep.mjsnew file mode 100644index 000000000..adafa0380--- /dev/null+++ b/scripts/forge-pay-to-keep.mjs@@ -0,0 +1,51 @@+#!/usr/bin/env node+// Turn Forge pay-to-keep on or off on the production Cloud Run service.+// Usage: npm run forge:pay-to-keep -- on|off|status [--dry-run]+// Uses --update-env-vars (never --set-env-vars, which replaces the whole env set).+import { spawnSync } from 'node:child_process';++const SERVICE = 'three-ws-api';+const REGION = 'us-central1';+const PROJECT = 'aerial-vehicle-466722-p5';++const [mode, ...flags] = process.argv.slice(2);+const dry = flags.includes('--dry-run');++function usage() {+ console.error('Usage: npm run forge:pay-to-keep -- on|off|status [--dry-run]');+ process.exit(2);+}++function gcloud(args) {+ return spawnSync('gcloud', [...args, '--project', PROJECT], { encoding: 'utf8' });+}++if (mode === 'status') {+ const r = gcloud([+ 'run', 'services', 'describe', SERVICE, '--region', REGION,+ '--format', 'value(spec.template.spec.containers[0].env)',+ ]);+ if (r.status !== 0) {+ console.error(r.stderr || 'gcloud describe failed');+ process.exit(1);+ }+ const m = /'name': 'FORGE_PAY_TO_KEEP', 'value': '([^']*)'/.exec(r.stdout);+ console.log(`FORGE_PAY_TO_KEEP=${m ? m[1] : '(unset, pay-to-keep is off)'}`);+ process.exit(0);+}++if (mode !== 'on' && mode !== 'off') usage();++const value = mode === 'on' ? '1' : '0';+const args = [+ 'run', 'services', 'update', SERVICE, '--region', REGION,+ '--update-env-vars', `FORGE_PAY_TO_KEEP=${value}`,+];+if (dry) {+ console.log(`gcloud ${args.join(' ')} --project ${PROJECT}`);+ process.exit(0);+}+const r = gcloud(args);+process.stdout.write(r.stdout || '');+process.stderr.write(r.stderr || '');+process.exit(r.status ?? 1);diff --git a/src/forge-keep.js b/src/forge-keep.jsnew file mode 100644index 000000000..ce4d7e675--- /dev/null+++ b/src/forge-keep.js@@ -0,0 +1,118 @@+// Forge cost preview line and pay-to-keep gate for the result Download button.+//+// The preview reads GET /api/forge-quote (public, spend-free): what the current+// quality, engine and input would cost, from the same tables the server enforces.+// Pay-to-keep is OFF unless the owner enables FORGE_PAY_TO_KEEP; with it off the+// keep check answers kept:true and Download behaves exactly as before.+//+// When it is on, a preview is free and the original file is released once per+// generation to a $THREE holder, or against one settled $THREE payment (the same+// quote, sign, settle rail High and Game-Ready use). Nothing here signs or spends+// without the wallet prompt in forge-pay.js, which asks first.++import { payForConsumption } from './forge-pay.js';+import { attachTierPass, getTierPass } from './three-access.js';++const usd = (n) => `$${Number(n).toFixed(2)}`;++/** One human line for a quote. Pure: unit-tested. */+export function describeQuote(q) {+ if (!q || !q.generation) return '';+ const g = q.generation;+ const bits = [];+ if (g.model === 'byok') {+ bits.push('Billed to your own vendor key, free on three.ws');+ } else if (g.model === 'hold_or_pay') {+ bits.push(`${usd(g.usd)} in $THREE per generation, free for ${g.gate?.holder_tier_label || 'holders'}`);+ } else {+ bits.push('Free to generate');+ }+ if (q.keep?.applies && q.keep.usd > 0) {+ bits.push(`keep the original file for ${usd(q.keep.usd)} in $THREE, free for holders`);+ }+ if (q.gameready?.usd > 0) {+ bits.push(`Game-Ready export ${usd(q.gameready.usd)}`);+ }+ return bits.join(' · ');+}++let seq = 0;++/**+ * Fetch and render the quote for the current composer state into `el`.+ * Stale responses (a faster, later request) are dropped. A failed preview clears+ * the line: the catalog estimate above it stays the fallback.+ */+export async function renderQuote(el, { tier, path, backend, images = false, headers = {} } = {}) {+ if (!el) return null;+ const mine = ++seq;+ const sp = new URLSearchParams();+ if (tier) sp.set('tier', tier);+ if (path) sp.set('path', path);+ if (backend) sp.set('backend', backend);+ if (images) sp.set('images', '1');+ try {+ const res = await fetch(`/api/forge-quote?${sp}`, { headers });+ if (!res.ok) throw new Error(String(res.status));+ const q = await res.json();+ if (mine !== seq) return null;+ el.textContent = describeQuote(q);+ el.hidden = !el.textContent;+ return q;+ } catch {+ if (mine === seq) {+ el.textContent = '';+ el.hidden = true;+ }+ return null;+ }+}++async function keepRequest(creationId, headers, payment) {+ const res = await fetch('/api/forge-keep', {+ method: 'POST',+ headers: attachTierPass({ 'content-type': 'application/json', ...headers }),+ body: JSON.stringify({+ creation_id: creationId,+ ...(payment ? { payment_id: payment.paymentId, ref_id: payment.refId } : {}),+ }),+ });+ const data = await res.json().catch(() => ({}));+ return { res, data };+}++/**+ * Gate a download on pay-to-keep. Resolves { ok:true } when the file may be+ * released (feature off, included, holder, or paid) and { ok:false, message } when+ * the user cancelled or the payment could not be verified. Never throws. A network+ * or server fault fails open (see below), so the default experience cannot regress.+ */+export async function ensureKept(creationId, { headers = {} } = {}) {+ if (!creationId) return { ok: true };+ try {+ await getTierPass({ interactive: false }).catch(() => null);+ let { res, data } = await keepRequest(creationId, headers);+ if (res.ok && data.kept) return { ok: true };+ // The keep check is a bonus gate, never a reason a download that worked before+ // stops working: a missing route or a server fault releases the file, since the+ // stored file URL is already public and the gate only adds the payment step.+ if (res.status === 404 || res.status >= 500) return { ok: true };+ const price = Number(data.pay_per_use?.usd) || 0;+ if (res.status === 402 && price > 0) {+ const paid = await payForConsumption({+ usd: price,+ unit: 'keeping this model',+ confirm: 'Keep the original file of this generation. Previewing stays free.',+ footnote: '$THREE is the only coin on three.ws. Holders keep every model free.',+ successText: 'Payment confirmed. Preparing your file…',+ refPrefix: 'forge-keep',+ });+ if (!paid?.ok) return { ok: false, message: 'Download cancelled. No $THREE was spent.' };+ ({ res, data } = await keepRequest(creationId, headers, paid));+ if (res.ok && data.kept) return { ok: true };+ }+ return { ok: false, message: data.message || 'Could not confirm this download. Try again.' };+ } catch {+ return { ok: true };+ }+}diff --git a/src/forge.js b/src/forge.jsindex e8b349c95..9963814d4 100644--- a/src/forge.js+++ b/src/forge.js@@ -21,6 +21,7 @@ import {import { injectFestivePresets } from './shared/festive-presets.js';import { renderLock, lockStateFromAccess } from './three-lock.js';import { payForHighGeneration } from './forge-pay.js';+import { renderQuote, ensureKept } from './forge-keep.js';import { initWalletButton, getConnectedWalletAddress } from './wallet.js';import { generateForgePrompt } from './forge-prompt-gen.js';import { createForgeTimeline } from './forge-timeline.js';@@ -119,6 +120,7 @@ const els = {resultQuality: document.getElementById('result-quality'),verdict: document.getElementById('verdict'),download: document.getElementById('download'),+ quote: document.getElementById('forge-quote'),materialize: document.getElementById('materialize-it'),again: document.getElementById('again'),refine: document.getElementById('refine'),@@ -1281,6 +1283,13 @@ function updateEstimate() {else parts.push('renders a preview image, then builds 3D');els.estimate.innerHTML = parts.join(' · ');updateTierTitles();+ renderQuote(els.quote, {+ tier: selectedTier,+ path: selectedEngine.path,+ backend: selectedEngine.backend,+ images: mode === 'image',+ headers: CLIENT_HEADERS,+ });}// Stamp each tier button's tooltip with the catalog's real blurb, the typical@@ -4088,9 +4097,15 @@ if (els.categoryPicker) {// hand the user the stamped file. Any failure falls back to the raw provider// file — stamping must never block a download.els.download.addEventListener('click', async (e) => {- sendFeedback({ downloaded: true });const glbUrl = els.download.href;- if (!glbUrl || glbUrl.startsWith('blob:') || els.download.dataset.stamping) return;+ if (els.download.dataset.stamping) return;+ // Pay-to-keep (off unless the owner enables it): a generation that is not yet+ // kept needs a holder or a $THREE payment before the original file is released.+ // Only a fresh or reopened durable creation can be gated; a local blob cannot.+ if (!glbUrl || glbUrl.startsWith('blob:')) {+ sendFeedback({ downloaded: true });+ return;+ }e.preventDefault();els.download.dataset.stamping = '1';els.download.setAttribute('aria-busy', 'true');@@ -4098,6 +4113,17 @@ els.download.addEventListener('click', async (e) => {els.download.textContent = 'Preparing…';const filename = els.download.getAttribute('download') || 'forge.glb';try {+ if (currentCreationId) {+ const keep = await ensureKept(currentCreationId, { headers: CLIENT_HEADERS });+ if (!keep.ok) {+ if (els.quote) {+ els.quote.textContent = keep.message;+ els.quote.hidden = false;+ }+ return;+ }+ }+ sendFeedback({ downloaded: true });const res = await fetch(glbUrl);if (!res.ok) throw new Error(`fetch ${res.status}`);const stamped = stampGlbAttribution(await res.arrayBuffer(), {diff --git a/tests/api/forge-keep.test.js b/tests/api/forge-keep.test.jsnew file mode 100644index 000000000..adde5e6e8--- /dev/null+++ b/tests/api/forge-keep.test.js@@ -0,0 +1,125 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';+import { signTierPass } from '../../api/_lib/three-tier.js';++const CREATION = '11111111-1111-4111-8111-111111111111';+let creation = { id: CREATION, tier: 'standard', glb_url: 'https://cdn.example/forge/a.glb', status: 'done' };+let kept = false;++vi.mock('../../api/_lib/forge-keep.js', () => ({+ loadKeepableCreation: vi.fn(async (id) => (id === CREATION ? creation : null)),+ isCreationKept: vi.fn(async () => kept),+}));+const assertForgePurchase = vi.fn(async () => ({ payment: { settledAt: new Date().toISOString() } }));+const redeemForgePurchase = vi.fn(async () => ({ redeemed: true }));+vi.mock('../../api/_lib/forge-consumption-payment.js', () => ({+ assertForgePurchase: (...a) => assertForgePurchase(...a),+ redeemForgePurchase: (...a) => redeemForgePurchase(...a),+}));++process.env.NODE_ENV = 'development';+delete process.env.HOLDER_PASS_SECRET;+const BRONZE = signTierPass({ wallet: 'THREEsynthetic1111111111111111111111111111', level: 1, tierId: 'bronze', usd: 30 });++const { default: handler } = await import('../../api/forge-keep.js');++async function call({ method = 'POST', body = null, query = '', pass = null } = {}) {+ const payload = body ? JSON.stringify(body) : '';+ const stream = Readable.from(payload ? [Buffer.from(payload)] : []);+ stream.method = method;+ stream.url = `/api/forge-keep${query}`;+ stream.headers = {+ 'content-type': 'application/json',+ 'x-forwarded-for': '203.0.113.70',+ ...(pass ? { 'x-three-tier-pass': pass } : {}),+ };+ const res = {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(n, v) {+ this.headers[String(n).toLowerCase()] = v;+ },+ end(b) {+ this.body = b ?? null;+ },+ };+ await handler(stream, res);+ return { status: res.statusCode, json: res.body ? JSON.parse(res.body) : null };+}++beforeEach(() => {+ creation = { id: CREATION, tier: 'standard', glb_url: 'https://cdn.example/forge/a.glb', status: 'done' };+ kept = false;+ assertForgePurchase.mockClear();+ redeemForgePurchase.mockClear();+ delete process.env.FORGE_PAY_TO_KEEP;+});++describe('/api/forge-keep with the flag off (default)', () => {+ it('releases every generation and asks for nothing', async () => {+ const r = await call({ body: { creation_id: CREATION } });+ expect(r.status).toBe(200);+ expect(r.json).toMatchObject({ enabled: false, kept: true, reason: 'pay_to_keep_off', download_url: creation.glb_url });+ const g = await call({ method: 'GET', query: `?creation_id=${CREATION}` });+ expect(g.json.kept).toBe(true);+ expect(assertForgePurchase).not.toHaveBeenCalled();+ });+});++describe('/api/forge-keep with FORGE_PAY_TO_KEEP=on', () => {+ beforeEach(() => {+ process.env.FORGE_PAY_TO_KEEP = 'on';+ });++ it('validates the creation id and 404s unknown creations', async () => {+ expect((await call({ body: { creation_id: 'nope' } })).json.error).toBe('invalid_creation');+ const missing = await call({ body: { creation_id: '22222222-2222-4222-8222-222222222222' } });+ expect(missing.status).toBe(404);+ });++ it('402s a non-holder with the tier price and withholds the file', async () => {+ const r = await call({ body: { creation_id: CREATION } });+ expect(r.status).toBe(402);+ expect(r.json.error).toBe('three_hold_required');+ expect(r.json.pay_per_use).toEqual({ action: 'forge.keep.standard', usd: 0.15 });+ expect(r.json.download_url).toBeUndefined();+ const g = await call({ method: 'GET', query: `?creation_id=${CREATION}` });+ expect(g.json).toMatchObject({ kept: false, reason: 'payment_required' });+ expect(g.json.download_url).toBeUndefined();+ });++ it('releases the file to a holder without a payment', async () => {+ const r = await call({ body: { creation_id: CREATION }, pass: BRONZE });+ expect(r.status).toBe(200);+ expect(r.json).toMatchObject({ kept: true, reason: 'holder', download_url: creation.glb_url });+ });++ it('redeems a settled payment against the creation exactly once', async () => {+ const body = { creation_id: CREATION, payment_id: '33333333-3333-4333-8333-333333333333', ref_id: 'forge-keep-x' };+ const r = await call({ body });+ expect(r.json).toMatchObject({ kept: true, reason: 'paid' });+ expect(assertForgePurchase).toHaveBeenCalledWith(expect.objectContaining({ action: 'forge.keep.standard' }));+ expect(redeemForgePurchase).toHaveBeenCalledWith(expect.objectContaining({ jobId: CREATION, action: 'forge.keep.standard' }));+ redeemForgePurchase.mockResolvedValueOnce({ redeemed: false });+ const again = await call({ body });+ expect(again.status).toBe(409);+ expect(again.json.error).toBe('payment_already_used');+ });++ it('echoes a rejected payment as a recoverable 402', async () => {+ assertForgePurchase.mockRejectedValueOnce(Object.assign(new Error('bad'), { status: 402, code: 'payment_invalid' }));+ const r = await call({ body: { creation_id: CREATION, payment_id: '33333333-3333-4333-8333-333333333333', ref_id: 'r' } });+ expect(r.status).toBe(402);+ expect(r.json.error).toBe('payment_invalid');+ expect(r.json.pay_per_use.usd).toBe(0.15);+ });++ it('treats an already-paid creation and a High generation as kept', async () => {+ kept = true;+ expect((await call({ body: { creation_id: CREATION } })).json.reason).toBe('paid');+ kept = false;+ creation = { ...creation, tier: 'high' };+ expect((await call({ body: { creation_id: CREATION } })).json.reason).toBe('included');+ });+});diff --git a/tests/api/forge-quote.test.js b/tests/api/forge-quote.test.jsnew file mode 100644index 000000000..d849b1947--- /dev/null+++ b/tests/api/forge-quote.test.js@@ -0,0 +1,131 @@+import { describe, it, expect } from 'vitest';+import { Readable } from 'node:stream';+import {+ buildForgeQuote,+ buildForgeQuoteTable,+ payToKeepEnabled,+ keepActionForTier,+} from '../../api/_lib/forge-quote.js';+import { TIERS, priceUsdcForTier, priceUsdcForOutput, BACKENDS } from '../../api/_lib/forge-tiers.js';+import { priceForAction } from '../../api/_lib/pricing/catalog.js';+import { describeQuote } from '../../src/forge-keep.js';++const OFF = {};+const ON = { FORGE_PAY_TO_KEEP: 'on' };++// A lane the router treats as platform-keyed (not BYOK) and one that is BYOK.+const platformLane = Object.values(BACKENDS).find((b) => b.byok === false && b.paths.includes('image'));+const byokLane = Object.values(BACKENDS).find((b) => b.byok && !b.houseKeyEnv && b.paths.includes('image'));++describe('forge cost preview', () => {+ it('prices High from the same catalog the gate charges', () => {+ const q = buildForgeQuote({ tier: 'high', backend: platformLane.id, env: OFF });+ expect(q.generation.model).toBe('hold_or_pay');+ expect(q.generation.usd).toBe(Number(priceForAction('forge.high').usd));+ expect(q.generation.usd).toBe(Number(priceUsdcForTier(TIERS.high)));+ expect(q.generation.gate.holder_tier).toBeTruthy();+ expect(q.total_usd).toBe(q.generation.usd);+ });++ it('reports draft and standard as free on a platform lane', () => {+ for (const tier of ['draft', 'standard']) {+ const q = buildForgeQuote({ tier, backend: platformLane.id, env: OFF });+ expect(q.generation.model).toBe('free');+ expect(q.generation.usd).toBe(0);+ expect(q.total_usd).toBe(0);+ }+ });++ it('never charges on a BYOK lane and surfaces the vendor credit estimate', () => {+ const q = buildForgeQuote({ tier: 'high', backend: byokLane.id, env: OFF });+ expect(q.generation.model).toBe('byok');+ expect(q.generation.usd).toBe(0);+ expect(q.keep.applies).toBe(false);+ });++ it('adds the Game-Ready export price only when asked', () => {+ const without = buildForgeQuote({ tier: 'standard', backend: platformLane.id, env: OFF });+ const withGr = buildForgeQuote({ tier: 'standard', backend: platformLane.id, gameready: true, env: OFF });+ expect(without.gameready).toBeNull();+ expect(withGr.gameready.usd).toBe(Number(priceUsdcForOutput('gameready')));+ expect(withGr.total_usd).toBe(withGr.gameready.usd);+ });++ it('defaults pay-to-keep off and leaves totals untouched', () => {+ expect(payToKeepEnabled({})).toBe(false);+ expect(payToKeepEnabled({ FORGE_PAY_TO_KEEP: 'off' })).toBe(false);+ const q = buildForgeQuote({ tier: 'standard', backend: platformLane.id, env: OFF });+ expect(q.keep).toEqual({ enabled: false, applies: false, action: null, usd: null });+ });++ it('prices keep at the tier price when enabled, never for High', () => {+ expect(payToKeepEnabled(ON)).toBe(true);+ const std = buildForgeQuote({ tier: 'standard', backend: platformLane.id, env: ON });+ expect(std.keep.action).toBe('forge.keep.standard');+ expect(std.keep.usd).toBe(Number(priceUsdcForTier(TIERS.standard)));+ expect(std.total_usd).toBe(std.keep.usd);+ const draft = buildForgeQuote({ tier: 'draft', backend: platformLane.id, env: ON });+ expect(draft.keep.usd).toBe(Number(priceUsdcForTier(TIERS.draft)));+ const high = buildForgeQuote({ tier: 'high', backend: platformLane.id, env: ON });+ expect(high.keep.applies).toBe(false);+ expect(keepActionForTier('high')).toBeNull();+ });++ it('quotes every tier in a table', () => {+ const t = buildForgeQuoteTable({ backend: platformLane.id, env: OFF });+ expect(t.map((q) => q.tier.id)).toEqual(['draft', 'standard', 'high']);+ });++ it('falls back to defaults for unknown path and tier', () => {+ const q = buildForgeQuote({ path: 'nope', tier: 'nope', env: OFF });+ expect(q.path).toBe('image');+ expect(q.tier.id).toBe('standard');+ });++ it('describes the quote in plain words', () => {+ const high = describeQuote(buildForgeQuote({ tier: 'high', backend: platformLane.id, env: OFF }));+ expect(high).toMatch(/\$0\.50 in \$THREE per generation/);+ const free = describeQuote(buildForgeQuote({ tier: 'draft', backend: platformLane.id, env: OFF }));+ expect(free).toBe('Free to generate');+ const keep = describeQuote(buildForgeQuote({ tier: 'standard', backend: platformLane.id, env: ON }));+ expect(keep).toMatch(/keep the original file for \$0\.15/);+ });+});++describe('GET /api/forge-quote', () => {+ async function call(url) {+ const { default: handler } = await import('../../api/forge-quote.js');+ const stream = Readable.from([]);+ stream.method = 'GET';+ stream.url = url;+ stream.headers = { 'x-forwarded-for': '203.0.113.50' };+ const res = {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(n, v) {+ this.headers[String(n).toLowerCase()] = v;+ },+ end(b) {+ this.body = b ?? null;+ },+ };+ await handler(stream, res);+ return { status: res.statusCode, json: res.body ? JSON.parse(res.body) : null, headers: res.headers };+ }++ it('returns a quote and the full table', async () => {+ const one = await call('/api/forge-quote?tier=high');+ expect(one.status).toBe(200);+ expect(one.json.tier.id).toBe('high');+ expect(one.headers['cache-control']).toMatch(/^private/);+ const table = await call('/api/forge-quote?table=1');+ expect(table.json.quotes).toHaveLength(3);+ });++ it('rejects bad input at the boundary', async () => {+ expect((await call('/api/forge-quote?tier=ultra')).json.error).toBe('invalid_tier');+ expect((await call('/api/forge-quote?path=zzz')).json.error).toBe('invalid_path');+ expect((await call('/api/forge-quote?backend=nope')).json.error).toBe('invalid_backend');+ });+});diff --git a/tests/three-access.test.js b/tests/three-access.test.jsindex 1f0d43cce..c7ad29d36 100644--- a/tests/three-access.test.js+++ b/tests/three-access.test.js@@ -29,6 +29,7 @@ const WALLET = 'So11111111111111111111111111111111111111112';const MIN_LEVEL = {'forge.high': 1,'forge.gameready': 1,+ 'forge.keep': 1,'worlds.private': 2,'mcp.priority': 2,'worlds.branded': 3,@@ -38,6 +39,7 @@ const MIN_LEVEL = {const REQUIRED_TIER_ID = {'forge.high': 'bronze','forge.gameready': 'bronze',+ 'forge.keep': 'bronze','worlds.private': 'silver','mcp.priority': 'silver','worlds.branded': 'gold',@@ -47,6 +49,7 @@ const REQUIRED_TIER_ID = {const PAY_PER_USE = {'forge.high': 'forge.high','forge.gameready': 'forge.gameready',+ 'forge.keep': null,'worlds.private': null,'mcp.priority': null,'worlds.branded': null,@@ -61,6 +64,7 @@ const PAY_PER_USE = {const ENFORCED = {'forge.high': true,'forge.gameready': true,+ 'forge.keep': false,'worlds.private': false,'mcp.priority': false,'worlds.branded': false,