@tora-editor/tora 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +108 -58
  2. package/assets/free-audio/arcade-pop/audio/loss.wav +0 -0
  3. package/assets/free-audio/arcade-pop/audio/reward.wav +0 -0
  4. package/assets/free-audio/arcade-pop/audio/win.wav +0 -0
  5. package/assets/free-audio/arcade-pop/source/INFO.txt +11 -11
  6. package/assets/kenney-food-starter/License.txt +28 -0
  7. package/assets/kenney-food-starter/burger.glb +0 -0
  8. package/assets/kenney-food-starter/frying-pan.glb +0 -0
  9. package/assets/kenney-food-starter/plan.json +61 -0
  10. package/assets/kenney-food-starter/plate.glb +0 -0
  11. package/assets/kenney-food-starter/pot.glb +0 -0
  12. package/assets/kenney-harvest/audio/victory.wav +0 -0
  13. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_NES/jingles_NES03.ogg +0 -0
  14. package/assets/kenney-harvest/source/music-jingles/OGG/jingles_PIZZA/jingles_PIZZA03.ogg +0 -0
  15. package/assets/kenney-harvest/source/music-jingles/license.txt +14 -0
  16. package/bin/tora.mjs +77 -9
  17. package/crates/packer/trusted/native-3d-meta.json +3 -2
  18. package/crates/packer/trusted/native-3d.js +181 -181
  19. package/crates/packer/trusted/native-meta.json +2 -2
  20. package/crates/packer/trusted/native.js +5 -5
  21. package/crates/packer/trusted/release-manifest.json +17 -17
  22. package/crates/packer/trusted/review-runtime-meta.json +3 -2
  23. package/crates/packer/trusted/review-runtime.js +182 -182
  24. package/docs/TORA_AGENT_SETUP.md +24 -13
  25. package/docs/TORA_CREATION_API.md +29 -12
  26. package/docs/reference/CORE_AUTHORING.md +2 -1
  27. package/docs/reference/PLAYABLE_STARTERS.md +20 -0
  28. package/docs/reference/packs/3d.md +9 -3
  29. package/network-rules/mintegral-appgrowth-single-html.json +10 -10
  30. package/package.json +6 -6
  31. package/packages/creative-project/project-v21.schema.json +264 -8
  32. package/scripts/lean/editor/review-editor.css +10 -0
  33. package/scripts/lean/editor/review-editor.js +117 -1
  34. package/scripts/lean/native/agent-tools.mjs +7 -7
  35. package/scripts/lean/native/api.mjs +16 -5
  36. package/scripts/lean/native/asset-catalog.mjs +7 -6
  37. package/scripts/lean/native/asset-lineage.mjs +54 -0
  38. package/scripts/lean/native/asset-prep.mjs +173 -40
  39. package/scripts/lean/native/assets.mjs +107 -11
  40. package/scripts/lean/native/author-expansion-proofs.mjs +2 -99
  41. package/scripts/lean/native/author-fps.mjs +545 -0
  42. package/scripts/lean/native/author-primitive-proofs.mjs +5 -4
  43. package/scripts/lean/native/build-cache.mjs +2 -2
  44. package/scripts/lean/native/cc0-inputs.mjs +24 -0
  45. package/scripts/lean/native/cc0-staging.mjs +28 -8
  46. package/scripts/lean/native/check-harvest-outcome-audio.mjs +7 -8
  47. package/scripts/lean/native/check-salvage.mjs +8 -5
  48. package/scripts/lean/native/compiler.mjs +9 -3
  49. package/scripts/lean/native/contracts.mjs +11 -8
  50. package/scripts/lean/native/creative-qa.mjs +305 -122
  51. package/scripts/lean/native/demos.mjs +47 -3
  52. package/scripts/lean/native/document.mjs +36 -10
  53. package/scripts/lean/native/export-budget.mjs +75 -0
  54. package/scripts/lean/native/glb-loader.mjs +468 -0
  55. package/scripts/lean/native/intake-creator-tools.mjs +83 -30
  56. package/scripts/lean/native/local-bundle.mjs +5 -3
  57. package/scripts/lean/native/mcp-server.mjs +33 -46
  58. package/scripts/lean/native/media-validate.mjs +124 -0
  59. package/scripts/lean/native/native-bin.mjs +3 -3
  60. package/scripts/lean/native/outcome-playthrough.mjs +97 -0
  61. package/scripts/lean/native/prepare-fps-assets.mjs +330 -0
  62. package/scripts/lean/native/project-bundle.mjs +3 -3
  63. package/scripts/lean/native/remote-cc0-fetcher.mjs +403 -197
  64. package/scripts/lean/native/review-agent-tools.mjs +2 -2
  65. package/scripts/lean/native/review.mjs +3 -0
  66. package/scripts/lean/native/runtime.mjs +242 -56
  67. package/scripts/lean/native/schema.mjs +7 -5
  68. package/scripts/lean/native/service.mjs +159 -32
  69. package/scripts/lean/native/stage-3d.mjs +343 -40
  70. package/scripts/lean/native/starters.mjs +436 -0
  71. package/scripts/lean/native/verify.mjs +1 -1
  72. package/scripts/lean/native/win-cues.mjs +96 -0
  73. package/skills/tora-playables/SKILL.md +1 -1
