Skip to content

armgit / kiln

Public Imported from GitHub
0

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.

24.2 KB
Raw Blame
/** Closed, engine-owned repair hints. Never serialize exception messages or stacks. */
export type AuthoringDiagnostic =
  | 'TUBE_RADIUS'
  | 'TAPER_CONE_AXIS'
  | 'SOLID_FLOAT32_COLLAPSE'
  | 'MESH_DATA_NONFINITE'
  | 'MATERIAL_ALPHA_MODE'
  | 'MATERIAL_COLOR_ARGUMENT'
  | 'MATERIAL_NAME'
  | 'MATERIAL_PACKED_CHANNELS'
  | 'MATERIAL_RECIPE_TEXTURE_BINDING'
  | 'PORTABLE_TEXTURE_REFERENCE'
  | 'PORTABLE_COLOR_ARGUMENT'
  | 'PART_NAME_ARGUMENT'
  | 'PART_GEOMETRY_ARGUMENT'
  | 'PART_MATERIAL_ARGUMENT'
  | 'REMOVED_HELPER'
  | 'UNBOUND_VARIABLE'
  | 'GEAR_RADII_ORDER'
  | 'ROUNDED_BOX_RADIUS'
  | 'PROCEDURAL_TEXTURE_UNKNOWN_KEY'
  | 'PROCEDURAL_TEXTURE_BLEND'
  | 'PROCEDURAL_TEXTURE_USAGE'
  | 'PROCEDURAL_TEXTURE_V3_CONTRACT'
  | 'PORTABLE_MATERIAL_V3_CONTRACT'
  | 'TEXTURE_ATLAS_CONTRACT'
  | 'MATERIAL_FRACTION_RANGE'
  | 'PARAMETRIC_PERIODIC_ENDPOINT'
  | 'PROFILE_HOLES_UNSUPPORTED'
  | 'PROFILE_BEVEL_COLLAPSE'
  | 'PROFILE_SOLID_FAILED'
  | 'PROFILE_CORRESPONDENCE_COLLAPSE'
  | 'UNINITIALIZED_BINDING'
  | 'BUILD_RESULT'
  | 'MATERIAL_RECIPE_OVERRIDE'
  | 'PROGRAM_TYPE_ERROR'
  | 'PROGRAM_RANGE_ERROR'
  | 'LOD_SET'
  | 'OPEN_SHELL'
  | 'DELIVERY_CONTRACT'
  | 'REQUIRE_SOLID'
  | 'BONE_CHAIN_ARGUMENT'
  | 'SKIN_BINDING_ARGUMENT'
  | 'EXPORT_MATERIAL_SIDE_UNSUPPORTED';
// Names no identifier on purpose. The identifier is only available from the
// sandboxed exception message, and this module's contract is that no captured
// identifier, path, message or stack crosses that boundary. Pointing at the
// discovery tool is engine-owned text, so it costs nothing to include and is
// the actionable half: an undeclared name here is usually a helper that does
// not exist rather than a typo in a local.
export const UNBOUND_VARIABLE_ADVICE =
  'Check variable spelling and scope: generated code used an undeclared variable. Read the current source and check declarations before retrying. If it was meant to be a Kiln helper, call kiln_discover to confirm the exact name and signature; the sandbox exposes only those globals.';
export const GEAR_RADII_ORDER_ADVICE =
  'gearGeo requires boreRadius < rootRadius < tipRadius; specify rootRadius when changing tipRadius. Omitted radii keep their absolute defaults.';
export const ROUNDED_BOX_RADIUS_ADVICE =
  'roundedBoxGeo: radius must be less than half the smallest dimension. Reduce radius or increase the smallest dimension; equality is invalid.';
export const PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE =
  'Remove unsupported proceduralTexture fields. Call kiln_discover with ids ["proceduralTexture"] and use only the documented fields for the selected layer op.';
export const PROCEDURAL_TEXTURE_USAGE_ADVICE =
  'proceduralTexture usage is one of albedo (the default), emissive, normal, roughness, metalness, metallicRoughness or occlusion; there is no data or height usage. Match it to the slot it fills: portable material baseColor takes albedo, normal takes normal, metallicRoughness takes metallicRoughness (G roughness, B metalness), emissive takes emissive and occlusion takes occlusion; pbrMaterial albedo, normal, roughness, metalness, metallicRoughness, emissive and aoMap take the matching usage. Call kiln_discover with ids ["proceduralTexture"].';
