sceneview-mcp 4.4.0 → 4.5.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.
@@ -0,0 +1,449 @@
1
+ /**
2
+ * Parametric mode of `generate_3d_model`: a deterministic GLB built from a
3
+ * structured list of primitives. No provider, no API key, no network — the
4
+ * same description always produces the same bytes.
5
+ *
6
+ * The model is an assembly of primitives (box, cylinder, cone, sphere,
7
+ * torus), each with its own size, position, rotation and PBR colour. Parts
8
+ * are combined by union-by-composition (one glTF node per part); there is no
9
+ * boolean subtraction. This mirrors the approach of the TWS printable-parts
10
+ * kernel: explicit closed surfaces, outward normals, sizes in real units.
11
+ *
12
+ * Every dimension is given in `units` (metres by default) and baked into the
13
+ * vertex data in metres, glTF's unit, so the output is real-world scale.
14
+ */
15
+ import { writeGlb } from "./glb.js";
16
+ /** Metres per unit. */
17
+ export const UNIT_TO_METERS = {
18
+ m: 1,
19
+ cm: 0.01,
20
+ mm: 0.001,
21
+ in: 0.0254,
22
+ ft: 0.3048,
23
+ };
24
+ // ─── Limits ─────────────────────────────────────────────────────────────────
25
+ export const MAX_PARTS = 64;
26
+ /** Largest accepted extent of a single dimension, in metres. */
27
+ const MAX_EXTENT_METERS = 1000;
28
+ const SEGMENTS = 32;
29
+ const SPHERE_RINGS = 16;
30
+ const TORUS_TUBE_SEGMENTS = 16;
31
+ const SHAPES = new Set(["box", "cylinder", "cone", "sphere", "torus"]);
32
+ function emptyGeometry() {
33
+ return { positions: [], normals: [], indices: [] };
34
+ }
35
+ function pushVertex(g, p, n) {
36
+ g.positions.push(p[0], p[1], p[2]);
37
+ g.normals.push(n[0], n[1], n[2]);
38
+ return g.positions.length / 3 - 1;
39
+ }
40
+ /** Axis-aligned box centred on the origin; flat-shaded (4 vertices per face). */
41
+ function boxGeometry(w, h, d) {
42
+ const g = emptyGeometry();
43
+ const x = w / 2;
44
+ const y = h / 2;
45
+ const z = d / 2;
46
+ // Each face: normal, then 4 corners counter-clockwise seen from outside.
47
+ const faces = [
48
+ [
49
+ [1, 0, 0],
50
+ [
51
+ [x, -y, z],
52
+ [x, -y, -z],
53
+ [x, y, -z],
54
+ [x, y, z],
55
+ ],
56
+ ],
57
+ [
58
+ [-1, 0, 0],
59
+ [
60
+ [-x, -y, -z],
61
+ [-x, -y, z],
62
+ [-x, y, z],
63
+ [-x, y, -z],
64
+ ],
65
+ ],
66
+ [
67
+ [0, 1, 0],
68
+ [
69
+ [-x, y, z],
70
+ [x, y, z],
71
+ [x, y, -z],
72
+ [-x, y, -z],
73
+ ],
74
+ ],
75
+ [
76
+ [0, -1, 0],
77
+ [
78
+ [-x, -y, -z],
79
+ [x, -y, -z],
80
+ [x, -y, z],
81
+ [-x, -y, z],
82
+ ],
83
+ ],
84
+ [
85
+ [0, 0, 1],
86
+ [
87
+ [-x, -y, z],
88
+ [x, -y, z],
89
+ [x, y, z],
90
+ [-x, y, z],
91
+ ],
92
+ ],
93
+ [
94
+ [0, 0, -1],
95
+ [
96
+ [x, -y, -z],
97
+ [-x, -y, -z],
98
+ [-x, y, -z],
99
+ [x, y, -z],
100
+ ],
101
+ ],
102
+ ];
103
+ for (const [normal, corners] of faces) {
104
+ const [a, b, c, e] = corners.map((p) => pushVertex(g, p, normal));
105
+ g.indices.push(a, b, c, a, c, e);
106
+ }
107
+ return g;
108
+ }
109
+ /** Capped frustum along y, centred on the origin. `top = 0` gives a cone. */
110
+ function cylinderGeometry(bottom, top, h) {
111
+ const g = emptyGeometry();
112
+ const half = h / 2;
113
+ const slope = (bottom - top) / h; // normal tilt for a frustum side
114
+ const len = Math.hypot(1, slope);
115
+ const side = [];
116
+ for (let i = 0; i <= SEGMENTS; i++) {
117
+ const a = (i / SEGMENTS) * Math.PI * 2;
118
+ const cx = Math.cos(a);
119
+ const sz = Math.sin(a);
120
+ const n = [cx / len, slope / len, sz / len];
121
+ side.push(pushVertex(g, [bottom * cx, -half, bottom * sz], n));
122
+ side.push(pushVertex(g, [top * cx, half, top * sz], n));
123
+ }
124
+ for (let i = 0; i < SEGMENTS; i++) {
125
+ const b0 = side[i * 2];
126
+ const t0 = side[i * 2 + 1];
127
+ const b1 = side[i * 2 + 2];
128
+ const t1 = side[i * 2 + 3];
129
+ g.indices.push(b0, t0, t1, b0, t1, b1);
130
+ }
131
+ const cap = (radius, y, up) => {
132
+ if (radius <= 0)
133
+ return;
134
+ const n = [0, up ? 1 : -1, 0];
135
+ const centre = pushVertex(g, [0, y, 0], n);
136
+ const ring = [];
137
+ for (let i = 0; i <= SEGMENTS; i++) {
138
+ const a = (i / SEGMENTS) * Math.PI * 2;
139
+ ring.push(pushVertex(g, [radius * Math.cos(a), y, radius * Math.sin(a)], n));
140
+ }
141
+ for (let i = 0; i < SEGMENTS; i++) {
142
+ if (up)
143
+ g.indices.push(centre, ring[i + 1], ring[i]);
144
+ else
145
+ g.indices.push(centre, ring[i], ring[i + 1]);
146
+ }
147
+ };
148
+ cap(top, half, true);
149
+ cap(bottom, -half, false);
150
+ return g;
151
+ }
152
+ function sphereGeometry(r) {
153
+ const g = emptyGeometry();
154
+ for (let ring = 0; ring <= SPHERE_RINGS; ring++) {
155
+ const phi = (ring / SPHERE_RINGS) * Math.PI; // 0 at the top
156
+ for (let seg = 0; seg <= SEGMENTS; seg++) {
157
+ const theta = (seg / SEGMENTS) * Math.PI * 2;
158
+ const n = [Math.sin(phi) * Math.cos(theta), Math.cos(phi), Math.sin(phi) * Math.sin(theta)];
159
+ pushVertex(g, [n[0] * r, n[1] * r, n[2] * r], n);
160
+ }
161
+ }
162
+ const row = SEGMENTS + 1;
163
+ for (let ring = 0; ring < SPHERE_RINGS; ring++) {
164
+ for (let seg = 0; seg < SEGMENTS; seg++) {
165
+ const a = ring * row + seg;
166
+ const b = a + row;
167
+ g.indices.push(a, a + 1, b + 1, a, b + 1, b);
168
+ }
169
+ }
170
+ return g;
171
+ }
172
+ /** Torus lying in the xz plane (hole along y). */
173
+ function torusGeometry(ringRadius, tube) {
174
+ const g = emptyGeometry();
175
+ for (let i = 0; i <= SEGMENTS; i++) {
176
+ const u = (i / SEGMENTS) * Math.PI * 2;
177
+ for (let j = 0; j <= TORUS_TUBE_SEGMENTS; j++) {
178
+ const v = (j / TORUS_TUBE_SEGMENTS) * Math.PI * 2;
179
+ const n = [Math.cos(v) * Math.cos(u), Math.sin(v), Math.cos(v) * Math.sin(u)];
180
+ const centre = [ringRadius * Math.cos(u), 0, ringRadius * Math.sin(u)];
181
+ pushVertex(g, [centre[0] + tube * n[0], tube * n[1], centre[2] + tube * n[2]], n);
182
+ }
183
+ }
184
+ const row = TORUS_TUBE_SEGMENTS + 1;
185
+ for (let i = 0; i < SEGMENTS; i++) {
186
+ for (let j = 0; j < TORUS_TUBE_SEGMENTS; j++) {
187
+ const a = i * row + j;
188
+ const b = a + row;
189
+ g.indices.push(a, a + 1, b + 1, a, b + 1, b);
190
+ }
191
+ }
192
+ return g;
193
+ }
194
+ // ─── Validation helpers ─────────────────────────────────────────────────────
195
+ function positive(value, label, scale) {
196
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
197
+ return `${label} must be a positive number.`;
198
+ }
199
+ const meters = value * scale;
200
+ if (meters > MAX_EXTENT_METERS)
201
+ return `${label} exceeds ${MAX_EXTENT_METERS} m.`;
202
+ return meters;
203
+ }
204
+ function vector3(value, label, fallback) {
205
+ if (value === undefined)
206
+ return fallback;
207
+ if (!Array.isArray(value) ||
208
+ value.length !== 3 ||
209
+ !value.every((v) => typeof v === "number" && Number.isFinite(v))) {
210
+ return `${label} must be an array of three finite numbers.`;
211
+ }
212
+ return value;
213
+ }
214
+ function unit01(value, label, fallback) {
215
+ if (value === undefined)
216
+ return fallback;
217
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {
218
+ return `${label} must be a number between 0 and 1.`;
219
+ }
220
+ return value;
221
+ }
222
+ function parseColor(value, label) {
223
+ if (value === undefined)
224
+ return [0.8, 0.8, 0.8, 1];
225
+ if (typeof value !== "string" || !/^#[0-9a-f]{6}$/i.test(value)) {
226
+ return `${label} must be a "#rrggbb" hex colour.`;
227
+ }
228
+ // sRGB hex → linear, as glTF baseColorFactor is linear.
229
+ const toLinear = (c) => {
230
+ const s = c / 255;
231
+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
232
+ };
233
+ const rgb = [1, 3, 5].map((i) => toLinear(Number.parseInt(value.slice(i, i + 2), 16)));
234
+ return [...rgb.map((c) => Math.round(c * 10_000) / 10_000), 1];
235
+ }
236
+ /** Euler XYZ (degrees) → quaternion [x, y, z, w]. */
237
+ function eulerToQuaternion(deg) {
238
+ const [x, y, z] = deg.map((d) => (d * Math.PI) / 360); // half angles
239
+ const cx = Math.cos(x);
240
+ const sx = Math.sin(x);
241
+ const cy = Math.cos(y);
242
+ const sy = Math.sin(y);
243
+ const cz = Math.cos(z);
244
+ const sz = Math.sin(z);
245
+ // q = qz * qy * qx (rotate around X first, then Y, then Z)
246
+ return [
247
+ sx * cy * cz - cx * sy * sz,
248
+ cx * sy * cz + sx * cy * sz,
249
+ cx * cy * sz - sx * sy * cz,
250
+ cx * cy * cz + sx * sy * sz,
251
+ ];
252
+ }
253
+ function round6(v) {
254
+ return Math.round(v * 1e6) / 1e6;
255
+ }
256
+ // ─── Builder ────────────────────────────────────────────────────────────────
257
+ /**
258
+ * Validate a parametric description and build it into a GLB. Pure and
259
+ * deterministic: no I/O, no randomness.
260
+ */
261
+ export function buildParametricGlb(description) {
262
+ const parts = description?.parts;
263
+ if (!Array.isArray(parts) || parts.length === 0) {
264
+ return { ok: false, message: "Parametric mode needs a non-empty `parts` array." };
265
+ }
266
+ if (parts.length > MAX_PARTS) {
267
+ return { ok: false, message: `Too many parts (${parts.length}); the limit is ${MAX_PARTS}.` };
268
+ }
269
+ const units = description.units ?? "m";
270
+ const scale = UNIT_TO_METERS[units];
271
+ if (scale === undefined) {
272
+ return {
273
+ ok: false,
274
+ message: `Unknown \`units\` "${String(units)}". Use one of: ${Object.keys(UNIT_TO_METERS).join(", ")}.`,
275
+ };
276
+ }
277
+ const json = {
278
+ asset: { version: "2.0", generator: "sceneview-mcp generate_3d_model (parametric)" },
279
+ scene: 0,
280
+ scenes: [{ nodes: [0] }],
281
+ nodes: [{ name: description.name?.slice(0, 64) || "parametric_model", children: [] }],
282
+ meshes: [],
283
+ materials: [],
284
+ accessors: [],
285
+ bufferViews: [],
286
+ buffers: [],
287
+ };
288
+ const chunks = [];
289
+ let byteLength = 0;
290
+ let triangleCount = 0;
291
+ const addView = (data, target) => {
292
+ const views = json.bufferViews;
293
+ views.push({ buffer: 0, byteOffset: byteLength, byteLength: data.length, target });
294
+ chunks.push(data);
295
+ byteLength += data.length;
296
+ const pad = (4 - (data.length % 4)) % 4;
297
+ if (pad) {
298
+ chunks.push(new Uint8Array(pad));
299
+ byteLength += pad;
300
+ }
301
+ return views.length - 1;
302
+ };
303
+ for (let i = 0; i < parts.length; i++) {
304
+ const part = parts[i];
305
+ const label = `parts[${i}]`;
306
+ if (!part || typeof part !== "object" || !SHAPES.has(part.shape)) {
307
+ return {
308
+ ok: false,
309
+ message: `${label}.shape must be one of: ${[...SHAPES].join(", ")}.`,
310
+ };
311
+ }
312
+ let geometry;
313
+ if (part.shape === "box") {
314
+ if (!Array.isArray(part.size) || part.size.length !== 3) {
315
+ return { ok: false, message: `${label}.size must be [width, height, depth] for a box.` };
316
+ }
317
+ const dims = part.size.map((v, axis) => positive(v, `${label}.size[${axis}]`, scale));
318
+ const bad = dims.find((d) => typeof d === "string");
319
+ if (bad)
320
+ return { ok: false, message: bad };
321
+ const [w, h, d] = dims;
322
+ geometry = boxGeometry(w, h, d);
323
+ }
324
+ else if (part.shape === "cylinder" || part.shape === "cone") {
325
+ const r = positive(part.radius, `${label}.radius`, scale);
326
+ if (typeof r === "string")
327
+ return { ok: false, message: r };
328
+ const h = positive(part.height, `${label}.height`, scale);
329
+ if (typeof h === "string")
330
+ return { ok: false, message: h };
331
+ let top = part.shape === "cone" ? 0 : r;
332
+ if (part.shape === "cylinder" && part.radiusTop !== undefined) {
333
+ if (typeof part.radiusTop !== "number" ||
334
+ !Number.isFinite(part.radiusTop) ||
335
+ part.radiusTop < 0) {
336
+ return { ok: false, message: `${label}.radiusTop must be a number ≥ 0.` };
337
+ }
338
+ top = part.radiusTop * scale;
339
+ }
340
+ geometry = cylinderGeometry(r, top, h);
341
+ }
342
+ else if (part.shape === "sphere") {
343
+ const r = positive(part.radius, `${label}.radius`, scale);
344
+ if (typeof r === "string")
345
+ return { ok: false, message: r };
346
+ geometry = sphereGeometry(r);
347
+ }
348
+ else {
349
+ const r = positive(part.radius, `${label}.radius`, scale);
350
+ if (typeof r === "string")
351
+ return { ok: false, message: r };
352
+ const t = positive(part.tube, `${label}.tube`, scale);
353
+ if (typeof t === "string")
354
+ return { ok: false, message: t };
355
+ geometry = torusGeometry(r, t);
356
+ }
357
+ const position = vector3(part.position, `${label}.position`, [0, 0, 0]);
358
+ if (typeof position === "string")
359
+ return { ok: false, message: position };
360
+ const rotation = vector3(part.rotation, `${label}.rotation`, [0, 0, 0]);
361
+ if (typeof rotation === "string")
362
+ return { ok: false, message: rotation };
363
+ const color = parseColor(part.color, `${label}.color`);
364
+ if (typeof color === "string")
365
+ return { ok: false, message: color };
366
+ const metallic = unit01(part.metallic, `${label}.metallic`, 0);
367
+ if (typeof metallic === "string")
368
+ return { ok: false, message: metallic };
369
+ const roughness = unit01(part.roughness, `${label}.roughness`, 0.8);
370
+ if (typeof roughness === "string")
371
+ return { ok: false, message: roughness };
372
+ // Positions/normals/indices → buffer views + accessors.
373
+ const pos = new Float32Array(geometry.positions);
374
+ const nrm = new Float32Array(geometry.normals);
375
+ const idx = new Uint16Array(geometry.indices);
376
+ const min = [Infinity, Infinity, Infinity];
377
+ const max = [-Infinity, -Infinity, -Infinity];
378
+ for (let v = 0; v < pos.length; v += 3) {
379
+ for (let axis = 0; axis < 3; axis++) {
380
+ if (pos[v + axis] < min[axis])
381
+ min[axis] = pos[v + axis];
382
+ if (pos[v + axis] > max[axis])
383
+ max[axis] = pos[v + axis];
384
+ }
385
+ }
386
+ const accessors = json.accessors;
387
+ const posView = addView(new Uint8Array(pos.buffer), 34962);
388
+ accessors.push({
389
+ bufferView: posView,
390
+ componentType: 5126,
391
+ count: pos.length / 3,
392
+ type: "VEC3",
393
+ min,
394
+ max,
395
+ });
396
+ const nrmView = addView(new Uint8Array(nrm.buffer), 34962);
397
+ accessors.push({
398
+ bufferView: nrmView,
399
+ componentType: 5126,
400
+ count: nrm.length / 3,
401
+ type: "VEC3",
402
+ });
403
+ const idxView = addView(new Uint8Array(idx.buffer), 34963);
404
+ accessors.push({ bufferView: idxView, componentType: 5123, count: idx.length, type: "SCALAR" });
405
+ const base = accessors.length - 3;
406
+ const materials = json.materials;
407
+ materials.push({
408
+ name: `${part.shape}_${i}_material`,
409
+ pbrMetallicRoughness: {
410
+ baseColorFactor: color,
411
+ metallicFactor: metallic,
412
+ roughnessFactor: roughness,
413
+ },
414
+ });
415
+ const meshes = json.meshes ?? [];
416
+ meshes.push({
417
+ name: `${part.shape}_${i}`,
418
+ primitives: [
419
+ {
420
+ attributes: { POSITION: base, NORMAL: base + 1 },
421
+ indices: base + 2,
422
+ material: materials.length - 1,
423
+ mode: 4,
424
+ },
425
+ ],
426
+ });
427
+ json.meshes = meshes;
428
+ const nodes = json.nodes ?? [];
429
+ const node = {
430
+ name: typeof part.name === "string" && part.name ? part.name.slice(0, 64) : `${part.shape}_${i}`,
431
+ mesh: meshes.length - 1,
432
+ };
433
+ if (position.some((v) => v !== 0))
434
+ node.translation = position.map((v) => round6(v * scale));
435
+ if (rotation.some((v) => v !== 0))
436
+ node.rotation = eulerToQuaternion(rotation).map(round6);
437
+ nodes.push(node);
438
+ nodes[0].children?.push(nodes.length - 1);
439
+ triangleCount += idx.length / 3;
440
+ }
441
+ const bin = new Uint8Array(byteLength);
442
+ let offset = 0;
443
+ for (const chunk of chunks) {
444
+ bin.set(chunk, offset);
445
+ offset += chunk.length;
446
+ }
447
+ json.buffers.push({ byteLength });
448
+ return { ok: true, glb: writeGlb(json, bin), partCount: parts.length, triangleCount };
449
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * `generate_3d_model` orchestration: picks the mode, runs it, then applies
3
+ * the shared output stage (real-world scale, `save_to_path`).
4
+ *
5
+ * Modes, all free on SceneView's side:
6
+ * - "parametric": deterministic primitives from a structured description,
7
+ * built locally — no key, no network (`generate-model-parametric.ts`).
8
+ * - "trellis" / "tripo": BYOK providers, billed to the user's own account
9
+ * (`generate-model.ts`, `generate-model-runware.ts`).
10
+ *
11
+ * There is no SceneView-hosted generation API behind any of these.
12
+ */
13
+ import { Buffer } from "node:buffer";
14
+ import { formatGenerateResult, generateModel, } from "./generate-model.js";
15
+ import { checkSavePath, downloadGlb, normalizeGlbScale, parseTargetSize, writeGlbFile, } from "./generate-model-output.js";
16
+ import { buildParametricGlb, } from "./generate-model-parametric.js";
17
+ /** Largest parametric GLB returned inline (base64) when no `save_to_path` is given. */
18
+ export const MAX_INLINE_GLB_BYTES = 512 * 1024;
19
+ function errorResult(text) {
20
+ return { content: [{ type: "text", text }], isError: true };
21
+ }
22
+ /** A shared, multi-user surface must never write to its own disk on a caller's behalf. */
23
+ function canWriteToDisk(ctx) {
24
+ return ctx.extras?.surface !== "remote" && !ctx.userId && !ctx.apiKeyId;
25
+ }
26
+ function fmt(v) {
27
+ return `${Math.round(v * 1000) / 1000}`;
28
+ }
29
+ function scaleLines(scale, savedToFile) {
30
+ const d = scale.dimensions;
31
+ const o = scale.originalDimensions;
32
+ const lines = [
33
+ "### Real-world scale",
34
+ "",
35
+ `- **Units:** metres (glTF's unit; 1 unit = 1 m in SceneView)`,
36
+ `- **Size (W × H × D):** ${fmt(d.width)} × ${fmt(d.height)} × ${fmt(d.depth)} m`,
37
+ ];
38
+ if (scale.target) {
39
+ lines.push(`- **Target:** \`${scale.target.key}\` = ${fmt(scale.target.meters)} m`, `- **Scale factor applied:** ${scale.scaleFactor} (from ${fmt(o.width)} × ${fmt(o.height)} × ${fmt(o.depth)} m)`);
40
+ if (!savedToFile) {
41
+ lines.push(`- The provider's file itself is unscaled: pass \`save_to_path\` to get a rescaled GLB, or scale the \`ModelNode\` by ${scale.scaleFactor}.`);
42
+ }
43
+ }
44
+ return lines;
45
+ }
46
+ /** Run `generate_3d_model` with raw MCP arguments. Never throws. */
47
+ export async function runGenerate3dModel(args, ctx = {}) {
48
+ const a = args ?? {};
49
+ // ── Validate the shared options first: a bad path never costs credits ────
50
+ const target = parseTargetSize(a.targetSize);
51
+ if (target && "error" in target)
52
+ return errorResult(target.error);
53
+ const targetSize = target && !("error" in target) ? target : null;
54
+ const overwrite = a.overwrite === true;
55
+ let savePath = null;
56
+ if (a.save_to_path !== undefined && a.save_to_path !== null) {
57
+ if (!canWriteToDisk(ctx)) {
58
+ return errorResult("`save_to_path` is only available in the local package (`npx -y sceneview-mcp`): the hosted endpoint is shared and has no access to your disk. Omit it, or run the server locally.");
59
+ }
60
+ const check = await checkSavePath(a.save_to_path, overwrite);
61
+ if (!check.ok)
62
+ return errorResult(check.message);
63
+ savePath = check.path;
64
+ }
65
+ const provider = a.provider;
66
+ const parametric = provider === "parametric" || (provider === undefined && a.parts !== undefined);
67
+ if (parametric) {
68
+ if (a.prompt !== undefined || a.imageUrl !== undefined) {
69
+ return errorResult('Parametric mode builds from `parts` only. Drop `prompt` / `imageUrl`, or use provider "trellis" / "tripo" for AI generation.');
70
+ }
71
+ const built = buildParametricGlb({
72
+ parts: a.parts,
73
+ units: a.units,
74
+ name: typeof a.name === "string" ? a.name : undefined,
75
+ });
76
+ if (!built.ok)
77
+ return errorResult(built.message);
78
+ const normalized = normalizeGlbScale(built.glb, targetSize);
79
+ if (!normalized.ok)
80
+ return errorResult(normalized.message);
81
+ const lines = [
82
+ "## Generated 3D model (parametric — deterministic primitives, no API key)",
83
+ "",
84
+ `- **Parts:** ${built.partCount} · **Triangles:** ${built.triangleCount} · **GLB size:** ${normalized.glb.length} bytes`,
85
+ ];
86
+ const structured = {
87
+ mode: "parametric",
88
+ bytes: normalized.glb.length,
89
+ ...normalized.scale,
90
+ };
91
+ if (savePath) {
92
+ const written = await writeGlbFile(savePath, normalized.glb, overwrite);
93
+ if (!written.ok)
94
+ return errorResult(written.message);
95
+ lines.push(`- **Saved to:** \`${savePath}\``);
96
+ structured.savedPath = savePath;
97
+ }
98
+ else if (normalized.glb.length <= MAX_INLINE_GLB_BYTES) {
99
+ lines.push("- **GLB:** returned base64-encoded in `structuredContent.glbBase64`. Pass `save_to_path` (local package) to write it straight to disk instead.");
100
+ structured.glbBase64 = Buffer.from(normalized.glb).toString("base64");
101
+ }
102
+ else {
103
+ return errorResult(`The parametric GLB is ${normalized.glb.length} bytes, too large to return inline (limit ${MAX_INLINE_GLB_BYTES}). Pass \`save_to_path\` to write it to disk.`);
104
+ }
105
+ lines.push("", ...scaleLines(normalized.scale, true), "", "### Load it in SceneView", "", "```kotlin", 'val model = rememberModelInstance(modelLoader, "models/parametric.glb")', "```");
106
+ return {
107
+ content: [{ type: "text", text: lines.join("\n") }],
108
+ structuredContent: structured,
109
+ };
110
+ }
111
+ // ── BYOK provider modes ─────────────────────────────────────────────────
112
+ const genResult = await generateModel({
113
+ prompt: a.prompt,
114
+ imageUrl: a.imageUrl,
115
+ quality: a.quality,
116
+ provider: provider,
117
+ });
118
+ const baseText = formatGenerateResult(genResult);
119
+ if (!genResult.ok)
120
+ return errorResult(baseText);
121
+ const structured = {
122
+ mode: genResult.model.provider,
123
+ modelUrl: genResult.model.modelUrl,
124
+ };
125
+ if (!targetSize && !savePath) {
126
+ return { content: [{ type: "text", text: baseText }], structuredContent: structured };
127
+ }
128
+ // Scale or save asked: fetch the file now, while its URL is still valid.
129
+ const failAfterGeneration = (why) => errorResult(`${baseText}\n\n### ⚠️ Post-processing failed\n\n${why}\nThe model was generated: download it from the URL above before it expires.`);
130
+ const downloaded = await downloadGlb(genResult.model.modelUrl);
131
+ if (!downloaded.ok)
132
+ return failAfterGeneration(downloaded.message);
133
+ const normalized = normalizeGlbScale(downloaded.glb, targetSize);
134
+ if (!normalized.ok)
135
+ return failAfterGeneration(normalized.message);
136
+ Object.assign(structured, normalized.scale, { bytes: normalized.glb.length });
137
+ const extra = [];
138
+ if (savePath) {
139
+ // Without a target the provider bytes are saved untouched.
140
+ const written = await writeGlbFile(savePath, targetSize ? normalized.glb : downloaded.glb, overwrite);
141
+ if (!written.ok)
142
+ return failAfterGeneration(written.message);
143
+ structured.savedPath = savePath;
144
+ extra.push(`- **Saved to:** \`${savePath}\` (${written.bytes} bytes)`);
145
+ }
146
+ const text = [
147
+ baseText,
148
+ "",
149
+ ...scaleLines(normalized.scale, savePath !== null),
150
+ ...(extra.length ? ["", ...extra] : []),
151
+ ].join("\n");
152
+ return { content: [{ type: "text", text }], structuredContent: structured };
153
+ }
@@ -8,6 +8,11 @@
8
8
  * `provider` picks one explicitly; otherwise Tripo is used when its key is
9
9
  * set (unchanged behaviour), then TRELLIS.2 when only the Runware key is.
10
10
  *
11
+ * This module holds the two AI providers only. The tool entry point is
12
+ * `generate-model-tool.ts`, which adds the key-free parametric mode
13
+ * (`generate-model-parametric.ts`) and the shared real-world-scale /
14
+ * `save_to_path` output stage (`generate-model-output.ts`).
15
+ *
11
16
  * `search_models` finds assets that already exist; this tool closes the other
12
17
  * half of the agentic asset loop: when no existing model fits, the assistant
13
18
  * generates a brand-new GLB from a text prompt or a source image using the