@@ -0,0 +1,468 @@
1
+ /* global btoa,Image,TextDecoder */
2
+ // Decodes the embedded, static glTF subset validated by the native packer.
3
+ import {
4
+ Bone, Box3, BufferAttribute, BufferGeometry, ClampToEdgeWrapping, Color, DoubleSide,
5
+ FrontSide, Group, LinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter,
6
+ Matrix4, Mesh, MeshBasicMaterial, MeshLambertMaterial, MeshStandardMaterial, MirroredRepeatWrapping,
7
+ NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NoColorSpace,
8
+ Quaternion, RepeatWrapping, Skeleton, SkinnedMesh, SRGBColorSpace, Texture, Vector2, Vector3,
9
+ } from 'three';
10
+
11
+ const arrays = {5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5126: Float32Array};
12
+ const sizes = {SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, MAT4: 16};
13
+ const attributes = {POSITION: 'position', NORMAL: 'normal', COLOR_0: 'color', TEXCOORD_0: 'uv', JOINTS_0: 'skinIndex', WEIGHTS_0: 'skinWeight'};
14
+ const wrapping = {33071: ClampToEdgeWrapping, 33648: MirroredRepeatWrapping, 10497: RepeatWrapping};
15
+ const filters = {9728: NearestFilter, 9729: LinearFilter, 9984: NearestMipmapNearestFilter,
16
+ 9985: LinearMipmapNearestFilter, 9986: NearestMipmapLinearFilter, 9987: LinearMipmapLinearFilter};
17
+
18
+ function check(value) {
19
+ if (!value) throw Error('E_MODEL_CORRUPT');
20
+ }
21
+
22
+ function attribute(bin, view, accessor) {
23
+ const ArrayType = arrays[accessor.componentType], size = sizes[accessor.type];
24
+ check(ArrayType && size && view && !accessor.sparse);
25
+ const unit = ArrayType.BYTES_PER_ELEMENT, packed = size * unit;
26
+ const stride = view.byteStride ?? packed, offset = accessor.byteOffset ?? 0;
27
+ const start = (view.byteOffset ?? 0) + offset, count = accessor.count;
28
+ check(Number.isSafeInteger(count) && count > 0 && offset >= 0 && start >= 0 &&
29
+ stride >= packed && stride % unit === 0 && start % unit === 0 &&
30
+ offset + (count - 1) * stride + packed <= view.byteLength &&
31
+ start + (count - 1) * stride + packed <= bin.length);
32
+ const scalars = new ArrayType(bin.buffer, bin.byteOffset + start, ((count - 1) * stride + packed) / unit);
33
+ if (stride === packed) return new BufferAttribute(scalars, size, !!accessor.normalized);
34
+ // Release padding and interleaved siblings without changing the integer GPU format.
35
+ const out = new ArrayType(count * size);
36
+ for (let i = 0; i < count; i++) {
37
+ const at = i * stride / unit;
38
+ out.set(scalars.subarray(at, at + size), i * size);
39
+ }
40
+ return new BufferAttribute(out, size, !!accessor.normalized);
41
+ }
42
+
43
+ function embeddedImage(bytes, mime, complete) {
44
+ let binary = '';
45
+ for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
46
+ const image = new Image();
47
+ image.onload = () => complete(true);
48
+ image.onerror = () => complete(false);
49
+ image.src = 'data:' + mime + ';base64,' + btoa(binary);
50
+ return image;
51
+ }
52
+
53
+ export function parseGlb(bytes, onTextureReady) {
54
+ check(bytes.byteLength >= 28 && bytes.byteLength <= 700000);
55
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
56
+ const word = offset => view.getUint32(offset, true);
57
+ check(word(0) === 0x46546c67 && word(4) === 2 && word(8) === bytes.byteLength && word(16) === 0x4e4f534a);
58
+ const binAt = 20 + word(12);
59
+ check(binAt % 4 === 0 && binAt + 8 <= bytes.byteLength && word(binAt + 4) === 0x004e4942 &&
60
+ word(binAt) === bytes.byteLength - binAt - 8);
61
+ const gltf = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes.subarray(20, binAt)));
62
+ check(gltf.asset?.version === '2.0' && gltf.buffers?.length === 1 && gltf.buffers[0].uri === undefined &&
63
+ (gltf.skins?.length ?? 0) <= 4 && (gltf.animations?.length ?? 0) <= 16);
64
+ const bin = bytes.subarray(binAt + 8);
65
+ const textureCache = new Map(), images = new Map(), accessors = new Map(), nodesByName = new Map();
66
+ const geometries = new Set(), materials = new Set();
67
+ function accessor(id) {
68
+ if (!accessors.has(id)) {
69
+ const a = gltf.accessors[id];
70
+ accessors.set(id, attribute(bin, gltf.bufferViews[a.bufferView], a));
71
+ }
72
+ return accessors.get(id);
73
+ }
74
+ function texture(info, colorSpace) {
75
+ if (!info) return null;
76
+ const transform = info.extensions?.KHR_texture_transform ?? {};
77
+ check((transform.texCoord ?? info.texCoord ?? 0) === 0);
78
+ const key = JSON.stringify([info.index, colorSpace, transform]);
79
+ if (textureCache.has(key)) return textureCache.get(key);
80
+ const def = gltf.textures[info.index], source = gltf.images[def.source], sampler = gltf.samplers?.[def.sampler] ?? {};
81
+ const tex = new Texture();
82
+ tex.colorSpace = colorSpace;
83
+ tex.flipY = false;
84
+ tex.wrapS = wrapping[sampler.wrapS ?? 10497];
85
+ tex.wrapT = wrapping[sampler.wrapT ?? 10497];
86
+ tex.magFilter = filters[sampler.magFilter ?? 9729];
87
+ tex.minFilter = filters[sampler.minFilter ?? 9987];
88
+ if (transform.offset) tex.offset.fromArray(transform.offset);
89
+ if (transform.scale) tex.repeat.fromArray(transform.scale);
90
+ tex.rotation = transform.rotation ?? 0;
91
+ textureCache.set(key, tex);
92
+ if (!images.has(def.source)) {
93
+ const imageView = gltf.bufferViews[source.bufferView], start = imageView?.byteOffset ?? 0;
94
+ check(imageView && !source.uri && ['image/png', 'image/jpeg'].includes(source.mimeType) &&
95
+ start + imageView.byteLength <= bin.length);
96
+ const entry = {textures: [], ready: false, failed: false};
97
+ images.set(def.source, entry);
98
+ entry.image = embeddedImage(bin.subarray(start, start + imageView.byteLength), source.mimeType, ok => {
99
+ entry.ready = true;
100
+ entry.failed = !ok;
101
+ if (ok) for (const t of entry.textures) t.needsUpdate = true;
102
+ onTextureReady?.();
103
+ });
104
+ }
105
+ const entry = images.get(def.source);
106
+ tex.image = entry.image;
107
+ entry.textures.push(tex);
108
+ if (entry.ready && !entry.failed) tex.needsUpdate = true;
109
+ return tex;
110
+ }
111
+
112
+ const materialCache = new Map();
113
+ function material(index, vertexColors) {
114
+ const key = String(index) + '/' + vertexColors;
115
+ if (materialCache.has(key)) return materialCache.get(key);
116
+ const def = gltf.materials?.[index] ?? {}, pbr = def.pbrMetallicRoughness ?? {};
117
+ const base = pbr.baseColorFactor ?? [1, 1, 1, 1], alpha = def.alphaMode ?? 'OPAQUE';
118
+ const params = {name: def.name ?? '', color: new Color().fromArray(base), vertexColors,
119
+ map: texture(pbr.baseColorTexture, SRGBColorSpace), side: def.doubleSided ? DoubleSide : FrontSide,
120
+ opacity: alpha === 'OPAQUE' ? 1 : base[3], transparent: alpha === 'BLEND',
121
+ depthWrite: alpha !== 'BLEND', alphaTest: alpha === 'MASK' ? (def.alphaCutoff ?? 0.5) : 0};
122
+ let mat;
123
+ if (def.extensions?.KHR_materials_unlit) mat = new MeshBasicMaterial(params);
124
+ else {
125
+ const orm = texture(pbr.metallicRoughnessTexture, NoColorSpace);
126
+ mat = new MeshStandardMaterial({...params, roughness: pbr.roughnessFactor ?? 1,
127
+ metalness: pbr.metallicFactor ?? 1, roughnessMap: orm, metalnessMap: orm,
128
+ normalMap: texture(def.normalTexture, NoColorSpace), normalScale: new Vector2().setScalar(def.normalTexture?.scale ?? 1),
129
+ aoMap: texture(def.occlusionTexture, NoColorSpace), aoMapIntensity: def.occlusionTexture?.strength ?? 1,
130
+ emissive: new Color().fromArray(def.emissiveFactor ?? [0, 0, 0]),
131
+ emissiveMap: texture(def.emissiveTexture, SRGBColorSpace),
132
+ emissiveIntensity: def.extensions?.KHR_materials_emissive_strength?.emissiveStrength ?? 1});
133
+ // Without supplied tangents, Three derives a basis in its default (+Y) texture convention.
134
+ mat.normalScale.y *= -1;
135
+ }
136
+ materials.add(mat);
137
+ materialCache.set(key, mat);
138
+ return mat;
139
+ }
140
+
141
+ const meshes = gltf.meshes.map(mesh => mesh.primitives.map(p => {
142
+ check((p.mode ?? 4) === 4 && p.attributes.POSITION !== undefined && !p.targets);
143
+ const geo = new BufferGeometry();
144
+ for (const [semantic, id] of Object.entries(p.attributes)) {
145
+ check(Object.hasOwn(attributes, semantic));
146
+ geo.setAttribute(attributes[semantic], accessor(id));
147
+ }
148
+ if (p.indices !== undefined) geo.setIndex(accessor(p.indices));
149
+ if (!geo.attributes.normal) geo.computeVertexNormals();
150
+ geometries.add(geo);
151
+ return {geo, mat: material(p.material, !!geo.attributes.color)};
152
+ }));
153
+ const jointIndices = new Set();
154
+ for (const s of gltf.skins ?? []) for (const j of s.joints ?? []) jointIndices.add(j);
155
+ const root = new Group(), visited = new Set(), nodesByIndex = new Map(), skinnedMeshes = [];
156
+ function node(index, parent) {
157
+ check(!visited.has(index) && visited.size < 128);
158
+ visited.add(index);
159
+ const def = gltf.nodes[index], obj = jointIndices.has(index) ? new Bone() : new Group();
160
+ obj.name = def.name ?? '';
161
+ obj.userData.gltfNodeIndex = index;
162
+ nodesByIndex.set(index, obj);
163
+ if (obj.name && !nodesByName.has(obj.name)) nodesByName.set(obj.name, obj);
164
+ if (def.matrix) obj.matrix.fromArray(def.matrix).decompose(obj.position, obj.quaternion, obj.scale);
165
+ else {
166
+ if (def.translation) obj.position.fromArray(def.translation);
167
+ if (def.rotation) obj.quaternion.fromArray(def.rotation);
168
+ if (def.scale) obj.scale.fromArray(def.scale);
169
+ }
170
+ parent.add(obj);
171
+ if (def.mesh !== undefined) {
172
+ for (const {geo, mat} of meshes[def.mesh]) {
173
+ if (def.skin !== undefined) {
174
+ const sm = new SkinnedMesh(geo, mat);
175
+ sm.userData.gltfSkinIndex = def.skin;
176
+ obj.add(sm);
177
+ skinnedMeshes.push(sm);
178
+ } else {
179
+ obj.add(new Mesh(geo, mat));
180
+ }
181
+ }
182
+ }
183
+ for (const id of def.children ?? []) node(id, obj);
184
+ }
185
+ for (const index of gltf.scenes[gltf.scene ?? 0].nodes ?? []) node(index, root);
186
+ root.updateMatrixWorld(true);
187
+ const skins = (gltf.skins ?? []).map(skinDef => {
188
+ const joints = skinDef.joints ?? [];
189
+ check(joints.length > 0 && joints.length <= 64);
190
+ let inverseBindMatrices;
191
+ if (skinDef.inverseBindMatrices !== undefined) {
192
+ const arr = accessor(skinDef.inverseBindMatrices).array;
193
+ inverseBindMatrices = Array.from({length: joints.length}, (_, i) => new Matrix4().fromArray(arr, i * 16));
194
+ } else {
195
+ inverseBindMatrices = joints.map(() => new Matrix4());
196
+ }
197
+ return {joints, inverseBindMatrices};
198
+ });
199
+ for (const sm of skinnedMeshes) {
200
+ const skin = skins[sm.userData.gltfSkinIndex];
201
+ check(skin);
202
+ const bones = skin.joints.map(j => nodesByIndex.get(j));
203
+ check(bones.every(Boolean));
204
+ sm.bind(new Skeleton(bones, skin.inverseBindMatrices.map(m => m.clone())), new Matrix4());
205
+ }
206
+ const animations = [], animationsByName = new Map();
207
+ for (const [clipIdx, anim] of (gltf.animations ?? []).entries()) {
208
+ const name = anim.name || ('clip_' + clipIdx);
209
+ const tracks = [];
210
+ let duration = 0;
211
+ for (const ch of anim.channels ?? []) {
212
+ const nodeIndex = ch.target?.node, path = ch.target?.path;
213
+ if (nodeIndex === undefined || !['translation', 'rotation', 'scale'].includes(path)) continue;
214
+ const sampler = anim.samplers?.[ch.sampler];
215
+ check(sampler);
216
+ const interp = sampler.interpolation ?? 'LINEAR';
217
+ check(interp === 'LINEAR' || interp === 'STEP');
218
+ const times = accessor(sampler.input).array;
219
+ const values = accessor(sampler.output).array;
220
+ if (times.length) duration = Math.max(duration, times[times.length - 1]);
221
+ tracks.push({nodeIndex, path, interp, times, values});
222
+ }
223
+ const clip = {name, duration, tracks};
224
+ animations.push(clip);
225
+ if (!animationsByName.has(name)) animationsByName.set(name, clip);
226
+ }
227
+ return {root, nodesByName, skins, animations, animationsByName, geometries, materials, textures: textureCache,
228
+ imageStatus() {
229
+ let texturesPending = 0, textureErrors = 0;
230
+ for (const image of images.values()) {
231
+ if (!image.ready) texturesPending++;
232
+ if (image.failed) textureErrors++;
233
+ }
234
+ return {texturesPending, textureErrors};
235
+ }};
236
+ }
237
+
238
+ function customMaterial(source, opts, external) {
239
+ const mode = opts.materialMode ?? 'asset';
240
+ const matches = !opts.overrideMaterialName || source.name === opts.overrideMaterialName;
241
+ const override = matches && Object.keys(external).length > 0;
242
+ if (mode === 'asset' && !override && (opts.opacity ?? 1) === 1 &&
243
+ (!opts.tintColor || opts.tintColor === '#ffffff') && (opts.roughnessScale ?? 1) === 1 &&
244
+ (opts.metalnessScale ?? 1) === 1) return source;
245
+ const ctor = {lambert: MeshLambertMaterial, unlit: MeshBasicMaterial, standard: MeshStandardMaterial}[mode];
246
+ let mat;
247
+ if (!ctor || source.constructor === ctor) mat = source.clone();
248
+ else {
249
+ mat = new ctor();
250
+ for (const key of ['name', 'map', 'alphaTest', 'transparent', 'opacity', 'side', 'depthWrite', 'vertexColors',
251
+ 'roughness', 'metalness', 'roughnessMap', 'metalnessMap', 'normalMap', 'aoMap', 'aoMapIntensity', 'emissiveMap', 'emissiveIntensity']) {
252
+ if (key in mat && key in source) mat[key] = source[key];
253
+ }
254
+ for (const key of ['color', 'emissive', 'normalScale']) if (mat[key] && source[key]) mat[key].copy(source[key]);
255
+ }
256
+ if (opts.tintColor) mat.color.multiply(new Color(opts.tintColor));
257
+ mat.opacity *= opts.opacity ?? 1;
258
+ if (mat.opacity < 1 && (opts.opacity ?? 1) < 1) { mat.transparent = true; mat.depthWrite = false; }
259
+ if (mat.isMeshStandardMaterial) {
260
+ mat.roughness = Math.min(1, mat.roughness * (opts.roughnessScale ?? 1));
261
+ mat.metalness = Math.min(1, mat.metalness * (opts.metalnessScale ?? 1));
262
+ }
263
+ if (override) {
264
+ if (external.texture) mat.map = external.texture;
265
+ if (external.normalMap && 'normalMap' in mat) mat.normalMap = external.normalMap;
266
+ if (external.emissiveMap && 'emissiveMap' in mat) mat.emissiveMap = external.emissiveMap;
267
+ }
268
+ return mat;
269
+ }
270
+
271
+ export function cloneModelTemplate(template, opts = {}, externalTextures = {}) {
272
+ const source = opts.subNode ? template.nodesByName.get(opts.subNode) : template.root;
273
+ if (!source) throw Error('E_MODEL_SUBNODE ' + opts.subNode);
274
+ const model = source.clone(true), root = new Group(), remapped = new Map();
275
+ if (opts.subNode) {
276
+ // Keep the authored orientation and inherited scale while placing the selected part at its own pivot.
277
+ model.position.set(0, 0, 0);
278
+ if (source.parent) {
279
+ const parentBasis = source.parent.matrixWorld.clone().setPosition(0, 0, 0);
280
+ model.updateMatrix();
281
+ model.matrix.premultiply(parentBasis);
282
+ model.matrixAutoUpdate = false;
283
+ }
284
+ }
285
+ root.add(model);
286
+ const clonedByIndex = new Map(), clonedSkinned = [];
287
+ model.traverse(obj => {
288
+ if (obj.userData?.gltfNodeIndex !== undefined) clonedByIndex.set(obj.userData.gltfNodeIndex, obj);
289
+ if (!obj.isMesh) return;
290
+ const original = obj.material;
291
+ if (!remapped.has(original)) remapped.set(original, customMaterial(original, opts, externalTextures));
292
+ obj.material = remapped.get(original);
293
+ obj.castShadow = !!opts.castShadow;
294
+ obj.receiveShadow = !!opts.receiveShadow;
295
+ if (obj.isSkinnedMesh && obj.userData?.gltfSkinIndex !== undefined) clonedSkinned.push(obj);
296
+ });
297
+ if (clonedSkinned.length) {
298
+ root.updateMatrixWorld(true);
299
+ for (const sm of clonedSkinned) {
300
+ const skin = template.skins?.[sm.userData.gltfSkinIndex];
301
+ if (!skin) continue;
302
+ const bones = skin.joints.map(j => clonedByIndex.get(j)).filter(Boolean);
303
+ if (bones.length === skin.joints.length) {
304
+ sm.bind(new Skeleton(bones, skin.inverseBindMatrices.map(m => m.clone())), new Matrix4());
305
+ }
306
+ }
307
+ }
308
+ root.userData.clonedByIndex = clonedByIndex;
309
+ root.userData.template = template;
310
+ const box = new Box3().setFromObject(root, true);
311
+ if (!box.isEmpty()) {
312
+ const size = box.getSize(new Vector3()), pivot = new Vector3();
313
+ const maxSide = Math.max(size.x, size.y, size.z);
314
+ if (opts.pivotMode === 'center' || opts.pivotMode === 'bottom-center') {
315
+ box.getCenter(pivot);
316
+ if (opts.pivotMode === 'bottom-center') pivot.y = box.min.y;
317
+ }
318
+ if (opts.normalizeSize > 0 && maxSide > 0) root.scale.setScalar(opts.normalizeSize / maxSide);
319
+ root.position.copy(pivot).multiplyScalar(-root.scale.x);
320
+ root.userData.modelBounds = {width: size.x * root.scale.x, height: size.y * root.scale.y, depth: size.z * root.scale.z};
321
+ }
322
+ return root;
323
+ }
324
+
325
+ const _vA = new Vector3(), _vB = new Vector3(), _qA = new Quaternion(), _qB = new Quaternion();
326
+
327
+ function sampleTrack(track, t, outVec, outQuat) {
328
+ const times = track.times, vals = track.values, n = times.length;
329
+ const stride = track.path === 'rotation' ? 4 : 3;
330
+ if (n === 0) return;
331
+ let i0 = 0, i1 = 0, u = 0;
332
+ if (n > 1 && t > times[0]) {
333
+ if (t >= times[n - 1]) { i0 = i1 = n - 1; }
334
+ else {
335
+ let lo = 0, hi = n - 1;
336
+ while (lo + 1 < hi) {
337
+ const mid = (lo + hi) >> 1;
338
+ if (times[mid] <= t) lo = mid; else hi = mid;
339
+ }
340
+ i0 = lo; i1 = hi;
341
+ u = track.interp === 'STEP' ? 0 : (t - times[i0]) / Math.max(1e-8, times[i1] - times[i0]);
342
+ }
343
+ }
344
+ const o0 = i0 * stride, o1 = i1 * stride;
345
+ if (track.path === 'rotation') {
346
+ _qA.set(vals[o0], vals[o0 + 1], vals[o0 + 2], vals[o0 + 3]);
347
+ if (i0 === i1 || u === 0) { outQuat.copy(_qA); return; }
348
+ _qB.set(vals[o1], vals[o1 + 1], vals[o1 + 2], vals[o1 + 3]);
349
+ outQuat.copy(_qA).slerp(_qB, u);
350
+ } else {
351
+ _vA.set(vals[o0], vals[o0 + 1], vals[o0 + 2]);
352
+ if (i0 === i1 || u === 0) { outVec.copy(_vA); return; }
353
+ _vB.set(vals[o1], vals[o1 + 1], vals[o1 + 2]);
354
+ outVec.copy(_vA).lerp(_vB, u);
355
+ }
356
+ }
357
+
358
+ function foldedTime(rawTime, duration, loop) {
359
+ if (duration <= 0) return 0;
360
+ if (loop === 'once') return Math.min(duration, Math.max(0, rawTime));
361
+ if (loop === 'pingpong') {
362
+ const cycle = duration * 2;
363
+ const m = ((rawTime % cycle) + cycle) % cycle;
364
+ return m <= duration ? m : cycle - m;
365
+ }
366
+ return ((rawTime % duration) + duration) % duration;
367
+ }
368
+
369
+ export function createModelAnimator(modelRoot) {
370
+ const template = modelRoot?.userData?.template;
371
+ const nodes = modelRoot?.userData?.clonedByIndex;
372
+ if (!template?.animations?.length || !nodes) return null;
373
+ const restPose = new Map();
374
+ for (const clip of template.animations) {
375
+ for (const tr of clip.tracks) {
376
+ const obj = nodes.get(tr.nodeIndex);
377
+ if (obj && !restPose.has(tr.nodeIndex)) {
378
+ restPose.set(tr.nodeIndex, {pos: obj.position.clone(), quat: obj.quaternion.clone(), scl: obj.scale.clone()});
379
+ }
380
+ }
381
+ }
382
+ const restoreRest = () => {
383
+ for (const [idx, rest] of restPose) {
384
+ const obj = nodes.get(idx);
385
+ if (!obj) continue;
386
+ obj.position.copy(rest.pos);
387
+ obj.quaternion.copy(rest.quat);
388
+ obj.scale.copy(rest.scl);
389
+ }
390
+ };
391
+ let active = null, prev = null, fadeElapsed = 0, fadeDuration = 0;
392
+ const scratchV = new Vector3(), scratchQ = new Quaternion();
393
+ const applyPose = () => {
394
+ restoreRest();
395
+ const alpha = prev && fadeDuration > 0 ? Math.min(1, fadeElapsed / fadeDuration) : 1;
396
+ if (prev && alpha < 1) {
397
+ const pt = foldedTime(prev.time, prev.clip.duration, prev.loop);
398
+ for (const tr of prev.clip.tracks) {
399
+ const obj = nodes.get(tr.nodeIndex);
400
+ if (!obj) continue;
401
+ sampleTrack(tr, pt, scratchV, scratchQ);
402
+ if (tr.path === 'translation') obj.position.copy(scratchV);
403
+ else if (tr.path === 'rotation') obj.quaternion.copy(scratchQ);
404
+ else if (tr.path === 'scale') obj.scale.copy(scratchV);
405
+ }
406
+ }
407
+ if (active) {
408
+ const ct = foldedTime(active.time, active.clip.duration, active.loop);
409
+ for (const tr of active.clip.tracks) {
410
+ const obj = nodes.get(tr.nodeIndex);
411
+ if (!obj) continue;
412
+ sampleTrack(tr, ct, scratchV, scratchQ);
413
+ if (tr.path === 'translation') { if (alpha < 1) obj.position.lerp(scratchV, alpha); else obj.position.copy(scratchV); }
414
+ else if (tr.path === 'rotation') { if (alpha < 1) obj.quaternion.slerp(scratchQ, alpha); else obj.quaternion.copy(scratchQ); }
415
+ else if (tr.path === 'scale') { if (alpha < 1) obj.scale.lerp(scratchV, alpha); else obj.scale.copy(scratchV); }
416
+ }
417
+ }
418
+ };
419
+ return {
420
+ play(clipName, {loop = 'repeat', speed = 1, fadeSeconds = 0.15, restart = false, startTime = 0} = {}) {
421
+ const clip = clipName ? template.animationsByName.get(clipName) : template.animations[0];
422
+ if (!clip) return false;
423
+ if (active?.clip === clip && !restart && active.playing) {
424
+ active.loop = loop;
425
+ active.speed = speed;
426
+ return true;
427
+ }
428
+ prev = active && fadeSeconds > 0 ? {...active} : null;
429
+ fadeDuration = prev ? fadeSeconds : 0;
430
+ fadeElapsed = 0;
431
+ active = {clip, loop, speed, time: startTime, playing: true, ended: false};
432
+ applyPose();
433
+ return true;
434
+ },
435
+ step(dt, onEnd) {
436
+ if (!active || !active.playing) return false;
437
+ const stepDt = Math.max(0, dt);
438
+ if (prev && fadeDuration > 0) {
439
+ prev.time += stepDt * prev.speed;
440
+ fadeElapsed += stepDt;
441
+ if (fadeElapsed >= fadeDuration) { prev = null; fadeDuration = 0; }
442
+ }
443
+ active.time += stepDt * active.speed;
444
+ let finishedClip = null;
445
+ if (active.loop === 'once' && active.clip.duration > 0 && active.time >= active.clip.duration) {
446
+ active.time = active.clip.duration;
447
+ active.playing = false;
448
+ if (!active.ended) { active.ended = true; finishedClip = active.clip.name; }
449
+ }
450
+ applyPose();
451
+ if (finishedClip) onEnd?.(finishedClip);
452
+ return true;
453
+ },
454
+ reset() {
455
+ active = null; prev = null; fadeElapsed = 0; fadeDuration = 0;
456
+ restoreRest();
457
+ },
458
+ snapshot() {
459
+ return {
460
+ clip: active?.clip?.name ?? null,
461
+ time: active ? Number(active.time.toFixed(4)) : 0,
462
+ playing: Boolean(active?.playing),
463
+ loop: active?.loop ?? 'repeat',
464
+ clips: template.animations.map(c => c.name),
465
+ };
466
+ },
467
+ };
468
+ }
@@ -1,24 +1,42 @@
1
1
  import {Buffer} from 'node:buffer';
