Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import sharp from 'sharp';
import { imageRecord } from './generate-commons.mjs';
import { readJson, writeJson, writeMirrorFile, upsertBy, sha256Hex } from './media-pins.mjs';
import { ASSET_BASE, verifyArchive, verifyBytes } from './mirror-core.mjs';
const site = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const commons = process.env.KILN_COMMONS_DIR;
if (!commons) throw new Error('Set KILN_COMMONS_DIR');
const data = join(site, 'src/data');
const mirror = process.env.KILN_ASSET_MIRROR ?? join(site, '.cache/round-4/mirror');
const review = join(commons, 'engine-work/local-v09-review/revision2-20260930');
const bundle = join(review, 'vehicles-runtime');
const author = join(commons, 'showcase/authors/codex-review2-asset-repairs');
const catalog = await readJson(join(review, 'inputs/vehicles-r2.json'));
const inventory = await readJson(join(bundle, 'delivery.json'));
const measurements = await readJson(join(bundle, 'measurements.json'));
const authorRunBytes = await readFile(join(author, 'delivery/VEHICLE-AUTHOR-RUN.json'));
if (sha256Hex(authorRunBytes) !== '594736b61d05bd42ad60aca561428e554f00dadf8dfdfbe215b62e167540e9e8') throw new Error('Author run receipt changed');
const authorRun = JSON.parse(authorRunBytes);
const release = inventory.release;
const prefix = `packs/vehicles/${release}`;
const archivePath = `${prefix}/generic-road-vehicles-runtime.zip`;
let manifest = await readJson(join(data, 'mirror-manifest.json'));
const plan = await readJson(join(data, 'commons-build.json'));
const pin = async (path, bytes) => {
const record = await writeMirrorFile(mirror, path, bytes);
manifest.files = upsertBy(manifest.files, 'path', record);
return record;
};
for (const [member, expected] of Object.entries(inventory.files)) await pin(`${prefix}/${member}`, verifyBytes(await readFile(join(bundle, member)), expected, member));
await pin(`${prefix}/delivery.json`, await readFile(join(bundle, 'delivery.json')));
const zip = await readFile(join(bundle, 'generic-road-vehicles-runtime.zip'));
verifyArchive(zip, 'delivery');
const zipPin = await pin(archivePath, zip);
for (const asset of catalog.assets) {
const saved = inventory.assets.find((entry) => entry.slug === asset.slug);
if (!saved) throw new Error(`Missing ${asset.slug}`);
const measured = measurements[asset.slug];
asset.runtimeDownload = { ...asset.runtimeDownload, ...inventory.files[saved.model], path: `${prefix}/${saved.model}`, url: `${ASSET_BASE}${prefix}/${saved.model}`, archive: archivePath };
asset.licence = { ...asset.licence, ...inventory.files[saved.licence], path: `${prefix}/${saved.licence}`, url: `${ASSET_BASE}${prefix}/${saved.licence}`, statesDeliveredGlbSha256: asset.runtimeDownload.sha256 };
plan.models = upsertBy(plan.models, 'output', { path: asset.runtimeDownload.path, output: asset.modelPath.slice(1), bytes: asset.runtimeDownload.bytes, sha256: asset.runtimeDownload.sha256 });
if (!saved.changed) continue;
const priorRevision = asset.revisionId;
const savedDir = join(author, 'assets/kiln', asset.assetId, 'revisions', saved.revisionId);
const savedManifest = await readJson(join(savedDir, 'manifest.json'));
const source = verifyBytes(await readFile(join(savedDir, 'source.kiln.js')), savedManifest.files['source.kiln.js'], `${asset.slug} source`);
const preview = verifyBytes(await readFile(join(savedDir, 'preview.png')), savedManifest.files['preview.png'], `${asset.slug} review`);
const editable = await readFile(join(author, 'delivery', asset.slug, 'editable.zip'));
const parsed = verifyArchive(editable, 'editable');
if (parsed.manifest.revisionId !== saved.revisionId || parsed.manifest.assetId !== asset.assetId) throw new Error(`Wrong editable identity: ${asset.slug}`);
const editablePin = await pin(`${prefix}/editable/${asset.slug}-editable.zip`, editable);
const previewPin = await pin(`media/vehicles/${release}/review/${asset.slug}.png`, preview);
const size = await sharp(preview).metadata();
asset.reviewImage = { ...imageRecord(previewPin.path, size.width, size.height, `Saved review views of ${asset.name}.`), sourceRevisionId: saved.revisionId, exactRevision: true, fidelity: savedManifest.preview?.fidelity };
asset.poster = { ...asset.poster, exactRevision: false, revisionQualification: 'Earlier accepted parent revision; a new child poster is pending.' };
asset.parentRevision = priorRevision;
asset.revisionId = saved.revisionId;
const drawn = measured.drawnByPlainLoader;
const parts = [...measured.tiers[0].parts, ...measured.wheels.flatMap((wheel) => wheel.parts)];
asset.metrics = { triangles: drawn.triangles, meshes: parts.length, materials: drawn.materials.length, bounds: drawn.bounds.size, boundsMin: drawn.bounds.min, boundsMax: drawn.bounds.max, clips: measured.animations, partPaths: parts };
asset.tiers = measured.tiers.map((tier, index) => ({ ...asset.tiers[index], bodyTriangles: tier.bodyTriangles, wheelTriangles: tier.wheelTriangles, triangles: tier.triangles, wheelsShown: tier.wheelsShown, bounds: tier.bounds.size, coverageBelow: tier.coverageBelow, distanceMetres: tier.distanceMetres, parts: tier.parts.length, materials: tier.materials }));
asset.sourceSha256 = sha256Hex(source);
asset.editableDownload = { ...asset.editableDownload, ...editablePin, url: `${ASSET_BASE}${editablePin.path}`, glbForm: 'MSFT_lod' };
const revision = { stage: 'Owner review 2 · rear lamp repair', request: 'owner-review-2', revisionId: saved.revisionId, parentRevisionId: priorRevision, savedAt: savedManifest.createdAt, brief: savedManifest.description, model: 'GPT-6 Astra', modelId: authorRun.requestedModel, savedModelLabel: savedManifest.attribution.model, requestedEffort: authorRun.requestedEffort, confirmedEffort: null, harness: authorRun.harness, harnessVersion: authorRun.harnessVersion, confirmation: authorRun.attributionNote, run: { stage: authorRun.stage, label: authorRun.label, status: authorRun.status, stop: authorRun.stop, startedAt: authorRun.startedAt, endedAt: authorRun.endedAt, receiptSha256: sha256Hex(authorRunBytes), invocationSha256: authorRun.sessionRecordSha256 } };
asset.revisions.push(revision);
asset.provenance.history.push(revision);
asset.provenance.refinementModels.push('GPT-6 Astra');
asset.review = { status: 'awaiting-owner-review', ownerAccepted: false, scope: 'A preserved child revision repairs rear lamp fit across the existing detail tiers. The previous revision remains preserved; owner acceptance of this child is pending.', correction: `${asset.name}: rear lamp fit repaired in a new revision; awaiting owner review.`, recordedAt: '2026-10-01', source: 'Local owner review 2 repair receipt and exact saved child manifest' };
const sourceMember = Object.keys(parsed.files).find((path) => path.endsWith('/source.kiln.js'));
if (!sourceMember) throw new Error(`No editable source: ${asset.slug}`);
plan.sources = upsertBy(plan.sources, 'output', { archive: editablePin.path, member: sourceMember, output: asset.sourcePath.slice(1), bytes: source.length, sha256: asset.sourceSha256 });
plan.archives = [...new Set([...plan.archives, editablePin.path])];
plan.images = upsertBy(plan.images, 'inputPath', asset.reviewImage);
}
catalog.release = release;
catalog.downloads = [{ ...catalog.downloads[0], ...zipPin, path: archivePath, url: `${ASSET_BASE}${archivePath}` }];
catalog.ownerReview = { acceptedAssets: 3, total: 6, status: 'three-preserved-three-awaiting-review', date: '2026-10-01', statement: 'Three unchanged vehicle revisions retain their recorded acceptance. Hatchback, sedan and SUV have new rear-light repairs awaiting owner review.', source: 'Local owner review 2', awaiting: ['hatchback', 'sedan', 'suv'] };
catalog.licenceNote = 'Each licence text names the exact delivered revision and GLB hash. New repair revisions preserve the prior CC0-1.0 scope and parent identity; unchanged vehicles retain their prior licence text.';
await writeJson(join(data, 'packs/vehicles.json'), catalog);
await writeJson(join(data, 'commons-build.json'), plan);
await writeJson(join(data, 'mirror-manifest.json'), manifest);
await mkdir(join(review, 'vehicles-site-intake'), { recursive: true });
await writeFile(join(review, 'vehicles-site-intake/catalog.json'), `${JSON.stringify(catalog, null, 2)}\n`);
console.log(JSON.stringify({ release, assets: catalog.assets.length, pendingOwnerReview: catalog.ownerReview.awaiting, next: 'Render exact child rig posters, then fetch-mirror and rebuild.' }));