export const MATERIAL_NAME_ADVICE =
  'A material name is the key a destination runtime groups draws by, so it is 1 to 200 visible characters: a plain string, no control characters. gameMaterial, basicMaterial, glassMaterial and lambertMaterial take it in their options object, pbrMaterial and foliageMaterial in theirs, for example gameMaterial(0x25342a, { roughness: 0.58, name: "ParkerisedSteel" }). Omit it to leave the material unnamed; materialRecipe and the portable material specs name their output already.';
export const MATERIAL_FRACTION_RANGE_ADVICE =
  'Material fractions must be finite numbers between 0 and 1, inclusive. In proceduralTexture, mortarWidth and stagger are fractions, not pixels; opacity uses the same range. materialRecipe roughness, metalness, opacity, alphaCutoff and emissiveIntensity use 0..1. portableMaterial roughness, metalness and alphaCutoff also use 0..1; its emissiveIntensity has a separate 0..64 range. Call kiln_discover for the exact field contracts.';
export const PARAMETRIC_PERIODIC_ENDPOINT_ADVICE =
  'Periodic parametricSurface endpoints must return matching positions. For periodicU, sample(uMin, v) and sample(uMax, v) must match; for periodicV, sample(u, vMin) and sample(u, vMax) must match.';
export const PROFILE_HOLES_UNSUPPORTED_ADVICE =
  'loftProfiles and sweepProfile: holes are unsupported in options or sections. Use extrudeProfile for a holed cross-section with optional twist/taper; independently varying contours need explicit geometry or solid subtraction. cap:false does not create inner walls or thickness.';
export const PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE =
  'loftProfiles or sweepProfile: corresponding profile edges collapse between stations. Check matching start vertices and vertex order; for an intended twist, add intermediate sections or path stations. No automatic correspondence repair is applied. Other self-intersections remain unchecked.';
// Engine-owned and bounded: no outline, coordinate or library message crosses the sandbox,
// so the hint names the inputs that make the profile solid path fail (#178).
export const PROFILE_SOLID_FAILED_ADVICE =
  'PROFILE_SOLID_FAILED: extrudeProfile or revolveProfile could not build a solid from this outline. Reduce bevel or set it to 0. Keep the outline one simple closed loop: no self-intersections, repeated points or zero-length edges, and no neck narrower than twice the bevel. Holes must lie inside the outline and leave material. For revolveProfile, keep points off the axis (x = 0) unless the solid should close there. Keep coordinates at asset scale. Render that helper call alone with kiln_render and simplify the outline until it builds. Call kiln_discover with ids ["extrudeProfile", "revolveProfile"].';
export const UNINITIALIZED_BINDING_ADVICE =
  'A const, let or class binding was read before its declaration ran (temporal dead zone). Move the declaration above the first code that reads it; top-level constants must be declared before other top-level code uses them. kiln_validate names the binding and line when the read runs immediately.';
export const BUILD_RESULT_ADVICE =
  'Define a top-level function build() (it may be async) that returns the root Object3D, for example const root = createRoot("Name"); ...; return root;. A build() that returns nothing, or returns a geometry or material, is rejected.';
export const MATERIAL_RECIPE_OVERRIDE_ADVICE =
  'materialRecipe takes a listed kiln.material.*.v1 ID and only the overrides that recipe allows; the allowed overrides differ by recipe (the emissive recipe has no metalness). Call kiln_discover with ids ["materialRecipe"] to see what each recipe allows; kiln_validate names the recipe and key when both are literals.';
export const PROGRAM_TYPE_ERROR_ADVICE =
  'The program or a helper it called threw a TypeError: a value had the wrong type. Usually something is undefined (a function without a return, an un-awaited async helper such as roundedBoxGeo, extrudeProfile or materialRecipe, or a misspelt property) or a non-function was called. Run kiln_validate, then check the helper contract with kiln_discover.';
export const PROGRAM_RANGE_ERROR_ADVICE =
  'The program or a helper it called threw a RangeError: a number was outside its allowed range, for example a non-positive size, an invalid array length or segment count, or unbounded recursion. Check the helper arguments against kiln_discover.';
export const LOD_SET_ADVICE =
  'Levels of detail: sibling nodes whose names share a stem and carry LOD0, LOD1, ... tokens (Body_LOD0, Body_LOD1) form one set. A set needs LOD0 and consecutive levels under one parent, outside any other tier, and one defineLod([lod0, lod1, ...], { screenCoverage: [...] }) call listing its tiers in level order with one value per level, each from 0 to 1 and strictly decreasing; the last may be 0, which never culls. Build one tier without LOD tokens unless the brief asks for levels. Call kiln_discover with ids ["defineLod"].';