2
2
  import {readFile} from 'node:fs/promises';
3
3
  import {resolve} from 'node:path';
4
- import {registerSource,safeFile} from './assets.mjs';
4
+ import {registerSourceBytes} from './assets.mjs';
5
5
  import {AssetCatalog,assertAssetSourceAllowed,inspectMedia} from './asset-catalog.mjs';
6
6
  import {NativeAgentTools} from './agent-tools.mjs';
7
- import {check,exact} from './document.mjs';
7
+ import {check,exact,identifier} from './document.mjs';
8
8
  import {RemoteCc0Fetcher} from './remote-cc0-fetcher.mjs';
9
9
  import {mapWithConcurrency} from './concurrency.mjs';
10
- import {assertSingleVisualStyleFamily} from './cc0-staging.mjs';
10
+ import {assertSingleVisualStyleFamily,compactAssetProvenance,resolveCc0SourceItem} from './cc0-staging.mjs';
11
+ import {fetchCc0Properties,stageCc0ItemSchema,validStageCc0Item} from './cc0-inputs.mjs';
11
12
 
12
13
  const identity=value=>({revisionId:value.revisionId,contentHash:value.contentHash});
13
- const compactAsset=asset=>({id:asset.id,name:asset.name,mime:asset.mime,kind:asset.kind??(asset.mime.startsWith('image/')?'sprite':'audio'),bytes:asset.bytes,width:asset.width,height:asset.height,durationSec:asset.durationSec,styleFamily:asset.styleFamily,license:asset.license??'creator-declared',source:asset.source??'studio',sourceUrl:asset.sourceUrl,author:asset.author});
14
+ function compactAsset(asset){
15
+ const kind=asset.kind??(asset.mime.startsWith('image/')?'sprite':asset.mime.startsWith('model/')?'mesh':'audio');
16
+ const facts={id:asset.id,name:asset.name,mime:asset.mime,kind,bytes:asset.bytes,width:asset.width,height:asset.height,
17
+ durationSec:asset.durationSec,styleFamily:asset.styleFamily,license:asset.license??'creator-declared',
18
+ source:asset.source??'studio',sourceUrl:asset.sourceUrl,author:asset.author};
19
+ if(kind==='mesh'){
20
+ const {subNodes=[],animations=[]}=asset;
21
+ Object.assign(facts,{triangles:asset.triangles,textureBytes:asset.textureBytes,
22
+ subNodes:subNodes.slice(0,6),subNodeCount:asset.subNodeCount??subNodes.length,
23
+ animations:animations.slice(0,4),animationCount:asset.animationCount??animations.length});
24
+ }
25
+ return facts;
26
+ }
27
+ const conciseSkippedModels=items=>items.slice(0,8).map(({path,code,reason})=>({path,code,reason:String(reason??'').slice(0,240)}));
28
+ const assetPick=({id,name,kind,styleFamily})=>({id,name,kind,styleFamily});
29
+ const sameStagingSource=(stored,requested)=>stored.sourceHash===requested.sourceHash&&
30
+ (!stored.sourceAssetId||stored.sourceAssetId===requested.sourceAssetId)&&
31
+ JSON.stringify(stored.stageOptions)===JSON.stringify(requested.stageOptions);
14
32
  function bounded(value,limit=24_000){
15
33
  const text=JSON.stringify(value);if(Buffer.byteLength(text)>limit)throw Error('E_CREATOR_TOOL_RESPONSE_LIMIT');return value;
16
34
  }
