@call-me-sensei/toonlab 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/AGENTS.md +127 -4
  2. package/ATTRIBUTION.md +41 -3
  3. package/README.md +234 -34
  4. package/docs/characters.md +144 -0
  5. package/docs/debug-panel.md +126 -0
  6. package/docs/docs.css +589 -0
  7. package/docs/environment.md +186 -0
  8. package/docs/getting-started.md +180 -0
  9. package/docs/index.html +14 -0
  10. package/docs/lab-architecture.md +100 -0
  11. package/docs/lighting.md +825 -0
  12. package/docs/main.jsx +739 -0
  13. package/docs/mcp.md +97 -0
  14. package/docs/post-processing.md +98 -0
  15. package/docs/settings-reference.md +1878 -0
  16. package/docs/shader-constants.md +77 -0
  17. package/docs/sky.md +182 -0
  18. package/docs/style-labs.md +309 -0
  19. package/docs/texture-lab.md +135 -0
  20. package/docs/toon-shading.md +183 -0
  21. package/docs/tsl-conventions.md +167 -0
  22. package/docs/vegetation-sky.md +275 -0
  23. package/docs/water.md +430 -0
  24. package/docs/weather.md +200 -0
  25. package/docs/world-scale.md +111 -0
  26. package/mcp/server.mjs +610 -0
  27. package/mcp/style-lab-tools.mjs +371 -0
  28. package/mcp/vite-plugin.mjs +174 -0
  29. package/mcp/workspace.mjs +397 -0
  30. package/package.json +64 -5
  31. package/src/ambientfx/INTEGRATION.md +164 -0
  32. package/src/ambientfx/ambientFxPresets.js +83 -0
  33. package/src/ambientfx/ambientFxSettings.js +368 -0
  34. package/src/ambientfx/emitters.js +169 -0
  35. package/src/ambientfx/index.js +5 -0
  36. package/src/ambientfx/particleBackbone.js +493 -0
  37. package/src/ambientfx/stylizedAmbientFx.js +450 -0
  38. package/src/assetlib/ambientcg.js +117 -0
  39. package/src/assetlib/assetRef.js +91 -0
  40. package/src/assetlib/importedEntry.js +40 -0
  41. package/src/assetlib/index.js +23 -0
  42. package/src/assetlib/kaykit.js +192 -0
  43. package/src/assetlib/kaykitStaticIndex.js +700 -0
  44. package/src/assetlib/loadImported.js +143 -0
  45. package/src/assetlib/opensource3d.js +113 -0
  46. package/src/assetlib/polyhaven.js +182 -0
  47. package/src/assetlib/polypizza.js +115 -0
  48. package/src/assetlib/smithsonian.js +214 -0
  49. package/src/assetlib/sources.js +279 -0
  50. package/src/assetlib/zip.js +58 -0
  51. package/src/biome/biomeGenerator.js +385 -0
  52. package/src/biome/biomeRuntime.js +299 -0
  53. package/src/biome/index.js +2 -0
  54. package/src/buildinggen/buildingAsset.js +44 -0
  55. package/src/buildinggen/buildingGrammar.js +311 -0
  56. package/src/buildinggen/buildingMesh.js +451 -0
  57. package/src/buildinggen/buildingPresets.js +46 -0
  58. package/src/buildinggen/buildingRecipe.js +100 -0
  59. package/src/buildinggen/buildingSettings.js +238 -0
  60. package/src/buildinggen/index.js +6 -0
  61. package/src/camera/cameraDirector.js +157 -0
  62. package/src/camera/cameraGenerator.js +367 -0
  63. package/src/camera/cameraRig.js +570 -0
  64. package/src/camera/cameraSettings.js +236 -0
  65. package/src/camera/index.js +7 -0
  66. package/src/catalog/builtinEntries.js +245 -0
  67. package/src/catalog/catalog.js +210 -0
  68. package/src/catalog/index.js +3 -0
  69. package/src/catalog/manifest.js +84 -0
  70. package/src/core/generation.js +529 -0
  71. package/src/environment/environmentRigs.js +21 -1
  72. package/src/environment/environmentSettings.js +4 -0
  73. package/src/environment/environmentSunShadowPass.js +8 -0
  74. package/src/fauna/INTEGRATION.md +174 -0
  75. package/src/fauna/boids.js +861 -0
  76. package/src/fauna/faunaBodies.js +492 -0
  77. package/src/fauna/faunaPresets.js +52 -0
  78. package/src/fauna/faunaSettings.js +525 -0
  79. package/src/fauna/index.js +5 -0
  80. package/src/fauna/stylizedFauna.js +395 -0
  81. package/src/game-feel/gameFeelGenerator.js +402 -0
  82. package/src/game-feel/gameFeelRuntime.js +549 -0
  83. package/src/game-feel/index.js +2 -0
  84. package/src/index.js +17 -6
  85. package/src/lighting/colorIntensity.js +177 -0
  86. package/src/lighting/index.js +161 -0
  87. package/src/lighting/lightDescriptors.js +249 -0
  88. package/src/lighting/lightingCapabilities.js +79 -0
  89. package/src/lighting/lightingDocuments.js +247 -0
  90. package/src/lighting/lightingFixtures.js +446 -0
  91. package/src/lighting/lightingGenerator.js +449 -0
  92. package/src/lighting/lightingPresets.js +319 -0
  93. package/src/lighting/lightingRuntime.js +723 -0
  94. package/src/lighting/lightingStyle.js +386 -0
  95. package/src/lighting/lightingSystem.js +774 -0
  96. package/src/lighting/unrealExport.js +186 -0
  97. package/src/lighting/utils.js +87 -0
  98. package/src/motion/index.js +5 -0
  99. package/src/motion/motionClip.js +441 -0
  100. package/src/motion/motionController.js +628 -0
  101. package/src/motion/motionDocuments.js +225 -0
  102. package/src/motion/motionGraph.js +307 -0
  103. package/src/motion/motionSettings.js +222 -0
  104. package/src/pathgen/index.js +7 -0
  105. package/src/pathgen/pathBridge.js +232 -0
  106. package/src/pathgen/pathPresets.js +35 -0
  107. package/src/pathgen/pathRibbon.js +410 -0
  108. package/src/pathgen/pathRouter.js +380 -0
  109. package/src/pathgen/pathSettings.js +335 -0
  110. package/src/pathgen/pathTextures.js +123 -0
  111. package/src/pathgen/stylizedPaths.js +453 -0
  112. package/src/post/index.js +1 -0
  113. package/src/post/postGenerator.js +177 -0
  114. package/src/post/postProcessing.js +41 -0
  115. package/src/propgen/generatorsWave1.js +379 -0
  116. package/src/propgen/generatorsWave2.js +462 -0
  117. package/src/propgen/index.js +5 -0
  118. package/src/propgen/propAsset.js +323 -0
  119. package/src/propgen/propParts.js +170 -0
  120. package/src/propgen/propPlacement.js +459 -0
  121. package/src/propgen/propPresets.js +82 -0
  122. package/src/propgen/propSettings.js +395 -0
  123. package/src/shaders-tsl/chunks/projected-water-caustics.js +242 -0
  124. package/src/shaders-tsl/chunks/vegetation-style.js +360 -0
  125. package/src/shaders-tsl/chunks/water-shore-state.js +31 -0
  126. package/src/shaders-tsl/chunks/water-waves.js +90 -11
  127. package/src/shaders-tsl/environment.js +15 -1
  128. package/src/shaders-tsl/flower.js +279 -30
  129. package/src/shaders-tsl/grass.js +60 -33
  130. package/src/shaders-tsl/sky.js +125 -31
  131. package/src/shaders-tsl/tree-leaf.js +61 -25
  132. package/src/shaders-tsl/water-breaker.js +7 -4
  133. package/src/shaders-tsl/water-shore-state-simulation.js +523 -0
  134. package/src/shaders-tsl/water.js +439 -49
  135. package/src/shaders-tsl/woody-surface.js +154 -0
  136. package/src/sky/sceneOverrideLayers.js +10 -0
  137. package/src/sky/skyQuality.js +26 -0
  138. package/src/sky/stylizedSky.js +753 -45
  139. package/src/soundscape/index.js +4 -0
  140. package/src/soundscape/soundscapeGenerator.js +179 -0
  141. package/src/soundscape/soundscapeRuntime.js +806 -0
  142. package/src/soundscape/soundscapeSettings.js +292 -0
  143. package/src/styles/index.js +13 -0
  144. package/src/styles/styleBundle.js +325 -0
  145. package/src/stylizedTerrain.js +32 -2
  146. package/src/stylizedWorld.js +423 -20
  147. package/src/texgen/evaluateTexture.js +675 -0
  148. package/src/texgen/index.js +60 -0
  149. package/src/texgen/noise2.js +210 -0
  150. package/src/texgen/textureAi.js +436 -0
  151. package/src/texgen/textureGenerators.js +516 -0
  152. package/src/texgen/texturePresets.js +490 -0
  153. package/src/texgen/textureSettings.js +342 -0
  154. package/src/texgen/textureThree.js +59 -0
  155. package/src/vegetation/flowerSpecies.js +15 -3
  156. package/src/vegetation/grassPalettes.js +153 -0
  157. package/src/vegetation/index.js +6 -0
  158. package/src/vegetation/stylizedBush.js +2 -0
  159. package/src/vegetation/stylizedFlower.js +82 -0
  160. package/src/vegetation/stylizedFlowers.js +48 -7
  161. package/src/vegetation/stylizedForest.js +29 -1
  162. package/src/vegetation/stylizedGrass.js +291 -56
  163. package/src/vegetation/stylizedTree.js +38 -2
  164. package/src/vegetation/stylizedTreeFoliage.js +2 -1
  165. package/src/vegetation/vegetationShaders.js +1110 -0
  166. package/src/vfxgen/INTEGRATION.md +145 -0
  167. package/src/vfxgen/core/burstBackbone.js +380 -0
  168. package/src/vfxgen/core/projectileCore.js +92 -0
  169. package/src/vfxgen/core/spriteShapes.js +98 -0
  170. package/src/vfxgen/core/trailRibbon.js +272 -0
  171. package/src/vfxgen/core/vfxRandom.js +29 -0
  172. package/src/vfxgen/effects/emitHelpers.js +37 -0
  173. package/src/vfxgen/effects/magicEffects.js +162 -0
  174. package/src/vfxgen/effects/movementEffects.js +87 -0
  175. package/src/vfxgen/effects/weaponEffects.js +118 -0
  176. package/src/vfxgen/index.js +18 -0
  177. package/src/vfxgen/moves/moveController.js +146 -0
  178. package/src/vfxgen/moves/moveLibrary.js +335 -0
  179. package/src/vfxgen/vfxPresets.js +98 -0
  180. package/src/vfxgen/vfxSettings.js +384 -0
  181. package/src/vfxgen/vfxSystem.js +449 -0
  182. package/src/vfxgen/weapons/stylizedWeapons.js +137 -0
  183. package/src/villagegen/index.js +4 -0
  184. package/src/villagegen/stylizedVillage.js +490 -0
  185. package/src/villagegen/villageArchetypes.js +160 -0
  186. package/src/villagegen/villageNames.js +40 -0
  187. package/src/villagegen/villageSites.js +105 -0
  188. package/src/water/sceneOverrideLayers.js +23 -0
  189. package/src/water/water.js +5 -0
  190. package/src/water/waterBreakerSystem.js +15 -1
  191. package/src/water/waterCurrentField.js +447 -0
  192. package/src/water/waterMaterial.js +12 -0
  193. package/src/water/waterNearshorePhase.js +320 -0
  194. package/src/water/waterScenePasses.js +83 -30
  195. package/src/water/waterSettings.js +325 -13
  196. package/src/water/waterShoreMaterial.js +322 -0
  197. package/src/water/waterShoreStateField.js +605 -0
  198. package/src/water/waterSurface.js +797 -28
  199. package/src/weather/index.js +6 -0
  200. package/src/weather/weatherPrecipitation.js +221 -0
  201. package/src/weather/weatherPresets.js +258 -0
  202. package/src/weather/weatherSettings.js +269 -0
  203. package/src/weather/weatherSystem.js +871 -0
  204. package/src/worldMinimap.js +62 -0
  205. package/src/worldPresets.js +4 -1