export const OPEN_SHELL_ADVICE =
  'markOpenShell(part, reason) marks a part as intentionally open: part is the mesh createPart returned or a group whose meshes it covers, and reason is a non-empty string of at most 200 characters saying why, for example markOpenShell(rail, "C-channel closed by the end plates"). The engine owns the kilnOpenShell userData key; set it only through markOpenShell. Call kiln_discover with ids ["markOpenShell"].';
export const DELIVERY_CONTRACT_ADVICE =
  'Delivery helpers: colliderBox(size, { id }), colliderCapsule(radius, height, { id }) with height the total height of at least 2 * radius, colliderHull(mesh, { id }), anchor(kind, id), port(id) and defineModule(root, { footprint: [w, d], height, snapAxis: "x"|"y"|"z", origin: "corner"|"center" }). Ids and kinds are one segment of letters, digits, "_" or "-" with no dots; sizes are positive metres. The engine owns the kilnKit userData key; set it only through defineModule. defineBudget({ triangles: n | { LOD0, LOD1, ... }, draws?, images?, decodedBytes?, materialTier? }) takes positive integers for triangles and draws, non-negative integers for images and decodedBytes, and a reference tier such as "web.portable.v1/standard" for materialTier; definePalette(colors, { threshold? }) takes 1..64 hex colours. Call kiln_discover with ids ["colliderBox", "anchor", "defineModule", "defineBudget"].';
export const REQUIRE_SOLID_ADVICE =
  'REQUIRE_SOLID: a part marked with requireSolid(part) is not a closed, manifold, outward solid. Close every boundary (caps, end plates, a hull or a solid helper such as boxGeo or extrudeProfile), remove faces shared by three or more triangles, and keep one consistent outward winding; do not flip normals alone. Check the part with geometryDiagnostics(geometry).solid, or remove the requireSolid mark if the part is open on purpose. Call kiln_discover with ids ["requireSolid", "geometryDiagnostics"].';
/**
 * The advice behind the generic rejection, when no closed cause crossed the boundary.
 * Engine-owned text only: it states the contract and names the two tools that answer
 * what a thrown Error cannot (a scene session of 2 October 2026 threw one to print
 * bounding boxes and got the bare sentence, H30; decision 24).
 */
export const EXECUTION_REJECTED_ADVICE =
  'No message, stack or identifier crosses the sandbox: a thrown Error, a source-policy denial and any other failure are each reported only as this sentence. kiln_validate (CLI: kiln validate <program.js|ref>) checks syntax and static source rules such as policy denials; it cannot see execution-time failures, such as geometry a helper rejects while build() runs. Reproduce those with kiln_render, simplifying or removing the failing part until the program renders. To read values, render the program and call kiln_inspect (listParts, measurements) instead of throwing. A TypeError, RangeError, unbound variable, build() mistake or profile solid failure is named when it is the cause.';
