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
feat(materials): runtime-delivered approved texture resources (#15)
Matthew Kissinger7790cb1341d2
diff --git a/src/__tests__/material-resource-registry.test.ts b/src/__tests__/material-resource-registry.test.tsnew file mode 100644index 00000000..7ad11ac0--- /dev/null+++ b/src/__tests__/material-resource-registry.test.ts@@ -0,0 +1,258 @@+/**+ * T2.1 runtime-delivered texture resources.+ *+ * A resource that is not in the package has to be fetched, and the whole point of+ * a closed approved registry is that fetching cannot become a way to put+ * arbitrary pixels into an asset. These tests are about the two properties that+ * makes true: bytes are verified against a pinned length and hash before anything+ * decodes them, and a resource the environment cannot produce is refused loudly+ * rather than skipped.+ */+import { describe, expect, test } from 'bun:test';++import {+ APPROVED_TEXTURE_RESOURCE_IDS,+ APPROVED_TEXTURE_RESOURCES_V1,+ type ApprovedTextureResourceDescriptorV1,+ type ApprovedTextureResourceId,+} from '../material-recipes';+import {+ ApprovedTextureResourceCache,+ ApprovedTextureResourceUnavailableError,+ approvedTextureCatalogV1,+} from '../material-resources';+import { buildMaterialRecipePromptContextV1 } from '../material-recipe-prompt';++const SUBJECT: ApprovedTextureResourceId = 'kiln.texture.bark-albedo.v1';++/** The shipped bark bytes, re-declared as runtime-delivered production content. */+const shipped = APPROVED_TEXTURE_RESOURCES_V1[SUBJECT];+const RUNTIME_REGISTRY: Readonly<+ Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>+> = Object.freeze({+ ...APPROVED_TEXTURE_RESOURCES_V1,+ [SUBJECT]: Object.freeze({+ ...shipped,+ delivery: 'runtime',+ quality: 'production',+ } satisfies ApprovedTextureResourceDescriptorV1),+});++/** Byte-identical to what the package embeds, so the pinned hash still holds. */+function goodBytes(): Uint8Array {+ return new ApprovedTextureResourceCache().resolve(SUBJECT).bytes;+}++describe('runtime-delivered approved resources', () => {+ test('a runtime resource cannot be produced synchronously', () => {+ const cache = new ApprovedTextureResourceCache({ registry: RUNTIME_REGISTRY });++ // resolve() has no way to await a host call. Returning anything at all here+ // would mean returning bytes that are not the requested resource.+ expect(() => cache.resolve(SUBJECT)).toThrow(ApprovedTextureResourceUnavailableError);+ expect(() => cache.resolve(SUBJECT)).toThrow(/resolveAsync\(\) or load\(\)/);+ // The other four are still embedded and still work synchronously.+ expect(cache.resolve('kiln.texture.neutral-normal.v1').bytes.byteLength).toBeGreaterThan(0);+ });++ test('with no resolver registered it fails by name instead of silently degrading', async () => {+ const cache = new ApprovedTextureResourceCache({ registry: RUNTIME_REGISTRY });++ expect(cache.available(SUBJECT)).toBe(false);+ const error = await cache.resolveAsync(SUBJECT).catch((value: unknown) => value);+ expect(error).toBeInstanceOf(ApprovedTextureResourceUnavailableError);+ expect((error as ApprovedTextureResourceUnavailableError).resourceId).toBe(SUBJECT);+ expect((error as Error).message).toMatch(/no runtime texture resolver is registered/);+ });++ test('resolved bytes carry the same provenance as embedded ones, marked by delivery', async () => {+ const cache = new ApprovedTextureResourceCache({+ registry: RUNTIME_REGISTRY,+ resolver: async () => goodBytes(),+ });++ const resolved = await cache.resolveAsync(SUBJECT);+ expect(resolved.provenance.contentHash).toBe(shipped.contentHash);+ expect(resolved.provenance.delivery).toBe('runtime');+ expect(resolved.provenance.usage).toBe('albedo');+ // Delivery is the only difference. A consumer that verifies provenance must+ // not have to care where the bytes came from, only that they were verified.+ const embedded = new ApprovedTextureResourceCache().resolve(SUBJECT);+ expect({ ...resolved.provenance, delivery: 'embedded' }).toEqual(embedded.provenance);+ expect(resolved.bytes).toEqual(embedded.bytes);+ });++ test('a resolver returning the wrong bytes is rejected, not trusted', async () => {+ const wrong = new ApprovedTextureResourceCache({+ registry: RUNTIME_REGISTRY,+ // Right length, wrong content: the case a length check alone would pass.+ resolver: async () => {+ const bytes = goodBytes();+ const last = bytes.byteLength - 1;+ bytes.set([(bytes[last] ?? 0) ^ 0xff], last);+ return bytes;+ },+ });+ await expect(wrong.resolveAsync(SUBJECT)).rejects.toThrow(/does not match the pinned/);++ const truncated = new ApprovedTextureResourceCache({+ registry: RUNTIME_REGISTRY,+ resolver: async () => goodBytes().subarray(0, 40),+ });+ // Reported as a length, because the usual cause is an error document or a+ // partial body, and a hash mismatch would read as corruption instead.+ await expect(truncated.resolveAsync(SUBJECT)).rejects.toThrow(+ /expected 100 bytes, received 40/,+ );+ });++ test('concurrent requests for one resource share a single fetch', async () => {+ let calls = 0;+ const cache = new ApprovedTextureResourceCache({+ registry: RUNTIME_REGISTRY,+ resolver: async () => {+ calls += 1;+ await Promise.resolve();+ return goodBytes();+ },+ });++ // A scene binds the same resource from several materials at once. Without+ // in-flight deduplication each one is its own network round trip.+ await Promise.all([+ cache.resolveAsync(SUBJECT),+ cache.resolveAsync(SUBJECT),+ cache.resolveAsync(SUBJECT),+ ]);+ await cache.resolveAsync(SUBJECT);+ expect(calls).toBe(1);+ });++ test('a failed fetch is retryable rather than cached as a permanent failure', async () => {+ let calls = 0;+ const cache = new ApprovedTextureResourceCache({+ registry: RUNTIME_REGISTRY,+ resolver: async () => {+ calls += 1;+ if (calls === 1) throw new Error('transient network failure');+ return goodBytes();+ },+ });++ await expect(cache.resolveAsync(SUBJECT)).rejects.toThrow(/transient/);+ // A cached rejection would turn one blip into a dead resource for the life+ // of the process, which for a long-lived runtime means until redeploy.+ expect((await cache.resolveAsync(SUBJECT)).provenance.contentHash).toBe(shipped.contentHash);+ expect(calls).toBe(2);+ });++ test('a resolver only ever sees approved descriptors, never a caller-supplied string', async () => {+ const seen: string[] = [];+ const cache = new ApprovedTextureResourceCache({+ registry: RUNTIME_REGISTRY,+ resolver: async (descriptor) => {+ seen.push(descriptor.id);+ return goodBytes();+ },+ });++ await expect(cache.resolveAsync('kiln.texture.invented.v1' as never)).rejects.toThrow(+ /Unsupported/,+ );+ await cache.resolveAsync(SUBJECT);+ // The descriptor is the entire input. There is no path, URL, or credential+ // in it for a model to reach through, and an unapproved ID never arrives.+ expect(seen).toEqual([SUBJECT]);+ expect(JSON.stringify(APPROVED_TEXTURE_RESOURCES_V1[SUBJECT])).not.toMatch(+ /(?:https?:|s3:|path|token|secret)/i,+ );+ });+});++describe('what the model is told it can bind', () => {+ test('placeholder swatches are withheld, so the catalogue is empty as shipped', () => {+ // Every shipped resource is a 2x2 or 4x4 swatch that exists to prove a slot+ // binds. Offering one to a model competes with proceduralTexture() and looks+ // worse than it, so the honest catalogue today is empty.+ expect(approvedTextureCatalogV1()).toEqual([]);+ expect(approvedTextureCatalogV1({ includePlaceholders: true })).toHaveLength(+ APPROVED_TEXTURE_RESOURCE_IDS.length,+ );+ });++ test('the catalogue reports only what this environment can resolve', () => {+ const production: Readonly<+ Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>+ > = Object.freeze({+ ...RUNTIME_REGISTRY,+ [SUBJECT]: Object.freeze({+ ...RUNTIME_REGISTRY[SUBJECT],+ quality: 'production',+ } satisfies ApprovedTextureResourceDescriptorV1),+ });++ const withoutResolver = new ApprovedTextureResourceCache({ registry: production });+ expect(approvedTextureCatalogV1({ cache: withoutResolver })).toEqual([]);++ const withResolver = new ApprovedTextureResourceCache({+ registry: production,+ resolver: async () => goodBytes(),+ });+ const catalog = approvedTextureCatalogV1({ cache: withResolver });+ expect(catalog.map((entry) => entry.id)).toEqual([SUBJECT]);+ expect(catalog[0]?.delivery).toBe('runtime');+ });++ test('the prompt names resolvable IDs, and says so plainly when there are none', () => {+ const empty = buildMaterialRecipePromptContextV1([]);+ // The historical text claimed slots accept "IDs reported by capabilities"+ // while nothing reported any, so the only way to use a slot was to guess an+ // ID and be rejected by validation.+ expect(empty).toContain('none are available in this');+ expect(empty).toContain('proceduralTexture()');+ // It still names the shape of the IDs, but no concrete one — there is+ // nothing to bind, and a guessable example would be guessed.+ expect(empty).not.toMatch(/kiln\.texture\.[a-z]/);++ const named = buildMaterialRecipePromptContextV1([+ { id: SUBJECT, usage: 'albedo', allowedSlots: ['baseColor'] },+ ]);+ expect(named).toContain(`- ${SUBJECT} (albedo) for slots: baseColor`);+ expect(named).toContain('do not invent one');+ });+});++describe('package weight', () => {+ test('runtime resources ship no bytes, and the embedded set stays negligible', () => {+ for (const id of APPROVED_TEXTURE_RESOURCE_IDS) {+ const descriptor = APPROVED_TEXTURE_RESOURCES_V1[id];+ expect(descriptor.byteLength).toBeGreaterThan(0);+ if (descriptor.delivery !== 'runtime') continue;+ // The budget this task was asked to document is enforced by construction+ // rather than by a number: runtime resources have nowhere in the package+ // to put bytes, so a photographic library cannot grow the tarball at all.+ expect(() => new ApprovedTextureResourceCache().resolve(id)).toThrow(+ ApprovedTextureResourceUnavailableError,+ );+ }++ const embedded = APPROVED_TEXTURE_RESOURCE_IDS.filter(+ (id) => APPROVED_TEXTURE_RESOURCES_V1[id].delivery === 'embedded',+ ).reduce((sum, id) => sum + APPROVED_TEXTURE_RESOURCES_V1[id].byteLength, 0);+ // The engine is vendored as a tarball and installed into two container+ // images by two package managers, so embedded bytes are paid for on every+ // image build. 64 KB is far above today's 508 and far below one photo.+ expect(embedded).toBeLessThanOrEqual(64 * 1024);+ });++ test('every resource records a licence, so silence is never the default', () => {+ for (const id of APPROVED_TEXTURE_RESOURCE_IDS) {+ const license = APPROVED_TEXTURE_RESOURCES_V1[id].license;+ expect(license.spdx.length).toBeGreaterThan(0);+ expect(license.source.length).toBeGreaterThan(0);+ // `attribution` may be empty, but it is never absent: an empty string is a+ // recorded decision that this licence requires none.+ expect(typeof license.attribution).toBe('string');+ }+ });+});diff --git a/src/material-recipe-prompt.ts b/src/material-recipe-prompt.tsindex f8b8af00..d6174991 100644--- a/src/material-recipe-prompt.ts+++ b/src/material-recipe-prompt.ts@@ -6,6 +6,17 @@ import {type MaterialRecipeRequestV1,} from './material-recipes';+/**+ * Structural copy of `ApprovedTextureCatalogEntryV1`. This module is imported by+ * capability and SDK surfaces, so it stays free of Three and `node:crypto` — the+ * caller builds the catalogue and passes it in.+ */+export interface MaterialPromptTextureEntry {+ id: string;+ usage: string;+ allowedSlots: readonly string[];+}+export const MATERIAL_RECIPE_HELPER_SIGNATURE ='await materialRecipe(recipeId, { baseColor?, roughness?, metalness?, opacity?, alphaCutoff?, doubleSided?, emissiveColor?, emissiveIntensity?, textureResources? })';@@ -25,15 +36,50 @@ const glass = await materialRecipe('kiln.material.glass.v1');const glow = await materialRecipe('kiln.material.emissive.v1');\`\`\``;-export const MATERIAL_RECIPE_PROMPT_CONTEXT_V1 = `## Portable material recipes+/**+ * The texture-slot paragraph, built from what this environment can actually bind.+ *+ * Historically this block told the model that slots accept "approved+ * kiln.texture.* resource IDs reported by capabilities" while nothing reported+ * any, so the only way to use a slot was to guess an ID and be rejected by+ * validation. Naming the resolvable IDs — and saying plainly when there are none+ * — is the whole difference between a usable slot and a decorative sentence.+ */+function textureSlotContext(catalog: readonly MaterialPromptTextureEntry[]): string {+ if (catalog.length === 0) {+ return `Texture slots take approved kiln.texture.* resource IDs, and none are available in this+environment: leave textureResources unset and build any surface detail with proceduralTexture().`;+ }+ const lines = catalog.map(+ (entry) => `- ${entry.id} (${entry.usage}) for slots: ${entry.allowedSlots.join(', ')}`,+ );+ return `Texture slots accept only these approved resource IDs; do not invent one and do not pass a+host path. For any surface not covered here, build it with proceduralTexture() rather than+substituting an unrelated ID:+${lines.join('\n')}`;+}++export function buildMaterialRecipePromptContextV1(+ catalog: readonly MaterialPromptTextureEntry[] = [],+): string {+ return `## Portable material recipesUse ${MATERIAL_RECIPE_HELPER_SIGNATURE}. Recipe IDs are versioned and executable; do not invent anID or pass a host path. Available IDs: ${MATERIAL_RECIPE_IDS.join(', ')}. Recipes export through core-glTF pbrMetallicRoughness. Leaf uses MASK (not BLEND); glass is the explicit blended recipe. Texture-slots accept only approved kiln.texture.* resource IDs reported by capabilities.+glTF pbrMetallicRoughness. Leaf uses MASK (not BLEND); glass is the explicit blended recipe.++${textureSlotContext(catalog)}Choose recipes from the requested real-world material even when the user does not name this helper:${MATERIAL_RECIPE_EXECUTABLE_EXAMPLES_V1}`;+}++/**+ * Snapshot for callers that need a stable string (the W6 ablation hashes it).+ * Prompt assembly should call the builder so a host that registers a resolver+ * gets its runtime resources named.+ */+export const MATERIAL_RECIPE_PROMPT_CONTEXT_V1 = buildMaterialRecipePromptContextV1();export function materialRecipeRequestDirective(request: MaterialRecipeRequestV1): string {const recipe = MATERIAL_RECIPE_LIBRARY_V1[request.id];diff --git a/src/material-recipes.ts b/src/material-recipes.tsindex f8f5aa07..2d3130e7 100644--- a/src/material-recipes.ts+++ b/src/material-recipes.ts@@ -104,6 +104,34 @@ export interface MaterialRecipeDescriptorV1 {defaults: PortablePbrRecipeV1;}+/**+ * Where a resource's bytes come from.+ *+ * `embedded` bytes ship inside the engine package. `runtime` bytes do not exist+ * in the tarball at all and are fetched through a host-registered resolver+ * against the pinned `contentHash`. The distinction is what keeps a photographic+ * library off the critical path of a package that is vendored as a tarball and+ * installed into two container images by two package managers.+ */+export type TextureResourceDelivery = 'embedded' | 'runtime';++/**+ * `placeholder` marks a resource that exists to prove a slot binds, not to look+ * like anything — the historical 4x4/2x2 swatches. Only `production` resources+ * are offered to a model, because naming a 4x4 bark swatch to a model that would+ * otherwise call `proceduralTexture()` makes the output worse, not better.+ */+export type TextureResourceQuality = 'placeholder' | 'production';++/** Recorded per resource so a shipped asset can state what it is allowed to be. */+export interface TextureResourceLicenseV1 {+ /** SPDX identifier, or `CC0-1.0` for public-domain scans. */+ spdx: string;+ /** Empty when the licence requires none; never omitted, so silence is a choice. */+ attribution: string;+ source: string;+}+export interface ApprovedTextureResourceDescriptorV1 {schemaVersion: 1;id: ApprovedTextureResourceId;@@ -113,6 +141,12 @@ export interface ApprovedTextureResourceDescriptorV1 {colorSpace: 'srgb' | 'linear';mime: 'image/png';contentHash: string;+ delivery: TextureResourceDelivery;+ quality: TextureResourceQuality;+ /** Bytes the resolver must return. Checked before hashing so a truncated or+ * wrong-object response fails on size rather than on an opaque hash mismatch. */+ byteLength: number;+ license: TextureResourceLicenseV1;allowedSlots: readonly MaterialTextureSlot[];recipeIds: readonly MaterialRecipeId[];}@@ -310,6 +344,14 @@ export const APPROVED_TEXTURE_RESOURCES_V1: Readonly<colorSpace: 'srgb',mime: 'image/png',contentHash: 'ec74fd42fe317f578018a13a65d81a726e9baeade068ae016cff30c15507017f',+ delivery: 'embedded',+ quality: 'placeholder',+ byteLength: 100,+ license: Object.freeze({+ spdx: 'CC0-1.0',+ attribution: '',+ source: 'authored in-repo',+ }),allowedSlots: Object.freeze(['baseColor'] as const),recipeIds: Object.freeze(['kiln.material.bark.v1', 'kiln.material.wood.v1'] as const),}),@@ -322,6 +364,14 @@ export const APPROVED_TEXTURE_RESOURCES_V1: Readonly<colorSpace: 'srgb',mime: 'image/png',contentHash: 'ae9ad7f5389529a42fd9e63cb16aa7dc2c803739953242422b0ccc8003bd827c',+ delivery: 'embedded',+ quality: 'placeholder',+ byteLength: 119,+ license: Object.freeze({+ spdx: 'CC0-1.0',+ attribution: '',+ source: 'authored in-repo',+ }),allowedSlots: Object.freeze(['baseColor'] as const),recipeIds: Object.freeze(['kiln.material.leaf.v1'] as const),}),@@ -334,6 +384,14 @@ export const APPROVED_TEXTURE_RESOURCES_V1: Readonly<colorSpace: 'linear',mime: 'image/png',contentHash: '2be025139faed13fb12ac50101f7d91f8a758ce6a668104a7e8003eccdab7db7',+ delivery: 'embedded',+ quality: 'placeholder',+ byteLength: 95,+ license: Object.freeze({+ spdx: 'CC0-1.0',+ attribution: '',+ source: 'authored in-repo',+ }),allowedSlots: Object.freeze(['normal'] as const),recipeIds: Object.freeze(['kiln.material.bark.v1',@@ -353,6 +411,14 @@ export const APPROVED_TEXTURE_RESOURCES_V1: Readonly<colorSpace: 'linear',mime: 'image/png',contentHash: '5e03d1e2863800c5f1a88411dd4447ccc0ec8470232129d8682db8f6ea76ad52',+ delivery: 'embedded',+ quality: 'placeholder',+ byteLength: 94,+ license: Object.freeze({+ spdx: 'CC0-1.0',+ attribution: '',+ source: 'authored in-repo',+ }),allowedSlots: Object.freeze(['metallicRoughness'] as const),recipeIds: Object.freeze(['kiln.material.rubber.v1',@@ -368,6 +434,14 @@ export const APPROVED_TEXTURE_RESOURCES_V1: Readonly<colorSpace: 'srgb',mime: 'image/png',contentHash: 'a0b2f4e243ec0ec914b80d4998cf4624ff68181aafc4b97a6bafa765a41e4814',+ delivery: 'embedded',+ quality: 'placeholder',+ byteLength: 100,+ license: Object.freeze({+ spdx: 'CC0-1.0',+ attribution: '',+ source: 'authored in-repo',+ }),allowedSlots: Object.freeze(['emissive'] as const),recipeIds: Object.freeze(['kiln.material.emissive.v1'] as const),}),diff --git a/src/material-resources.ts b/src/material-resources.tsindex a4836062..d1b3ffb0 100644--- a/src/material-resources.ts+++ b/src/material-resources.ts@@ -6,7 +6,9 @@ import type * as THREE from 'three';import {APPROVED_TEXTURE_RESOURCE_IDS,APPROVED_TEXTURE_RESOURCES_V1,+ type ApprovedTextureResourceDescriptorV1,type ApprovedTextureResourceId,+ type TextureResourceDelivery,} from './material-recipes';import {loadTexture,@@ -25,6 +27,47 @@ export interface MaterialResourceProvenanceV1 {colorSpace: 'srgb' | 'linear';resourceVersion: 1;recipeVersion: 1;+ /** Recorded so a persisted asset states whether its pixels came from the+ * package or from the host registry. Both are hash-verified; they differ in+ * who has to be reachable for the asset to be reproducible. */+ delivery: TextureResourceDelivery;+}++/**+ * Host-supplied byte source for `delivery: 'runtime'` resources.+ *+ * It receives the descriptor and nothing else. The engine holds no URL, bucket,+ * path, or credential, and cannot be steered to one by a model — a resolver is+ * registered by the host process, and every ID it can be asked for is a member+ * of the closed approved list. Returned bytes are checked against the pinned+ * length and hash before anything decodes them, so a resolver that is wrong,+ * stale, or compromised fails loudly instead of substituting pixels.+ */+export type ApprovedTextureResolver = (+ descriptor: ApprovedTextureResourceDescriptorV1,+) => Promise<Uint8Array>;++export interface ApprovedTextureResourceCacheOptions {+ resolver?: ApprovedTextureResolver;+ /**+ * Descriptor table this cache reads. Defaults to the shipped registry.+ *+ * It cannot widen the approved set: the key type is the closed ID union, so an+ * override can only restate a resource that is already approved — typically to+ * exercise the runtime delivery path, or to pin a different resource version.+ * The module-level helpers always use the shipped table.+ */+ registry?: Readonly<Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>>;+}++export class ApprovedTextureResourceUnavailableError extends Error {+ readonly resourceId: ApprovedTextureResourceId;++ constructor(id: ApprovedTextureResourceId, reason: string) {+ super(`Approved texture resource ${id} is unavailable: ${reason}`);+ this.name = 'ApprovedTextureResourceUnavailableError';+ this.resourceId = id;+ }}export interface ApprovedTextureResolutionV1 {@@ -66,24 +109,50 @@ const isApprovedId = (value: string): value is ApprovedTextureResourceId =>const bytesFromBase64 = (value: string): Uint8Array => new Uint8Array(Buffer.from(value, 'base64'));const sha256 = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');-function usageForResource(id: ApprovedTextureResourceId): TextureUsage {- return APPROVED_TEXTURE_RESOURCES_V1[id].usage;-}--function provenance(id: ApprovedTextureResourceId, hash: string): MaterialResourceProvenanceV1 {- const descriptor = APPROVED_TEXTURE_RESOURCES_V1[id];+function provenance(+ descriptor: ApprovedTextureResourceDescriptorV1,+ hash: string,+): MaterialResourceProvenanceV1 {return {schemaVersion: 1,- resourceId: id,+ resourceId: descriptor.id,contentHash: hash,hashAlgorithm: 'sha256',- usage: usageForResource(id),+ usage: descriptor.usage,colorSpace: descriptor.colorSpace,resourceVersion: descriptor.version,recipeVersion: 1,+ delivery: descriptor.delivery,};}+/**+ * The single gate every byte passes, whichever delivery produced it.+ *+ * Length first: a truncated body, an S3 error document, or the wrong object all+ * fail here with a number a human can act on, rather than as an opaque hash+ * mismatch that reads like corruption.+ */+function verifyResourceBytes(+ descriptor: ApprovedTextureResourceDescriptorV1,+ bytes: Uint8Array,+): string {+ if (bytes.byteLength !== descriptor.byteLength) {+ throw new ApprovedTextureResourceUnavailableError(+ descriptor.id,+ `expected ${descriptor.byteLength} bytes, received ${bytes.byteLength}`,+ );+ }+ const hash = sha256(bytes);+ if (hash !== descriptor.contentHash) {+ throw new ApprovedTextureResourceUnavailableError(+ descriptor.id,+ `content hash ${hash} does not match the pinned ${descriptor.contentHash}`,+ );+ }+ return hash;+}+/*** The only path used by new generations/refines. Inputs are closed approved* IDs, and the returned DTO contains no filesystem location, URL, credential,@@ -93,36 +162,127 @@ export class ApprovedTextureResourceCache {readonly #bytesByHash = new Map<string, Uint8Array>();readonly #hashById = new Map<ApprovedTextureResourceId, string>();readonly #textureByVariant = new Map<string, Promise<THREE.DataTexture>>();+ readonly #pendingById = new Map<+ ApprovedTextureResourceId,+ Promise<ApprovedTextureResolutionV1>+ >();+ readonly #registry: Readonly<+ Record<ApprovedTextureResourceId, ApprovedTextureResourceDescriptorV1>+ >;+ #resolver: ApprovedTextureResolver | undefined;- resolve(id: ApprovedTextureResourceId): ApprovedTextureResolutionV1 {+ constructor(options: ApprovedTextureResourceCacheOptions = {}) {+ this.#resolver = options.resolver;+ this.#registry = options.registry ?? APPROVED_TEXTURE_RESOURCES_V1;+ }++ /**+ * Registered once by the host process at startup, never by generated code.+ * Returns the previous resolver so a test can restore it.+ */+ setResolver(resolver: ApprovedTextureResolver | undefined): ApprovedTextureResolver | undefined {+ const previous = this.#resolver;+ this.#resolver = resolver;+ return previous;+ }++ /**+ * Whether this environment can actually produce the bytes. Embedded resources+ * are always available; runtime ones need a registered resolver. Callers use+ * this to decide what to offer a model, so it never promises what it cannot+ * deliver.+ */+ /** The descriptor this cache reads, which an override may have replaced. */+ descriptor(id: ApprovedTextureResourceId): ApprovedTextureResourceDescriptorV1 {if (!isApprovedId(id)) throw new RangeError(`Unsupported approved texture resource ID ${id}.`);- let hash = this.#hashById.get(id);- let canonical: Uint8Array | undefined;- if (!hash) {- const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);- hash = sha256(decoded);- if (hash !== APPROVED_TEXTURE_RESOURCES_V1[id].contentHash) {- throw new Error(`Approved resource ${id} failed its pinned content hash.`);- }- canonical = this.#bytesByHash.get(hash);- if (!canonical) {- canonical = decoded;- this.#bytesByHash.set(hash, canonical);- }- this.#hashById.set(id, hash);- } else {- canonical = this.#bytesByHash.get(hash);+ return this.#registry[id];+ }++ available(id: ApprovedTextureResourceId): boolean {+ if (!isApprovedId(id)) return false;+ return this.#registry[id].delivery === 'embedded' || this.#resolver !== undefined;+ }++ #cacheBytes(id: ApprovedTextureResourceId, hash: string, bytes: Uint8Array): Uint8Array {+ let canonical = this.#bytesByHash.get(hash);+ if (!canonical) {+ canonical = bytes;+ this.#bytesByHash.set(hash, canonical);}+ this.#hashById.set(id, hash);+ return canonical;+ }++ #resolution(id: ApprovedTextureResourceId, hash: string): ApprovedTextureResolutionV1 {+ const canonical = this.#bytesByHash.get(hash);if (!canonical) throw new Error(`Approved resource cache lost content ${hash}.`);return {- descriptor: APPROVED_TEXTURE_RESOURCES_V1[id],+ descriptor: this.#registry[id],bytes: canonical.slice(),- provenance: provenance(id, hash),+ provenance: provenance(this.#registry[id], hash),};}+ /**+ * Synchronous resolution. Only ever succeeds for embedded bytes — a runtime+ * resource cannot be produced without awaiting a host call, and quietly+ * returning something else is the failure mode this whole registry exists to+ * prevent.+ */+ resolve(id: ApprovedTextureResourceId): ApprovedTextureResolutionV1 {+ if (!isApprovedId(id)) throw new RangeError(`Unsupported approved texture resource ID ${id}.`);+ const hash = this.#hashById.get(id);+ if (hash) return this.#resolution(id, hash);++ const descriptor = this.#registry[id];+ if (descriptor.delivery !== 'embedded') {+ throw new ApprovedTextureResourceUnavailableError(+ id,+ 'it is delivered at runtime; use resolveAsync() or load()',+ );+ }+ const decoded = bytesFromBase64(EMBEDDED_RESOURCE_BASE64[id]);+ this.#cacheBytes(id, verifyResourceBytes(descriptor, decoded), decoded);+ return this.#resolution(id, this.#hashById.get(id)!);+ }++ /**+ * Resolution for either delivery. Concurrent callers share one fetch: the+ * generation path asks for the same resource from several materials at once,+ * and each duplicate would otherwise be a separate network round trip.+ */+ async resolveAsync(id: ApprovedTextureResourceId): Promise<ApprovedTextureResolutionV1> {+ if (!isApprovedId(id)) throw new RangeError(`Unsupported approved texture resource ID ${id}.`);+ const hash = this.#hashById.get(id);+ if (hash) return this.#resolution(id, hash);+ if (this.#registry[id].delivery === 'embedded') return this.resolve(id);++ let pending = this.#pendingById.get(id);+ if (!pending) {+ const descriptor = this.#registry[id];+ const resolver = this.#resolver;+ pending = (async () => {+ if (!resolver) {+ throw new ApprovedTextureResourceUnavailableError(+ id,+ 'no runtime texture resolver is registered in this environment',+ );+ }+ const bytes = await resolver(descriptor);+ this.#cacheBytes(id, verifyResourceBytes(descriptor, bytes), bytes);+ return this.#resolution(id, this.#hashById.get(id)!);+ })().finally(() => {+ // Dropped either way: a success is served from #hashById afterwards, and+ // a failure must be retryable rather than cached forever.+ this.#pendingById.delete(id);+ });+ this.#pendingById.set(id, pending);+ }+ return pending;+ }+async load(id: ApprovedTextureResourceId): Promise<LoadedApprovedTextureV1> {- const resolved = this.resolve(id);+ const resolved = await this.resolveAsync(id);const variantKey = [resolved.provenance.contentHash,resolved.provenance.usage,@@ -175,6 +335,60 @@ export async function loadApprovedTextureResource(return DEFAULT_APPROVED_TEXTURE_CACHE.load(id);}+/** Registers the host's byte source for runtime-delivered resources. */+export function setApprovedTextureResolver(+ resolver: ApprovedTextureResolver | undefined,+): ApprovedTextureResolver | undefined {+ return DEFAULT_APPROVED_TEXTURE_CACHE.setResolver(resolver);+}++export interface ApprovedTextureCatalogEntryV1 {+ id: ApprovedTextureResourceId;+ label: string;+ usage: TextureUsage;+ delivery: TextureResourceDelivery;+ allowedSlots: readonly string[];+ recipeIds: readonly string[];+}++export interface ApprovedTextureCatalogOptions {+ cache?: ApprovedTextureResourceCache;+ /** Placeholder swatches are excluded by default; they exist to prove a slot+ * binds, and offering one to a model competes with `proceduralTexture()`+ * while looking worse than it. */+ includePlaceholders?: boolean;+}++/**+ * What this environment can actually bind, in the order the IDs are declared.+ *+ * The material prompt has always told models that texture slots accept "approved+ * kiln.texture.* resource IDs reported by capabilities" while no surface reported+ * any, so a model could only guess an ID and be rejected. This is that surface,+ * and it is filtered by real availability so it cannot advertise a resource whose+ * bytes no resolver can produce.+ */+export function approvedTextureCatalogV1(+ options: ApprovedTextureCatalogOptions = {},+): ApprovedTextureCatalogEntryV1[] {+ const cache = options.cache ?? DEFAULT_APPROVED_TEXTURE_CACHE;+ return APPROVED_TEXTURE_RESOURCE_IDS.filter((id) => {+ const descriptor = cache.descriptor(id);+ if (descriptor.quality === 'placeholder' && options.includePlaceholders !== true) return false;+ return cache.available(id);+ }).map((id) => {+ const descriptor = cache.descriptor(id);+ return {+ id,+ label: descriptor.label,+ usage: descriptor.usage,+ delivery: descriptor.delivery,+ allowedSlots: descriptor.allowedSlots,+ recipeIds: descriptor.recipeIds,+ };+ });+}+/*** Compatibility-only reader for historical source programs. New manifests and* prompts must use loadApprovedTextureResource() so an untrusted model cannotdiff --git a/src/prompt.ts b/src/prompt.tsindex 869ebc14..28f46dd1 100644--- a/src/prompt.ts+++ b/src/prompt.ts@@ -19,7 +19,8 @@ import { listPrimitives } from './list-primitives';import { renderApiSection } from './prompt-api';import { KILN_ASSET_FRAME, type AssetCategory, type AssetIntentV1 } from './contracts';import { characterBodyPlanRecipe } from './character';-import { MATERIAL_RECIPE_PROMPT_CONTEXT_V1 } from './material-recipe-prompt';+import { buildMaterialRecipePromptContextV1 } from './material-recipe-prompt';+import { approvedTextureCatalogV1 } from './material-resources';import { vegetationSubtypePromptContext } from './vegetation-prompt';import { vehicleSubtypeRecipe } from './vehicle';import { renderAssetScopePrompt, renderVfxBreadthPrompt } from './breadth-prompt';@@ -1078,7 +1079,10 @@ export function buildUserPrompt(request: KilnGenerateRequest): string {request.intent?.material.mode === 'pbrRecipe' ||request.intent?.material.mode === 'texturedHero') {- parts.push(`\n${MATERIAL_RECIPE_PROMPT_CONTEXT_V1}`);+ // Built per call, not from the static snapshot: a host that has registered+ // a runtime texture resolver has more resources to offer than one that has+ // not, and naming an ID the environment cannot resolve is worse than none.+ parts.push(`\n${buildMaterialRecipePromptContextV1(approvedTextureCatalogV1())}`);}}