@@ -0,0 +1,371 @@
1
+ import {
2
+ createGeneratedPostPresetDocument,
3
+ createPostGeneratorRecipe,
4
+ getPostGeneratorFamilyOptions,
5
+ validatePostGeneratorRecipe,
6
+ validatePostProcessingPresetDocument,
7
+ } from '../src/post/index.js';
8
+ import {
9
+ createCameraGeneratorRecipeDocument,
10
+ generateCameraPreset,
11
+ getCameraGeneratorArchetypeOptions,
12
+ validateCameraGeneratorRecipeDocument,
13
+ validateCameraPresetDocument,
14
+ } from '../src/camera/index.js';
15
+ import {
16
+ createGameFeelGeneratorRecipe,
17
+ createGeneratedGameFeelPresetDocument,
18
+ getGameFeelGeneratorFamilyOptions,
19
+ validateGameFeelGeneratorRecipe,
20
+ validateGameFeelPresetDocument,
21
+ } from '../src/game-feel/index.js';
22
+ import {
23
+ createGeneratedLightFixtureDocument,
24
+ createGeneratedLightingStyleDocument,
25
+ createLightFixtureGeneratorRecipe,
26
+ createLightingStyleGeneratorRecipe,
27
+ getLightFixtureGeneratorFamilyOptions,
28
+ getLightingStyleGeneratorFamilyOptions,
29
+ validateLightFixtureDocument,
30
+ validateLightFixtureGeneratorRecipe,
31
+ validateLightingStyleGeneratorRecipe,
32
+ validateLightingStylePresetDocument,
33
+ } from '../src/lighting/index.js';
34
+
35
+ const QUALITY_OPTIONS = Object.freeze(['mobile', 'balanced', 'cinematic']);
36
+
37
+ function clone(value) {
38
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
39
+ }
40
+
41
+ function cleanId(value, fallback) {
42
+ return String(value ?? fallback)
43
+ .trim()
44
+ .replace(/[^a-zA-Z0-9._/-]+/g, '_') || fallback;
45
+ }
46
+
47
+ function parseDocument(value, label) {
48
+ if (typeof value !== 'string') return value;
49
+ try {
50
+ return JSON.parse(value);
51
+ } catch (error) {
52
+ throw new Error(`${label} is not valid JSON: ${error.message}`);
53
+ }
54
+ }
55
+
56
+ function normalizedValidation(result) {
57
+ if (result?.ok) return result;
58
+ const errors = result?.errors?.length ? result.errors : ['Document validation failed.'];
59
+ return { errors, ok: false, value: null, warnings: result?.warnings ?? [] };
60
+ }
61
+
62
+ const ADAPTERS = new Map([
63
+ ['post', {
64
+ create: createPostGeneratorRecipe,
65
+ families: getPostGeneratorFamilyOptions,
66
+ generate: (recipe, options) => createGeneratedPostPresetDocument(recipe, options),
67
+ validatePreset: validatePostProcessingPresetDocument,
68
+ validateRecipe: validatePostGeneratorRecipe,
69
+ }],
70
+ ['camera', {
71
+ create: createCameraGeneratorRecipeDocument,
72
+ families: getCameraGeneratorArchetypeOptions,
73
+ generate: (recipe, options) => generateCameraPreset(recipe, options),
74
+ validatePreset: validateCameraPresetDocument,
75
+ validateRecipe: validateCameraGeneratorRecipeDocument,
76
+ }],
77
+ ['game-feel', {
78
+ create: createGameFeelGeneratorRecipe,
79
+ families: getGameFeelGeneratorFamilyOptions,
80
+ generate: (recipe, options) => createGeneratedGameFeelPresetDocument(recipe, options),
81
+ validatePreset: validateGameFeelPresetDocument,
82
+ validateRecipe: validateGameFeelGeneratorRecipe,
83
+ }],
84
+ ['lighting-style', {
85
+ create: createLightingStyleGeneratorRecipe,
86
+ families: getLightingStyleGeneratorFamilyOptions,
87
+ generate: (recipe, options) => createGeneratedLightingStyleDocument(recipe, options),
88
+ validatePreset: validateLightingStylePresetDocument,
89
+ validateRecipe: validateLightingStyleGeneratorRecipe,
90
+ }],
91
+ ['light-fixture', {
92
+ create: createLightFixtureGeneratorRecipe,
93
+ families: getLightFixtureGeneratorFamilyOptions,
94
+ generate: (recipe, options) => createGeneratedLightFixtureDocument(recipe, options),
95
+ validatePreset: validateLightFixtureDocument,
96
+ validateRecipe: validateLightFixtureGeneratorRecipe,
97
+ }],
98
+ ]);
99
+
100
+ const LAB_METADATA = Object.freeze({
101
+ post: Object.freeze({
102
+ budgetedQuality: true,
103
+ label: 'Post & Color Lab',
104
+ packageImport: '@call-me-sensei/toonlab/post',
105
+ runtimeApis: ['createPostProcessingPipeline'],
106
+ scope: 'Color grading, bloom, outline, vignette, depth cues, and screen-space effects.',
107
+ }),
108
+ camera: Object.freeze({
109
+ budgetedQuality: false,
110
+ label: 'Camera Lab',
111
+ packageImport: '@call-me-sensei/toonlab/camera',
112
+ runtimeApis: ['createCameraRig', 'createCameraDirector'],
113
+ scope: 'Composable follow, framing, collision, damping, noise, impulse, and lens behavior.',
114
+ }),
115
+ 'game-feel': Object.freeze({
116
+ budgetedQuality: true,
117
+ label: 'Game Feel Lab',
118
+ packageImport: '@call-me-sensei/toonlab/game-feel',
119
+ runtimeApis: ['createGameFeelRuntime'],
120
+ scope: 'Event-driven camera, time, motion, haptics, audio, flash, and project-defined effect orchestration.',
121
+ }),
122
+ 'lighting-style': Object.freeze({
123
+ budgetedQuality: true,
124
+ label: 'Lighting Lab · Styles',
125
+ labPath: '/lighting-lab/',
126
+ packageImport: '@call-me-sensei/toonlab/lighting',
127
+ runtimeApis: ['createLightingSystem'],
128
+ scope: 'Game-wide lighting identity: day-cycle palette, sun path, ambient/exposure philosophy, shadow policy.',
129
+ }),
130
+ 'light-fixture': Object.freeze({
131
+ budgetedQuality: false,
132
+ label: 'Lighting Lab · Fixtures',
133
+ labPath: '/lighting-lab/',
134
+ packageImport: '@call-me-sensei/toonlab/lighting',
135
+ runtimeApis: ['createLightingSystem', 'resolveFixturePlacement'],
136
+ scope: 'Reusable light fixtures with seeded per-placement variation, flicker, and day/night schedules.',
137
+ }),
138
+ });
139
+
140
+ const LAB_IDS = Object.freeze([...ADAPTERS.keys()]);
141
+
142
+ function getAdapter(id) {
143
+ const adapter = ADAPTERS.get(id);
144
+ if (!adapter) throw new Error(`Unknown style lab "${id}". Expected one of: ${LAB_IDS.join(', ')}.`);
145
+ return adapter;
146
+ }
147
+
148
+ function recipeDefinition(args, lab = null) {
149
+ const definition = {};
150
+ for (const [input, output = input] of [
151
+ ['base_preset', 'basePreset'],
152
+ ['configuration'],
153
+ ['description'],
154
+ ['domains'],
155
+ ['family'],
156
+ ['label'],
157
+ ['locks'],
158
+ ['seed'],
159
+ ]) {
160
+ if (args[input] !== undefined) definition[output] = clone(args[input]);
161
+ }
162
+ // Camera calls its starting families archetypes and stores the selected id
163
+ // in basePreset. Keep the generic MCP `family` vocabulary consistent while
164
+ // mapping it to the camera document contract.
165
+ if (lab === 'camera' && args.family !== undefined && args.base_preset === undefined) {
166
+ definition.basePreset = String(args.family);
167
+ }
168
+ return definition;
169
+ }
170
+
171
+ export function listStyleLabs() {
172
+ return {
173
+ architecture: {
174
+ designTime: 'Labs and MCP author generator recipes, inspect variants, validate documents, and save presets.',
175
+ runtime: 'The npm package applies resolved presets deterministically without editor dependencies.',
176
+ },
177
+ count: LAB_IDS.length,
178
+ labs: LAB_IDS.map((id) => ({
179
+ id,
180
+ ...LAB_METADATA[id],
181
+ families: getAdapter(id).families(),
182
+ generation: {
183
+ deterministic: true,
184
+ domainOverrides: true,
185
+ locks: true,
186
+ maxMcpBatch: 64,
187
+ qualities: LAB_METADATA[id].budgetedQuality ? QUALITY_OPTIONS : [],
188
+ seedSpace: 'uint32 (zero normalizes to 1)',
189
+ },
190
+ })),
191
+ };
192
+ }
193
+
194
+ export async function createStyleRecipe(args, { saveCreation, workspace } = {}) {
195
+ const lab = String(args.lab ?? '');
196
+ const adapter = getAdapter(lab);
197
+ const id = cleanId(args.id, `${lab}-generator`);
198
+ const recipe = adapter.create(id, recipeDefinition(args, lab));
199
+ const validation = normalizedValidation(adapter.validateRecipe(recipe));
200
+ if (!validation.ok) throw new Error(validation.errors.join(' '));
201
+ const file = args.save === false || !saveCreation ? null : await saveCreation(workspace, {
202
+ document: validation.value,
203
+ kind: `${lab}-recipe`,
204
+ name: args.name ?? validation.value.label ?? id,
205
+ });
206
+ return {
207
+ file,
208
+ lab,
209
+ recipe: validation.value,
210
+ runtime: LAB_METADATA[lab],
211
+ };
212
+ }
213
+
214
+ export async function generateStylePresets(args, { saveCreation, workspace } = {}) {
215
+ const lab = String(args.lab ?? '');
216
+ const adapter = getAdapter(lab);
217
+ const provided = parseDocument(args.recipe, 'recipe');
218
+ const recipe = provided ?? adapter.create(`${lab}-generator`, recipeDefinition(args, lab));
219
+ const validation = normalizedValidation(adapter.validateRecipe(recipe));
220
+ if (!validation.ok) throw new Error(validation.errors.join(' '));
221
+ const count = Math.max(1, Math.min(64, Math.floor(Number(args.count) || 1)));
222
+ const startSeed = (Number(args.start_seed ?? args.seed ?? validation.value.seed ?? 1) >>> 0) || 1;
223
+ const requestedQuality = QUALITY_OPTIONS.includes(args.quality) ? args.quality : 'balanced';
224
+ const quality = LAB_METADATA[lab].budgetedQuality ? requestedQuality : null;
225
+ const presets = [];
226
+ for (let index = 0; index < count; index += 1) {
227
+ // Recipes reserve zero as the default seed. Wrap over 1..2^32-1 without
228
+ // producing the duplicate `1, 1` pair at the uint32 boundary.
229
+ const seed = ((startSeed - 1 + index) % 0xffffffff) + 1;
230
+ const seededRecipe = { ...validation.value, seed };
231
+ const id = `${validation.value.id}-${seed}`;
232
+ const preset = adapter.generate(seededRecipe, {
233
+ id,
234
+ label: `${validation.value.label} · ${seed}`,
235
+ presetId: id,
236
+ ...(quality ? { quality } : {}),
237
+ seed,
238
+ });
239
+ const presetValidation = normalizedValidation(adapter.validatePreset(preset));
240
+ if (!presetValidation.ok) throw new Error(`Seed ${seed}: ${presetValidation.errors.join(' ')}`);
241
+ presets.push(presetValidation.value);
242
+ }
243
+ const document = {
244
+ lab,
245
+ presets,
246
+ quality,
247
+ qualityApplied: Boolean(quality),
248
+ recipe: validation.value,
249
+ schema: 'toonlab/style-preset-batch',
250
+ startSeed,
251
+ version: 1,
252
+ };
253
+ const file = args.save === false || !saveCreation ? null : await saveCreation(workspace, {
254
+ document,
255
+ kind: `${lab}-presets`,
256
+ name: args.name ?? `${validation.value.label} ${startSeed}-${((startSeed - 1 + count - 1) % 0xffffffff) + 1}`,
257
+ });
258
+ return {
259
+ count: presets.length,
260
+ file,
261
+ lab,
262
+ presets,
263
+ quality,
264
+ qualityApplied: Boolean(quality),
265
+ recipe: validation.value,
266
+ startSeed,
267
+ };
268
+ }
269
+
270
+ export function validateStyleDocument(args) {
271
+ const lab = String(args.lab ?? '');
272
+ const adapter = getAdapter(lab);
273
+ const document = parseDocument(args.document, 'document');
274
+ const kind = args.kind === 'preset' ? 'preset' : 'recipe';
275
+ return {
276
+ kind,
277
+ lab,
278
+ ...normalizedValidation(kind === 'preset'
279
+ ? adapter.validatePreset(document)
280
+ : adapter.validateRecipe(document)),
281
+ };
282
+ }
283
+
284
+ export const STYLE_LAB_TOOLS = Object.freeze([
285
+ Object.freeze({
286
+ annotations: { readOnlyHint: true },
287
+ description: 'List the seven generative style labs, their open domains, authoring capabilities, and npm runtime APIs.',
288
+ inputSchema: { additionalProperties: false, properties: {}, type: 'object' },
289
+ name: 'list_style_labs',
290
+ title: 'List ToonLab style labs',
291
+ }),
292
+ Object.freeze({
293
+ annotations: { destructiveHint: false, idempotentHint: true },
294
+ description: 'Create and optionally save an editable deterministic generator recipe for any style lab. Domains may be replaced or extended; this is not a fixed preset catalog.',
295
+ inputSchema: {
296
+ additionalProperties: false,
297
+ properties: {
298
+ base_preset: { type: ['string', 'null'] },
299
+ configuration: { type: 'object' },
300
+ description: { type: 'string' },
301
+ domains: { type: 'object' },
302
+ family: { type: 'string' },
303
+ id: { type: 'string' },
304
+ lab: { enum: LAB_IDS, type: 'string' },
305
+ label: { type: 'string' },
306
+ locks: { items: { type: 'string' }, type: 'array' },
307
+ name: { type: 'string' },
308
+ save: { default: true, type: 'boolean' },
309
+ seed: { type: 'integer' },
310
+ },
311
+ required: ['lab'],
312
+ type: 'object',
313
+ },
314
+ name: 'create_style_recipe',
315
+ title: 'Create a ToonLab style recipe',
316
+ }),
317
+ Object.freeze({
318
+ annotations: { destructiveHint: false, idempotentHint: true },
319
+ description: 'Resolve one to 64 deterministic runtime presets from a style recipe and optionally save the batch. Any uint32 seed can produce another variant.',
320
+ inputSchema: {
321
+ additionalProperties: false,
322
+ properties: {
323
+ count: { default: 1, maximum: 64, minimum: 1, type: 'integer' },
324
+ lab: { enum: LAB_IDS, type: 'string' },
325
+ name: { type: 'string' },
326
+ quality: {
327
+ default: 'balanced',
328
+ description: 'Applied by Post, Biome, Soundscape, and Game Feel; other lab presets have no tiered runtime budget.',
329
+ enum: QUALITY_OPTIONS,
330
+ type: 'string',
331
+ },
332
+ recipe: { type: ['object', 'string'] },
333
+ save: { default: true, type: 'boolean' },
334
+ seed: { type: 'integer' },
335
+ start_seed: { type: 'integer' },
336
+ },
337
+ required: ['lab'],
338
+ type: 'object',
339
+ },
340
+ name: 'generate_style_presets',
341
+ title: 'Generate ToonLab style presets',
342
+ }),
343
+ Object.freeze({
344
+ annotations: { readOnlyHint: true },
345
+ description: 'Validate an editable recipe or resolved runtime preset against the selected lab schema.',
346
+ inputSchema: {
347
+ additionalProperties: false,
348
+ properties: {
349
+ document: { type: ['object', 'string'] },
350
+ kind: { enum: ['recipe', 'preset'], type: 'string' },
351
+ lab: { enum: LAB_IDS, type: 'string' },
352
+ },
353
+ required: ['document', 'kind', 'lab'],
354
+ type: 'object',
355
+ },
356
+ name: 'validate_style_document',
357
+ title: 'Validate a ToonLab style document',
358
+ }),
359
+ ]);
360
+
361
+ export function isStyleLabTool(name) {
362
+ return STYLE_LAB_TOOLS.some((tool) => tool.name === name);
363
+ }
364
+
365
+ export async function callStyleLabTool(name, args, context = {}) {
366
+ if (name === 'list_style_labs') return listStyleLabs();
367
+ if (name === 'create_style_recipe') return createStyleRecipe(args, context);
368
+ if (name === 'generate_style_presets') return generateStylePresets(args, context);
369
+ if (name === 'validate_style_document') return validateStyleDocument(args);
370
+ throw new Error(`Unknown style-lab tool "${name}".`);
371
+ }
@@ -0,0 +1,174 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import {
4
+ clearBrowserStorage,
5
+ deleteBrowserStorageValue,
6
+ deleteLibraryEntry,
7
+ getLibraryState,
8
+ getWorkspaceInfo,
9
+ importBrowserStorage,
10
+ migrateLibraryEntries,
11
+ readBrowserStorage,
12
+ readWorkspaceFile,
13
+ resolveWorkspacePath,
14
+ saveLibraryEntry,
15
+ setBrowserStorageValue,
16
+ writeWorkspaceFile,
17
+ } from './workspace.mjs';
18
+
19
+ const JSON_LIMIT = 8 * 1024 * 1024;
20
+ const FILE_LIMIT = 128 * 1024 * 1024;
21
+
22
+ function readBody(request, limit) {
23
+ return new Promise((resolveBody, reject) => {
24
+ const chunks = [];
25
+ let size = 0;
26
+ request.on('data', (chunk) => {
27
+ size += chunk.length;
28
+ if (size > limit) {
29
+ reject(Object.assign(new Error('Request body is too large.'), { statusCode: 413 }));
30
+ request.destroy();
31
+ return;
32
+ }
33
+ chunks.push(chunk);
34
+ });
35
+ request.on('end', () => resolveBody(Buffer.concat(chunks)));
36
+ request.on('error', reject);
37
+ });
38
+ }
39
+
40
+ async function readJsonBody(request) {
41
+ const body = await readBody(request, JSON_LIMIT);
42
+ if (!body.length) return {};
43
+ try {
44
+ return JSON.parse(body.toString('utf8'));
45
+ } catch {
46
+ throw Object.assign(new Error('Request body must be valid JSON.'), { statusCode: 400 });
47
+ }
48
+ }
49
+
50
+ function sendJson(response, status, value) {
51
+ response.statusCode = status;
52
+ response.setHeader('content-type', 'application/json; charset=utf-8');
53
+ response.setHeader('cache-control', 'no-store');
54
+ response.end(`${JSON.stringify(value)}\n`);
55
+ }
56
+
57
+ function methodNotAllowed(response, methods) {
58
+ response.setHeader('allow', methods.join(', '));
59
+ sendJson(response, 405, { error: 'Method not allowed.' });
60
+ }
61
+
62
+ export function toonlabWorkspacePlugin({ rootDirectory = process.cwd(), workspace = '.toonlab' } = {}) {
63
+ const projectRoot = resolve(rootDirectory);
64
+ const workspacePath = resolveWorkspacePath(workspace, projectRoot);
65
+ const serverPath = join(projectRoot, 'mcp', 'server.mjs');
66
+
67
+ async function middleware(request, response, next) {
68
+ const url = new URL(request.url ?? '/', 'http://localhost');
69
+ if (!url.pathname.startsWith('/api/toonlab/')) return next();
70
+
71
+ try {
72
+ if (url.pathname === '/api/toonlab/workspace') {
73
+ if (request.method !== 'GET') return methodNotAllowed(response, ['GET']);
74
+ const info = await getWorkspaceInfo(workspacePath);
75
+ return sendJson(response, 200, {
76
+ ...info,
77
+ mcp: {
78
+ args: [serverPath, '--workspace', workspacePath],
79
+ command: process.execPath,
80
+ transport: 'stdio',
81
+ },
82
+ projectRoot,
83
+ });
84
+ }
85
+
86
+ if (url.pathname === '/api/toonlab/storage') {
87
+ if (request.method === 'GET') return sendJson(response, 200, await readBrowserStorage(workspacePath));
88
+ if (request.method === 'DELETE') return sendJson(response, 200, { entries: await clearBrowserStorage(workspacePath) });
89
+ return methodNotAllowed(response, ['GET', 'DELETE']);
90
+ }
91
+
92
+ if (url.pathname === '/api/toonlab/storage/import') {
93
+ if (request.method !== 'POST') return methodNotAllowed(response, ['POST']);
94
+ const body = await readJsonBody(request);
95
+ return sendJson(response, 200, await importBrowserStorage(workspacePath, body.entries));
96
+ }
97
+
98
+ if (url.pathname.startsWith('/api/toonlab/storage/')) {
99
+ const key = decodeURIComponent(url.pathname.slice('/api/toonlab/storage/'.length));
100
+ if (request.method === 'PUT') {
101
+ const body = await readJsonBody(request);
102
+ return sendJson(response, 200, { entries: await setBrowserStorageValue(workspacePath, key, body.value) });
103
+ }
104
+ if (request.method === 'DELETE') {
105
+ return sendJson(response, 200, { entries: await deleteBrowserStorageValue(workspacePath, key) });
106
+ }
107
+ return methodNotAllowed(response, ['PUT', 'DELETE']);
108
+ }
109
+
110
+ if (url.pathname === '/api/toonlab/library') {
111
+ if (request.method !== 'GET') return methodNotAllowed(response, ['GET']);
112
+ return sendJson(response, 200, await getLibraryState(workspacePath));
113
+ }
114
+
115
+ if (url.pathname === '/api/toonlab/library/migrate') {
116
+ if (request.method !== 'POST') return methodNotAllowed(response, ['POST']);
117
+ const body = await readJsonBody(request);
118
+ return sendJson(response, 200, await migrateLibraryEntries(workspacePath, body.entries));
119
+ }
120
+
121
+ if (url.pathname.startsWith('/api/toonlab/library/')) {
122
+ const id = decodeURIComponent(url.pathname.slice('/api/toonlab/library/'.length));
123
+ if (request.method === 'PUT') {
124
+ const entry = await readJsonBody(request);
125
+ if (entry.id !== id) throw Object.assign(new Error('Library entry id does not match the URL.'), { statusCode: 400 });
126
+ return sendJson(response, 200, { entry: await saveLibraryEntry(workspacePath, entry) });
127
+ }
128
+ if (request.method === 'DELETE') {
129
+ return sendJson(response, 200, { deleted: await deleteLibraryEntry(workspacePath, id) });
130
+ }
131
+ return methodNotAllowed(response, ['PUT', 'DELETE']);
132
+ }
133
+
134
+ if (url.pathname.startsWith('/api/toonlab/files/')) {
135
+ const relativePath = decodeURIComponent(url.pathname.slice('/api/toonlab/files/'.length));
136
+ if (request.method === 'PUT') {
137
+ const body = await readBody(request, FILE_LIMIT);
138
+ return sendJson(response, 200, { file: await writeWorkspaceFile(workspacePath, relativePath, body) });
139
+ }
140
+ if (request.method === 'GET') {
141
+ const file = await readWorkspaceFile(workspacePath, relativePath);
142
+ response.statusCode = 200;
143
+ response.setHeader('content-type', file.mimeType);
144
+ response.setHeader('content-length', String(file.data.length));
145
+ response.end(file.data);
146
+ return;
147
+ }
148
+ return methodNotAllowed(response, ['PUT', 'GET']);
149
+ }
150
+
151
+ return sendJson(response, 404, { error: 'Unknown ToonLab workspace route.' });
152
+ } catch (error) {
153
+ const status = Number(error?.statusCode) || (error?.code === 'ENOENT' ? 404 : 500);
154
+ return sendJson(response, status, { error: error?.message ?? String(error) });
155
+ }
156
+ }
157
+
158
+ return {
159
+ configurePreviewServer(server) {
160
+ server.middlewares.use(middleware);
161
+ },
162
+ configureServer(server) {
163
+ server.middlewares.use(middleware);
164
+ },
165
+ name: 'toonlab-workspace',
166
+ async transformIndexHtml() {
167
+ return [{
168
+ children: await readFile(join(projectRoot, 'labs', 'shared', 'workspace-bootstrap.js'), 'utf8'),
169
+ injectTo: 'head-prepend',
170
+ tag: 'script',
171
+ }];
172
+ },
173
+ };
174
+ }