export function authoringDiagnosticAdvice(diagnostic: AuthoringDiagnostic | undefined): string {
  if (diagnostic === 'PORTABLE_MATERIAL_V3_CONTRACT')
    return 'compilePortableMaterialSpecV3 requires schemaVersion 3, model pbrMetallicRoughness, typed V3 procedural or injected resource references, and complete minFilter/magFilter/wrapS/wrapT samplers. Match texture usage to its slot and split work exceeding the material budget. Resource bindings need a host with verified-byte admission. V2 remains available unchanged. Shader code, paths, raw textures and V3 height derivation are unsupported. Read kiln_discover ids ["compilePortableMaterialSpecV3"] for the exact contract.';
  if (diagnostic === 'TEXTURE_ATLAS_CONTRACT')
    return 'textureAtlas requires bounded named integer content rectangles with nonoverlapping gutter allocations, matching source crops and usage, and explicit portable sampling. Sources are V3 recipes or exact host-injected library map pins. Split atlases exceeding aggregate work or allocation budgets. remapUVToAtlas requires finite unit UV0, a named content region, inputOrigin and mapping mode; it preserves topology and does not unwrap or tile a region. Read kiln_discover ids ["textureAtlas", "remapUVToAtlas"] for the exact contracts.';
  if (diagnostic === 'PROCEDURAL_TEXTURE_V3_CONTRACT')
    return 'proceduralTexture schemaVersion 3 requires bounded JSON: width/height 4..1024, byte RGBA, integer pixel shapes and at most 64 operations. Palette/dither supports only albedo/emissive; seeded stamps accept every usage. Work includes polygon edges and periodic copies. Read kiln_discover ids ["proceduralTexture"] for the V3 contract; keep schemaVersion 2 for existing opaque patterns.';
  if (diagnostic === 'BONE_CHAIN_ARGUMENT')
    return 'createBoneChain requires 1..1024 valid local joint descriptors with unique roles and animation-safe names across the parent hierarchy. Use normalized perpendicular forward/bend axes and finite rest transforms; an explicit parentRole must match the declared parent. Read the retained source and kiln_discover ids ["createBoneChain"] for the exact contract.';
  if (diagnostic === 'SKIN_BINDING_ARGUMENT')
    return 'createSkinnedPart requires four valid bone indices and finite nonnegative weights per vertex, summing to one unless normalizeWeights:true is explicit. Zero sums are rejected. Assemble distinct named Bones and the parent in one rest-pose hierarchy before binding. Use unbound geometry within the documented budgets and finite invertible transforms. Read the retained source and kiln_discover ids ["createSkinnedPart"] for the exact contract; the Three exporter is required for skin delivery.';
  if (diagnostic === 'EXPORT_MATERIAL_SIDE_UNSUPPORTED')
    return 'EXPORT_MATERIAL_SIDE_UNSUPPORTED: A used material has BackSide, which glTF cannot encode directly. Author inward-facing triangles with FrontSide, or choose DoubleSide when both faces are intended. Neither adds missing geometry. Read the retained program with kiln_source query BackSide to locate the material; source names and exception text do not cross the evaluator boundary.';
  if (diagnostic === 'UNINITIALIZED_BINDING') return UNINITIALIZED_BINDING_ADVICE;
  if (diagnostic === 'LOD_SET') return LOD_SET_ADVICE;
  if (diagnostic === 'OPEN_SHELL') return OPEN_SHELL_ADVICE;
  if (diagnostic === 'DELIVERY_CONTRACT') return DELIVERY_CONTRACT_ADVICE;
  if (diagnostic === 'REQUIRE_SOLID') return REQUIRE_SOLID_ADVICE;
  if (diagnostic === 'BUILD_RESULT') return BUILD_RESULT_ADVICE;
  if (diagnostic === 'MATERIAL_RECIPE_OVERRIDE') return MATERIAL_RECIPE_OVERRIDE_ADVICE;
  if (diagnostic === 'PROGRAM_TYPE_ERROR') return PROGRAM_TYPE_ERROR_ADVICE;
  if (diagnostic === 'PROGRAM_RANGE_ERROR') return PROGRAM_RANGE_ERROR_ADVICE;
  if (diagnostic === 'MESH_DATA_NONFINITE')
    return 'meshGeo positions, normals, UVs and tangents must contain finite numbers representable in Float32. Check missing XYZ components, undefined values, division by zero and overflowing calculations before constructing the arrays. Do not replace invalid values blindly with zero; correct the source calculation. Call kiln_discover for the exact meshGeo data contract.';
  if (diagnostic === 'PORTABLE_COLOR_ARGUMENT')
    return 'compilePortableMaterialSpecV2 baseColor and emissive must be numeric color integers from 0x000000 to 0xffffff, for example baseColor: 0x8a867c. CSS strings and materialRecipe hex-string overrides use different contracts. Omit these fields for their defaults, or call kiln_discover for the exact helper contract.';
  if (diagnostic === 'MATERIAL_RECIPE_TEXTURE_BINDING')
    return 'materialRecipe textureResources maps portable slots to approved resource ID strings. Slots are baseColor, normal, metallicRoughness, emissive and occlusion. albedo is a pbrMaterial field, not a recipe slot. Use kiln_discover to check each resource allowedSlots and recipeIds before binding it; no slot or resource substitution is applied.';
  if (diagnostic === 'PORTABLE_TEXTURE_REFERENCE')
    return 'compilePortableMaterialSpecV2 textures require typed references: { kind: "resource", resourceId: "kiln.texture..." } for an approved resource, or { kind: "procedural", spec: { schemaVersion: 2, ... } } for a procedural texture. Bare resource ID strings are invalid here. Use portable slots such as baseColor and check the exact helper/resource contracts with kiln_discover.';
  if (diagnostic === 'TAPER_CONE_AXIS')
    return 'taperConeGeo(radiusBottom, radiusTop, height, axis, segments): the fourth argument is axis, "x", "y" or "z" (default "y"). Segment count is the fifth argument, for example taperConeGeo(0.03, 0.02, 0.01, "x", 12). Call kiln_discover for the full contract.';
  if (diagnostic === 'PROCEDURAL_TEXTURE_BLEND')
    return 'proceduralTexture layer blend must be normal, multiply, screen, or overlay. Omit blend for normal compositing. Call kiln_discover with ids ["proceduralTexture"] for the supported layer fields.';
  if (diagnostic === 'PART_NAME_ARGUMENT')
    return 'createPart(name, geometry, material, options?): the first argument is a string name. Put the parent Object3D in the fourth argument as { parent: root }.';
  if (diagnostic === 'PART_GEOMETRY_ARGUMENT')
    return 'createPart(name, geometry, material, options?): the second argument must be a BufferGeometry. Call geometry helpers, for example boxGeo(1, 1, 1), instead of passing the function. For async helpers such as roundedBoxGeo, extrudeProfile and revolveProfile, await the result inside async build() before passing it to createPart. Call kiln_discover for the exact return contract.';
  if (diagnostic === 'PART_MATERIAL_ARGUMENT')
    return 'createPart(name, geometry, material, options?): the third argument must be a Three.js material. Wrap a color with gameMaterial(0x808080); a number or settings object alone is not a material. Call kiln_discover for the chosen material helper contract.';
  if (diagnostic === 'SOLID_FLOAT32_COLLAPSE')
    return 'Solid output cannot retain valid faces at Float32 precision. Simplify subprecision features or recenter local geometry; review coincident cut boundaries. Smoothing or replacing normals does not repair collapsed triangles. Kiln did not export a partially repaired solid.';
  if (diagnostic === 'PROFILE_BEVEL_COLLAPSE')
    return 'extrudeProfile or revolveProfile: bevel is too large for this profile; erosion leaves nothing. Reduce bevel below half the narrowest section width, set bevel to 0, or widen the profile. Dimensions and bevel use the same asset units.';
  if (diagnostic === 'TUBE_RADIUS')
    return 'curveToMesh and pipeAlongPath require an explicit positive finite radius representable in Float32, in asset units. A missing or undefined radius is invalid; check the referenced dimension. Radius is half the tube diameter.';
  if (diagnostic === 'MATERIAL_ALPHA_MODE')
    return 'pbrMaterial and portable material specs require lowercase alphaMode: "opaque", "mask", or "blend". Omit it for opaque. Exported glTF uses uppercase mode names; those are not authoring input values.';
  if (diagnostic === 'MATERIAL_COLOR_ARGUMENT')
    return 'gameMaterial, basicMaterial, glassMaterial and lambertMaterial take a color first: a hex number or CSS string. Settings belong in the second argument, for example gameMaterial(0x9a9a96, { roughness: 0.4, metalness: 0.8 }). pbrMaterial uses a different object-form contract; call kiln_discover for its texture and material fields.';
  if (diagnostic === 'MATERIAL_PACKED_CHANNELS')
    return 'pbrMaterial requires one packed texture with G=roughness and B=metalness. Generate or load it for usage "metallicRoughness" and pass metallicRoughness, or pass the same packed texture in both roughness and metalness. Do not combine those forms or pass a texture in only one scalar slot. Plain roughness and metalness values are 0..1 numbers. Call kiln_discover for the exact texture contract.';
  if (diagnostic === 'REMOVED_HELPER')
    return 'Generated source references a retired Kiln global. Call kiln_validate for name-specific migration guidance, then kiln_discover for the replacement contract. No compatibility aliases are provided.';
  if (diagnostic === 'UNBOUND_VARIABLE') return UNBOUND_VARIABLE_ADVICE;
  if (diagnostic === 'ROUNDED_BOX_RADIUS') return ROUNDED_BOX_RADIUS_ADVICE;
  if (diagnostic === 'GEAR_RADII_ORDER') return GEAR_RADII_ORDER_ADVICE;
  if (diagnostic === 'PROCEDURAL_TEXTURE_UNKNOWN_KEY') return PROCEDURAL_TEXTURE_UNKNOWN_KEY_ADVICE;
  if (diagnostic === 'PROCEDURAL_TEXTURE_USAGE') return PROCEDURAL_TEXTURE_USAGE_ADVICE;
  if (diagnostic === 'MATERIAL_FRACTION_RANGE') return MATERIAL_FRACTION_RANGE_ADVICE;
  if (diagnostic === 'MATERIAL_NAME') return MATERIAL_NAME_ADVICE;
  if (diagnostic === 'PROFILE_HOLES_UNSUPPORTED') return PROFILE_HOLES_UNSUPPORTED_ADVICE;
  if (diagnostic === 'PROFILE_SOLID_FAILED') return PROFILE_SOLID_FAILED_ADVICE;
  if (diagnostic === 'PROFILE_CORRESPONDENCE_COLLAPSE')
    return PROFILE_CORRESPONDENCE_COLLAPSE_ADVICE;
  return diagnostic === 'PARAMETRIC_PERIODIC_ENDPOINT' ? PARAMETRIC_PERIODIC_ENDPOINT_ADVICE : '';
}
export class AuthoringDiagnosticError extends Error {
  constructor(
    readonly diagnostic: AuthoringDiagnostic | undefined,
    message = authoringDiagnosticAdvice(diagnostic),
  ) {
    super(message);
    this.name = 'AuthoringDiagnosticError';
  }
}
/**
 * Longest author material name written to a glTF `materials[].name`.
 *
 * Matches the portable material spec's own 1..200 name bound, so naming a material
 * through a helper and naming one through `compilePortableMaterialSpecV3` accept the
 * same strings; that contract checks length only, and this path also rejects control
 * characters.
 */