17
35
  export const creatorToolDefinitions=[
18
36
  {name:'discover_contracts',description:'Discover exact Tora contracts before authoring. Use packs for complete domains, names for individual descriptors, or both. Use format:"compact" for concise schema with units.',parameters:{type:'object',properties:{names:{type:'array',items:{type:'string'},maxItems:16},packs:{type:'array',items:{type:'string'},maxItems:7},format:{type:'string',enum:['full','compact']}},additionalProperties:false}},
19
37
  {name:'list_assets',description:'List creator uploads and verified local CC0 media with dimensions and provenance. Optionally search allowlisted live CC0 providers.',parameters:{type:'object',properties:{query:{type:'string'},kind:{type:'string',enum:['sprite','audio','mesh']},styleFamily:{type:'string'},includeRemote:{type:'boolean'}},additionalProperties:false}},
20
- {name:'fetch_remote_pack',description:'Fetch and verify one allowlisted Kenney or OpenGameArt CC0 pack. Returns cached normalized media and license receipts.',parameters:{type:'object',properties:{sourceUrl:{type:'string'},packId:{type:'string'},fileFilter:{type:'string'}},required:['sourceUrl'],additionalProperties:false}},
21
- {name:'stage_assets',description:'Stage verified uploaded, local catalog, or fetched remote assets into the draft in one atomic revision. Asset-source slider and one visual style family are enforced.',parameters:{type:'object',properties:{intakeAssetIds:{type:'array',items:{type:'string'}},catalogAssetIds:{type:'array',items:{type:'string'}},remoteAssetIds:{type:'array',items:{type:'string'}}},additionalProperties:false}},
38
+ {name:'fetch_remote_pack',description:'Fetch and verify one allowlisted Kenney, Quaternius, or OpenGameArt CC0 pack. Returns cached normalized 2D, audio, or 3D media and license receipts.',parameters:{type:'object',properties:fetchCc0Properties,required:['sourceUrl'],additionalProperties:false}},
39
+ {name:'stage_assets',description:'Stage verified uploaded, local catalog, or cached remote assets into the draft. Use remoteItems to set a target asset ID or per-model preparation options. Asset-source mode and one visual style family are enforced.',parameters:{type:'object',properties:{intakeAssetIds:{type:'array',items:{type:'string'}},catalogAssetIds:{type:'array',items:{type:'string'}},remoteAssetIds:{type:'array',items:{type:'string'}},remoteItems:{type:'array',items:stageCc0ItemSchema}},additionalProperties:false}},
22
40
  {name:'inspect_draft',description:'Inspect draft revision, records, and dependencies with bounded results. Use tree:true for a compact scene outline.',parameters:{type:'object',properties:{ids:{type:'array',items:{type:'string'}},search:{type:'string'},tree:{type:'boolean'},sceneId:{type:'string'}},additionalProperties:false}},
23
41
  {name:'apply_operations',description:'Preview and atomically commit a tora-transaction-1 operation batch. Register assets only through stage_assets.',parameters:{type:'object',properties:{operations:{type:'array',items:{type:'object'}},summary:{type:'string'}},required:['operations','summary'],additionalProperties:false}},
24
42
  {name:'run_qa',description:'Compile and run static, acoustic, four-viewport, and interaction Creative QA. Returned screenshots must be visually inspected before finishing.',parameters:{type:'object',properties:{target:{type:'string',enum:['standalone-browser-draft','unity-ads-ua-playable','applovin-growth-playable']}},additionalProperties:false}},
@@ -27,7 +45,7 @@ export const creatorToolDefinitions=[
27
45
 
28
46
  export class IntakeCreatorTools{
29
47
  constructor(service,intakes,intake,{catalog,fetcher,onProgress=()=>{},signal}={}){
30
- this.service=service;this.intakes=intakes;this.intake=intake;this.catalog=catalog??new AssetCatalog();this.fetcher=fetcher??new RemoteCc0Fetcher({catalog:this.catalog});this.onProgress=onProgress;this.signal=signal;this.agent=new NativeAgentTools(service);this.remote=new Map();this.qaCount=0;this.lastQa=null;this.finished=null;
48
+ this.service=service;this.intakes=intakes;this.intake=intake;this.catalog=catalog??new AssetCatalog();this.fetcher=fetcher??new RemoteCc0Fetcher({workspaceRoot:service.store.workspaceRoot,catalog:this.catalog});this.onProgress=onProgress;this.signal=signal;this.agent=new NativeAgentTools(service);this.qaCount=0;this.lastQa=null;this.finished=null;
31
49
  }
32
50
  async execute(name,args={}){
33
51
  if(this.signal?.aborted)throw Error('E_BUILD_CANCELLED');
@@ -59,17 +77,43 @@ export class IntakeCreatorTools{
59
77
  const localMatches=(result.assets??[]).filter(item=>!item.isRemotePack&&(item.mime||!item.sourceUrl));
60
78
  localAssets=[...studio,...localMatches];
61
79
  }
62
- const query=String(args.query??'').toLowerCase();
63
- const filteredLocal=localAssets.filter(asset=>(!args.kind||asset.kind===args.kind)&&(!args.styleFamily||asset.styleFamily===args.styleFamily)&&(!query||JSON.stringify(asset).toLowerCase().includes(query))).slice(0,40);
64
- const filteredRemote=remotePacks.slice(0,12);
65
- return bounded({mode,online,warning,assets:filteredLocal,remotePacks:filteredRemote,fallbackLocalMatches:fallbackLocalMatches.slice(0,12),localCatalog:this.catalog.summary()});
80
+ const words=String(args.query??'').toLowerCase().split(/\s+/).filter(Boolean);
81
+ const matching=localAssets.filter(asset=>{
82
+ if(args.kind&&asset.kind!==args.kind||args.styleFamily&&asset.styleFamily!==args.styleFamily)return false;
83
+ if(!words.length)return true;
84
+ const searchable=JSON.stringify(asset).toLowerCase();
85
+ return words.every(word=>searchable.includes(word));
86
+ });
87
+ const filteredLocal=matching.slice(0,40).map(compactAsset);
88
+ const filteredRemote=remotePacks.slice(0,12),fallback=fallbackLocalMatches.slice(0,12).map(assetPick);
89
+ let assets=filteredLocal,packs=filteredRemote,truncated=matching.length>40||remotePacks.length>12;
90
+ const payload=()=>({mode,online,warning,assets,remotePacks:packs,...(!online?{fallbackLocalMatches:fallback}:{}),...(truncated?{truncated}:{}),localCatalog:this.catalog.summary()});
91
+ while(Buffer.byteLength(JSON.stringify(payload()))>=24_000&&assets.length){assets=assets.slice(0,-1);truncated=true;}
92
+ while(Buffer.byteLength(JSON.stringify(payload()))>=24_000&&packs.length){packs=packs.slice(0,-1);truncated=true;}
93
+ return bounded(payload());
66
94
  }
67
95
  async fetchRemotePack(args){
68
- check(exact(args,['sourceUrl','packId','fileFilter']),'E_CREATOR_TOOL_ARGUMENT');assertAssetSourceAllowed(this.intake.assetSource??'studio-assets','remote');
96
+ check(exact(args,Object.keys(fetchCc0Properties))&&typeof args.sourceUrl==='string','E_CREATOR_TOOL_ARGUMENT');assertAssetSourceAllowed(this.intake.assetSource??'studio-assets','remote');
69
97
  await this.onProgress({phase:'assets',stepLabel:'Verifying licensed CC0 assets…'});
70
- const receipt=await this.fetcher.fetchPackWithFallback({...args,signal:this.signal});
71
- for(const file of receipt.files??[])this.remote.set(file.id,{file,receipt});
72
- return bounded(receipt);
98
+ let receipt;
99
+ try{receipt=await this.fetcher.fetchPackWithFallback({...args,signal:this.signal});}
100
+ catch(error){
101
+ if(error.detail?.skippedModels){
102
+ const skippedModels=conciseSkippedModels(error.detail.skippedModels);
103
+ error.detail={...error.detail,skippedModels,...(skippedModels.length<error.detail.skippedModels.length?{truncated:true}:{})};
104
+ }
105
+ throw error;
106
+ }
107
+ const {licenseEvidence,files:allFiles=[],remainingModelPaths:allRemaining=[],skippedModels:allSkipped=[],fallbackLocalMatches,...summary}=receipt;
108
+ const compactEvidence=licenseEvidence&&Buffer.byteLength(licenseEvidence)<=1024?licenseEvidence:undefined;
109
+ let files=allFiles.map(file=>({...compactAsset(file),path:file.path,sha256:file.sha256,licenseEntry:file.licenseEntry}));
110
+ let remainingModelPaths=allRemaining.slice(0,16),skippedModels=conciseSkippedModels(allSkipped);
111
+ let truncated=Boolean(receipt.truncated)||remainingModelPaths.length<allRemaining.length||skippedModels.length<allSkipped.length;
112
+ const output=()=>({...summary,...(compactEvidence?{licenseEvidence:compactEvidence}:{}),files,remainingModelPaths,skippedModels,...(fallbackLocalMatches?{fallbackLocalMatches:fallbackLocalMatches.slice(0,12).map(assetPick)}:{}),...(truncated?{truncated}:{})});
113
+ while(Buffer.byteLength(JSON.stringify(output()))>24_000&&files.length){files=files.slice(0,-1);truncated=true;}
114
+ while(Buffer.byteLength(JSON.stringify(output()))>24_000&&remainingModelPaths.length){remainingModelPaths=remainingModelPaths.slice(0,-1);truncated=true;}
115
+ while(Buffer.byteLength(JSON.stringify(output()))>24_000&&skippedModels.length){skippedModels=skippedModels.slice(0,-1);truncated=true;}
116
+ return bounded(output());
73
117
  }
74
118
  async ensureDraft(){
75
119
  try{return await this.service.read(this.intake.projectId);}catch(error){
@@ -79,31 +123,42 @@ export class IntakeCreatorTools{
79
123
  }
80
124
  }
81
125
  async stageAssets(args){
82
- check(exact(args,['intakeAssetIds','catalogAssetIds','remoteAssetIds']),'E_CREATOR_TOOL_ARGUMENT');await this.catalog.load();
126
+ check(exact(args,['intakeAssetIds','catalogAssetIds','remoteAssetIds','remoteItems']),'E_CREATOR_TOOL_ARGUMENT');
127
+ const {intakeAssetIds=[],catalogAssetIds=[],remoteAssetIds=[],remoteItems=[]}=args;
128
+ check([intakeAssetIds,catalogAssetIds,remoteAssetIds].every(ids=>Array.isArray(ids)&&ids.length<=64&&ids.every(identifier))&&Array.isArray(remoteItems)&&remoteItems.length<=64&&remoteItems.every(validStageCc0Item),'E_CREATOR_TOOL_ARGUMENT');
129
+ const requests=[...remoteAssetIds.map(sourceId=>({sourceId})),...remoteItems];
130
+ const ids=new Set([...intakeAssetIds,...catalogAssetIds,...requests.map(item=>item.assetId??item.sourceId)]);
131
+ check(ids.size<=64&&[...ids].every(identifier),'E_ASSET_LIMIT');
132
+ await this.catalog.load();
83
133
  const current=await this.ensureDraft();
84
- const ids=new Set([...(args.intakeAssetIds??[]),...(args.catalogAssetIds??[]),...(args.remoteAssetIds??[])]);check(ids.size<=64,'E_ASSET_LIMIT');
85
134
  const candidates=[];
86
- for(const id of args.intakeAssetIds??[]){
135
+ for(const id of intakeAssetIds){
87
136
  const asset=this.intake.assets.find(entry=>entry.id===id);check(asset,'E_ASSET_NOT_FOUND');const {bytes,mime}=await this.intakes.sourceAsset(this.intake.id,asset);
88
137
  candidates.push({id,mime,bytes,rights:this.intake.rights,source:'studio',styleFamily:this.intake.projectId,provenance:{origin:'studio-original',studio:this.intake.studio,sourceFile:asset.name,sourceHash:asset.hash,intakeId:this.intake.id,styleFamily:this.intake.projectId}});
89
138
  }
90
- for(const entry of this.catalog.get(args.catalogAssetIds??[])){
139
+ for(const entry of this.catalog.get(catalogAssetIds)){
91
140
  const bytes=await this.catalog.bytes(entry.id);candidates.push({...entry,bytes,source:'local'});
92
141
  }
93
- for(const id of args.remoteAssetIds??[]){
94
- const remote=this.remote.get(id);check(remote,'E_ASSET_NOT_FOUND');const {file,receipt}=remote,bytes=await safeFile(resolve(this.fetcher.cacheRoot,receipt.cacheKey,file.storedPath));
95
- const provenance={origin:'remote-cc0',sourceId:receipt.sourceId,sourceFile:file.path,sourceHash:file.sha256,author:receipt.author,license:'CC0-1.0',licenseEvidence:receipt.licenseEvidence,sourceUrl:receipt.sourceUrl,archiveSha256:receipt.archiveSha256,styleFamily:file.styleFamily};
96
- candidates.push({id:file.id,mime:file.mime,bytes,rights:`${receipt.author}, CC0-1.0. ${receipt.sourceUrl}`,source:'remote',styleFamily:file.styleFamily,provenance});
142
+ for(const {sourceId,assetId,...input} of requests){
143
+ assertAssetSourceAllowed(this.intake.assetSource??'studio-assets','remote');
144
+ const source=await resolveCc0SourceItem(sourceId,{remoteFetcher:this.fetcher});
145
+ const stageOptions=Object.keys(input).length?Object.fromEntries(Object.entries(input).sort(([a],[b])=>a.localeCompare(b))):undefined;
146
+ candidates.push({...source,id:assetId??sourceId,input,provenance:{...source.provenance,...(stageOptions?{stageOptions}:{})}});
97
147
  }
98
148
  const existingById=new Map(current.project.assets.map(asset=>[asset.id,asset]));
99
149
  const pendingById=new Map(),plan=[];
100
150
  for(const item of candidates){
101
151
  assertAssetSourceAllowed(this.intake.assetSource??'studio-assets',item.source);
102
152
  const existing=existingById.get(item.id);
103
- if(existing){check(existing.hash===item.provenance.sourceHash,'E_ASSET_DUPLICATE_ID');plan.push({existing});continue;}
153
+ if(existing){
154
+ let provenance;
155
+ try{provenance=JSON.parse(existing.provenance);}catch{provenance=null;}
156
+ check(sameStagingSource({sourceHash:existing.hash,...provenance},item.provenance),'E_ASSET_DUPLICATE_ID');
157
+ plan.push({existing});continue;
158
+ }
104
159
  if(pendingById.has(item.id)){
105
160
  const prior=pendingById.get(item.id);
106
- check(prior.provenance.sourceHash===item.provenance.sourceHash,'E_ASSET_DUPLICATE_ID');
161
+ check(sameStagingSource(prior.provenance,item.provenance),'E_ASSET_DUPLICATE_ID');
107
162
  plan.push({duplicateOf:item.id});continue;
108
163
  }
109
164
  pendingById.set(item.id,item);plan.push({item});
@@ -111,15 +166,13 @@ export class IntakeCreatorTools{
111
166
  const toRegister=[...pendingById.values()],projectRoot=resolve(this.service.store.root,this.intake.projectId);
112
167
  assertSingleVisualStyleFamily(current.project.assets,toRegister);
113
168
  const registeredList=await mapWithConcurrency(toRegister,4,async item=>{
114
- const metadata=await registerSource(projectRoot,{id:item.id,mime:item.mime,data:item.bytes.toString('base64'),rights:item.rights},{provenance:JSON.stringify(item.provenance)});
115
- const record={...metadata};delete record.optimization;
116
- return record;
169
+ return registerSourceBytes(projectRoot,{id:item.id,mime:item.mime,rights:item.rights,...item.input},item.bytes,{provenance:compactAssetProvenance(item.provenance),...(item.master?{master:item.master}:{})});
117
170
  });
118
171
  const registeredById=new Map(registeredList.map(asset=>[asset.id,asset]));
119
172
  if(registeredList.length){
120
- const envelope={format:'tora-transaction-1',expected:identity(current),operations:registeredList.map(asset=>({kind:'registerAsset',asset}))};
173
+ const envelope={format:'tora-transaction-1',expected:identity(current),operations:registeredList.map(metadata=>{const {optimization,...asset}=metadata;void optimization;return {kind:'registerAsset',asset};})};
121
174
  const preview=await this.service.preview(this.intake.projectId,envelope);
122
- await this.service.transact(this.intake.projectId,{...envelope,previewDigest:preview.previewDigest});
175
+ await this.service.transact(this.intake.projectId,{...envelope,previewDigest:preview.previewDigest},{registeredAssets:registeredList});
123
176
  this.lastQa=null;
124
177
  }
125
178
  const staged=plan.map(entry=>entry.existing??registeredById.get(entry.duplicateOf??entry.item.id));