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
style(print): drop the banned dashes and the two comment lines the rule reads as commented-out code
nirholas2ee315e0491c
diff --git a/api/_lib/print/adapters/manual.js b/api/_lib/print/adapters/manual.jsindex de691e6ea..7c685d22b 100644--- a/api/_lib/print/adapters/manual.js+++ b/api/_lib/print/adapters/manual.js@@ -5,7 +5,7 @@// is always a human: an operator takes the prepared STL/3MF off the queue,// runs it on a real bureau's machines (or their own), and reports what// happened. This adapter is the machine-readable face of that person. Its-// submit() puts the job on the operator's queue and pages the operator channel;+// submit() puts the job on the operator's queue and pages the operator channel.// its status() reads back what the operator recorded through the console.//// Consequences worth stating, because they are what makes this honest ratherdiff --git a/api/_lib/print/editions.js b/api/_lib/print/editions.jsindex b8923d59c..eff1b2fbf 100644--- a/api/_lib/print/editions.js+++ b/api/_lib/print/editions.js@@ -10,7 +10,7 @@// - the quote path calls assertEditionAvailable() BEFORE any money moves, so// a sold-out model refuses at the price, never after the payment;// - the certificate issuer claims the next edition number atomically at ship-// time (api/_lib/print/certificate.js) and freezes the cap onto the row;+// time (api/_lib/print/certificate.js) and freezes the cap onto the row,// - the creator sets it through setEditionLimit(), which refuses to cap a// series below what has already shipped.//diff --git a/api/_lib/print/export-3mf.js b/api/_lib/print/export-3mf.jsnew file mode 100644index 000000000..e42eff813--- /dev/null+++ b/api/_lib/print/export-3mf.js@@ -0,0 +1,238 @@+// 3MF: the format that carries the print, not just the shape.+//+// STL is what every bureau accepts; 3MF is what makes a print worth ordering.+// It is an OPC package (a zip with a relationship graph) holding one XML model+// that declares real units, indexed vertices, and per-vertex color through the+// Materials and Properties extension. That last part is the whole reason this+// writer exists: full-color sandstone and binder-jet machines reproduce color+// per vertex, so a generated model whose color lives in a 2K albedo texture can+// only be printed in color if something samples that texture per vertex and+// writes it into the manufacturing file. mesh-io.js does the sampling; this+// module writes it out. A download button that hands over a GLB leaves the+// color behind.+//+// Spec subset, deliberately small and deliberately exact:+// [Content_Types].xml default parts for .rels and .model+// _rels/.rels one 3D-model start-part relationship+// 3D/3dmodel.model unit="millimeter", resources, one build item+//+// The color group is declared in the material namespace but NOT listed in+// `requiredextensions`. A color-capable slicer reads it; a mono slicer ignores+// the attributes and still prints the geometry. Requiring the extension would+// make a monochrome printer reject a file it could have printed.+//+// The 3MF spec puts the build volume in the positive octant, so the mesh is+// translated to sit at the origin corner before it is written.++import { Buffer } from 'node:buffer';+import { zipSync, strToU8 } from 'fflate';++const MM_PER_METER = 1000;++export const CONTENT_TYPES_PART = '[Content_Types].xml';+export const RELS_PART = '_rels/.rels';+export const MODEL_PART = '3D/3dmodel.model';++export const CORE_NAMESPACE = 'http://schemas.microsoft.com/3dmanufacturing/core/2015/02';+export const MATERIAL_NAMESPACE = 'http://schemas.microsoft.com/3dmanufacturing/material/2015/02';+const MODEL_RELATIONSHIP = 'http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel';+const MODEL_CONTENT_TYPE = 'application/vnd.ms-package.3dmanufacturing-3dmodel+xml';+const RELS_CONTENT_TYPE = 'application/vnd.openxmlformats-package.relationships+xml';++// Resource ids. 3MF requires them unique within the model; two constants are+// clearer than a counter for a package that always holds exactly one object.+const COLOR_GROUP_ID = 1;+const OBJECT_ID = 2;++// Coordinates are written at micron resolution. Finer is noise no printer can+// hit, and it keeps the XML (the dominant cost of a 3MF) roughly a third+// smaller than full float printing on a large mesh.+const COORD_DECIMALS = 3;++// The earliest instant a zip's DOS timestamp can express. Used as a constant so+// two exports of one mesh differ in no byte at all.+const ZIP_EPOCH = new Date(Date.UTC(1980, 0, 1));++export class ThreeMfExportError extends Error {+ constructor(code, message) {+ super(message);+ this.name = 'ThreeMfExportError';+ this.code = code;+ }+}++function xmlEscape(value) {+ return String(value)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++// Trim the trailing zeros a fixed-decimal render leaves behind: on a 200k+// triangle mesh that is megabytes of "000".+function coord(value) {+ const fixed = value.toFixed(COORD_DECIMALS);+ return fixed.includes('.') ? fixed.replace(/\.?0+$/, '') || '0' : fixed;+}++function hex2(v) {+ return Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0').toUpperCase();+}++/**+ * Collapse per-vertex RGB into the palette a 3MF colorgroup holds, plus the+ * per-vertex index into it. Identical colors share one entry, which is what+ * keeps a flat-shaded model's group at a handful of colors instead of one per+ * vertex.+ */+export function buildColorGroup(colors, vertexCount) {+ if (!colors || colors.length < vertexCount * 3) return null;+ const palette = [];+ const seen = new Map();+ const indexOf = new Uint32Array(vertexCount);+ for (let v = 0; v < vertexCount; v += 1) {+ const key = `${hex2(colors[v * 3])}${hex2(colors[v * 3 + 1])}${hex2(colors[v * 3 + 2])}`;+ let id = seen.get(key);+ if (id === undefined) {+ id = palette.length;+ seen.set(key, id);+ palette.push(key);+ }+ indexOf[v] = id;+ }+ return { palette, indexOf };+}++function buildModelXml({ positions, indices, colorGroup, scale, metadata }) {+ const vertexCount = positions.length / 3;+ // The positive-octant shift the spec asks for.+ let minX = Infinity;+ let minY = Infinity;+ let minZ = Infinity;+ for (let i = 0; i < positions.length; i += 3) {+ if (positions[i] < minX) minX = positions[i];+ if (positions[i + 1] < minY) minY = positions[i + 1];+ if (positions[i + 2] < minZ) minZ = positions[i + 2];+ }++ const parts = [];+ parts.push('<?xml version="1.0" encoding="UTF-8"?>\n');+ parts.push(+ `<model unit="millimeter" xml:lang="en-US" xmlns="${CORE_NAMESPACE}" xmlns:m="${MATERIAL_NAMESPACE}">`,+ );+ for (const [name, value] of Object.entries(metadata)) {+ if (value === null || value === undefined || value === '') continue;+ parts.push(`<metadata name="${xmlEscape(name)}">${xmlEscape(value)}</metadata>`);+ }+ parts.push('<resources>');+ if (colorGroup) {+ parts.push(`<m:colorgroup id="${COLOR_GROUP_ID}">`);+ for (const hex of colorGroup.palette) parts.push(`<m:color color="#${hex}FF"/>`);+ parts.push('</m:colorgroup>');+ }+ // pid/pindex give the object a default color, so a reader that ignores the+ // per-triangle indices still shows something rather than untextured grey.+ const objectAttrs = colorGroup+ ? `id="${OBJECT_ID}" type="model" pid="${COLOR_GROUP_ID}" pindex="0"`+ : `id="${OBJECT_ID}" type="model"`;+ parts.push(`<object ${objectAttrs}><mesh><vertices>`);+ for (let v = 0; v < vertexCount; v += 1) {+ const x = coord((positions[v * 3] - minX) * scale);+ const y = coord((positions[v * 3 + 1] - minY) * scale);+ const z = coord((positions[v * 3 + 2] - minZ) * scale);+ parts.push(`<vertex x="${x}" y="${y}" z="${z}"/>`);+ }+ parts.push('</vertices><triangles>');+ for (let t = 0; t < indices.length; t += 3) {+ const a = indices[t];+ const b = indices[t + 1];+ const c = indices[t + 2];+ if (colorGroup) {+ parts.push(+ `<triangle v1="${a}" v2="${b}" v3="${c}" p1="${colorGroup.indexOf[a]}" p2="${colorGroup.indexOf[b]}" p3="${colorGroup.indexOf[c]}"/>`,+ );+ } else {+ parts.push(`<triangle v1="${a}" v2="${b}" v3="${c}"/>`);+ }+ }+ parts.push('</triangles></mesh></object>');+ parts.push('</resources>');+ parts.push(`<build><item objectid="${OBJECT_ID}"/></build>`);+ parts.push('</model>');+ return parts.join('');+}++const CONTENT_TYPES_XML =+ '<?xml version="1.0" encoding="UTF-8"?>\n' ++ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">' ++ `<Default Extension="rels" ContentType="${RELS_CONTENT_TYPE}"/>` ++ `<Default Extension="model" ContentType="${MODEL_CONTENT_TYPE}"/>` ++ '</Types>';++const RELS_XML =+ '<?xml version="1.0" encoding="UTF-8"?>\n' ++ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">' ++ `<Relationship Id="rel0" Target="/${MODEL_PART}" Type="${MODEL_RELATIONSHIP}"/>` ++ '</Relationships>';++/**+ * Write a 3MF package.+ *+ * @param {{positions: Float64Array|number[], indices: Uint32Array|number[], colors?: Uint8Array|null}} mesh+ * Indexed triangles in glTF meters; `colors` is per-vertex RGB bytes as+ * mesh-io.js samples them.+ * @param {{scale?: number, color?: boolean, title?: string, designer?: string,+ * description?: string, license?: string}} [opts]+ * @returns {Buffer} the .3mf bytes+ */+export function export3mf(mesh, opts = {}) {+ const positions = mesh?.positions;+ const indices = mesh?.indices;+ if (!positions || !indices || indices.length < 3) {+ throw new ThreeMfExportError('empty_mesh', 'no triangles to export');+ }+ if (indices.length % 3 !== 0) {+ throw new ThreeMfExportError('bad_indices', 'index buffer is not a whole number of triangles');+ }+ const vertexCount = positions.length / 3;+ for (let i = 0; i < indices.length; i += 1) {+ if (indices[i] >= vertexCount) {+ throw new ThreeMfExportError('bad_indices', 'index buffer references a vertex that does not exist');+ }+ }++ const colorGroup = opts.color === false ? null : buildColorGroup(mesh.colors, vertexCount);+ const modelXml = buildModelXml({+ positions,+ indices,+ colorGroup,+ scale: opts.scale ?? MM_PER_METER,+ metadata: {+ Application: 'three.ws Materialize',+ Title: opts.title ?? '',+ Designer: opts.designer ?? '',+ Description: opts.description ?? '',+ LicenseTerms: opts.license ?? '',+ },+ });++ // Deterministic package: a fixed timestamp, one compression level, parts in+ // a fixed order. Two prepares of the same mesh must produce the same bytes,+ // because the print certificate hashes exactly this file. The zip clock only+ // spans 1980-2099, so the DOS epoch stands in for "no time".+ const zipped = zipSync(+ {+ [CONTENT_TYPES_PART]: strToU8(CONTENT_TYPES_XML),+ [RELS_PART]: strToU8(RELS_XML),+ [MODEL_PART]: strToU8(modelXml),+ },+ { level: 6, mtime: ZIP_EPOCH },+ );+ return Buffer.from(zipped);+}++/** Colors survived the round trip only if the group was actually written. */+export function threeMfHasColor(modelXml) {+ return modelXml.includes('<m:colorgroup') && modelXml.includes('<m:color color="#');+}diff --git a/api/_lib/print/gate.js b/api/_lib/print/gate.jsindex cf53ef4ae..f300d7509 100644--- a/api/_lib/print/gate.js+++ b/api/_lib/print/gate.js@@ -41,6 +41,33 @@ export { POLICY_URL };// well under the ~150 mm of the shortest real handgun.export const MINIATURE_MAX_MM = 120;+// The generation classifier's categories this gate honours, with the message+// rewritten in the fabrication voice (its own copy says "This 3D Studio",+// which is the wrong product to name when someone is buying an object). Its+// `weapon_drug` category is deliberately absent: see screenDeterministic().+const UPSTREAM_CATEGORIES = Object.freeze({+ csam: {+ label: 'prohibited content',+ message: 'This request is not allowed.',+ allowed: null,+ },+ sexual: {+ label: 'adult content',+ message: 'three.ws does not manufacture sexual or adult content.',+ allowed: 'Characters, creatures and figures without explicit themes are fine.',+ },+ gore: {+ label: 'graphic violence',+ message: 'three.ws does not manufacture graphically violent or gore content.',+ allowed: 'Describe the same subject without the graphic detail and it can be printed.',+ },+ hate: {+ label: 'hateful or extremist iconography',+ message: 'three.ws does not manufacture hateful or extremist content or iconography.',+ allowed: 'Original designs, historical subjects without the iconography, and ordinary symbols are fine.',+ },+});+const SCREENING_SYSTEM = `You review 3D models that a manufacturing service is about to physically print.Refuse only these categories:- firearm components or anything that becomes part of a working firearm@@ -148,19 +175,30 @@ function refusal({ category, label, message, allowed, layer, matched = null }) {export function screenDeterministic({ subject, analysis = null }) {const geometry = geometrySignal(analysis);- // Layer 1: whatever the generation gate would have refused, fabrication- // refuses too. A mesh that should never have been generated must never be- // manufactured, including one generated before that gate covered its terms.+ // Layer 1: the generation content classifier, for the categories whose+ // answer does not depend on what is being made out of the mesh.+ //+ // Generation verdicts are not persisted anywhere (checkPromptSafety refuses+ // inline in api/3d/studio.js and api/_mcp-studio/tools.js and stores+ // nothing), and the main /forge lane never called it at all, so this is a+ // re-evaluation of the lineage rather than a lookup. Only the four+ // scale-independent categories are honoured: the classifier's fifth,+ // `weapon_drug`, refuses the bare word "pistol", which would refuse every+ // tabletop miniature carrying one. Weapons and drug paraphernalia are owned+ // by the fabrication rules below, which distinguish a display piece from a+ // working part; deferring to a 13+ chat-app word list here would make that+ // distinction unreachable.const upstream = checkPromptSafety(subject);- if (!upstream.allowed) {+ if (!upstream.allowed && UPSTREAM_CATEGORIES[upstream.category]) {+ const mapped = UPSTREAM_CATEGORIES[upstream.category];return {decision: refusal({category: `generation_${upstream.category}`,- label: 'generation content policy',+ label: mapped.label,layer: 'upstream',matched: upstream.matched || null,- message: upstream.message,- allowed: 'Describe a character, creature, prop or object without that theme and generate it again.',+ message: mapped.message,+ allowed: mapped.allowed,}),layers: {upstream: { verdict: 'refuse', category: upstream.category, matched: upstream.matched || null },@@ -348,21 +386,27 @@ export async function runFabricationGate({};}+ const softFlags = deterministic.layers.denylist.soft || [];const llm = await screenWithLlm({subject,geometry: deterministic.layers.geometry,- softRules: deterministic.layers.denylist.soft || [],+ softRules: softFlags,});if (llm.verdict === 'refuse') {// The model may name a category the denylist knows; when it does, the// buyer gets that rule's written message and its "what is allowed"// sentence rather than raw model prose.+ // The model is asked for a rule id but free models routinely answer with a+ // sentence. Only a category the denylist actually knows is kept as the+ // category; anything else is recorded as the model's `reason` and the+ // order is refused under the general policy, so a stored verdict always+ // carries a slug a UI and a report can group on.const known = ruleById(llm.category);return {...base,verdict: 'refuse',- category: llm.category || 'fabrication_policy',+ category: known ? known.id : 'fabrication_policy',label: known?.label || 'fabrication content policy',layer: 'llm',matched: null,@@ -374,6 +418,20 @@ export async function runFabricationGate({}if (llm.verdict === 'review') {+ // An unreachable model must not hold an order the deterministic layers+ // had no question about: that order already cleared the same bar its+ // quote cleared, and paging an operator for every teapot during a+ // provider outage trains them to ignore the channel. Only a request the+ // denylist deliberately left undecided (a soft rule) is held.+ if (softFlags.length === 0) {+ return {+ ...base,+ verdict: 'allow',+ category: null,+ message: null,+ layers: { ...deterministic.layers, llm },+ };+ }return {...base,verdict: 'review',diff --git a/api/_lib/print/ops-auth.js b/api/_lib/print/ops-auth.jsindex 0da9c2b03..0a70871a5 100644--- a/api/_lib/print/ops-auth.js+++ b/api/_lib/print/ops-auth.js@@ -81,7 +81,7 @@ export async function authorizeOperator(req) {}}} catch {- /* no or invalid session — fall through to the secret door */+ /* no or invalid session: fall through to the secret door */}const secret = process.env.OPS_SECRET;diff --git a/api/_lib/print/quote.js b/api/_lib/print/quote.jsindex 3fe411d79..bca57f105 100644--- a/api/_lib/print/quote.js+++ b/api/_lib/print/quote.js@@ -100,6 +100,60 @@ function unitPhysicals({ report, material, scale, volumeCm3, catalog }) {};}+/**+ * The heights at which THIS mesh can actually be printed in THIS material.+ *+ * The catalog's own min/max are a property of the machine; this narrows them by+ * the two properties of the mesh: its widest axis has to fit the bed, and its+ * thinnest wall has to survive at the chosen scale. The /materialize size slider+ * is bounded by this, which is why a buyer moving it never lands on a rejection+ * they could not have predicted.+ *+ * `limitedBy` names which constraint bit, so the UI can label the end of the+ * track ("as tall as the bed allows") instead of just stopping.+ *+ * @returns {{ minHeightMm: number, maxHeightMm: number, feasible: boolean,+ * limitedBy: { min: string, max: string } }}+ */+export function fitHeightRange({ report, material }) {+ const heightMm = report?.bbox_mm?.y;+ if (!(heightMm > 0)) {+ return { minHeightMm: material.minHeightMm, maxHeightMm: material.maxHeightMm, feasible: false, limitedBy: { min: 'material', max: 'material' } };+ }++ let minHeightMm = material.minHeightMm;+ let minLimit = 'material';+ // Wall thickness scales linearly with height, so the smallest printable height+ // is the one where the thinnest measured wall reaches the material's minimum.+ if (report.min_wall_mm > 0) {+ const wallFloor = (material.minWallMm / report.min_wall_mm) * heightMm;+ if (wallFloor > minHeightMm) {+ minHeightMm = wallFloor;+ minLimit = 'wall';+ }+ }++ let maxHeightMm = material.maxHeightMm;+ let maxLimit = 'material';+ for (const axis of ['x', 'z']) {+ const span = report.bbox_mm?.[axis];+ if (!(span > 0)) continue;+ // Uniform scale: the height at which this axis exactly fills the bed.+ const cap = (material.maxBoundingBoxMm[axis] / span) * heightMm;+ if (cap < maxHeightMm) {+ maxHeightMm = cap;+ maxLimit = 'build_volume';+ }+ }++ return {+ minHeightMm: round(minHeightMm, 1),+ maxHeightMm: round(maxHeightMm, 1),+ feasible: maxHeightMm >= minHeightMm,+ limitedBy: { min: minLimit, max: maxLimit },+ };+}+/*** Every reason a mesh cannot be printed in a material, with the fix attached.* A rejection that only says "no" makes the buyer guess; each one here names the@@ -133,10 +187,17 @@ function constraintFailures({ report, material, targetHeightMm, scale }) {for (const axis of ['x', 'z']) {const value = report.bbox_mm[axis] * scale;if (value > box[axis]) {+ // The fix is a number, not an instruction to fiddle: the tallest this+ // model can be printed in this material before its widest axis runs out+ // of bed. A slider that already clamps to fitHeightRange() rarely lands+ // here, but a deep link or an agent request can.+ const fits = Math.floor(fitHeightRange({ report, material }).maxHeightMm);failures.push({code: 'exceeds_build_volume',message: `At this size the model is ${round(value, 1)} mm across, over the ${box[axis]} mm build volume for ${material.name}.`,- fix: 'Reduce the size, or choose a material with a larger build volume.',+ fix: fits >= material.minHeightMm+ ? `Print it at ${fits} mm tall or under, or choose a material with a larger build volume.`+ : 'This model is too wide for this material at any printable height; choose a material with a larger build volume.',measured: round(value, 1),required: box[axis],});@@ -164,6 +225,38 @@ function constraintFailures({ report, material, targetHeightMm, scale }) {return failures;}+/**+ * Every material measured against THIS mesh: the height range it can actually be+ * printed at, and, when none exists, the reason in the buyer's words.+ *+ * The /materialize material cards render straight off this, so a card that cannot+ * take the model says why on its face rather than failing after it is clicked.+ */+export function materialFits({ report, catalog = loadCatalog() }) {+ return catalog.materials.map((material) => {+ const fit = fitHeightRange({ report, material });+ let blocked = null;+ if (material.requiresTexture && !report.has_textures) {+ blocked = `${material.name} prints the model's own colours, and this model has no texture.`;+ } else if (!fit.feasible) {+ blocked = fit.limitedBy.max === 'build_volume'+ ? `This model is too wide for the ${material.name} build volume at any height that keeps its walls printable.`+ : `This model cannot hold a ${material.minWallMm} mm wall anywhere in the ${material.minHeightMm} to ${material.maxHeightMm} mm range ${material.name} prints.`;+ }+ return {+ id: material.id,+ name: material.name,+ class: material.class,+ minHeightMm: fit.minHeightMm,+ maxHeightMm: fit.maxHeightMm,+ limitedBy: fit.limitedBy,+ quoteOnRequest: Boolean(material.quoteOnRequest),+ hollowSupported: Boolean(material.hollow?.supported),+ blocked,+ };+ });+}+/*** Materials that would accept this mesh at this height. A rejection hands the* buyer this list so the next click is a working order rather than a retry.diff --git a/api/print/catalog.js b/api/print/catalog.jsindex c22b44a6e..07a060747 100644--- a/api/print/catalog.js+++ b/api/print/catalog.js@@ -1,4 +1,4 @@-// GET /api/print/catalog — the Materialize price list, as data.+// GET /api/print/catalog: the Materialize price list, as data.//// Everything a buyer or an agent needs to build a valid quote request: the// materials with their real constraints (minimum wall, build volume, lead time),diff --git a/api/print/certs/[id].js b/api/print/certs/[id].jsindex 2a5987d65..68e87dca7 100644--- a/api/print/certs/[id].js+++ b/api/print/certs/[id].js@@ -1,5 +1,5 @@/**- * GET /api/print/certs/:id — one Materialize certificate, publicly readable.+ * GET /api/print/certs/:id: one Materialize certificate, publicly readable.** A certificate is a public proof by design: the QR printed on the box has to* resolve for whoever is holding the box, which is frequently not the buyer anddiff --git a/api/print/ops/[action].js b/api/print/ops/[action].jsindex 87c45f806..0b465c193 100644--- a/api/print/ops/[action].js+++ b/api/print/ops/[action].js@@ -108,7 +108,7 @@ function queueRow(order) {// ── order detail ─────────────────────────────────────────────────────────────-/** GET /api/print/ops/order?id=… — everything needed to run one job. */+/** GET /api/print/ops/order?id=…: everything needed to run one job. */async function handleOrderDetail(req, res) {const order = await loadOrder(req, res);if (!order) return;@@ -311,7 +311,7 @@ async function handleRefund(req, res, operator) {});}-/** GET /api/print/ops/adapters — the lanes this deployment can route to. */+/** GET /api/print/ops/adapters: the lanes this deployment can route to. */async function handleAdapters(_req, res) {return json(res, 200, { adapters: adapterSummaries() });}diff --git a/api/print/quote.js b/api/print/quote.jsnew file mode 100644index 000000000..a61d2c231--- /dev/null+++ b/api/print/quote.js@@ -0,0 +1,177 @@+// POST /api/print/quote: printability and price for a real print, in one call.+//+// The /materialize page asks this endpoint every time the buyer changes a+// material, a size or a quantity, so it does two things at once:+//+// 1. Analyzes the mesh (api/_lib/print/analyze.js) and returns the printability+// report: manifold, shells, open edges, the thinnest wall, the volume money+// hangs off, and a score with named deductions.+// 2. Prices it (api/_lib/print/quote.js) and returns the itemization plus an+// HMAC-signed quote token that checkout later charges against.+//+// Omit `materialId` and it is a pure analyze call: free, keyless, no price. That+// is the shape an agent uses to decide whether a mesh is worth printing at all.+//+// Why the server analyzes rather than accepting a client-supplied report: the+// volume in that report IS the price. A report that arrived in the request body+// would let a caller quote a 200 cm3 figure at 2 cm3. The analysis is cached per+// source URL for the life of the process, so dragging the size slider re-prices+// against an already-parsed mesh and never re-downloads it.+//+// Every number here comes from the quote engine. No price is computed anywhere+// else, in this file or in any frontend module.++import { createHash } from 'node:crypto';++import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { getSessionUser } from '../_lib/auth.js';+import { createCache, cached } from '../_lib/mem-cache.js';+import { loadMeshFromUrl, MeshIoError } from '../_lib/print/mesh-io.js';+import { analyzeMesh } from '../_lib/print/analyze.js';+import { loadCatalog, materialFits, quotePrint, signQuote } from '../_lib/print/quote.js';+import { getPublicCreation } from '../_lib/forge-store.js';+import { holderDiscountBps } from '../_lib/three-tier.js';++// One analysis per source model, held for an hour. The report is deterministic+// for given bytes, so a cache hit is the same answer the analysis would produce,+// and a model whose URL content changed gets a new URL from the forge anyway.+const reports = createCache({ max: 256, ttlMs: 60 * 60 * 1000 });++// MeshIoError codes carry their own correct HTTP status: a mesh that is too big+// is the caller's input, not our failure, and a fetch that died upstream is a 502.+const MESH_ERROR_STATUS = {+ invalid_model: 422,+ no_geometry: 422,+ too_large: 413,+ too_complex: 413,+ invalid_url: 400,+ fetch_failed: 502,+};++function reportHashOf(report) {+ return createHash('sha256')+ .update(JSON.stringify([report.version, report.volume_cm3, report.bbox_mm, report.min_wall_mm, report.triangles]))+ .digest('hex')+ .slice(0, 32);+}++async function resolveSource(body) {+ const creationId = typeof body.creationId === 'string' ? body.creationId.trim() : '';+ if (creationId) {+ const creation = await getPublicCreation({ id: creationId });+ if (!creation) return { error: { status: 404, code: 'creation_not_found', message: 'No finished public creation with that id.' } };+ if (!creation.glb_url) return { error: { status: 409, code: 'creation_has_no_model', message: 'That creation has no finished model to print yet.' } };+ return {+ url: creation.glb_url,+ creationId: creation.id,+ creation: {+ id: creation.id,+ prompt: creation.prompt,+ preview_image_url: creation.preview_image_url ?? null,+ model_category: creation.model_category ?? null,+ creator_username: creation.creator_username ?? null,+ },+ };+ }+ const glbUrl = typeof body.glbUrl === 'string' ? body.glbUrl.trim() : '';+ if (!glbUrl) {+ return { error: { status: 400, code: 'validation_error', message: 'Pass a creationId or a glbUrl to print.' } };+ }+ return { url: glbUrl, creationId: null, creation: null };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const rate = await limits.printQuoteIp(clientIp(req));+ if (!rate.success) return rateLimited(res, rate, 'too many quote requests');++ const body = await readJson(req, 8_000).catch(() => null);+ if (!body || typeof body !== 'object') {+ return error(res, 400, 'validation_error', 'a JSON body is required');+ }++ const source = await resolveSource(body);+ if (source.error) {+ return error(res, source.error.status, source.error.code, source.error.message);+ }++ let report;+ try {+ report = await cached(reports, source.url, async () => {+ const mesh = await loadMeshFromUrl(source.url);+ return analyzeMesh(mesh, { sourceUrl: source.url });+ });+ } catch (err) {+ if (err instanceof MeshIoError) {+ return error(res, MESH_ERROR_STATUS[err.code] ?? 422, err.code, err.message, err.extra || {});+ }+ throw err;+ }++ const catalog = loadCatalog();+ const base = {+ report,+ creation: source.creation,+ sourceUrl: source.url,+ reportHash: reportHashOf(report),+ // Every material measured against this mesh: the height band it can be+ // printed at, or the reason it cannot. The page builds its material cards+ // and bounds its size slider from this, so a buyer never drags into a+ // rejection the server could have predicted.+ fits: materialFits({ report, catalog: loadCatalog() }),+ };++ // No material chosen: this is the analyze call. Free, keyless, no price.+ if (!body.materialId) return json(res, 200, base, { 'cache-control': 'no-store' });++ // The holder discount reads the signed-in user's $THREE tier. Anonymous+ // buyers quote at list price and the panel says so, rather than showing a+ // discount they cannot claim at checkout.+ const user = await getSessionUser(req).catch(() => null);+ const discountBps = user ? await holderDiscountBps(user) : 0;++ const priced = quotePrint({+ report,+ materialId: String(body.materialId),+ finishId: body.finishId ? String(body.finishId) : null,+ targetHeightMm: Number(body.targetHeightMm),+ quantity: Number(body.quantity) || 1,+ country: body.country,+ hollow: Boolean(body.hollow),+ holderDiscountBps: discountBps,+ catalog,+ });++ if (!priced.ok) {+ // A rejection is guidance, not an error: it names the measured number, the+ // required number, the fix, and every material that would take this mesh.+ return json(res, 200, { ...base, quote: null, rejection: priced.rejection }, { 'cache-control': 'no-store' });+ }++ // A quote-on-request material (metal) is priced as an estimate and gets no+ // token: nothing can be checked out at a number an engineer has not confirmed.+ const token = priced.quote.quoteOnRequest+ ? null+ : signQuote(priced.quote, {+ reportHash: base.reportHash,+ sourceUrl: source.url,+ creationId: source.creationId,+ });++ return json(+ res,+ 200,+ {+ ...base,+ quote: priced.quote,+ rejection: null,+ token,+ holderTierApplied: discountBps > 0,+ expiresInSeconds: token ? catalog.pricing.quoteTtlSeconds : null,+ },+ { 'cache-control': 'no-store' },+ );+});diff --git a/api/print/webhook/[provider].js b/api/print/webhook/[provider].jsindex e7a8c9465..94df7ecf5 100644--- a/api/print/webhook/[provider].js+++ b/api/print/webhook/[provider].js@@ -1,5 +1,5 @@// @ts-check-// POST /api/print/webhook/:provider — a fulfillment provider reporting in.+// POST /api/print/webhook/:provider: a fulfillment provider reporting in.//// Three properties, in the order they are enforced://diff --git a/prompts/store-submissions/_generated/TRACKER.md b/prompts/store-submissions/_generated/TRACKER.mdindex b1d1304ee..a1abcbae9 100644--- a/prompts/store-submissions/_generated/TRACKER.md+++ b/prompts/store-submissions/_generated/TRACKER.md@@ -1,6 +1,6 @@# three.ws Store Submission Tracker-Last updated: 2026-09-02 (tool-count reconciliation: the free studio connector serves **eleven** tools live, not the nine or ten quoted around the repo. `look_at_model` landed 2026-08-28 and `check_job` before it, and every count, listing table, annotation table, announcement document and social card is now reconciled against a fresh `tools/list` pull, with `tests/mcp-studio.test.js` pinning the total so the next tool cannot re-open the drift. Also re-verified live the same day: `/.well-known/3d-studio-openapi.yaml`, `/.well-known/ai-plugin.json`, `/legal/privacy`, `/legal/tos` and `/support` all return 200, and `resources/list` returns the two widget resources. Dated notes below are kept as the record of what was true when written.) Prior: 2026-07-15 (live re-verification of the Claude Connectors free-lane blocker: production `POST /api/mcp-studio tools/call forge_free` returned HTTP 200 in 16.1s with a real 1,553,784-byte GLB (`glTF` magic, served from `/cdn/forge/anon/…`), and the emitted `/viewer?src=` link returned 200. The 2026-07-08 90-100s hang no longer reproduces; the Connectors package is clear to file once the two `[HUMAN:]` items in its row (org/portal access, `MCP_REVIEW_SECRET` + reviewer-credential decision) are done.) Prior: 2026-07-14 (owner CREATED the GPT Store GPT — URL recorded in its row; store visibility still to confirm. Same day: verified organization confirmed on platform.openai.com; submission package finalized with support contact, privacy URL, and the live 9-tool surface; fresh E2E on both the MCP studio and the Actions lane). Prior: 2026-07-10 Track G build-status reconciliation. Re-run prompt 14 near the end to refresh status.+Last updated: 2026-09-02 (tool-count reconciliation: the free studio connector serves **eleven** tools live, not the nine or ten quoted around the repo. `look_at_model` landed 2026-08-28 and `check_job` before it, and every count, listing table, annotation table, announcement document and social card is now reconciled against a fresh `tools/list` pull, with `tests/mcp-studio.test.js` pinning the total so the next tool cannot re-open the drift. Also re-verified live the same day: `/.well-known/3d-studio-openapi.yaml`, `/.well-known/ai-plugin.json`, `/legal/privacy`, `/legal/tos` and `/support` all return 200, and `resources/list` returns the two widget resources. Dated notes below are kept as the record of what was true when written.) Prior: 2026-07-15 (live re-verification of the Claude Connectors free-lane blocker: production `POST /api/mcp-studio tools/call forge_free` returned HTTP 200 in 16.1s with a real 1,553,784-byte GLB (`glTF` magic, served from `/cdn/forge/anon/…`), and the emitted `/viewer?src=` link returned 200. The 2026-07-08 90-100s hang no longer reproduces; the Connectors package is clear to file once the two `[HUMAN:]` items in its row (org/portal access, `MCP_REVIEW_SECRET` + reviewer-credential decision) are done.) Prior: 2026-07-14 (owner CREATED the GPT Store GPT: URL recorded in its row; store visibility still to confirm. Same day: verified organization confirmed on platform.openai.com; submission package finalized with support contact, privacy URL, and the live 9-tool surface; fresh E2E on both the MCP studio and the Actions lane). Prior: 2026-07-10 Track G build-status reconciliation. Re-run prompt 14 near the end to refresh status.**Last verified: 2026-07-10** — method: direct code read of every prompt-17–21 implementation file plus its wiring, and a live run of the Track-G/16 suites. `npx vitest run tests/spatial-mcp.test.js tests/provenance-3d.test.js tests/ar-export.test.js tests/embed-gate.test.js tests/mcp3d-persona-identity.test.js tests/tokenize-3d.test.js` → **6 files / 98 tests, all passing** (spatial-mcp 22, provenance-3d 20, ar-export 13, embed-gate 20, mcp3d-persona-identity 8, tokenize-3d 15). Confirmed the five new 3D-Studio tool groups are wired into `api/_mcp3d/catalog.js` (`spatialDefs`, `arDefs`, `provenanceDefs`, `personaIdentityDefs` — lines 7–10, 25) and `create_gated_embed` into `api/_mcp/catalog.js` (line 13/21). Confirmed the P0 `readBody` fix is present in the tree (commit `ba37182f3`).@@ -36,7 +36,7 @@ Legend: **not-started** | **blocked** | **ready-to-submit** | **submitted** | **| 14 | Cross-store asset kit | ✅ complete | `_generated/assets/`, `listing-copy.md`, `TRACKER.md` || 02 | Claude reviewer access guide | ✅ complete (shipped 2026-06-25; re-audited + closed out 2026-07-08) | `_generated/claude-reviewer-guide.md` + `_generated/claude-tool-call-evidence.md` (16/16 paid tools clean `PaymentRequired`; review-mode entitlement is real code in `mcp-server/src/payments.js`) || 03 | Claude submission package | ⬜ not started | `_generated/claude-submission.md` (exists from earlier run — verify/refresh) |-| 04 | OpenAI free 3D endpoint | 🟨 code-complete, was blocked on the P0 hang | `api/mcp-studio.js` + `api/_mcp-studio/*` — 11 tools live as of 2026-09-02 (6 generation incl. `refine_model`, the `check_job` collector, the `look_at_model` inspector, 3 persona), real rate limiting (`api/_lib/rate-limit.js`: `studioGenBurst`, `studioGenHourly`, `studioPersonaWrite`, `studioGenerateGlobal`), zero coin surface (grep-clean), 42/42 tests pass (`tests/mcp-studio*.test.js`, re-run 2026-09-02). `server-studio.json` description corrected (was stale "five tools"). Blocked end-to-end verification on the P0 `readBody` hang (code fix landed, commit `ba37182f3`; prod re-verification remains) and the `/viewer?src=` 404 (dist/viewer.html exists and the vercel.json rewrite is correct — likely just stale on the previously-deployed container; re-verify against the live revision) |+| 04 | OpenAI free 3D endpoint | 🟨 code-complete, was blocked on the P0 hang | `api/mcp-studio.js` + `api/_mcp-studio/*`: 11 tools live as of 2026-09-02 (6 generation incl. `refine_model`, the `check_job` collector, the `look_at_model` inspector, 3 persona), real rate limiting (`api/_lib/rate-limit.js`: `studioGenBurst`, `studioGenHourly`, `studioPersonaWrite`, `studioGenerateGlobal`), zero coin surface (grep-clean), 42/42 tests pass (`tests/mcp-studio*.test.js`, re-run 2026-09-02). `server-studio.json` description corrected (was stale "five tools"). Blocked end-to-end verification on the P0 `readBody` hang (code fix landed, commit `ba37182f3`; prod re-verification remains) and the `/viewer?src=` 404 (dist/viewer.html exists and the vercel.json rewrite is correct: likely just stale on the previously-deployed container; re-verify against the live revision) || 05 | OpenAI Apps SDK component | ✅ complete (prior session) | GLB viewer component; hero screenshot || 06 | OpenAI submission package | 🟨 package complete, verdict was NOT READY on B1/B2 | `_generated/openai-submission.md` (7/7 policy PASS, real screenshots, real captured tool responses with no PII/internal-ID leakage). Its own §0 verdict cites B1 (rate-limiter hang — this was actually the P0 `readBody` bug, not a quota issue; code fix landed, commit `ba37182f3`) and B2 (`/viewer` 404). Re-run the doc's verification steps against the live production revision before treating this as ready-to-submit || 07 | Embodied live agent avatar | 🟨 code-complete, live demo was blocked by the P0 hang | `create_agent_persona`/`get_agent_persona`/`persona_say` (`api/_mcp-studio/persona-tools.js`, mirrored in `api/_mcp3d/tools/studio.js`), real Postgres+R2 persistence (`api/_lib/persona-store.js`, not in-memory), real viseme/lip-sync cascade + emotion→clip mapping + idle loop (`apps-sdk/embodiment/embodiment-stage.js`, `src/embodiment/*`), never-T-pose fallback gate. 67/67 tests pass. Evidence (6 real rendered screenshots) in `_generated/embodiment/` — captured locally (`npm run dev`), not yet re-confirmed against redeployed prod |diff --git a/prompts/store-submissions/_generated/openai-submission.md b/prompts/store-submissions/_generated/openai-submission.mdindex f2a38d3c9..e9da4e568 100644--- a/prompts/store-submissions/_generated/openai-submission.md+++ b/prompts/store-submissions/_generated/openai-submission.md@@ -417,14 +417,14 @@ curl -s -X POST https://three.ws/api/mcp-studio -H 'content-type: application/js- [x] App discovery schema served + guarded — `/.well-known/3d-studio-openapi.yaml`, free-only,`security: []`, byte-identical to the custom-GPT Action file, crypto/payment-free(`tests/api/3d-studio-openapi.test.js`).-- [x] Served discovery schema is live — `https://three.ws/.well-known/3d-studio-openapi.yaml` returns+- [x] Served discovery schema is live: `https://three.ws/.well-known/3d-studio-openapi.yaml` returns200 in production, as do `/.well-known/ai-plugin.json`, `/legal/privacy`, `/legal/tos` and`/support` (re-verified 2026-09-02).- [ ] Screenshots — **re-capture the landscape widget shots against the shipped inline widget**(`api/_mcp-studio/component.js`); the earlier standalone-viewer captures were removed as part ofcollapsing the duplicate viewers. Confirm the form's required dimensions. `[HUMAN]`- [x] Compliance audit: 7/7 policy items PASS (§2), with the review-surface separation documented (§2.1a).-- [x] Listing metadata drafted (§1) — tool list is the live 11-tool surface (re-pulled 2026-09-02);+- [x] Listing metadata drafted (§1): tool list is the live 11-tool surface (re-pulled 2026-09-02);`forge_free` tier note corrected to the honest standard default (2026-07-18).- [x] MCP connectivity documented (§3).- [x] Reviewer guide written (§5).