export const MATERIAL_NAME_MAX_LENGTH = 200;

/**
 * Bound an author material name on the way into the file.
 *
 * A destination runtime groups draws by this string, so it is worth having, but it
 * is also the only author-supplied text the exporters copy verbatim into a
 * `materials[].name`. Rejecting C0 controls and DEL, as `proceduralTexture`'s name
 * rule does, keeps a name out of the business of smuggling a newline into a log
 * line or a NUL into a consumer's string handling; the length bound keeps it from
 * arriving as an unbounded blob in everything that reads the manifest.
 *
 * Fails closed on a non-string for the reason `requireColor` does: a model that
 * half-remembers a different engine passes the wrong shape, and silently
 * stringifying it would put `[object Object]` on a part and call it named.
 */
export function assertMaterialName(name: unknown, fn: string): string {
  if (
    typeof name !== 'string' ||
    !name.length ||
    name.length > MATERIAL_NAME_MAX_LENGTH ||
    [...name].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127)
  )
    throw new AuthoringDiagnosticError(
      'MATERIAL_NAME',
      `${fn}: name must be 1..${MATERIAL_NAME_MAX_LENGTH} visible characters, got ${
        typeof name === 'string' ? JSON.stringify(name.slice(0, 32)) : typeof name
      }. ${MATERIAL_NAME_ADVICE}`,
    );
  return name;
}

