@pinepaper.studio/mcp-server 1.6.7 → 1.6.8

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 (164) hide show
  1. package/README.de.md +9 -5
  2. package/README.es.md +9 -5
  3. package/README.fr.md +9 -5
  4. package/README.hi.md +8 -5
  5. package/README.ja.md +8 -5
  6. package/README.ko.md +8 -4
  7. package/README.md +171 -17
  8. package/README.pt-BR.md +9 -5
  9. package/README.zh-CN.md +6 -4
  10. package/dist/character/data/concepts.json +1 -0
  11. package/dist/character/data/depictions.json +1 -0
  12. package/dist/character/data/styles.json +1 -0
  13. package/dist/character/duration-scale.d.ts +13 -0
  14. package/dist/character/duration-scale.d.ts.map +1 -0
  15. package/dist/character/duration-scale.js +13 -0
  16. package/dist/character/duration-scale.js.map +1 -0
  17. package/dist/character/path-bbox.d.ts +82 -0
  18. package/dist/character/path-bbox.d.ts.map +1 -0
  19. package/dist/character/path-bbox.js +496 -0
  20. package/dist/character/path-bbox.js.map +1 -0
  21. package/dist/character/perform.d.ts +149 -0
  22. package/dist/character/perform.d.ts.map +1 -0
  23. package/dist/character/perform.js +626 -0
  24. package/dist/character/perform.js.map +1 -0
  25. package/dist/character/resolve.d.ts +51 -0
  26. package/dist/character/resolve.d.ts.map +1 -0
  27. package/dist/character/resolve.js +239 -0
  28. package/dist/character/resolve.js.map +1 -0
  29. package/dist/design/design-systems.d.ts +126 -0
  30. package/dist/design/design-systems.d.ts.map +1 -0
  31. package/dist/design/design-systems.js +240 -0
  32. package/dist/design/design-systems.js.map +1 -0
  33. package/dist/execution/canvas-state.d.ts +7 -0
  34. package/dist/execution/canvas-state.d.ts.map +1 -1
  35. package/dist/execution/canvas-state.js +20 -8
  36. package/dist/execution/canvas-state.js.map +1 -1
  37. package/dist/index.d.ts +20 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +12 -4
  40. package/dist/index.js.map +1 -1
  41. package/dist/ontology/design-graph.d.ts +9 -0
  42. package/dist/ontology/design-graph.d.ts.map +1 -1
  43. package/dist/ontology/design-graph.js +98 -3
  44. package/dist/ontology/design-graph.js.map +1 -1
  45. package/dist/ontology/types.d.ts +42 -0
  46. package/dist/ontology/types.d.ts.map +1 -1
  47. package/dist/ontology/vocabulary.d.ts.map +1 -1
  48. package/dist/ontology/vocabulary.js +20 -0
  49. package/dist/ontology/vocabulary.js.map +1 -1
  50. package/dist/tools/compact-descriptions.d.ts.map +1 -1
  51. package/dist/tools/compact-descriptions.js +25 -0
  52. package/dist/tools/compact-descriptions.js.map +1 -1
  53. package/dist/tools/definitions.d.ts +1 -1
  54. package/dist/tools/definitions.d.ts.map +1 -1
  55. package/dist/tools/definitions.js +343 -24
  56. package/dist/tools/definitions.js.map +1 -1
  57. package/dist/tools/engine-methods.d.ts +18 -0
  58. package/dist/tools/engine-methods.d.ts.map +1 -0
  59. package/dist/tools/engine-methods.js +239 -0
  60. package/dist/tools/engine-methods.js.map +1 -0
  61. package/dist/tools/handlers/character.d.ts +121 -0
  62. package/dist/tools/handlers/character.d.ts.map +1 -0
  63. package/dist/tools/handlers/character.js +315 -0
  64. package/dist/tools/handlers/character.js.map +1 -0
  65. package/dist/tools/handlers.d.ts +2 -0
  66. package/dist/tools/handlers.d.ts.map +1 -1
  67. package/dist/tools/handlers.js +316 -16
  68. package/dist/tools/handlers.js.map +1 -1
  69. package/dist/tools/minimal-descriptions.d.ts.map +1 -1
  70. package/dist/tools/minimal-descriptions.js +13 -2
  71. package/dist/tools/minimal-descriptions.js.map +1 -1
  72. package/dist/tools/toolkits.d.ts.map +1 -1
  73. package/dist/tools/toolkits.js +7 -0
  74. package/dist/tools/toolkits.js.map +1 -1
  75. package/dist/types/code-generator.d.ts +96 -1
  76. package/dist/types/code-generator.d.ts.map +1 -1
  77. package/dist/types/code-generator.js +1200 -12
  78. package/dist/types/code-generator.js.map +1 -1
  79. package/dist/types/schemas.d.ts +6792 -151
  80. package/dist/types/schemas.d.ts.map +1 -1
  81. package/dist/types/schemas.js +587 -17
  82. package/dist/types/schemas.js.map +1 -1
  83. package/dist/vendor/design/art-deco-generator.d.ts +52 -0
  84. package/dist/vendor/design/art-deco-generator.d.ts.map +1 -0
  85. package/dist/vendor/design/art-deco-generator.js +144 -0
  86. package/dist/vendor/design/art-deco-generator.js.map +1 -0
  87. package/dist/vendor/design/art-nouveau-generator.d.ts +46 -0
  88. package/dist/vendor/design/art-nouveau-generator.d.ts.map +1 -0
  89. package/dist/vendor/design/art-nouveau-generator.js +134 -0
  90. package/dist/vendor/design/art-nouveau-generator.js.map +1 -0
  91. package/dist/vendor/design/bauhaus-generator.d.ts +53 -0
  92. package/dist/vendor/design/bauhaus-generator.d.ts.map +1 -0
  93. package/dist/vendor/design/bauhaus-generator.js +126 -0
  94. package/dist/vendor/design/bauhaus-generator.js.map +1 -0
  95. package/dist/vendor/design/brutalist-generator.d.ts +53 -0
  96. package/dist/vendor/design/brutalist-generator.d.ts.map +1 -0
  97. package/dist/vendor/design/brutalist-generator.js +148 -0
  98. package/dist/vendor/design/brutalist-generator.js.map +1 -0
  99. package/dist/vendor/design/claymorphism-generator.d.ts +46 -0
  100. package/dist/vendor/design/claymorphism-generator.d.ts.map +1 -0
  101. package/dist/vendor/design/claymorphism-generator.js +135 -0
  102. package/dist/vendor/design/claymorphism-generator.js.map +1 -0
  103. package/dist/vendor/design/corporate-memphis-generator.d.ts +47 -0
  104. package/dist/vendor/design/corporate-memphis-generator.d.ts.map +1 -0
  105. package/dist/vendor/design/corporate-memphis-generator.js +144 -0
  106. package/dist/vendor/design/corporate-memphis-generator.js.map +1 -0
  107. package/dist/vendor/design/cyberpunk-generator.d.ts +52 -0
  108. package/dist/vendor/design/cyberpunk-generator.d.ts.map +1 -0
  109. package/dist/vendor/design/cyberpunk-generator.js +162 -0
  110. package/dist/vendor/design/cyberpunk-generator.js.map +1 -0
  111. package/dist/vendor/design/de-stijl-generator.d.ts +50 -0
  112. package/dist/vendor/design/de-stijl-generator.d.ts.map +1 -0
  113. package/dist/vendor/design/de-stijl-generator.js +154 -0
  114. package/dist/vendor/design/de-stijl-generator.js.map +1 -0
  115. package/dist/vendor/design/design-style.d.ts +3 -0
  116. package/dist/vendor/design/design-style.d.ts.map +1 -0
  117. package/dist/vendor/design/design-style.js +12 -0
  118. package/dist/vendor/design/design-style.js.map +1 -0
  119. package/dist/vendor/design/design-systems-dtcg.d.ts +59 -0
  120. package/dist/vendor/design/design-systems-dtcg.d.ts.map +1 -0
  121. package/dist/vendor/design/design-systems-dtcg.js +571 -0
  122. package/dist/vendor/design/design-systems-dtcg.js.map +1 -0
  123. package/dist/vendor/design/frutiger-aero-generator.d.ts +46 -0
  124. package/dist/vendor/design/frutiger-aero-generator.d.ts.map +1 -0
  125. package/dist/vendor/design/frutiger-aero-generator.js +133 -0
  126. package/dist/vendor/design/frutiger-aero-generator.js.map +1 -0
  127. package/dist/vendor/design/memphis-generator.d.ts +56 -0
  128. package/dist/vendor/design/memphis-generator.d.ts.map +1 -0
  129. package/dist/vendor/design/memphis-generator.js +158 -0
  130. package/dist/vendor/design/memphis-generator.js.map +1 -0
  131. package/dist/vendor/design/mid-century-upa-generator.d.ts +46 -0
  132. package/dist/vendor/design/mid-century-upa-generator.d.ts.map +1 -0
  133. package/dist/vendor/design/mid-century-upa-generator.js +137 -0
  134. package/dist/vendor/design/mid-century-upa-generator.js.map +1 -0
  135. package/dist/vendor/design/neumorphic-generator.d.ts +53 -0
  136. package/dist/vendor/design/neumorphic-generator.d.ts.map +1 -0
  137. package/dist/vendor/design/neumorphic-generator.js +182 -0
  138. package/dist/vendor/design/neumorphic-generator.js.map +1 -0
  139. package/dist/vendor/design/op-art-generator.d.ts +45 -0
  140. package/dist/vendor/design/op-art-generator.d.ts.map +1 -0
  141. package/dist/vendor/design/op-art-generator.js +116 -0
  142. package/dist/vendor/design/op-art-generator.js.map +1 -0
  143. package/dist/vendor/design/pixel-art-generator.d.ts +45 -0
  144. package/dist/vendor/design/pixel-art-generator.d.ts.map +1 -0
  145. package/dist/vendor/design/pixel-art-generator.js +143 -0
  146. package/dist/vendor/design/pixel-art-generator.js.map +1 -0
  147. package/dist/vendor/design/pop-art-generator.d.ts +53 -0
  148. package/dist/vendor/design/pop-art-generator.d.ts.map +1 -0
  149. package/dist/vendor/design/pop-art-generator.js +164 -0
  150. package/dist/vendor/design/pop-art-generator.js.map +1 -0
  151. package/dist/vendor/design/risograph-generator.d.ts +53 -0
  152. package/dist/vendor/design/risograph-generator.d.ts.map +1 -0
  153. package/dist/vendor/design/risograph-generator.js +170 -0
  154. package/dist/vendor/design/risograph-generator.js.map +1 -0
  155. package/dist/vendor/design/swiss-style-generator.d.ts +55 -0
  156. package/dist/vendor/design/swiss-style-generator.d.ts.map +1 -0
  157. package/dist/vendor/design/swiss-style-generator.js +147 -0
  158. package/dist/vendor/design/swiss-style-generator.js.map +1 -0
  159. package/dist/vendor/design/vaporwave-generator.d.ts +51 -0
  160. package/dist/vendor/design/vaporwave-generator.d.ts.map +1 -0
  161. package/dist/vendor/design/vaporwave-generator.js +139 -0
  162. package/dist/vendor/design/vaporwave-generator.js.map +1 -0
  163. package/manifest.json +29 -1
  164. package/package.json +13 -5
@@ -4,6 +4,7 @@
4
4
  * Converts MCP tool inputs to executable PinePaper JavaScript code.
5
5
  * This code is designed to run in the browser context where window.PinePaper is available.
6
6
  */
7
+ import { REQUIRED_ENGINE_METHODS, OPTIONAL_ENGINE_METHODS } from '../tools/engine-methods.js';
7
8
  import { generateP5DrawCode } from '../tools/p5-compat/p5-helpers.js';
