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,lstat,realpath} from 'node:fs/promises';import {dirname,resolve,join} from 'node:path';import {fileURLToPath,pathToFileURL} from 'node:url';import {createHash} from 'node:crypto';import {unzipSync} from 'fflate';
import {prepareRuntimeTransport} from './prepare-runtime-transport.mjs';
const ROOT=resolve(dirname(fileURLToPath(import.meta.url)),'..'),hash=bytes=>createHash('sha256').update(bytes).digest('hex'),MAX_ARCHIVE=128*1024*1024;
export function safeRuntimePath(path){if(typeof path!=='string'||!path||path.includes('\\')||path.includes(':')||/[\u0000-\u001f]/.test(path)||decodeURIComponent(path)!==path||path.startsWith('/')||path.replace(/\/$/,'').split('/').some(p=>!p||p==='.'||p==='..'||/[. ]$/.test(p)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))throw Error('Unsafe runtime archive path '+path);return path;}
export function checkedRuntimeArchive(bytes,pin,{maxFileBytes=64*1024*1024,maxTotalBytes=384*1024*1024}={}){
if(pin?.schema!=='kiln.troy-runtime-pin/1'||!Number.isSafeInteger(pin.bytes)||pin.bytes<1||pin.bytes>MAX_ARCHIVE||!/^[a-f0-9]{64}$/.test(pin.sha256))throw Error('Invalid runtime pin');
if(bytes.byteLength!==pin.bytes)throw Error('Runtime archive size mismatch');if(hash(bytes)!==pin.sha256)throw Error('Runtime archive hash mismatch');let total=0;
const files=unzipSync(bytes,{filter:entry=>{safeRuntimePath(entry.name);if(entry.originalSize>maxFileBytes)throw Error('Runtime file byte limit');total+=entry.originalSize;if(total>maxTotalBytes)throw Error('Runtime archive decoded byte limit');return /^web\//.test(entry.name)&&!/^web\/(vendor|bundle|qualification)\//.test(entry.name)&&!(/\.(?:mjs|js|html|css)$/.test(entry.name))&&!entry.name.endsWith('/');}});
return files;
}
export async function hydrateRuntime({root=ROOT,pin=undefined,archivePath=undefined,fetch:request=fetch}={}){
root=resolve(root);pin??=JSON.parse(await readFile(join(root,'runtime-pin.json'),'utf8'));if(!/^[a-z0-9-]+$/.test(pin.release))throw Error('Unsafe release identifier');safeRuntimePath(pin.path);const cache=join(root,'.runtime');await mkdir(cache,{recursive:true});const actualCache=await realpath(cache),expectedCache=join(await realpath(root),'.runtime'),samePath=process.platform==='win32'?actualCache.toLowerCase()===expectedCache.toLowerCase():actualCache===expectedCache;if((await lstat(cache)).isSymbolicLink()||!samePath)throw Error('Runtime cache must be a local directory');
let bytes;if(archivePath)bytes=await readFile(resolve(archivePath));else{const url=new URL(pin.path.replace(/^\//,''),pin.base.replace(/\/$/,'')+'/');if(url.protocol!=='https:')throw Error('Runtime downloads require HTTPS');const response=await request(url);if(!response.ok)throw Error('Runtime download failed '+response.status);const advertised=Number(response.headers.get('Content-Length'));if(advertised&&advertised!==pin.bytes)throw Error('Runtime archive advertised size mismatch');const reader=response.body.getReader(),chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>pin.bytes||size>MAX_ARCHIVE)throw Error('Runtime archive download byte limit');chunks.push(part.value);}}catch(error){await reader.cancel(error).catch(()=>{});throw error;}finally{reader.releaseLock();}bytes=Buffer.concat(chunks);}
const files=checkedRuntimeArchive(bytes,pin),target=join(cache,pin.release+'-'+pin.sha256.slice(0,12));await mkdir(target,{recursive:true});if((await lstat(target)).isSymbolicLink())throw Error('Runtime destination must be a local directory');
for(const [path,data]of Object.entries(files)){const output=resolve(target,path);if(!output.startsWith(target+'/')&&!output.startsWith(target+'\\'))throw Error('Unsafe runtime extraction');const parts=path.split('/');let parent=target;for(const part of parts.slice(0,-1)){parent=join(parent,part);try{const item=await lstat(parent);if(item.isSymbolicLink()||!item.isDirectory())throw Error('Runtime extraction refuses symlinks');}catch(error){if(error.code!=='ENOENT')throw error;await mkdir(parent);}}try{if((await lstat(output)).isSymbolicLink())throw Error('Runtime extraction refuses symlinks');}catch(error){if(error.code!=='ENOENT')throw error;}await writeFile(output,data);}
await prepareRuntimeTransport(join(target,'web'));await writeFile(join(cache,'current.json'),JSON.stringify({release:pin.release,sha256:pin.sha256,directory:pin.release+'-'+pin.sha256.slice(0,12)},null,2)+'\n');return {release:pin.release,files:Object.keys(files).length,bytes:pin.bytes,target};
}
if(process.argv[1]&&import.meta.url===pathToFileURL(resolve(process.argv[1])).href)console.log(JSON.stringify(await hydrateRuntime({archivePath:process.argv[2]})));