/**
 * Closed cause for an error that crosses the worker boundary without a diagnostic.
 * Built-in error classes only, never message text: a temporal-dead-zone read is
 * recognised from the engine's own ReferenceError wording, and TypeError and
 * RangeError name a class of mistake. Anything else stays a generic rejection,
 * as do policy denials.
 */
export function programErrorDiagnostic(error: unknown): AuthoringDiagnostic | undefined {
  if (error instanceof AuthoringDiagnosticError) return error.diagnostic;
  if (
    error instanceof ReferenceError &&
    /^Cannot access (?:'[^']*' before initialization|uninitialized variable)\.?$/.test(
      error.message,
    )
  )
    return 'UNINITIALIZED_BINDING';
  if (error instanceof TypeError) return 'PROGRAM_TYPE_ERROR';
  if (error instanceof RangeError) return 'PROGRAM_RANGE_ERROR';
  return undefined;
}
export function rethrowAuthoringError(error: unknown): never {
  // Unsupported ambient/resource APIs stay generic, including the legacy loadTexture probe.
  // Classification only. No captured identifier, path, message, or stack crosses the boundary.
  if (
    error instanceof ReferenceError &&
    /(?: is not defined$|^Can't find variable: )/.test(error.message) &&
    !/\b(?:loadTexture|process|fetch|globalThis|require|Bun|Deno)\b/.test(error.message)
  ) {
    throw new AuthoringDiagnosticError('UNBOUND_VARIABLE');
  }
  throw error;
}