8
9
  import { CreateItemInputSchema, ImportMotionCaptureInputSchema, ModifyItemInputSchema, AddRelationInputSchema, AnimateItemInputSchema, KeyframeAnimateInputSchema, ExecuteGeneratorInputSchema, ApplyEffectInputSchema, SetBackgroundColorInputSchema, SetCanvasSizeInputSchema, CreateGlossySphereInputSchema, CreateDiagonalStripesInputSchema, BatchCreateInputSchema, BatchModifyInputSchema, CreateGridInputSchema, CreateSceneInputSchema,
9
10
  // Diagram types
@@ -960,6 +961,17 @@ const PLATFORM_TO_CANVAS_PRESET = {
960
961
  export function canvasPresetFor(platform) {
961
962
  return PLATFORM_TO_CANVAS_PRESET[platform] || platform;
962
963
  }
964
+ /**
965
+ * Largest export the emitted code will hand back as an inline base64 data URL.
966
+ *
967
+ * Only reached on a studio with no `app.exportEngine.exportToStore` — with the
968
+ * store, mp4/webm never base64 in the page at all. Set above what that legacy
969
+ * path could already deliver (60 s at 8 Mbps is roughly 60 MB, ~80 MB once
970
+ * base64'd) so raising the duration cap cannot make a previously working
971
+ * export start refusing; past it the code names the ceiling instead of dying
972
+ * inside the encode.
973
+ */
974
+ export const INLINE_MAX_BYTES = 96 * 1024 * 1024;
963
975
  export class PinePaperCodeGenerator {
964
976
  /**
965
977
  * Generate code for creating an item
@@ -997,6 +1009,28 @@ export class PinePaperCodeGenerator {
997
1009
  */
998
1010
  generateAddRelation(input) {
999
1011
  const validated = AddRelationInputSchema.parse(input);
1012
+ // A PRESET decides its own relationType and params, so this is a different
1013
+ // call, not a defaulted one. applyRelationPreset refuses with
1014
+ // `{ok:false, errors:[{field, reason}]}` — a third refusal shape on this
1015
+ // surface, after {ok, reason} and {error} — so the errors are joined rather
1016
+ // than read as a single string, which would render "[object Object]".
1017
+ if (validated.presetId) {
1018
+ return `
1019
+ // Adopt relation preset "${validated.presetId}" on ${validated.sourceId}
1020
+ (async function() {
1021
+ if (typeof app.applyRelationPreset !== 'function') { return { success: false, error: 'app.applyRelationPreset unavailable — update FxTool' }; }
1022
+ const r = await app.applyRelationPreset(${JSON.stringify(validated.sourceId)}, ${JSON.stringify(validated.presetId)}, ${JSON.stringify(validated.presetValues ?? {})});
1023
+ if (!r || r.ok === false) {
1024
+ const why = (r && Array.isArray(r.errors))
1025
+ ? r.errors.map(function(e) { return e.field + ': ' + e.reason; }).join('; ')
1026
+ : 'the preset did not apply';
1027
+ return { success: false, error: why };
1028
+ }
1029
+ // The preset's own type and resolved values come back, so the caller learns
1030
+ // what it actually adopted rather than only that something worked.
1031
+ return { success: true, presetId: ${JSON.stringify(validated.presetId)}, relationType: r.relationType, params: r.params, values: r.values };
1032
+ })();`.trim();
1033
+ }
1000
1034
  return generateAddRelationCode(validated.sourceId, validated.targetId || validated.sourceId, validated.relationType, validated.params);
1001
1035
  }
1002
1036
  /**
@@ -1234,8 +1268,29 @@ throw new Error('Either svgString or url must be provided');
1234
1268
  };
1235
1269
  }
1236
1270
  const ctx = app.exportCanvasOntology(${optsJson});
1271
+ // SAY WHEN THE ANSWER IS PARTIAL. The engine returns itemCount =
1272
+ // allItems.length (the TRUE total) beside items = allItems.slice(0,
1273
+ // maxItems), and childCount beside a children array capped at maxChildren.
1274
+ // So a caller receives itemCount 800 with 500 items and nothing marking the
1275
+ // gap — an answer indistinguishable from a complete one unless the reader
1276
+ // thinks to compare two fields. That is the silent-refusal shape this repo
1277
+ // has fixed elsewhere; the marker below is the same idiom generateHatching
1278
+ // uses for its 40-path cap.
1279
+ var _shown = Array.isArray(ctx.items) ? ctx.items.length : 0;
1280
+ var _total = typeof ctx.itemCount === 'number' ? ctx.itemCount : _shown;
1281
+ var _clipped = (Array.isArray(ctx.items) ? ctx.items : []).filter(function (i) {
1282
+ return i && typeof i.childCount === 'number' && Array.isArray(i.children)
1283
+ && i.children.length < i.childCount;
1284
+ });
1237
1285
  return {
1238
1286
  success: true,
1287
+ ...(_total > _shown ? { truncated:
1288
+ 'showing ' + _shown + ' of ' + _total + ' items. Raise maxItems (up to 500) '
1289
+ + 'to see more; past 500 the scene is truncated rather than paginated, so '
1290
+ + 'narrow with pinepaper_get_items or read a group at a time.' } : {}),
1291
+ ...(_clipped.length ? { childrenTruncated: _clipped.map(function (i) {
1292
+ return i.id + ': ' + i.children.length + ' of ' + i.childCount + ' children';
1293
+ }) } : {}),
1239
1294
  canvasWidth: ctx.canvasWidth,
1240
1295
  canvasHeight: ctx.canvasHeight,
1241
1296
  canvasPreset: ctx.canvasPreset,
@@ -2414,6 +2469,45 @@ return { success: true, action: 'seek', time: ${op.time || 0} };
2414
2469
  /**
2415
2470
  * Generate code for smart export
2416
2471
  */
2472
+ /**
2473
+ * Read one slice of a held export, base64-encoded.
2474
+ *
2475
+ * The handler calls this in a loop and appends each chunk to the file it was
2476
+ * going to write anyway, so no more than one chunk is ever in memory on
2477
+ * either side of the bridge. Every refusal the engine can give is passed
2478
+ * through untouched — a bad range names the real size, and an id that was
2479
+ * EVICTED to make room says so rather than reporting not-found, because
2480
+ * those are different bugs from the caller's side.
2481
+ */
2482
+ generateReadExportChunk(exportId, offset, length) {
2483
+ const range = { offset };
2484
+ if (typeof length === 'number')
2485
+ range.length = length;
2486
+ return `
2487
+ // Read export chunk at ${offset}
2488
+ (async function() {
2489
+ if (!app.exportEngine || typeof app.exportEngine.readExport !== 'function') {
2490
+ return { ok: false, reason: 'app.exportEngine.readExport unavailable — update FxTool' };
2491
+ }
2492
+ return await app.exportEngine.readExport(${JSON.stringify(exportId)}, ${JSON.stringify(range)});
2493
+ })();`.trim();
2494
+ }
2495
+ /**
2496
+ * Drop a held export once its bytes are safely on disk here.
2497
+ *
2498
+ * Called only after the whole file has been written. A release before that
2499
+ * would be unrecoverable: the store is the only copy.
2500
+ */
2501
+ generateReleaseExport(exportId) {
2502
+ return `
2503
+ // Release held export
2504
+ (async function() {
2505
+ if (!app.exportEngine || typeof app.exportEngine.releaseExport !== 'function') {
2506
+ return { ok: false, reason: 'app.exportEngine.releaseExport unavailable — update FxTool' };
2507
+ }
2508
+ return await app.exportEngine.releaseExport(${JSON.stringify(exportId)});
2509
+ })();`.trim();
2510
+ }
2417
2511
  generateAgentExport(input) {
2418
2512
  const validated = AgentExportInputSchema.parse(input);
2419
2513
  const { platform, format, quality, framing, duration, estimateOnly } = validated;
@@ -2441,6 +2535,76 @@ return { success: true, action: 'seek', time: ${op.time || 0} };
2441
2535
  const preset = platformPresets[platform] || platformPresets['web'];
2442
2536
  // Resolve "auto" format to the platform's recommended format
2443
2537
  const exportFormat = (!format || format === 'auto') ? preset.staticFormat : format;
2538
+ // AUDIO-ONLY EXPORT, off the visual path entirely.
2539
+ //
2540
+ // It takes the OFFLINE renderer, not exportEngine.exportAudio. The latter
2541
+ // is async, needs the videoExporter's Web Audio path, hands back a Blob
2542
+ // that cannot cross page.evaluate, and downloads unless told not to.
2543
+ // renderSoundtrackWav is synchronous, returns bytes, and needs no audio
2544
+ // context — the engine commit that added it is titled "the soundtrack
2545
+ // without Web Audio", and this is the context it was written for.
2546
+ //
2547
+ // No platform preset resolves to wav, so reaching here means it was asked
2548
+ // for by name. Dimensions, framing, fps and bitrate are all absent rather
2549
+ // than passed and ignored.
2550
+ // @engine-methods renderSoundtrackWav exportEngine.sceneHasAudio
2551
+ if (exportFormat === 'wav') {
2552
+ const sr = validated.sampleRate ?? 48000;
2553
+ const bd = validated.bitDepth ?? 16;
2554
+ return `
2555
+ // Export: the soundtrack on its own, rendered offline
2556
+ (function() {
2557
+ if (typeof app.renderSoundtrackWav !== 'function') {
2558
+ return { success: false, format: 'wav', error: 'app.renderSoundtrackWav unavailable — update FxTool. This build cannot export audio on its own; mp4/webm still mux the soundtrack into the video.' };
2559
+ }
2560
+ // EXACT, not estimated. Uncompressed PCM is header + rate x bytes x channels
2561
+ // x seconds, so a model is not needed and would only be less true. The mix
2562
+ // is mono — the engine encodes a single channel.
2563
+ var exact = 44 + Math.round(${sr} * (${bd} / 8) * 1 * ${videoDuration});
2564
+ if (${estimateOnly ? 'true' : 'false'}) {
2565
+ return { success: true, estimateOnly: true, format: 'wav', bytes: exact,
2566
+ expected: exact, confidence: 'exact',
2567
+ note: 'uncompressed PCM: ' + ${videoDuration} + 's at ' + ${sr} + ' Hz, ' + ${bd} + '-bit mono' };
2568
+ }
2569
+ var r = app.renderSoundtrackWav({ duration: ${videoDuration}, sampleRate: ${sr}, bitDepth: ${bd} });
2570
+ if (!r || !r.wav) {
2571
+ // WHY IT IS EMPTY, NOT JUST THAT IT IS. The offline renderer bakes
2572
+ // SYNTHESIZED sounds only, while the engine's sceneHasAudio() counts
2573
+ // uploaded audio files too. A scene carrying an uploaded track would
2574
+ // otherwise be told it has no audio, which is false and sends the caller
2575
+ // to add a sound they already have.
2576
+ var anyAudio = null;
2577
+ try {
2578
+ if (app.exportEngine && typeof app.exportEngine.sceneHasAudio === 'function') {
2579
+ anyAudio = app.exportEngine.sceneHasAudio();
2580
+ }
2581
+ } catch (_) { /* predicate absent — fall back to the generic answer */ }
2582
+ return {
2583
+ success: false, format: 'wav',
2584
+ error: anyAudio === true
2585
+ ? 'this scene has audio, but it is uploaded file(s) rather than synthesized sounds, and the offline renderer bakes only what it can synthesize. Export mp4 or webm to get that audio muxed with the picture.'
2586
+ : 'no synthesized sounds are placed on this scene, so there is no soundtrack to render. Create one with pinepaper_sound action "create", or place an existing one with "set_placement".',
2587
+ sceneHasAudio: anyAudio,
2588
+ };
2589
+ }
2590
+ var bytes = r.wav;
2591
+ // Chunked: String.fromCharCode.apply over a multi-megabyte array blows the
2592
+ // stack, and a ten-minute soundtrack is tens of megabytes.
2593
+ var bin = '';
2594
+ for (var i = 0; i < bytes.length; i += 8192) {
2595
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192));
2596
+ }
2597
+ return {
2598
+ success: true, format: 'wav', platform: '${platform}',
2599
+ data: 'data:audio/wav;base64,' + btoa(bin),
2600
+ size: bytes.length,
2601
+ duration: r.duration, sampleRate: r.sampleRate, sounds: r.sounds, placed: r.placed,
2602
+ // A mix that dropped sounds is a valid file quietly missing tracks.
2603
+ ...(r.dropped > 0 ? { dropped: r.dropped, incomplete:
2604
+ 'mixed ' + r.placed + ' sound(s); ' + r.dropped + ' could not be rendered and are absent from this file' } : {}),
2605
+ };
2606
+ })();`.trim();
2607
+ }
2444
2608
  return `
2445
2609
  // Smart export for ${platform}
2446
2610
  (async function() {
@@ -2480,7 +2644,12 @@ return { success: true, action: 'seek', time: ${op.time || 0} };
2480
2644
 
2481
2645
  // Resolve camera-view framing dims when requested. Reads the first
2482
2646
  // camera_animates keyframe's zoom and divides the canvas dims by it
2483
- // (mirrors FxTool ExportEngine.js:466-485). Camera animation still
2647
+ // (mirrors the camera-view framing block in FxTool's
2648
+ // ExportEngine.showVideoExportOptions). Cited by METHOD, not by line: the
2649
+ // previous citation named a line range that had rotted to point at
2650
+ // DPI/canvas-size code in a file nobody here edits. A cross-file line range
2651
+ // cannot be kept accurate — it breaks on any edit above it — so this repo
2652
+ // does not use them. Camera animation still
2484
2653
  // drives motion during export — framing only fixes the output frame.
2485
2654
  let cameraDims = null;
2486
2655
  if (framing === 'camera') {
@@ -2565,32 +2734,110 @@ return { success: true, action: 'seek', time: ${op.time || 0} };
2565
2734
  r.onloadend = () => resolve(r.result);
2566
2735
  r.readAsDataURL(b);
2567
2736
  });
2737
+
2738
+ // THE EXPORT STORE. A long export cannot come back as one base64
2739
+ // string: base64 of a gigabyte is larger than the gigabyte, and it
2740
+ // crosses the browser→server bridge as a single page.evaluate return
2741
+ // value. exportToStore() streams the encode straight to the studio's
2742
+ // origin-private store and hands back an id, so the bytes stay on disk
2743
+ // and the handler pages them into the file it was going to write
2744
+ // anyway. mp4/webm ALWAYS land in a file on the server side, so there
2745
+ // is no size at which building a data URL for them is worth doing —
2746
+ // the id goes back at every size and nothing is base64'd in the page.
2747
+ // gif is refused by name by the store (it has its own encoder and
2748
+ // never streams), so gif keeps the buffered path below.
2749
+ const store = (app.exportEngine
2750
+ && typeof app.exportEngine.exportToStore === 'function'
2751
+ && typeof app.exportEngine.readExport === 'function')
2752
+ ? app.exportEngine : null;
2753
+
2754
+ if (store && format !== 'gif') {
2755
+ const stored = await store.exportToStore({
2756
+ format,
2757
+ duration: baseVideoSettings.duration,
2758
+ fps: settings.fps,
2759
+ // A NUMBER, not the quality tier's name. _calculateBitrate
2760
+ // multiplies by it, and a non-finite value used to survive its
2761
+ // Math.max(100000, NaN) "floor" all the way to
2762
+ // VideoEncoder.configure.
2763
+ quality: settings.compression,
2764
+ width: cameraDims ? cameraDims.width : dimensions.width,
2765
+ height: cameraDims ? cameraDims.height : dimensions.height,
2766
+ });
2767
+ if (!stored || stored.ok === false) {
2768
+ result = { success: false, platform, format, error: (stored && stored.reason) || 'the export store refused the export without saying why' };
2769
+ } else {
2770
+ let chunkBytes = 4 * 1024 * 1024;
2771
+ try {
2772
+ const declared = app.exportEngine.constructor && app.exportEngine.constructor.EXPORT_CHUNK_BYTES;
2773
+ if (typeof declared === 'number' && declared > 0) chunkBytes = declared;
2774
+ } catch (_) { /* keep the default */ }
2775
+ result = {
2776
+ success: true, platform, framing,
2777
+ // Trust the container the store reports over the one asked for:
2778
+ // mp4 falls back to WebM without WebCodecs, and WebM bytes named
2779
+ // .mp4 fail in container-validating players.
2780
+ format: stored.format || format,
2781
+ retained: true,
2782
+ exportId: stored.exportId,
2783
+ mimeType: stored.mimeType || videoMimeType,
2784
+ size: stored.size,
2785
+ chunkBytes: chunkBytes,
2786
+ dimensions: cameraDims || dimensions,
2787
+ };
2788
+ }
2789
+ break;
2790
+ }
2791
+
2792
+ // NO EXPORT STORE ON THIS STUDIO, or gif. Both remaining failures are
2793
+ // named rather than left to blow up: a streamed export hands back a
2794
+ // marker instead of a Blob and FileReader throws on it, and an export
2795
+ // past the inline ceiling used to die somewhere in the base64 rather
2796
+ // than say so. The ceiling sits above what this path could already do
2797
+ // (60 s at 8 Mbps is roughly 60 MB) so nothing that works today starts
2798
+ // refusing.
2799
+ const INLINE_MAX_BYTES = ${INLINE_MAX_BYTES};
2800
+ const mb = (n) => (n / (1024 * 1024)).toFixed(1);
2801
+ const deliver = async (blob) => {
2802
+ if (!blob || typeof blob.size !== 'number' || typeof blob.slice !== 'function') {
2803
+ return {
2804
+ success: false, platform, format,
2805
+ error: 'this export streamed to a file instead of returning bytes, and this studio has no app.exportEngine.exportToStore to page it back from — update FxTool for long-form export',
2806
+ };
2807
+ }
2808
+ if (blob.size > INLINE_MAX_BYTES) {
2809
+ return {
2810
+ success: false, platform, format, size: blob.size,
2811
+ error: 'export is ' + mb(blob.size) + ' MB, over the ' + mb(INLINE_MAX_BYTES)
2812
+ + ' MB inline ceiling, and this studio has no app.exportEngine.exportToStore to page it out of — update FxTool, or lower duration/quality',
2813
+ };
2814
+ }
2815
+ return { success: true, platform, format, framing, data: await blobToDataUrl(blob), mimeType: videoMimeType, size: blob.size };
2816
+ };
2817
+
2568
2818
  // Camera framing requires going direct to videoExporter so width/height
2569
2819
  // pass through — _quickExportVideo strips dim fields.
2570
2820
  if (cameraDims && app.exportEngine && app.exportEngine.videoExporter) {
2571
2821
  const blob = await app.exportEngine.videoExporter.export({ ...baseVideoSettings, width: cameraDims.width, height: cameraDims.height });
2572
- const dataUrl = await blobToDataUrl(blob);
2573
- result = { success: true, platform, format, framing, data: dataUrl, mimeType: videoMimeType, size: blob.size, dimensions: cameraDims };
2822
+ result = await deliver(blob);
2823
+ if (result.success) result.dimensions = cameraDims;
2574
2824
  } else if ((format === 'mp4' || format === 'webm') && app.exportEngine && app.exportEngine.videoExporter) {
2575
2825
  // Bypass _quickExportVideo for mp4/webm — it hardcodes
2576
2826
  // quality:undefined for these formats and produces a NaN bitrate.
2577
2827
  const blob = await app.exportEngine.videoExporter.export(baseVideoSettings);
2578
- const dataUrl = await blobToDataUrl(blob);
2579
- result = { success: true, platform, format, framing, data: dataUrl, mimeType: videoMimeType, size: blob.size };
2828
+ result = await deliver(blob);
2580
2829
  } else if (app.exportEngine && app.exportEngine._quickExportVideo) {
2581
2830
  // GIF path (working): _quickExportVideo forwards gifQuality to
2582
2831
  // gif.js. Also serves as the fallback if videoExporter is absent.
2583
2832
  const videoResult = await app.exportEngine._quickExportVideo(format, baseVideoSettings, false);
2584
2833
  if (videoResult && videoResult.blob) {
2585
- const dataUrl = await blobToDataUrl(videoResult.blob);
2586
- result = { success: true, platform, format, framing, data: dataUrl, mimeType: videoMimeType, size: videoResult.blob.size };
2834
+ result = await deliver(videoResult.blob);
2587
2835
  } else {
2588
2836
  result = { success: false, error: format.toUpperCase() + ' export returned no data' };
2589
2837
  }
2590
2838
  } else if (app.exportEngine && app.exportEngine.videoExporter) {
2591
2839
  const blob = await app.exportEngine.videoExporter.export(baseVideoSettings);
2592
- const dataUrl = await blobToDataUrl(blob);
2593
- result = { success: true, platform, format, framing, data: dataUrl, mimeType: videoMimeType, size: blob.size };
2840
+ result = await deliver(blob);
2594
2841
  } else {
2595
2842
  result = { success: false, error: format.toUpperCase() + ' export not available' };
2596
2843
  }
@@ -5227,6 +5474,79 @@ ${resolve}
5227
5474
  const key = ${S(validated.key)};
5228
5475
  const exclude = ${S(validated.exclude)};
5229
5476
 
5477
+ // WHICH ENGINE METHODS THIS STUDIO HAS.
5478
+ //
5479
+ // Every tool guards the methods it needs and refuses by name without them,
5480
+ // which is right per call and useless in advance: an agent otherwise learns a
5481
+ // studio is too old one tool at a time. getCapabilities cannot answer this —
5482
+ // it reports the engine's VOCABULARY (styles, palettes, relations), not which
5483
+ // of its methods exist.
5484
+ //
5485
+ // The list is DERIVED from the emitters' own guards by
5486
+ // scripts/sync-engine-methods.mjs, so it cannot drift from what the tools
5487
+ // actually check. Required and optional are kept apart because an older
5488
+ // studio that degrades is not an unusable one.
5489
+ if (action === 'studio') {
5490
+ const required = ${S(REQUIRED_ENGINE_METHODS)};
5491
+ const optional = ${S(OPTIONAL_ENGINE_METHODS)};
5492
+ const has = (path) => {
5493
+ // Dotted paths: thirteen methods live behind a sub-facade
5494
+ // (exportEngine.exportToStore, mapSystem.worldTour).
5495
+ let node = app;
5496
+ for (const part of path.split('.')) {
5497
+ if (!node) return false;
5498
+ node = node[part];
5499
+ }
5500
+ return typeof node === 'function';
5501
+ };
5502
+ const missingRequired = required.filter((m) => !has(m));
5503
+ const missingOptional = optional.filter((m) => !has(m));
5504
+ return {
5505
+ success: true,
5506
+ studio: {
5507
+ requiredTotal: required.length,
5508
+ requiredPresent: required.length - missingRequired.length,
5509
+ missingRequired: missingRequired,
5510
+ optionalTotal: optional.length,
5511
+ missingOptional: missingOptional,
5512
+ // A studio missing nothing required can serve every tool this server
5513
+ // publishes. Missing something optional only narrows an answer.
5514
+ complete: missingRequired.length === 0,
5515
+ },
5516
+ };
5517
+ }
5518
+
5519
+ // The registries getCapabilities does NOT aggregate. Each is a capability an
5520
+ // agent otherwise has to guess at, which by this project's rule is the same
5521
+ // as its not existing. Read one at a time and name a missing facade rather
5522
+ // than answering with an empty list, which would read as "none exist".
5523
+ if (action === 'catalogue') {
5524
+ const READERS = {
5525
+ rig_presets: 'listRigPresets', shader_effects: 'listShaderEffects',
5526
+ stroke_decorations: 'listStrokeDecorations', precomps: 'listPrecomps',
5527
+ images: 'listImages', segment_edit_kinds: 'listSegmentEditKinds',
5528
+ shatter_orders: 'listShatterOrders', world_meshes: 'listWorldMeshes',
5529
+ relation_presets: 'loadRelationPresets',
5530
+ };
5531
+ const want = ${S(validated.catalogue)};
5532
+ const fn = READERS[want];
5533
+ if (!fn) { return { success: false, error: 'unknown catalogue ' + JSON.stringify(want) + ' — try ' + Object.keys(READERS).join(', ') }; }
5534
+ if (typeof app[fn] !== 'function') { return { success: false, error: 'app.' + fn + ' unavailable — update FxTool' }; }
5535
+ const entries = await app[fn]();
5536
+ // loadRelationPresets answers {presets, rejected, source} rather than a bare
5537
+ // array, and REJECTED is the half worth surfacing: a preset this build
5538
+ // cannot use is a named absence, where dropping it silently would read as
5539
+ // the catalogue simply being smaller.
5540
+ if (entries && !Array.isArray(entries) && Array.isArray(entries.presets)) {
5541
+ return {
5542
+ success: true, catalogue: want, reader: 'app.' + fn,
5543
+ count: entries.presets.length, entries: entries.presets,
5544
+ rejected: entries.rejected || [], source: entries.source || null,
5545
+ };
5546
+ }
5547
+ return { success: true, catalogue: want, reader: 'app.' + fn, count: Array.isArray(entries) ? entries.length : undefined, entries: entries };
5548
+ }
5549
+
5230
5550
  if (typeof app.getCapabilities !== 'function') {
5231
5551
  return { success: false, error: 'app.getCapabilities unavailable — update FxTool' };
5232
5552
  }
@@ -5876,6 +6196,7 @@ ${resolve}
5876
6196
  * (bringToFront / sendToBack / bringForward / sendBackward).
5877
6197
  */
5878
6198
  generateArrange(input) {
6199
+ // @engine-methods bringToFront sendToBack bringForward sendBackward
5879
6200
  const method = {
5880
6201
  front: 'bringToFront',
5881
6202
  back: 'sendToBack',
@@ -6114,9 +6435,41 @@ ${resolve}
6114
6435
  }).compile(input.doc);
6115
6436
  const opsJson = JSON.stringify(ops, null, 2);
6116
6437
  const diagJson = JSON.stringify(diagnostics);
6438
+ const docJson = JSON.stringify(input.doc);
6439
+ // awaitImages: the studio decorates a raster (fit, keyframes, mask) on its
6440
+ // 'load' event and re-runs its finalize steps when the last one lands; a
6441
+ // tool call that screenshots next wants that to have happened.
6442
+ const engineOptsJson = JSON.stringify({ canvas: input.canvas, defaultGeometry: input.defaultGeometry, awaitImages: true });
6117
6443
  return `
6118
6444
  // Instantiate ontology → scene (${ops.filter((o) => o.op === 'create').length} items, ${ops.filter((o) => o.op === 'addRelation').length} relations)
6119
- (function() {
6445
+ (async function() {
6446
+ // Engine door first: the studio's own OntologyCompiler reads every node facet
6447
+ // (geometry, paint, text, the keyframe track, masks) and builds through the
6448
+ // template loader's paths — the round trip the studio's pixel tests verify
6449
+ // (e2e/graph-instantiate-parity.spec.js). The server-side compile above is
6450
+ // kept for the diagnostics preview and for studios that predate the facade,
6451
+ // which get the box loop below and a note saying so.
6452
+ const doc = ${docJson};
6453
+ if (typeof app.instantiateOntology === 'function') {
6454
+ const r = await app.instantiateOntology(doc, ${engineOptsJson});
6455
+ const diags = r.diagnostics || [];
6456
+ return {
6457
+ success: !diags.some(function(d) { return d && d.level === 'error'; }) && !r.imagesFailed,
6458
+ engine: 'studio',
6459
+ itemIds: r.itemIds, itemCount: r.itemIds.length,
6460
+ // Every count the engine returns, not a chosen three. imagesFailed is the
6461
+ // one that matters most: a raster that never decoded leaves a scene that
6462
+ // looks built and is not, and dropping the count is how that becomes
6463
+ // invisible. relationsApplied and connectorsApplied are the only way to
6464
+ // tell "the doc declared no edges" from "the edges did not bind".
6465
+ keyframesApplied: r.keyframesApplied, masksApplied: r.masksApplied, deferred: r.deferred,
6466
+ relationsApplied: r.relationsApplied, connectorsApplied: r.connectorsApplied,
6467
+ interactionsApplied: r.interactionsApplied, effectsApplied: r.effectsApplied,
6468
+ groupsCreated: r.groupsCreated, nested: r.nested,
6469
+ imagesFailed: r.imagesFailed, backgroundApplied: r.backgroundApplied, duration: r.duration,
6470
+ diagnostics: diags, errors: [],
6471
+ };
6472
+ }
6120
6473
  if (typeof app.create !== 'function' || typeof app.addRelation !== 'function') {
6121
6474
  return { success: false, error: 'app.create / app.addRelation unavailable' };
6122
6475
  }
@@ -6137,7 +6490,7 @@ ${resolve}
6137
6490
  }
6138
6491
  }
6139
6492
  if (app.historyManager) app.historyManager.saveState();
6140
- return { success: errors.length === 0, itemIds: itemIds, itemCount: itemIds.length, diagnostics: diagnostics, errors: errors };
6493
+ return { success: errors.length === 0, engine: 'server-box', note: 'this studio predates app.instantiateOntology: items were placed as boxes without paint, text, keyframes or masks', itemIds: itemIds, itemCount: itemIds.length, diagnostics: diagnostics, errors: errors };
6141
6494
  })();`.trim();
6142
6495
  }
6143
6496
  /**
@@ -6360,6 +6713,48 @@ ${guard}
6360
6713
  };
6361
6714
  })();`.trim();
6362
6715
  }
6716
+ case 'cursive':
6717
+ return `
6718
+ // Text: write it as STROKED handwriting — a path, not a glyph
6719
+ (function() {
6720
+ if (typeof app.createCursiveText !== 'function') { return { success: false, error: 'app.createCursiveText unavailable — update FxTool' }; }
6721
+ const item = app.createCursiveText(${S(input.text)}, ${S(input.cursiveOptions ?? {})});
6722
+ if (!item) { return { success: false, error: 'the cursive text produced no path' }; }
6723
+ return { success: true, itemId: item.data && item.data.id };
6724
+ })();`.trim();
6725
+ case 'wrap':
6726
+ return `
6727
+ // Text: break to a width — reversibly
6728
+ (function() {
6729
+ if (typeof app.wrapText !== 'function') { return { success: false, error: 'app.wrapText unavailable — update FxTool' }; }
6730
+ const r = app.wrapText(${S(input.itemId)}, ${S(input.maxWidth)});
6731
+ if (!r || r.ok === false) { return { success: false, error: (r && r.error) || 'that item could not be wrapped' }; }
6732
+ return { success: true, ...r };
6733
+ })();`.trim();
6734
+ case 'unwrap':
6735
+ return `
6736
+ // Text: restore the single line wrap replaced
6737
+ (function() {
6738
+ if (typeof app.unwrapText !== 'function') { return { success: false, error: 'app.unwrapText unavailable — update FxTool' }; }
6739
+ // 'not wrapped' is the engine's own refusal and is more useful than
6740
+ // anything this layer could infer, so it is passed through.
6741
+ const r = app.unwrapText(${S(input.itemId)});
6742
+ if (!r || r.ok === false) { return { success: false, error: (r && r.error) || 'that item is not wrapped' }; }
6743
+ return { success: true, ...r };
6744
+ })();`.trim();
6745
+ case 'to_collage':
6746
+ return `
6747
+ // Text: turn an EXISTING text item into a letter collage, in place
6748
+ (function() {
6749
+ if (typeof app.convertTextToCollage !== 'function') { return { success: false, error: 'app.convertTextToCollage unavailable — update FxTool' }; }
6750
+ const item = app.getItemById ? app.getItemById(${S(input.itemId)}) : null;
6751
+ if (!item) { return { success: false, error: 'no such item: ' + ${S(input.itemId)} }; }
6752
+ // Returns null when there is no letterCollage subsystem — a bare null that
6753
+ // would otherwise read as "the conversion did nothing to your text".
6754
+ const r = app.convertTextToCollage(item, ${S(input.text ?? null)} || item.content, ${S(input.collageOptions ?? {})});
6755
+ if (!r) { return { success: false, error: 'the collage system is unavailable in this build, so the text was left as it was' }; }
6756
+ return { success: true, collage: r };
6757
+ })();`.trim();
6363
6758
  }
6364
6759
  }
6365
6760
  /**
@@ -6406,7 +6801,14 @@ ${guard}
6406
6801
  ...(input.color !== undefined ? { color: input.color } : {}),
6407
6802
  ...(input.seed !== undefined ? { seed: input.seed } : {}),
6408
6803
  ...(input.count !== undefined ? { count: input.count } : {}),
6804
+ ...(input.slant !== undefined ? { slant: input.slant } : {}),
6805
+ ...(input.overlap !== undefined ? { overlap: input.overlap } : {}),
6806
+ ...(input.stagger !== undefined ? { stagger: input.stagger } : {}),
6807
+ ...(input.gapLen !== undefined ? { gapLen: input.gapLen } : {}),
6808
+ ...(input.gridSize !== undefined ? { gridSize: input.gridSize } : {}),
6409
6809
  });
6810
+ const roughStr = JSON.stringify(input.roughness ?? 0);
6811
+ const seedStr = JSON.stringify(input.seed ?? 1);
6410
6812
  return wrap('Medium: render in thread', ` if (typeof app.applyThreadPainting !== 'function') { return { success: false, error: 'thread medium unavailable — update FxTool' }; }
6411
6813
  const entry = app.itemRegistry && app.itemRegistry.get(${S(input.itemId)});
6412
6814
  const src = entry && entry.item;
@@ -6418,7 +6820,23 @@ ${guard}
6418
6820
  }
6419
6821
  const g = app.applyThreadPainting(${S(input.itemId)}, ${opts});
6420
6822
  if (!g) { return { success: false, action: 'apply_thread', error: 'nothing stitchable here — thread needs a CLOSED path, a compound path, or a group containing them. An open stroke, a raster and an empty group all land here. (If you passed a stitch name, check it against list_stitches.)' }; }
6421
- return { success: true, action: 'apply_thread', groupId: (g.data && g.data.id) || null, stitches: g.children.length };`);
6823
+ // HAND WOBBLE, applied here rather than in the engine, which has no such
6824
+ // option. Every point of every stitch gets its own phase off the seed, so a
6825
+ // long contour wobbles along its whole length instead of shearing at one end,
6826
+ // and the same seed sews the same irregularities every run.
6827
+ const rough = ${roughStr};
6828
+ if (rough > 0 && g.children) {
6829
+ const rseed = ${seedStr};
6830
+ for (let i = 0; i < g.children.length; i++) {
6831
+ const line = g.children[i];
6832
+ if (!line || !line.segments) continue;
6833
+ for (let j = 0; j < line.segments.length; j++) {
6834
+ line.segments[j].point.x += Math.sin(rseed + i * 2.13 + j * 1.71) * rough * 0.4;
6835
+ line.segments[j].point.y += Math.cos(rseed + i * 3.47 + j * 2.29) * rough * 0.4;
6836
+ }
6837
+ }
6838
+ }
6839
+ return { success: true, action: 'apply_thread', groupId: (g.data && g.data.id) || null, stitches: g.children.length, roughness: rough };`);
6422
6840
  }
6423
6841
  case 'list_flow_fields':
6424
6842
  return wrap('Medium: list flow fields', ` if (typeof app.listFlowFields !== 'function') { return { success: false, error: 'hatch medium unavailable — update FxTool' }; }
@@ -6735,6 +7153,761 @@ ${needWorld}
6735
7153
  (function() {
6736
7154
  if (typeof app.removeWorld3D !== 'function') { return { success: false, error: 'app.removeWorld3D unavailable — update FxTool' }; }
6737
7155
  return { success: !!app.removeWorld3D() };
7156
+ })();`.trim();
7157
+ // --- Mesh authoring ---------------------------------------------------
7158
+ // extrudeToMesh / latheToMesh REFUSE by name when there is no world
7159
+ // ({ok:false, reason}), so their reason is passed through rather than
7160
+ // pre-empted with a second wording for the same condition. The facade
7161
+ // check stays, because a studio without the method is a different fault.
7162
+ case 'extrude_path':
7163
+ case 'lathe_path': {
7164
+ const fn = input.action === 'extrude_path' ? 'extrudeToMesh' : 'latheToMesh';
7165
+ const mesh = { ...(input.mesh ?? {}) };
7166
+ // rotY is RADIANS on this path — stored raw and handed to cos()/sin()
7167
+ // in the shader. rotYDegrees is the convenience spelling and is folded
7168
+ // in here so only one of them ever reaches the engine.
7169
+ if (typeof mesh.rotYDegrees === 'number') {
7170
+ if (mesh.rotY === undefined)
7171
+ mesh.rotY = mesh.rotYDegrees * Math.PI / 180;
7172
+ delete mesh.rotYDegrees;
7173
+ }
7174
+ return `
7175
+ // World3D: ${input.action} — a canvas path becomes real geometry
7176
+ (async function() {
7177
+ // @engine-methods extrudeToMesh latheToMesh importOBJToWorld importGLTFToWorld
7178
+ if (typeof app.${fn} !== 'function') { return { success: false, error: 'app.${fn} unavailable — update FxTool to a world3d-capable build' }; }
7179
+ const r = await app.${fn}(${S(input.pathId)}, ${S(mesh)});
7180
+ if (!r || r.ok === false) { return { success: false, error: (r && r.reason) || 'the world refused the mesh' }; }
7181
+ return { success: true, meshId: r.id, op: ${S(input.action === 'extrude_path' ? 'extrude' : 'lathe')}, sourceId: ${S(input.pathId)} };
7182
+ })();`.trim();
7183
+ }
7184
+ case 'list_meshes':
7185
+ return `
7186
+ // World3D: every authored mesh on the stage
7187
+ (function() {
7188
+ if (typeof app.listWorldMeshes !== 'function') { return { success: false, error: 'app.listWorldMeshes unavailable — update FxTool' }; }
7189
+ return { success: true, meshes: app.listWorldMeshes() };
7190
+ })();`.trim();
7191
+ case 'remove_mesh':
7192
+ return `
7193
+ // World3D: drop a mesh
7194
+ (function() {
7195
+ if (typeof app.removeWorldMesh !== 'function') { return { success: false, error: 'app.removeWorldMesh unavailable — update FxTool' }; }
7196
+ return { success: !!app.removeWorldMesh(${S(input.meshId)}) };
7197
+ })();`.trim();
7198
+ // --- Lights -----------------------------------------------------------
7199
+ // addWorldLight THROWS when there is no world, so this one is guarded
7200
+ // ahead of the call rather than reading a refusal back.
7201
+ case 'add_light':
7202
+ return `
7203
+ // World3D: add a point light — at most 8, and the ninth is refused by name
7204
+ (function() {
7205
+ if (typeof app.addWorldLight !== 'function') { return { success: false, error: 'app.addWorldLight unavailable — update FxTool' }; }
7206
+ ${needWorld}
7207
+ const r = app.addWorldLight(${S(input.light ?? {})});
7208
+ if (!r || r.ok === false) { return { success: false, error: (r && r.error) || 'the world refused the light' }; }
7209
+ return { success: true, lightId: r.id, light: r.light };
7210
+ })();`.trim();
7211
+ case 'set_light':
7212
+ return `
7213
+ // World3D: edit a light in place
7214
+ (function() {
7215
+ if (typeof app.setWorldLight !== 'function') { return { success: false, error: 'app.setWorldLight unavailable — update FxTool' }; }
7216
+ return { success: !!app.setWorldLight(${S(input.lightId)}, ${S(input.light ?? {})}) };
7217
+ })();`.trim();
7218
+ case 'remove_light':
7219
+ return `
7220
+ // World3D: drop a light
7221
+ (function() {
7222
+ if (typeof app.removeWorldLight !== 'function') { return { success: false, error: 'app.removeWorldLight unavailable — update FxTool' }; }
7223
+ return { success: !!app.removeWorldLight(${S(input.lightId)}) };
7224
+ })();`.trim();
7225
+ case 'list_lights':
7226
+ return `
7227
+ // World3D: every light, with position, colour, intensity and range
7228
+ (function() {
7229
+ if (typeof app.listWorldLights !== 'function') { return { success: false, error: 'app.listWorldLights unavailable — update FxTool' }; }
7230
+ return { success: true, lights: app.listWorldLights() };
7231
+ })();`.trim();
7232
+ // --- Materials --------------------------------------------------------
7233
+ case 'add_material':
7234
+ return `
7235
+ // World3D: a named, SHARED surface — one edit restyles every object using it
7236
+ (function() {
7237
+ if (typeof app.addWorldMaterial !== 'function') { return { success: false, error: 'app.addWorldMaterial unavailable — update FxTool' }; }
7238
+ ${needWorld}
7239
+ const r = app.addWorldMaterial(${S(input.material ?? {})});
7240
+ if (!r || r.ok === false) { return { success: false, error: (r && r.error) || 'the world refused the material' }; }
7241
+ return { success: true, materialId: r.id, material: r.material };
7242
+ })();`.trim();
7243
+ case 'set_material':
7244
+ return `
7245
+ // World3D: patch a material — every object referencing it changes next frame
7246
+ (function() {
7247
+ if (typeof app.setWorldMaterial !== 'function') { return { success: false, error: 'app.setWorldMaterial unavailable — update FxTool' }; }
7248
+ return { success: !!app.setWorldMaterial(${S(input.materialId)}, ${S(input.material ?? {})}) };
7249
+ })();`.trim();
7250
+ case 'remove_material':
7251
+ return `
7252
+ // World3D: drop a material
7253
+ (function() {
7254
+ if (typeof app.removeWorldMaterial !== 'function') { return { success: false, error: 'app.removeWorldMaterial unavailable — update FxTool' }; }
7255
+ return { success: !!app.removeWorldMaterial(${S(input.materialId)}) };
7256
+ })();`.trim();
7257
+ case 'list_materials':
7258
+ return `
7259
+ // World3D: every material, with the knobs that actually render
7260
+ (function() {
7261
+ if (typeof app.listWorldMaterials !== 'function') { return { success: false, error: 'app.listWorldMaterials unavailable — update FxTool' }; }
7262
+ return { success: true, materials: app.listWorldMaterials() };
7263
+ })();`.trim();
7264
+ // --- Import -----------------------------------------------------------
7265
+ // Both importers THROW when there is no world, so both are guarded ahead.
7266
+ case 'import_obj':
7267
+ case 'import_gltf': {
7268
+ const fn = input.action === 'import_obj' ? 'importOBJToWorld' : 'importGLTFToWorld';
7269
+ return `
7270
+ // World3D: ${input.action}
7271
+ (async function() {
7272
+ // @engine-methods extrudeToMesh latheToMesh importOBJToWorld importGLTFToWorld
7273
+ if (typeof app.${fn} !== 'function') { return { success: false, error: 'app.${fn} unavailable — update FxTool to a world3d-capable build' }; }
7274
+ ${needWorld}
7275
+ const r = await app.${fn}(${S(input.source)}, ${S(input.importOptions ?? {})});
7276
+ if (!r || r.ok === false) { return { success: false, error: (r && (r.error || r.reason)) || 'the world refused the import' }; }
7277
+ return { success: true, meshIds: r.ids, ...r };
7278
+ })();`.trim();
7279
+ }
7280
+ case 'list_mesh_clips':
7281
+ return `
7282
+ // World3D: the animation clips an imported skinned mesh carries
7283
+ (function() {
7284
+ if (typeof app.listWorldMeshClips !== 'function') { return { success: false, error: 'app.listWorldMeshClips unavailable — update FxTool' }; }
7285
+ ${needWorld}
7286
+ return { success: true, clips: app.listWorldMeshClips(${S(input.meshId)}) };
7287
+ })();`.trim();
7288
+ case 'set_mesh_clip':
7289
+ return `
7290
+ // World3D: choose which clip a skinned mesh plays
7291
+ (function() {
7292
+ if (typeof app.setWorldMeshClip !== 'function') { return { success: false, error: 'app.setWorldMeshClip unavailable — update FxTool' }; }
7293
+ ${needWorld}
7294
+ return { success: !!app.setWorldMeshClip(${S(input.meshId)}, ${S(input.clip)}${input.crossfade !== undefined ? `, { crossfade: ${S(input.crossfade)} }` : ''}) };
7295
+ })();`.trim();
7296
+ // --- Navigation, picking, camera --------------------------------------
7297
+ // These facades answer `null` — or 0, for groundHeightAt — when there is
7298
+ // NO WORLD, which is indistinguishable from a real answer: ground really
7299
+ // can be at height 0, and a ray really can hit nothing. Guarded ahead so
7300
+ // "there is no world" never arrives disguised as a measurement.
7301
+ case 'set_nav_target':
7302
+ return `
7303
+ // World3D: point the pointer at the 2D canvas or the 3D world
7304
+ (function() {
7305
+ if (typeof app.setWorldNavTarget !== 'function') { return { success: false, error: 'app.setWorldNavTarget unavailable — update FxTool' }; }
7306
+ const r = app.setWorldNavTarget(${S(input.navTarget)});
7307
+ if (!r || r.ok === false) { return { success: false, error: (r && r.error) || 'the nav target was refused' }; }
7308
+ return { success: true, navTarget: ${S(input.navTarget)} };
7309
+ })();`.trim();
7310
+ case 'get_nav_target':
7311
+ return `
7312
+ // World3D: which layer the pointer currently drives
7313
+ (function() {
7314
+ if (typeof app.getWorldNavTarget !== 'function') { return { success: false, error: 'app.getWorldNavTarget unavailable — update FxTool' }; }
7315
+ return { success: true, navTarget: app.getWorldNavTarget() };
7316
+ })();`.trim();
7317
+ case 'ground_height':
7318
+ return `
7319
+ // World3D: the terrain height under a world (x, z)
7320
+ (function() {
7321
+ if (typeof app.groundHeightAt !== 'function') { return { success: false, error: 'app.groundHeightAt unavailable — update FxTool' }; }
7322
+ ${needWorld}
7323
+ const p = ${S(input.point)};
7324
+ return { success: true, height: app.groundHeightAt(p.x, p.z !== undefined ? p.z : p.y) };
7325
+ })();`.trim();
7326
+ case 'raycast':
7327
+ return `
7328
+ // World3D: cast a ray and report what it hits
7329
+ (function() {
7330
+ if (typeof app.raycastWorld !== 'function') { return { success: false, error: 'app.raycastWorld unavailable — update FxTool' }; }
7331
+ ${needWorld}
7332
+ const hit = app.raycastWorld(${S(input.origin)}, ${S(input.direction)}, {});
7333
+ // A null here means MISSED, not "no world" — the guard above already
7334
+ // separated those two, which is the whole reason it is there.
7335
+ return { success: true, hit: hit || null, missed: !hit };
7336
+ })();`.trim();
7337
+ case 'dolly_camera':
7338
+ return `
7339
+ // World3D: dolly the camera — >1 away, <1 closer
7340
+ (function() {
7341
+ if (typeof app.dollyWorldCamera !== 'function') { return { success: false, error: 'app.dollyWorldCamera unavailable — update FxTool' }; }
7342
+ ${needWorld}
7343
+ return { success: true, camera: app.dollyWorldCamera(${S(input.multiplier)}) };
7344
+ })();`.trim();
7345
+ case 'pan_camera':
7346
+ return `
7347
+ // World3D: pan the camera across the ground, in SCREEN pixels
7348
+ (function() {
7349
+ if (typeof app.panWorldCamera !== 'function') { return { success: false, error: 'app.panWorldCamera unavailable — update FxTool' }; }
7350
+ ${needWorld}
7351
+ return { success: true, camera: app.panWorldCamera(${S(input.dx)}, ${S(input.dy)}) };
7352
+ })();`.trim();
7353
+ case 'world_to_canvas':
7354
+ return `
7355
+ // World3D: project a world point onto the Paper canvas
7356
+ (function() {
7357
+ if (typeof app.worldToCanvas !== 'function') { return { success: false, error: 'app.worldToCanvas unavailable — update FxTool' }; }
7358
+ ${needWorld}
7359
+ return { success: true, point: app.worldToCanvas(${S(input.point)}) };
7360
+ })();`.trim();
7361
+ case 'canvas_to_ground':
7362
+ return `
7363
+ // World3D: where a canvas (x, y) lands on the world's ground
7364
+ (function() {
7365
+ if (typeof app.canvasToGround !== 'function') { return { success: false, error: 'app.canvasToGround unavailable — update FxTool' }; }
7366
+ ${needWorld}
7367
+ const p = ${S(input.point)};
7368
+ return { success: true, ground: app.canvasToGround(p.x, p.y) };
7369
+ })();`.trim();
7370
+ // --- Physics in the world ---------------------------------------------
7371
+ // addPhysicsBody3D and fireProjectile3D THROW without a world; the rest
7372
+ // return false, [] or a hollow {contacts:[],removed:[]} — each of which
7373
+ // is a plausible real answer. Both shapes are guarded the same way here.
7374
+ case 'add_body':
7375
+ return `
7376
+ // World3D: a body under gravity, colliding with the world
7377
+ (function() {
7378
+ if (typeof app.addPhysicsBody3D !== 'function') { return { success: false, error: 'app.addPhysicsBody3D unavailable — update FxTool' }; }
7379
+ ${needWorld}
7380
+ const r = app.addPhysicsBody3D(${S(input.body)});
7381
+ if (!r || r.ok === false) { return { success: false, error: (r && (r.error || r.reason)) || 'the world refused the body' }; }
7382
+ return { success: true, bodyId: r.id, ...r };
7383
+ })();`.trim();
7384
+ case 'fire_projectile':
7385
+ return `
7386
+ // World3D: fire a projectile
7387
+ (function() {
7388
+ if (typeof app.fireProjectile3D !== 'function') { return { success: false, error: 'app.fireProjectile3D unavailable — update FxTool' }; }
7389
+ ${needWorld}
7390
+ const r = app.fireProjectile3D(${S(input.body)});
7391
+ if (!r || r.ok === false) { return { success: false, error: (r && (r.error || r.reason)) || 'the projectile was refused' }; }
7392
+ return { success: true, ...r };
7393
+ })();`.trim();
7394
+ case 'remove_body':
7395
+ return `
7396
+ // World3D: drop a body
7397
+ (function() {
7398
+ if (typeof app.removePhysicsBody3D !== 'function') { return { success: false, error: 'app.removePhysicsBody3D unavailable — update FxTool' }; }
7399
+ ${needWorld}
7400
+ return { success: !!app.removePhysicsBody3D(${S(input.bodyId)}) };
7401
+ })();`.trim();
7402
+ case 'list_bodies':
7403
+ return `
7404
+ // World3D: every physics body
7405
+ (function() {
7406
+ if (typeof app.listPhysicsBodies3D !== 'function') { return { success: false, error: 'app.listPhysicsBodies3D unavailable — update FxTool' }; }
7407
+ ${needWorld}
7408
+ return { success: true, bodies: app.listPhysicsBodies3D() };
7409
+ })();`.trim();
7410
+ case 'step_physics':
7411
+ return `
7412
+ // World3D: advance the simulation, and report what touched what
7413
+ (function() {
7414
+ if (typeof app.stepPhysics3D !== 'function') { return { success: false, error: 'app.stepPhysics3D unavailable — update FxTool' }; }
7415
+ ${needWorld}
7416
+ // Without a world this answers {contacts:[],removed:[]} — a perfectly
7417
+ // ordinary quiet step. The guard above is what keeps those apart.
7418
+ const r = app.stepPhysics3D(${S(input.dt)});
7419
+ return { success: true, contacts: r && r.contacts, removed: r && r.removed };
7420
+ })();`.trim();
7421
+ case 'impulse':
7422
+ return `
7423
+ // World3D: apply an impulse
7424
+ (function() {
7425
+ if (typeof app.applyPhysicsImpulse3D !== 'function') { return { success: false, error: 'app.applyPhysicsImpulse3D unavailable — update FxTool' }; }
7426
+ ${needWorld}
7427
+ return { success: !!app.applyPhysicsImpulse3D(${S(input.bodyId)}, ${S(input.vector)}) };
7428
+ })();`.trim();
7429
+ case 'set_velocity':
7430
+ return `
7431
+ // World3D: set a body's velocity outright
7432
+ (function() {
7433
+ if (typeof app.setPhysicsVelocity3D !== 'function') { return { success: false, error: 'app.setPhysicsVelocity3D unavailable — update FxTool' }; }
7434
+ ${needWorld}
7435
+ return { success: !!app.setPhysicsVelocity3D(${S(input.bodyId)}, ${S(input.vector)}) };
7436
+ })();`.trim();
7437
+ case 'line_of_sight':
7438
+ return `
7439
+ // World3D: can one point see another
7440
+ (function() {
7441
+ if (typeof app.worldLineOfSight !== 'function') { return { success: false, error: 'app.worldLineOfSight unavailable — update FxTool' }; }
7442
+ ${needWorld}
7443
+ return { success: true, clear: app.worldLineOfSight(${S(input.from)}, ${S(input.to)}) };
7444
+ })();`.trim();
7445
+ case 'set_mesh_instances':
7446
+ return `
7447
+ // World3D: replace a mesh's instance data — six floats each
7448
+ (function() {
7449
+ if (typeof app.setWorldMeshInstances !== 'function') { return { success: false, error: 'app.setWorldMeshInstances unavailable — update FxTool' }; }
7450
+ ${needWorld}
7451
+ // x, y, z, scale, rotY (RADIANS, as everywhere on this path), variant.
7452
+ return { success: !!app.setWorldMeshInstances(${S(input.meshId)}, ${S(input.instances)}) };
7453
+ })();`.trim();
7454
+ }
7455
+ }
7456
+ /**
7457
+ * pinepaper_design_system — answered in this server, not in the browser.
7458
+ *
7459
+ * Only `compose` with `draw` produces code at all: the tokens, the easings
7460
+ * and the style list are computed here and returned by the handler, because
7461
+ * a design decision does not need the canvas to be open. When a scene IS
7462
+ * drawn, it arrives as a finished list of create calls — the layout was
7463
+ * already decided by a pure function, so nothing is left for the page to
7464
+ * work out.
7465
+ */
7466
+ generateDesignCompose(scene, ops, style) {
7467
+ const S = (v) => JSON.stringify(v);
7468
+ return `
7469
+ // Design: compose a ${style} scene — ${ops.length} items, laid out server-side
7470
+ (function() {
7471
+ if (typeof app.create !== 'function') { return { success: false, error: 'app.create unavailable — update FxTool' }; }
7472
+ const size = ${S({ width: scene.width, height: scene.height })};
7473
+ if (typeof app.setCanvasSize === 'function') { try { app.setCanvasSize(size.width, size.height); } catch (_) { /* a fixed canvas is not a failure */ } }
7474
+ ${scene.backgroundHex ? `if (typeof app.setBackgroundColor === 'function') { try { app.setBackgroundColor(${S(scene.backgroundHex)}); } catch (_) { /* ditto */ } }` : '// this style paints no background of its own'}
7475
+ const ops = ${S(ops)};
7476
+ const ids = [];
7477
+ const failed = [];
7478
+ for (const op of ops) {
7479
+ const { type, note, name, ...props } = op;
7480
+ try {
7481
+ const item = app.create(type, props);
7482
+ if (item) { ids.push(item.data && item.data.id); } else { failed.push({ name: name, type: type, reason: 'create returned nothing' }); }
7483
+ } catch (e) { failed.push({ name: name, type: type, reason: (e && e.message) || String(e) }); }
7484
+ }
7485
+ if (app.historyManager) app.historyManager.saveState();
7486
+ // A partial composition is reported as one. Half a poster that claims
7487
+ // success is worse than a poster that says which four elements are missing.
7488
+ return { success: failed.length === 0, style: ${S(style)}, itemIds: ids, itemCount: ids.length, failed: failed };
7489
+ })();`.trim();
7490
+ }
7491
+ /**
7492
+ * pinepaper_stick — the vendored stick-figure kit.
7493
+ *
7494
+ * Both facades take one options bag, so the schema's named fields are
7495
+ * reassembled into it. Naming them individually is the point: the kit's
7496
+ * options were discoverable only by reading FxTool's source.
7497
+ */
7498
+ generateStick(input) {
7499
+ const S = (v) => JSON.stringify(v);
7500
+ const { action, ...rest } = input;
7501
+ const opts = {};
7502
+ for (const [k, v] of Object.entries(rest))
7503
+ if (v !== undefined)
7504
+ opts[k] = v;
7505
+ const fn = action === 'figure' ? 'stickFigure' : 'stickSet';
7506
+ return `
7507
+ // Stick: ${action}
7508
+ (async function() {
7509
+ // @engine-methods stickFigure stickSet
7510
+ if (typeof app.${fn} !== 'function') { return { success: false, error: 'app.${fn} unavailable — update FxTool (the stick kit is vendored from mcp-cloud)' }; }
7511
+ const r = await app.${fn}(${S(opts)});
7512
+ if (!r || r.ok === false) { return { success: false, error: (r && (r.reason || r.error)) || 'the stick kit produced nothing' }; }
7513
+ return { success: true, ...r };
7514
+ })();`.trim();
7515
+ }
7516
+ /**
7517
+ * pinepaper_story — prose becomes a scene.
7518
+ *
7519
+ * `distill` deliberately draws nothing. A caller should be able to read what
7520
+ * the distiller made of the text and edit it before a scene is assembled
7521
+ * from it, rather than discovering the reading by looking at the result.
7522
+ */
7523
+ generateStory(input) {
7524
+ const S = (v) => JSON.stringify(v);
7525
+ const opts = S(input.options ?? {});
7526
+ switch (input.action) {
7527
+ case 'distill':
7528
+ return `
7529
+ // Story: reduce prose to beats, drawing NOTHING
7530
+ (async function() {
7531
+ if (typeof app.distillArticle !== 'function') { return { success: false, error: 'app.distillArticle unavailable — update FxTool' }; }
7532
+ const beats = await app.distillArticle(${S(input.text)});
7533
+ if (!beats) { return { success: false, error: 'the distiller made nothing of that text' }; }
7534
+ return { success: true, beats: beats };
7535
+ })();`.trim();
7536
+ case 'from_text':
7537
+ return `
7538
+ // Story: distill and assemble in one call
7539
+ (async function() {
7540
+ if (typeof app.storyFromText !== 'function') { return { success: false, error: 'app.storyFromText unavailable — update FxTool' }; }
7541
+ const r = await app.storyFromText(${S(input.text)}, ${opts});
7542
+ if (!r || r.ok === false) { return { success: false, error: (r && (r.reason || r.error)) || 'the story did not assemble' }; }
7543
+ return { success: true, ...r };
7544
+ })();`.trim();
7545
+ case 'apply_spec':
7546
+ return `
7547
+ // Story: assemble a spec you already have
7548
+ (async function() {
7549
+ if (typeof app.applyStorySpec !== 'function') { return { success: false, error: 'app.applyStorySpec unavailable — update FxTool' }; }
7550
+ const r = await app.applyStorySpec(${S(input.spec)}, ${opts});
7551
+ if (!r || r.ok === false) { return { success: false, error: (r && (r.reason || r.error)) || 'the spec did not assemble' }; }
7552
+ return { success: true, ...r };
7553
+ })();`.trim();
7554
+ case 'plan_book':
7555
+ return `
7556
+ // Story: lay images out as pages
7557
+ (function() {
7558
+ if (typeof app.planBook !== 'function') { return { success: false, error: 'app.planBook unavailable — update FxTool' }; }
7559
+ const plan = app.planBook(${S(input.images)}, ${opts});
7560
+ if (!plan) { return { success: false, error: 'no plan came back for those images' }; }
7561
+ return { success: true, plan: plan };
7562
+ })();`.trim();
7563
+ }
7564
+ }
7565
+ /**
7566
+ * pinepaper_interchange — Lottie, dotLottie, GLB, BVH, PNG sequence.
7567
+ *
7568
+ * Three of these refuse through `console.warn` and a falsy return, which the
7569
+ * production build strips — exportGLB with no perspective objects and
7570
+ * exportBVH with no rigging system both do exactly that. Over MCP there is no
7571
+ * console to read, so the PRECONDITION is checked here and named, rather than
7572
+ * letting a caller receive nothing and guess why.
7573
+ */
7574
+ // @engine-methods exportLottie exportDotLottie exportEngine.exportToStore exportEngine.readExport exportEngine.releaseExport
7575
+ generateInterchange(input) {
7576
+ const S = (v) => JSON.stringify(v);
7577
+ const guard = (fn) => ` if (typeof app.${fn} !== 'function') { return { success: false, error: 'app.${fn} unavailable — update FxTool' }; }`;
7578
+ const opts = S(input.options ?? {});
7579
+ switch (input.action) {
7580
+ case 'export_lottie':
7581
+ case 'export_dotlottie': {
7582
+ const fn = input.action === 'export_lottie' ? 'exportLottie' : 'exportDotLottie';
7583
+ return `
7584
+ // Interchange: ${fn}
7585
+ (async function() {
7586
+ ${guard(fn)}
7587
+ const out = await app.${fn}(${opts});
7588
+ if (!out) { return { success: false, error: '${fn} produced nothing — the scene may have no animatable content' }; }
7589
+ return { success: true, format: ${S(input.action === 'export_lottie' ? 'lottie' : 'dotlottie')}, data: out };
7590
+ })();`.trim();
7591
+ }
7592
+ case 'import_lottie':
7593
+ return `
7594
+ // Interchange: a Lottie back onto the canvas
7595
+ (async function() {
7596
+ ${guard('importLottie')}
7597
+ // importLottie logs and returns falsy when the importer is absent — a
7598
+ // stripped console makes that indistinguishable from an empty animation.
7599
+ const r = await app.importLottie(${S(input.data)}, ${opts});
7600
+ if (!r) { return { success: false, error: 'the Lottie did not import — it may be malformed, or this build has no Lottie importer' }; }
7601
+ return { success: true, imported: r };
7602
+ })();`.trim();
7603
+ case 'export_glb':
7604
+ return `
7605
+ // Interchange: GLB of the perspective 3D objects
7606
+ (async function() {
7607
+ ${guard('exportGLB')}
7608
+ // exportGLB warns and bails when nothing perspective exists. The warning is
7609
+ // stripped in production, so the precondition is checked here instead.
7610
+ const has3d = app._initialized && app._initialized.has && app._initialized.has('threeD');
7611
+ if (!has3d) { return { success: false, error: 'no perspective objects to export — create one with createObject3D first' }; }
7612
+ const out = await app.exportGLB(${opts});
7613
+ if (!out) { return { success: false, error: 'GLB export produced nothing' }; }
7614
+ return { success: true, format: 'glb', data: out };
7615
+ })();`.trim();
7616
+ case 'export_bvh':
7617
+ return `
7618
+ // Interchange: BVH of one skeleton's motion
7619
+ (async function() {
7620
+ ${guard('exportBVH')}
7621
+ // Same shape as GLB: exportBVH warns and bails without a RiggingSystem.
7622
+ const rigged = app._initialized && app._initialized.has && app._initialized.has('riggingSystem');
7623
+ if (!rigged) { return { success: false, error: 'no rig to export — create a skeleton first (pinepaper_rigging)' }; }
7624
+ const out = await app.exportBVH(${S(input.skeletonId)}, ${opts});
7625
+ if (!out) { return { success: false, error: 'BVH export produced nothing for skeleton ' + ${S(input.skeletonId)} }; }
7626
+ return { success: true, format: 'bvh', skeletonId: ${S(input.skeletonId)}, data: out };
7627
+ })();`.trim();
7628
+ case 'export_png_sequence':
7629
+ return `
7630
+ // Interchange: one PNG per frame
7631
+ (async function() {
7632
+ ${guard('exportPNGSequence')}
7633
+ const out = await app.exportPNGSequence(${opts});
7634
+ if (!out) { return { success: false, error: 'PNG sequence produced nothing' }; }
7635
+ return { success: true, format: 'png-sequence', result: out };
7636
+ })();`.trim();
7637
+ }
7638
+ }
7639
+ /**
7640
+ * pinepaper_sound — synthesis, and the drawing that is the same object.
7641
+ *
7642
+ * Every facade here rides `app.audioGraph`, which is lazily built, so each
7643
+ * action guards the METHOD rather than assuming the graph. The canvas half
7644
+ * (`create`, `timbre_from_path`) goes through PinePaper directly.
7645
+ */
7646
+ generateSound(input) {
7647
+ const S = (v) => JSON.stringify(v);
7648
+ const guard = (fn) => ` if (typeof app.${fn} !== 'function') { return { success: false, error: 'app.${fn} unavailable — update FxTool' }; }`;
7649
+ const simple = (fn, args, key, label) => `
7650
+ // Sound: ${label}
7651
+ (function() {
7652
+ ${guard(fn)}
7653
+ return { success: true, ${key}: app.${fn}(${args}) };
7654
+ })();`.trim();
7655
+ switch (input.action) {
7656
+ case 'list_instruments': return simple('listInstruments', '', 'instruments', 'the instrument catalogue');
7657
+ case 'list_percussion': return simple('listPercussion', '', 'percussion', 'the percussion catalogue');
7658
+ case 'list_sfx': return simple('listSfx', '', 'sfx', 'the SFX catalogue');
7659
+ case 'play_tone': return simple('playTone', `${S(input.note)}, ${S(input.options ?? {})}`, 'played', `tone ${input.note}`);
7660
+ case 'play_chord': return simple('playChord', `${S(input.root)}, ${S(input.chord)}, ${S(input.options ?? {})}`, 'played', `${input.chord} chord on ${input.root}`);
7661
+ case 'chord_frequencies': return simple('chordFrequencies', `${S(input.root)}, ${S(input.chord)}, ${S(input.options ?? {})}`, 'frequencies', `the Hz of ${input.chord} on ${input.root}`);
7662
+ case 'play_percussion': return simple('playPercussion', `${S(input.name)}, ${S(input.options ?? {})}`, 'played', `percussion ${input.name}`);
7663
+ case 'play_sfx': return simple('playSfx', `${S(input.name)}, ${S(input.options ?? {})}`, 'played', `sfx ${input.name}`);
7664
+ case 'play_spec': return simple('playSound', S(input.spec), 'played', 'a raw spec');
7665
+ case 'play_from_text': return simple('playSoundFromText', S(input.text), 'played', `"${input.text}"`);
7666
+ case 'from_text':
7667
+ return `
7668
+ // Sound: resolve "${input.text}" to a spec WITHOUT playing it
7669
+ (function() {
7670
+ ${guard('buildSoundFromText')}
7671
+ const spec = app.buildSoundFromText(${S(input.text)});
7672
+ // A description the resolver cannot read comes back empty rather than
7673
+ // throwing. Saying so beats handing back a spec that plays silence.
7674
+ if (!spec) { return { success: false, error: 'could not resolve ' + ${S(input.text)} + ' into a sound' }; }
7675
+ return { success: true, spec: spec };
7676
+ })();`.trim();
7677
+ // DEFINING A SOUND. The engine's three tables are "a curated starting set,
7678
+ // not a claim that music contains six instruments" — its words. Anything
7679
+ // it does not model can be registered at runtime and is then first-class:
7680
+ // listInstruments() reads the LIVE table, so a defined instrument shows
7681
+ // up in list_instruments and plays by name like any built-in.
7682
+ //
7683
+ // The canonical name is RETURNED rather than assumed. Registration
7684
+ // normalises to [a-z][a-z0-9_-]{0,31}, so a model that registers
7685
+ // 'Rhodes' and then plays 'Rhodes' is playing something that does not
7686
+ // exist — the name it actually got is 'rhodes', and it needs to be told.
7687
+ case 'define_instrument':
7688
+ case 'define_percussion':
7689
+ case 'define_sfx': {
7690
+ const fn = input.action === 'define_instrument' ? 'registerInstrument'
7691
+ : input.action === 'define_percussion' ? 'registerPercussion' : 'registerSfx';
7692
+ const listFn = input.action === 'define_instrument' ? 'listInstruments'
7693
+ : input.action === 'define_percussion' ? 'listPercussion' : 'listSfx';
7694
+ const spec = {
7695
+ ...(input.partials ? { partials: input.partials } : {}),
7696
+ ...(input.envelope ? { envelope: input.envelope } : {}),
7697
+ ...(input.gain !== undefined ? { gain: input.gain } : {}),
7698
+ ...(input.aliases ? { aliases: input.aliases } : {}),
7699
+ ...(input.noise !== undefined ? { noise: input.noise } : {}),
7700
+ ...(input.noiseFreq !== undefined ? { noiseFreq: input.noiseFreq } : {}),
7701
+ ...(input.hz !== undefined ? { hz: input.hz } : {}),
7702
+ ...(input.pitch ? { pitch: input.pitch } : {}),
7703
+ };
7704
+ // @engine-methods registerInstrument registerPercussion registerSfx
7705
+ // The guard below is INTERPOLATED — `guard(fn)` takes a variable, not a
7706
+ // literal — so sync-engine-methods.mjs cannot read the names out of it
7707
+ // and the studio probe would report a studio as complete while never
7708
+ // checking the method a caller needs. It extracted only
7709
+ // renderSoundtrackWav until this line existed.
7710
+ return `
7711
+ // Sound: define ${input.name} at runtime
7712
+ (function() {
7713
+ ${guard(fn)}
7714
+ var name;
7715
+ // The engine THROWS on an unusable name or a silent spec, with a message
7716
+ // naming what was wrong. That is the useful answer, so it is caught and
7717
+ // returned rather than allowed to surface as a bridge error with no subject.
7718
+ try { name = app.${fn}(${S(input.name)}, ${S(spec)}); }
7719
+ catch (e) { return { success: false, error: (e && e.message) || String(e) }; }
7720
+ var listed = typeof app.${listFn} === 'function' ? app.${listFn}() : null;
7721
+ var found = Array.isArray(listed)
7722
+ ? listed.some(function (x) { return (x && x.name) === name; })
7723
+ : null;
7724
+ return {
7725
+ success: true,
7726
+ // The name the engine CHOSE, which is what plays. Registering 'Rhodes'
7727
+ // returns 'rhodes'.
7728
+ canonicalName: name,
7729
+ requestedName: ${S(input.name)},
7730
+ normalised: name !== ${S(input.name)},
7731
+ // Defined but unlistable would be a capability nobody can name. Proven per
7732
+ // call rather than assumed, because it is one table lookup.
7733
+ listed: found,
7734
+ };
7735
+ })();`.trim();
7736
+ }
7737
+ case 'render_soundtrack': {
7738
+ const opts = {
7739
+ ...(typeof input.options?.duration === 'number' ? { duration: input.options.duration } : {}),
7740
+ ...(input.sampleRate !== undefined ? { sampleRate: input.sampleRate } : {}),
7741
+ ...(input.bitDepth !== undefined ? { bitDepth: input.bitDepth } : {}),
7742
+ };
7743
+ return `
7744
+ // Sound: mix every placed sound to a WAV, offline
7745
+ (function() {
7746
+ ${guard('renderSoundtrackWav')}
7747
+ var r = app.renderSoundtrackWav(${S(opts)});
7748
+ // BARE NULL MEANS "NO SOUNDS PLACED". Returned for an empty scene and for a
7749
+ // scene whose sounds all failed to mix — indistinguishable from a malfunction
7750
+ // unless it is named, and "the export produced nothing" is the report that
7751
+ // sends someone debugging the exporter instead of placing a sound.
7752
+ if (!r || !r.wav) {
7753
+ return { success: false, error: 'no sounds are placed on this scene, so there is no soundtrack to render. Create one with action "create", or place an existing sound with "set_placement".' };
7754
+ }
7755
+ var bytes = r.wav;
7756
+ // Uint8Array cannot cross the bridge; base64 in chunks, because
7757
+ // String.fromCharCode.apply over a multi-megabyte array blows the stack.
7758
+ var bin = '';
7759
+ for (var i = 0; i < bytes.length; i += 8192) {
7760
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 8192));
7761
+ }
7762
+ return {
7763
+ success: true,
7764
+ wavBase64: btoa(bin),
7765
+ byteLength: bytes.length,
7766
+ duration: r.duration,
7767
+ sampleRate: r.sampleRate,
7768
+ sounds: r.sounds,
7769
+ placed: r.placed,
7770
+ // DROPPED IS THE SECOND SILENT REFUSAL. A mix with placed > 0 and dropped
7771
+ // > 0 is a valid WAV that is quietly missing sounds — the same shape as an
7772
+ // item list capped below its own itemCount. Reported only when it happened,
7773
+ // so the marker stays meaningful.
7774
+ ...(r.dropped > 0 ? { dropped: r.dropped, incomplete:
7775
+ 'mixed ' + r.placed + ' sound(s); ' + r.dropped + ' could not be rendered and are absent from this file' } : {}),
7776
+ };
7777
+ })();`.trim();
7778
+ }
7779
+ case 'create':
7780
+ return `
7781
+ // Sound: draw it AS a waveform path — the item and the sound are one thing
7782
+ (function() {
7783
+ ${guard('createSound')}
7784
+ const item = app.createSound(${S(input.spec ?? {})}, ${S(input.visual ?? {})});
7785
+ if (!item) { return { success: false, error: 'the sound produced no waveform path' }; }
7786
+ return { success: true, itemId: item.data && item.data.id, itemType: 'sound' };
7787
+ })();`.trim();
7788
+ case 'timbre_from_path':
7789
+ return `
7790
+ // Sound: read a drawn path's shape as harmonic content
7791
+ (function() {
7792
+ ${guard('timbreFromPath')}
7793
+ const item = app.getItemById ? app.getItemById(${S(input.itemId)}) : null;
7794
+ // timbreFromPath answers a flat {partials:[{h:1,amp:1}]} for anything that is
7795
+ // not a path with length — a real timbre and a refusal look identical, so the
7796
+ // item is checked HERE instead of reading that back as an answer.
7797
+ if (!item) { return { success: false, error: 'no such item: ' + ${S(input.itemId)} }; }
7798
+ if (typeof item.getPointAt !== 'function' || !(item.length > 0)) {
7799
+ return { success: false, error: 'timbre needs a path with length — ' + ${S(input.itemId)} + ' is not one' };
7800
+ }
7801
+ return { success: true, timbre: app.timbreFromPath(item, ${S(input.samples ?? 256)}) };
7802
+ })();`.trim();
7803
+ case 'set_placement': return simple('setSoundPlacement', `${S(input.itemId)}, ${S(input.placement ?? {})}`, 'placed', 'placement');
7804
+ case 'remove': return simple('removeSound', S(input.itemId), 'removed', 'remove');
7805
+ case 'stop_all': return simple('stopSounds', '', 'stopped', 'stop everything');
7806
+ }
7807
+ }
7808
+ /**
7809
+ * pinepaper_motion — the generators' Animation knob for any group.
7810
+ *
7811
+ * animateItems returns `{error}` on failure, NOT `{ok:false, reason}` like
7812
+ * the path facades — reading the wrong key here turns "could not attach
7813
+ * \"ripple\" (frame-callback limit reached?)" into undefined.
7814
+ */
7815
+ generateMotion(input) {
7816
+ const S = (v) => JSON.stringify(v);
7817
+ if (input.action === 'list') {
7818
+ return `
7819
+ // The engine's own motion catalogue — motions, waveforms, origins, knobs
7820
+ (async function() {
7821
+ if (typeof app.listGeneratorMotions !== 'function') { return { success: false, error: 'app.listGeneratorMotions unavailable — update FxTool' }; }
7822
+ const c = await app.listGeneratorMotions();
7823
+ return { success: true, ...c };
7824
+ })();`.trim();
7825
+ }
7826
+ const target = input.itemIds && input.itemIds.length ? S(input.itemIds) : S(input.itemId);
7827
+ const opts = { animation: input.motion };
7828
+ for (const k of ['speed', 'intensity', 'waveform', 'origin', 'seed']) {
7829
+ if (input[k] !== undefined)
7830
+ opts[k] = input[k];
7831
+ }
7832
+ return `
7833
+ // Motion: ${input.motion} on ${input.itemIds?.length ? `${input.itemIds.length} items` : input.itemId}
7834
+ (async function() {
7835
+ if (typeof app.animateItems !== 'function') { return { success: false, error: 'app.animateItems unavailable — update FxTool' }; }
7836
+ const r = await app.animateItems(${target}, ${S(opts)});
7837
+ // An unknown motion comes back with the known list attached, so a caller can
7838
+ // correct itself without a second round trip.
7839
+ if (!r || r.error) { return { success: false, error: (r && r.error) || 'the motion did not attach', motions: r && r.motions }; }
7840
+ return { success: true, motion: ${S(input.motion)} };
7841
+ })();`.trim();
7842
+ }
7843
+ /**
7844
+ * pinepaper_path — the destructive path operations.
7845
+ *
7846
+ * Every facade here returns `{ok:false, reason}` and names its own refusal
7847
+ * ("a boolean needs at least two paths", "that path has no stroke to
7848
+ * outline"), so the reason is passed through rather than reworded. A second
7849
+ * wording for one condition is the thing to avoid, not the guard.
7850
+ */
7851
+ generatePathOp(input) {
7852
+ const S = (v) => JSON.stringify(v);
7853
+ const guard = (fn) => ` if (typeof app.${fn} !== 'function') { return { success: false, error: 'app.${fn} unavailable — update FxTool' }; }`;
7854
+ const pass = (expr) => `
7855
+ const r = ${expr};
7856
+ if (!r || r.ok === false) { return { success: false, error: (r && r.reason) || 'the engine refused the operation' }; }
7857
+ return { success: true, ...r };`;
7858
+ switch (input.action) {
7859
+ case 'boolean':
7860
+ return `
7861
+ // Path boolean: ${input.op} — CONSUMES its operands and leaves one result
7862
+ (function() {
7863
+ ${guard('booleanOp')}${pass(`app.booleanOp(${S(input.itemIds)}, ${S(input.op)})`)}
7864
+ })();`.trim();
7865
+ case 'simplify':
7866
+ return `
7867
+ // Simplify: fewer segments, same shape
7868
+ (function() {
7869
+ ${guard('simplifyPath')}${pass(`app.simplifyPath(${S(input.itemId)}${input.tolerance !== undefined ? `, ${S(input.tolerance)}` : ''})`)}
7870
+ })();`.trim();
7871
+ case 'outline_stroke':
7872
+ return `
7873
+ // Outline stroke: a stroked line becomes a filled shape of the same width
7874
+ (function() {
7875
+ ${guard('outlineStroke')}${pass(`app.outlineStroke(${S(input.itemId)}, ${S(input.tolerance !== undefined ? { tolerance: input.tolerance } : {})})`)}
7876
+ })();`.trim();
7877
+ case 'toggle_closed':
7878
+ return `
7879
+ // Open or close the path
7880
+ (function() {
7881
+ ${guard('togglePathClosed')}${pass(`app.togglePathClosed(${S(input.itemId)})`)}
7882
+ })();`.trim();
7883
+ case 'pattern':
7884
+ return `
7885
+ // Pattern: repeat the item — ${input.kind}
7886
+ (function() {
7887
+ ${guard('patternFrom')}${pass(`app.patternFrom(${S(input.itemId)}, ${S(input.kind)}, ${S(input.pattern ?? {})})`)}
7888
+ })();`.trim();
7889
+ case 'get_geometry':
7890
+ return `
7891
+ // Read the path's segments back
7892
+ (function() {
7893
+ ${guard('getPathGeometry')}
7894
+ const g = app.getPathGeometry(${S(input.itemId)}, {});
7895
+ // null means no such item — the one facade here that does NOT name its
7896
+ // refusal, so this is the one place a wording is supplied rather than passed.
7897
+ if (!g) { return { success: false, error: 'no such item: ' + ${S(input.itemId)} }; }
7898
+ return { success: true, geometry: g };
7899
+ })();`.trim();
7900
+ case 'set_locked':
7901
+ return `
7902
+ // Lock or unlock — a locked item is also unselectable and undraggable
7903
+ (function() {
7904
+ ${guard('setItemLocked')}${pass(`app.setItemLocked(${S(input.itemId)}, ${S(input.locked)})`)}
7905
+ })();`.trim();
7906
+ case 'unlock_all':
7907
+ return `
7908
+ // Unlock everything on the canvas
7909
+ (function() {
7910
+ ${guard('unlockAllItems')}${pass('app.unlockAllItems()')}
6738
7911
  })();`.trim();
6739
7912
  }
6740
7913
  }
@@ -7197,6 +8370,21 @@ ${needWorld}
7197
8370
  * object. Guards on the app method so old FxTool builds degrade gracefully.
7198
8371
  */
7199
8372
  generateEquationPath(input) {
8373
+ // An ODE is INTEGRATED, not plotted: the caller gets the trajectory back as
8374
+ // data rather than a drawn path, so it can be inspected, fed to a path, or
8375
+ // used to drive keyframes. Branching here rather than in a separate tool
8376
+ // keeps one place that knows the equation vocabulary.
8377
+ if (input.solveOde) {
8378
+ const ode = input.solveOde;
8379
+ return `
8380
+ // Integrate an ODE and return the SOLUTION — nothing is drawn
8381
+ (async function() {
8382
+ if (typeof app.solveODE !== 'function') { return { success: false, error: 'app.solveODE unavailable — update FxTool' }; }
8383
+ const sol = await app.solveODE(${JSON.stringify({ equations: ode.equations, initialState: ode.initialState, tEnd: ode.tEnd, dt: ode.dt })}, ${JSON.stringify(ode.method ?? 'rk4')});
8384
+ if (!sol) { return { success: false, error: 'the solver returned nothing — check the equations and the initial state length' }; }
8385
+ return { success: true, method: ${JSON.stringify(ode.method ?? 'rk4')}, solution: sol };
8386
+ })();`.trim();
8387
+ }
7200
8388
  const optsJson = JSON.stringify(input);
7201
8389
  const kindJson = JSON.stringify(input.kind);
7202
8390
  return `