@genart-dev/mcp-server 0.3.0 → 0.4.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.
package/dist/index.js CHANGED
@@ -251,9 +251,40 @@ var EditorState = class extends EventEmitter {
251
251
  canvasHeight: def.canvas.height,
252
252
  rendererId: def.renderer.type
253
253
  };
254
+ const sketch = {
255
+ getSymbols() {
256
+ return loaded.definition.symbols ?? {};
257
+ },
258
+ setSymbols(symbols) {
259
+ loaded.definition = { ...loaded.definition, symbols };
260
+ },
261
+ getComponents() {
262
+ return loaded.definition.components ?? {};
263
+ },
264
+ setComponents(components) {
265
+ loaded.definition = { ...loaded.definition, components };
266
+ },
267
+ getThirdParty() {
268
+ const def2 = loaded.definition;
269
+ return def2["thirdParty"] ?? [];
270
+ },
271
+ setThirdParty(notices) {
272
+ loaded.definition["thirdParty"] = notices;
273
+ },
274
+ getRenderer() {
275
+ return loaded.definition.renderer.type;
276
+ },
277
+ getGenartVersion() {
278
+ return loaded.definition.genart;
279
+ },
280
+ setGenartVersion(version) {
281
+ loaded.definition = { ...loaded.definition, genart: version };
282
+ }
283
+ };
254
284
  return {
255
285
  layers: layerStack,
256
286
  sketchState,
287
+ sketch,
257
288
  canvasWidth: def.canvas.width,
258
289
  canvasHeight: def.canvas.height,
259
290
  async resolveAsset(_assetId) {
@@ -294,6 +325,20 @@ import typographyPlugin from "@genart-dev/plugin-typography";
294
325
  import filtersPlugin from "@genart-dev/plugin-filters";
295
326
  import shapesPlugin from "@genart-dev/plugin-shapes";
296
327
  import layoutGuidesPlugin from "@genart-dev/plugin-layout-guides";
328
+ import paintingPlugin from "@genart-dev/plugin-painting";
329
+ import texturesPlugin from "@genart-dev/plugin-textures";
330
+ import animationPlugin from "@genart-dev/plugin-animation";
331
+ import colorAdjustPlugin from "@genart-dev/plugin-color-adjust";
332
+ import compositingPlugin from "@genart-dev/plugin-compositing";
333
+ import constructionPlugin from "@genart-dev/plugin-construction";
334
+ import distributionPlugin from "@genart-dev/plugin-distribution";
335
+ import figurePlugin from "@genart-dev/plugin-figure";
336
+ import layoutCompositionPlugin from "@genart-dev/plugin-layout-composition";
337
+ import perspectivePlugin from "@genart-dev/plugin-perspective";
338
+ import posesPlugin from "@genart-dev/plugin-poses";
339
+ import stylesPlugin from "@genart-dev/plugin-styles";
340
+ import symbolsPlugin from "@genart-dev/plugin-symbols";
341
+ import tracePlugin from "@genart-dev/plugin-trace";
297
342
 
298
343
  // src/tools/workspace.ts
299
344
  import { readFile as readFile2, writeFile as writeFile2, stat } from "fs/promises";
@@ -731,8 +776,8 @@ async function createSketch(state, input) {
731
776
  }
732
777
  let algorithm = input.algorithm;
733
778
  if (!algorithm) {
734
- const registry4 = createDefaultRegistry();
735
- const adapter = registry4.resolve(rendererType);
779
+ const registry5 = createDefaultRegistry();
780
+ const adapter = registry5.resolve(rendererType);
736
781
  algorithm = adapter.getAlgorithmTemplate();
737
782
  }
738
783
  let resolvedComponents;
@@ -957,8 +1002,8 @@ async function updateAlgorithm(state, input) {
957
1002
  const shouldValidate = input.validate !== false;
958
1003
  let validationPassed = true;
959
1004
  if (shouldValidate) {
960
- const registry4 = createDefaultRegistry();
961
- const adapter = registry4.resolve(def.renderer.type);
1005
+ const registry5 = createDefaultRegistry();
1006
+ const adapter = registry5.resolve(def.renderer.type);
962
1007
  const result = adapter.validate(input.algorithm);
963
1008
  if (!result.valid) {
964
1009
  throw new Error(
@@ -1081,6 +1126,12 @@ async function forkSketch(state, input) {
1081
1126
  const seed = generateNewSeed ? Math.floor(Math.random() * 1e5) : sourceDef.state.seed;
1082
1127
  const title = input.title ?? `${sourceDef.title} (fork)`;
1083
1128
  const ts = now2();
1129
+ const sourceGeneration = sourceDef.lineage?.generation ?? 1;
1130
+ const lineage = {
1131
+ parentId: input.sourceId,
1132
+ parentTitle: sourceDef.title,
1133
+ generation: sourceGeneration + 1
1134
+ };
1084
1135
  const forkedDef = {
1085
1136
  genart: "1.1",
1086
1137
  id: input.newId,
@@ -1093,6 +1144,8 @@ async function forkSketch(state, input) {
1093
1144
  colors,
1094
1145
  state: buildState(parameters, colors, seed),
1095
1146
  algorithm,
1147
+ ...sourceDef.compositionLevel ? { compositionLevel: sourceDef.compositionLevel } : {},
1148
+ lineage,
1096
1149
  ...philosophy ? { philosophy } : {},
1097
1150
  ...sourceDef.themes ? { themes: [...sourceDef.themes] } : {},
1098
1151
  ...sourceDef.skills ? { skills: [...sourceDef.skills] } : {},
@@ -2058,6 +2111,13 @@ ${s.philosophy}`);
2058
2111
  params[p.key] = p.default;
2059
2112
  }
2060
2113
  const colorPalette = colors.map((c) => c.default);
2114
+ const maxGeneration = Math.max(
2115
+ ...sources.map((s) => s.lineage?.generation ?? 1)
2116
+ );
2117
+ const lineage = {
2118
+ blendSources: input.sourceIds,
2119
+ generation: maxGeneration + 1
2120
+ };
2061
2121
  const timestamp = now5();
2062
2122
  const newDef = {
2063
2123
  genart: "1.1",
@@ -2066,6 +2126,7 @@ ${s.philosophy}`);
2066
2126
  created: timestamp,
2067
2127
  modified: timestamp,
2068
2128
  ...skills.length > 0 ? { skills } : {},
2129
+ lineage,
2069
2130
  renderer: { type: renderer, version: sources[0].renderer.version },
2070
2131
  canvas: { width: canvasWidth, height: canvasHeight },
2071
2132
  ...philosophy ? { philosophy } : {},
@@ -2292,14 +2353,25 @@ async function getGuidelines(input) {
2292
2353
  color: "color",
2293
2354
  colours: "color",
2294
2355
  layout: "composition",
2295
- palette: "color"
2356
+ palette: "color",
2357
+ painting: "painting",
2358
+ watercolor: "painting",
2359
+ ink: "illustration",
2360
+ illustration: "illustration",
2361
+ "mixed-media": "illustration",
2362
+ "mixed media": "illustration",
2363
+ process: "process",
2364
+ layering: "process",
2365
+ "mark-making": "process",
2366
+ refinement: "process",
2367
+ constraints: "process"
2296
2368
  };
2297
2369
  const category = categoryMap[topic];
2298
2370
  if (!category) {
2299
2371
  return {
2300
2372
  success: false,
2301
2373
  topic,
2302
- error: `No guidelines found for topic: '${topic}'. Available topics: composition, color, parameters, animation, performance`,
2374
+ error: `No guidelines found for topic: '${topic}'. Available topics: composition, color, painting, illustration, process, parameters, animation, performance`,
2303
2375
  guidelines: null,
2304
2376
  relatedSkills: []
2305
2377
  };
@@ -2326,6 +2398,138 @@ ${guidelines}`,
2326
2398
  }))
2327
2399
  };
2328
2400
  }
2401
+ var CONTEXT_KEYWORDS = {
2402
+ // Composition keywords
2403
+ layout: ["golden-ratio", "rule-of-thirds", "visual-weight", "gestalt-grouping"],
2404
+ balance: ["visual-weight", "golden-ratio", "rule-of-thirds"],
2405
+ grid: ["rule-of-thirds", "gestalt-grouping", "rhythm-movement"],
2406
+ flow: ["rhythm-movement", "gestalt-grouping"],
2407
+ movement: ["rhythm-movement", "mark-making"],
2408
+ rhythm: ["rhythm-movement", "mark-making"],
2409
+ focal: ["rule-of-thirds", "visual-weight", "figure-ground"],
2410
+ negative: ["figure-ground", "visual-weight"],
2411
+ space: ["figure-ground", "visual-weight", "atmospheric-depth"],
2412
+ // Color keywords
2413
+ palette: ["color-harmony", "palette-generation", "color-mixing-strategy"],
2414
+ color: ["color-harmony", "color-temperature", "itten-contrasts", "color-mixing-strategy"],
2415
+ warm: ["color-temperature", "atmospheric-depth"],
2416
+ cool: ["color-temperature", "atmospheric-depth"],
2417
+ contrast: ["simultaneous-contrast", "itten-contrasts", "value-structure"],
2418
+ value: ["value-structure", "itten-contrasts", "layering-strategy"],
2419
+ gray: ["color-mixing-strategy", "value-structure"],
2420
+ // Painting keywords
2421
+ watercolor: ["watercolor-techniques", "layering-strategy", "material-behavior"],
2422
+ ink: ["ink-illustration", "mark-making", "material-behavior"],
2423
+ oil: ["painting-foundations", "layering-strategy", "material-behavior"],
2424
+ charcoal: ["material-behavior", "mark-making"],
2425
+ brush: ["mark-making", "material-behavior"],
2426
+ layer: ["layering-strategy", "mixed-media-workflow", "iterative-refinement"],
2427
+ texture: ["material-behavior", "mark-making"],
2428
+ // Process keywords
2429
+ study: ["thumbnail-studies", "creative-constraints", "iterative-refinement"],
2430
+ thumbnail: ["thumbnail-studies", "creative-constraints"],
2431
+ refine: ["iterative-refinement", "layering-strategy"],
2432
+ iterate: ["iterative-refinement", "thumbnail-studies"],
2433
+ depth: ["atmospheric-depth", "color-temperature", "value-structure"],
2434
+ atmosphere: ["atmospheric-depth", "color-temperature"],
2435
+ perspective: ["atmospheric-depth"],
2436
+ constraint: ["creative-constraints"],
2437
+ limit: ["creative-constraints", "color-mixing-strategy"],
2438
+ hatch: ["mark-making", "ink-illustration"],
2439
+ stipple: ["mark-making"],
2440
+ gestural: ["mark-making", "iterative-refinement"],
2441
+ mix: ["color-mixing-strategy", "mixed-media-workflow"],
2442
+ glaze: ["layering-strategy", "material-behavior"]
2443
+ };
2444
+ async function suggestSkills(state, input) {
2445
+ const allSkills = registry.list();
2446
+ const scored = /* @__PURE__ */ new Map();
2447
+ for (const skill of allSkills) {
2448
+ scored.set(skill.id, { score: 0, reasons: [] });
2449
+ }
2450
+ if (input.sketchId) {
2451
+ const loaded = state.getSketch(input.sketchId);
2452
+ if (loaded) {
2453
+ const sketch = loaded.definition;
2454
+ const usedSkills = new Set(sketch.skills ?? []);
2455
+ for (const skill of allSkills) {
2456
+ if (!usedSkills.has(skill.id)) {
2457
+ const entry = scored.get(skill.id);
2458
+ entry.score += 1;
2459
+ entry.reasons.push("not yet used in this sketch");
2460
+ }
2461
+ }
2462
+ const level = sketch.compositionLevel;
2463
+ if (level) {
2464
+ const levelSkills = {
2465
+ study: ["thumbnail-studies", "creative-constraints", "iterative-refinement"],
2466
+ sketch: ["iterative-refinement", "mark-making", "layering-strategy", "color-mixing-strategy"],
2467
+ developed: ["layering-strategy", "material-behavior", "atmospheric-depth", "color-mixing-strategy"],
2468
+ exhibition: ["layering-strategy", "material-behavior", "atmospheric-depth", "iterative-refinement", "mark-making"]
2469
+ };
2470
+ for (const id of levelSkills[level] ?? []) {
2471
+ const entry = scored.get(id);
2472
+ if (entry) {
2473
+ entry.score += 3;
2474
+ entry.reasons.push(`recommended for ${level}-level work`);
2475
+ }
2476
+ }
2477
+ }
2478
+ if (sketch.layers && sketch.layers.length > 0) {
2479
+ const layerTypes = sketch.layers.map((l) => l.type);
2480
+ if (layerTypes.some((t) => t.startsWith("painting:"))) {
2481
+ for (const id of ["layering-strategy", "material-behavior", "iterative-refinement"]) {
2482
+ const entry = scored.get(id);
2483
+ if (entry) {
2484
+ entry.score += 2;
2485
+ entry.reasons.push("sketch uses painting layers");
2486
+ }
2487
+ }
2488
+ }
2489
+ }
2490
+ }
2491
+ }
2492
+ if (input.context) {
2493
+ const words = input.context.toLowerCase().split(/\W+/);
2494
+ for (const word of words) {
2495
+ const matched = CONTEXT_KEYWORDS[word];
2496
+ if (matched) {
2497
+ for (const skillId of matched) {
2498
+ const entry = scored.get(skillId);
2499
+ if (entry) {
2500
+ entry.score += 2;
2501
+ if (!entry.reasons.includes(`matches context keyword "${word}"`)) {
2502
+ entry.reasons.push(`matches context keyword "${word}"`);
2503
+ }
2504
+ }
2505
+ }
2506
+ }
2507
+ }
2508
+ }
2509
+ if (!input.sketchId && !input.context) {
2510
+ for (const skill of allSkills) {
2511
+ if (skill.category === "process") {
2512
+ const entry = scored.get(skill.id);
2513
+ entry.score += 2;
2514
+ entry.reasons.push("process knowledge is broadly applicable");
2515
+ }
2516
+ }
2517
+ }
2518
+ const ranked = allSkills.map((skill) => ({
2519
+ id: skill.id,
2520
+ name: skill.name,
2521
+ category: skill.category,
2522
+ complexity: skill.complexity,
2523
+ description: skill.description,
2524
+ relevanceScore: scored.get(skill.id).score,
2525
+ rationale: scored.get(skill.id).reasons
2526
+ })).filter((s) => s.relevanceScore > 0).sort((a, b) => b.relevanceScore - a.relevanceScore).slice(0, 5);
2527
+ return {
2528
+ success: true,
2529
+ suggestions: ranked,
2530
+ total: ranked.length
2531
+ };
2532
+ }
2329
2533
 
2330
2534
  // src/tools/components.ts
2331
2535
  import { writeFile as writeFile5 } from "fs/promises";
@@ -2585,7 +2789,7 @@ async function captureHtml(options) {
2585
2789
  try {
2586
2790
  await page.setViewport({ width, height, deviceScaleFactor: 1 });
2587
2791
  await page.setContent(html, { waitUntil: "domcontentloaded", timeout: 3e4 });
2588
- await new Promise((resolve3) => setTimeout(resolve3, waitMs));
2792
+ await new Promise((resolve5) => setTimeout(resolve5, waitMs));
2589
2793
  const buffer = await page.screenshot({
2590
2794
  type: imageType,
2591
2795
  clip: { x: 0, y: 0, width, height },
@@ -2605,7 +2809,7 @@ async function captureHtmlMulti(options) {
2605
2809
  try {
2606
2810
  await page.setViewport({ width, height, deviceScaleFactor: 1 });
2607
2811
  await page.setContent(html, { waitUntil: "domcontentloaded", timeout: 3e4 });
2608
- await new Promise((resolve3) => setTimeout(resolve3, waitMs));
2812
+ await new Promise((resolve5) => setTimeout(resolve5, waitMs));
2609
2813
  const pngBuffer = await page.screenshot({
2610
2814
  type: "png",
2611
2815
  clip: { x: 0, y: 0, width, height }
@@ -2615,7 +2819,7 @@ async function captureHtmlMulti(options) {
2615
2819
  const inlineWidth = Math.round(width * scale);
2616
2820
  const inlineHeight = Math.round(height * scale);
2617
2821
  await page.setViewport({ width: inlineWidth, height: inlineHeight, deviceScaleFactor: 1 });
2618
- await new Promise((resolve3) => setTimeout(resolve3, 100));
2822
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
2619
2823
  const jpegBuffer = await page.screenshot({
2620
2824
  type: "jpeg",
2621
2825
  quality: jpegQuality,
@@ -2776,206 +2980,1271 @@ async function captureBatch(state, input) {
2776
2980
  };
2777
2981
  }
2778
2982
 
2779
- // src/tools/export.ts
2780
- import { createWriteStream } from "fs";
2781
- import { stat as stat4, writeFile as writeFile7 } from "fs/promises";
2782
- import { dirname as dirname6 } from "path";
2783
- import archiver from "archiver";
2784
- import {
2785
- createDefaultRegistry as createDefaultRegistry3,
2786
- serializeGenart as serializeGenart5
2787
- } from "@genart-dev/core";
2788
- var registry3 = createDefaultRegistry3();
2789
- async function validateOutputPath(outputPath) {
2790
- const parentDir = dirname6(outputPath);
2791
- try {
2792
- const s = await stat4(parentDir);
2793
- if (!s.isDirectory()) {
2794
- throw new Error(`Parent directory does not exist: ${parentDir}`);
2795
- }
2796
- } catch (e) {
2797
- if (e instanceof Error && e.message.startsWith("Parent directory")) throw e;
2798
- throw new Error(`Parent directory does not exist: ${parentDir}`);
2799
- }
2800
- try {
2801
- await stat4(outputPath);
2802
- throw new Error(
2803
- `File already exists at ${outputPath}. Delete it first or use a different path.`
2804
- );
2805
- } catch (e) {
2806
- if (e instanceof Error && e.message.startsWith("File already exists")) throw e;
2983
+ // src/tools/critique.ts
2984
+ import { createDefaultSkillRegistry as createDefaultSkillRegistry2 } from "@genart-dev/core";
2985
+ var registry3 = createDefaultSkillRegistry2();
2986
+ var ALL_ASPECTS = [
2987
+ "composition",
2988
+ "color",
2989
+ "rhythm",
2990
+ "unity",
2991
+ "expression"
2992
+ ];
2993
+ var SEVERITY = {
2994
+ study: {
2995
+ level: "study",
2996
+ description: "Fast, exploratory \u2014 value the energy of discovery over polish",
2997
+ focus: "Is the core idea visible? Does the sketch capture a single insight?",
2998
+ tolerance: "High tolerance for roughness, imbalance, and incomplete resolution. Studies should feel alive, not finished."
2999
+ },
3000
+ sketch: {
3001
+ level: "sketch",
3002
+ description: "Intentional but rough \u2014 the idea should read clearly",
3003
+ focus: "Do composition and color serve the concept? Are parameters well-chosen?",
3004
+ tolerance: "Moderate tolerance. Unresolved edges and raw marks are fine, but the structure should be deliberate."
3005
+ },
3006
+ developed: {
3007
+ level: "developed",
3008
+ description: "Refined \u2014 every major decision should be justified",
3009
+ focus: "Do all elements work together? Is there a clear visual hierarchy? Does the palette feel cohesive?",
3010
+ tolerance: "Low tolerance for accidental imbalance. Rough areas should be intentional, not neglected."
3011
+ },
3012
+ exhibition: {
3013
+ level: "exhibition",
3014
+ description: "Polished \u2014 every element earns its place",
3015
+ focus: "Could you defend every choice? Does the piece hold up under sustained viewing? Is the concept fully realized?",
3016
+ tolerance: "Minimal tolerance. Each mark, color, and spatial relationship should feel inevitable."
2807
3017
  }
3018
+ };
3019
+ function buildCompositionFramework() {
3020
+ return {
3021
+ aspect: "composition",
3022
+ questions: [
3023
+ "Where does the eye land first? Is that the intended focal point?",
3024
+ "Is there a clear visual hierarchy (primary, secondary, tertiary)?",
3025
+ "How does the composition use the edges and corners of the canvas?",
3026
+ "Is negative space working actively or is it leftover?",
3027
+ "Does the arrangement feel balanced or intentionally unbalanced?"
3028
+ ],
3029
+ principles: [
3030
+ "Visual weight distribution \u2014 dense, dark, saturated, or detailed areas carry more weight",
3031
+ "Entry points and eye paths \u2014 the viewer needs a way in and a journey through the piece",
3032
+ "Edge tension \u2014 elements near canvas edges create tension; use this deliberately",
3033
+ "Rule of thirds / golden ratio \u2014 useful starting points, not rigid rules",
3034
+ "Figure-ground clarity \u2014 the relationship between positive and negative space"
3035
+ ],
3036
+ pitfalls: [
3037
+ "Centering everything \u2014 creates static compositions unless intentionally symmetrical",
3038
+ "Filling the canvas uniformly \u2014 denies the viewer rest areas and focal emphasis",
3039
+ "Tangent lines \u2014 elements barely touching edges or each other create visual discomfort",
3040
+ "Competing focal points \u2014 multiple areas of equal emphasis confuse the eye",
3041
+ "Ignoring the canvas aspect ratio \u2014 composition should respond to the format"
3042
+ ]
3043
+ };
2808
3044
  }
2809
- function algorithmExtension(rendererType) {
2810
- return rendererType === "glsl" ? ".glsl" : ".js";
2811
- }
2812
- function applyOverrides2(sketch, overrides) {
2813
- if (overrides.seed === void 0 && overrides.params === void 0) {
2814
- return sketch;
2815
- }
2816
- const newState = {
2817
- seed: overrides.seed ?? sketch.state.seed,
2818
- params: overrides.params ? { ...sketch.state.params, ...overrides.params } : sketch.state.params,
2819
- colorPalette: sketch.state.colorPalette
3045
+ function buildColorFramework() {
3046
+ return {
3047
+ aspect: "color",
3048
+ questions: [
3049
+ "Does the palette feel intentional or arbitrary?",
3050
+ "Is there a dominant color temperature (warm/cool) or a deliberate tension between them?",
3051
+ "How many distinct hues are active? Is that number serving the concept?",
3052
+ "Are value contrasts (light/dark) creating readable structure?",
3053
+ "Do any colors feel out of place \u2014 or is dissonance intentional?"
3054
+ ],
3055
+ principles: [
3056
+ "Color harmony \u2014 analogous, complementary, triadic, or split-complementary relationships",
3057
+ "Value structure \u2014 squint at the piece; the composition should read in grayscale",
3058
+ "Temperature as depth \u2014 warm advances, cool recedes (atmospheric perspective)",
3059
+ "Saturation as emphasis \u2014 high saturation draws the eye; use it sparingly for focus",
3060
+ "Color proportion \u2014 unequal amounts create interest (e.g., 60-30-10 ratio)"
3061
+ ],
3062
+ pitfalls: [
3063
+ "Too many fully saturated colors competing for attention",
3064
+ "No value range \u2014 all mid-tones flatten the piece",
3065
+ "Random color assignment \u2014 palette should derive from concept, not just randomness",
3066
+ "Ignoring simultaneous contrast \u2014 adjacent colors alter each other's appearance",
3067
+ "Uniform opacity everywhere \u2014 varying transparency adds depth and atmosphere"
3068
+ ]
2820
3069
  };
2821
- return { ...sketch, state: newState };
2822
3070
  }
2823
- async function exportSketch(state, input) {
2824
- state.requireWorkspace();
2825
- const loaded = state.requireSketch(input.sketchId);
2826
- const sketch = applyOverrides2(loaded.definition, {
2827
- seed: input.seed,
2828
- params: input.params
2829
- });
2830
- await validateOutputPath(input.outputPath);
2831
- const adapter = registry3.resolve(sketch.renderer.type);
2832
- if (!adapter) {
2833
- throw new Error(
2834
- `Unsupported renderer type: '${sketch.renderer.type}'`
2835
- );
2836
- }
2837
- switch (input.format) {
2838
- case "html":
2839
- return await exportHtml(sketch, input.outputPath);
2840
- case "png":
2841
- return await exportPng(sketch, input);
2842
- case "svg":
2843
- return await exportSvg(sketch, input);
2844
- case "algorithm":
2845
- return await exportAlgorithm(sketch, input.outputPath);
2846
- case "zip":
2847
- return await exportZip(sketch, input);
2848
- default:
2849
- throw new Error(`Unsupported export format: '${input.format}'`);
2850
- }
3071
+ function buildRhythmFramework() {
3072
+ return {
3073
+ aspect: "rhythm",
3074
+ questions: [
3075
+ "Is there a repeating visual motif or interval?",
3076
+ "Does the rhythm accelerate, decelerate, or remain steady?",
3077
+ "Are there moments of syncopation \u2014 unexpected breaks in the pattern?",
3078
+ "Does the rhythm contribute to or fight against the composition?",
3079
+ "Is there scale variation \u2014 does the motif appear at multiple sizes?"
3080
+ ],
3081
+ principles: [
3082
+ "Regular rhythm creates calm and order; irregular rhythm creates energy",
3083
+ "Progressive rhythm (gradual change) creates movement and depth",
3084
+ "Alternating rhythm adds complexity without chaos",
3085
+ "Rhythm at multiple scales (fractal repetition) creates richness",
3086
+ "Silence (empty intervals) is as important as sound (marked intervals)"
3087
+ ],
3088
+ pitfalls: [
3089
+ "Perfectly regular grids without variation feel mechanical, not generative",
3090
+ "Random distribution reads as noise, not rhythm",
3091
+ "Single-scale repetition feels monotonous \u2014 vary size, spacing, or density",
3092
+ "Rhythm that ignores the composition's focal structure",
3093
+ "Over-complexity \u2014 too many overlapping rhythms create visual noise"
3094
+ ]
3095
+ };
2851
3096
  }
2852
- async function exportHtml(sketch, outputPath) {
2853
- const adapter = registry3.resolve(sketch.renderer.type);
2854
- const html = adapter.generateStandaloneHTML(sketch);
2855
- const content = Buffer.from(html, "utf-8");
2856
- await writeFile7(outputPath, content);
3097
+ function buildUnityFramework() {
2857
3098
  return {
2858
- success: true,
2859
- sketchId: sketch.id,
2860
- format: "html",
2861
- outputPath,
2862
- fileSize: content.byteLength,
2863
- renderer: sketch.renderer.type
3099
+ aspect: "unity",
3100
+ questions: [
3101
+ "Does the piece feel like one cohesive work or disconnected parts?",
3102
+ "Is there a unifying visual language (consistent mark quality, shape vocabulary)?",
3103
+ "Do the parameters work together or do some feel bolted on?",
3104
+ "Would removing any element weaken the whole?",
3105
+ "Does the algorithm express a single clear idea?"
3106
+ ],
3107
+ principles: [
3108
+ "Unity through repetition \u2014 shared elements tie the composition together",
3109
+ "Unity through proximity \u2014 grouped elements feel related",
3110
+ "Unity through continuation \u2014 aligned elements create visual connections",
3111
+ "Variety within unity \u2014 enough variation to hold interest, enough consistency to cohere",
3112
+ "Conceptual unity \u2014 all visual decisions serve the stated philosophy"
3113
+ ],
3114
+ pitfalls: [
3115
+ "Feature accumulation \u2014 adding elements that don't serve the core concept",
3116
+ "Inconsistent mark quality \u2014 mixing precise geometry with organic marks without intention",
3117
+ "Disconnected color and form \u2014 palette that doesn't relate to the spatial structure",
3118
+ "Parameter sprawl \u2014 too many controls that don't interact meaningfully",
3119
+ "Style mixing without integration \u2014 combining techniques that don't speak to each other"
3120
+ ]
2864
3121
  };
2865
3122
  }
2866
- async function exportPng(sketch, input) {
2867
- const adapter = registry3.resolve(sketch.renderer.type);
2868
- const html = adapter.generateStandaloneHTML(sketch);
2869
- const width = input.width ?? sketch.canvas.width;
2870
- const height = input.height ?? sketch.canvas.height;
2871
- const result = await captureHtml({ html, width, height });
2872
- await writeFile7(input.outputPath, result.bytes);
3123
+ function buildExpressionFramework() {
2873
3124
  return {
2874
- success: true,
2875
- sketchId: sketch.id,
2876
- format: "png",
2877
- outputPath: input.outputPath,
2878
- fileSize: result.bytes.byteLength,
2879
- renderer: sketch.renderer.type
3125
+ aspect: "expression",
3126
+ questions: [
3127
+ "What mood or feeling does this piece evoke?",
3128
+ "Is the generative process visible in the output? Should it be?",
3129
+ "Does the algorithm's logic contribute to the emotional quality?",
3130
+ "Is there a sense of the unexpected \u2014 does the piece surprise even its creator?",
3131
+ "Does the philosophy statement match the visual experience?"
3132
+ ],
3133
+ principles: [
3134
+ "Generative art is a conversation between intention and emergence",
3135
+ "The algorithm is a medium \u2014 its constraints and affordances shape expression",
3136
+ "Controlled randomness creates life; pure randomness creates noise",
3137
+ "The seed is a collaborator \u2014 different seeds should produce meaningfully different moods",
3138
+ "Process and result are both the artwork \u2014 the code embodies artistic decisions"
3139
+ ],
3140
+ pitfalls: [
3141
+ "Over-control \u2014 leaving no room for generative surprise",
3142
+ "Under-control \u2014 no discernible artistic intention behind the randomness",
3143
+ "Technique as end \u2014 impressive code that produces emotionally flat output",
3144
+ "Derivative work \u2014 reproducing established generative art tropes without adding perspective",
3145
+ "Mismatched intent \u2014 the philosophy says one thing but the visual says another"
3146
+ ]
2880
3147
  };
2881
3148
  }
2882
- async function exportSvg(sketch, input) {
2883
- const width = input.width ?? sketch.canvas.width;
2884
- const height = input.height ?? sketch.canvas.height;
2885
- if (sketch.renderer.type === "svg") {
2886
- const content2 = Buffer.from(sketch.algorithm, "utf-8");
2887
- await writeFile7(input.outputPath, content2);
2888
- return {
2889
- success: true,
2890
- sketchId: sketch.id,
2891
- format: "svg",
2892
- outputPath: input.outputPath,
2893
- fileSize: content2.byteLength,
2894
- renderer: sketch.renderer.type,
2895
- notice: null
2896
- };
3149
+ var ASPECT_BUILDERS = {
3150
+ composition: buildCompositionFramework,
3151
+ color: buildColorFramework,
3152
+ rhythm: buildRhythmFramework,
3153
+ unity: buildUnityFramework,
3154
+ expression: buildExpressionFramework
3155
+ };
3156
+ async function critiqueSketch(state, input) {
3157
+ state.requireWorkspace();
3158
+ let sketchId;
3159
+ if (input.sketchId) {
3160
+ sketchId = input.sketchId;
3161
+ } else if (state.selection.size > 0) {
3162
+ sketchId = [...state.selection][0];
3163
+ } else {
3164
+ throw new Error("No sketch specified and nothing selected");
2897
3165
  }
2898
- const adapter = registry3.resolve(sketch.renderer.type);
2899
- const html = adapter.generateStandaloneHTML(sketch);
2900
- const result = await captureHtml({ html, width, height });
2901
- const b64 = Buffer.from(result.bytes).toString("base64");
2902
- const svg = `<?xml version="1.0" encoding="UTF-8"?>
2903
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
2904
- width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
2905
- <image width="${width}" height="${height}"
2906
- href="data:image/png;base64,${b64}"/>
2907
- </svg>`;
2908
- const content = Buffer.from(svg, "utf-8");
2909
- await writeFile7(input.outputPath, content);
2910
- return {
3166
+ const loaded = state.requireSketch(sketchId);
3167
+ const sketch = loaded.definition;
3168
+ const capture = await captureScreenshot(state, {
3169
+ target: "sketch",
3170
+ sketchId,
3171
+ previewSize: input.previewSize ?? 400
3172
+ });
3173
+ const aspects = input.aspects ?? [...ALL_ASPECTS];
3174
+ const frameworks = aspects.map((a) => ASPECT_BUILDERS[a]());
3175
+ const level = sketch.compositionLevel ?? "sketch";
3176
+ const severity = SEVERITY[level] ?? SEVERITY["sketch"];
3177
+ const relevantSkills = gatherRelevantSkills(aspects);
3178
+ const metadata = {
2911
3179
  success: true,
2912
- sketchId: sketch.id,
2913
- format: "svg",
2914
- outputPath: input.outputPath,
2915
- fileSize: content.byteLength,
2916
- renderer: sketch.renderer.type,
2917
- notice: "Non-SVG renderer \u2014 rasterized PNG embedded in SVG container"
3180
+ sketchId,
3181
+ title: sketch.title,
3182
+ compositionLevel: level,
3183
+ philosophy: sketch.philosophy ?? null,
3184
+ severity: {
3185
+ level: severity.level,
3186
+ description: severity.description,
3187
+ focus: severity.focus,
3188
+ tolerance: severity.tolerance
3189
+ },
3190
+ frameworks,
3191
+ relevantSkills,
3192
+ instructions: [
3193
+ "Use the image above and the frameworks below to perform a structured self-critique.",
3194
+ `Calibrate your critique to the ${severity.level} level: ${severity.description}`,
3195
+ "For each aspect, answer the questions, check the principles, and watch for the pitfalls.",
3196
+ "Be honest but constructive \u2014 identify what works as well as what could improve.",
3197
+ "End with 2-3 specific, actionable improvements ranked by impact."
3198
+ ]
2918
3199
  };
2919
- }
2920
- async function exportAlgorithm(sketch, outputPath) {
2921
- const content = Buffer.from(sketch.algorithm, "utf-8");
2922
- await writeFile7(outputPath, content);
2923
3200
  return {
2924
- success: true,
2925
- sketchId: sketch.id,
2926
- format: "algorithm",
2927
- outputPath,
2928
- fileSize: content.byteLength,
2929
- renderer: sketch.renderer.type
3201
+ metadata,
3202
+ previewJpegBase64: capture.previewJpegBase64
2930
3203
  };
2931
3204
  }
2932
- async function exportZip(sketch, input) {
2933
- const adapter = registry3.resolve(sketch.renderer.type);
2934
- const width = input.width ?? sketch.canvas.width;
2935
- const height = input.height ?? sketch.canvas.height;
2936
- const html = adapter.generateStandaloneHTML(sketch);
2937
- const genartJson = serializeGenart5(sketch);
2938
- const algorithm = sketch.algorithm;
2939
- const algExt = algorithmExtension(sketch.renderer.type);
2940
- const captureResult = await captureHtml({ html, width, height });
2941
- const output = createWriteStream(input.outputPath);
2942
- const archive = archiver("zip", { zlib: { level: 9 } });
2943
- const finished = new Promise((resolve3, reject) => {
2944
- output.on("close", resolve3);
2945
- archive.on("error", reject);
3205
+ async function compareSketches(state, input) {
3206
+ state.requireWorkspace();
3207
+ const ids = input.sketchIds;
3208
+ if (ids.length < 2) {
3209
+ throw new Error("compare_sketches requires at least 2 sketch IDs");
3210
+ }
3211
+ if (ids.length > 4) {
3212
+ throw new Error("compare_sketches supports a maximum of 4 sketches");
3213
+ }
3214
+ const sketchInfos = ids.map((id) => {
3215
+ const loaded = state.requireSketch(id);
3216
+ return {
3217
+ id,
3218
+ title: loaded.definition.title,
3219
+ compositionLevel: loaded.definition.compositionLevel ?? "sketch",
3220
+ philosophy: loaded.definition.philosophy ?? null,
3221
+ renderer: loaded.definition.renderer.type,
3222
+ seed: loaded.definition.state.seed
3223
+ };
2946
3224
  });
2947
- archive.pipe(output);
2948
- archive.append(html, { name: `${sketch.id}.html` });
2949
- archive.append(Buffer.from(captureResult.bytes), { name: `${sketch.id}.png` });
2950
- archive.append(algorithm, { name: `${sketch.id}${algExt}` });
2951
- archive.append(genartJson, { name: `${sketch.id}.genart` });
2952
- await archive.finalize();
2953
- await finished;
2954
- const s = await stat4(input.outputPath);
2955
- return {
3225
+ const batchResult = await captureBatch(state, {
3226
+ sketchIds: ids,
3227
+ previewSize: input.previewSize ?? 300
3228
+ });
3229
+ const previews = batchResult.items.map((item) => ({
3230
+ sketchId: item.metadata["sketchId"],
3231
+ inlineJpegBase64: item.inlineJpegBase64
3232
+ }));
3233
+ const aspects = input.aspects ?? [...ALL_ASPECTS];
3234
+ const frameworks = aspects.map((a) => ASPECT_BUILDERS[a]());
3235
+ const comparisonQuestions = aspects.map((aspect) => ({
3236
+ aspect,
3237
+ questions: buildComparisonQuestions(aspect, sketchInfos.length)
3238
+ }));
3239
+ const metadata = {
2956
3240
  success: true,
2957
- sketchId: sketch.id,
2958
- format: "zip",
2959
- outputPath: input.outputPath,
2960
- fileSize: s.size,
2961
- renderer: sketch.renderer.type,
2962
- contents: [
2963
- `${sketch.id}.html`,
2964
- `${sketch.id}.png`,
2965
- `${sketch.id}${algExt}`,
2966
- `${sketch.id}.genart`
3241
+ sketches: sketchInfos,
3242
+ aspects,
3243
+ frameworks,
3244
+ comparisonQuestions,
3245
+ instructions: [
3246
+ `Compare the ${ids.length} sketches shown above across the specified aspects.`,
3247
+ "For each aspect, use the framework questions and comparison questions to analyze differences.",
3248
+ "Identify which sketch handles each aspect most effectively and why.",
3249
+ "Note where sketches complement each other \u2014 techniques from one could improve another.",
3250
+ "End with a ranking per aspect and overall, with specific observations justifying each placement."
3251
+ ]
3252
+ };
3253
+ return { metadata, previews };
3254
+ }
3255
+ function buildComparisonQuestions(aspect, count) {
3256
+ const base = {
3257
+ composition: [
3258
+ "Which sketch has the strongest focal point?",
3259
+ "How do the compositions differ in their use of space?",
3260
+ "Which creates the most effective visual hierarchy?"
3261
+ ],
3262
+ color: [
3263
+ "Which palette feels most intentional?",
3264
+ "How do the value ranges compare \u2014 which has the strongest lights and darks?",
3265
+ "Which color temperature creates the most effective mood?"
3266
+ ],
3267
+ rhythm: [
3268
+ "Which sketch has the most engaging visual rhythm?",
3269
+ "How do the rhythmic structures differ \u2014 regular vs progressive vs irregular?",
3270
+ "Which achieves the best balance of repetition and variation?"
3271
+ ],
3272
+ unity: [
3273
+ "Which sketch feels most cohesive as a single work?",
3274
+ "Where does unity break down in each \u2014 what elements feel disconnected?",
3275
+ "Which has the tightest relationship between concept and execution?"
3276
+ ],
3277
+ expression: [
3278
+ "Which sketch evokes the strongest emotional response?",
3279
+ "How does each sketch's generative process contribute to its expression?",
3280
+ "Which most successfully balances intention with emergence?"
2967
3281
  ]
2968
3282
  };
3283
+ const questions = [...base[aspect]];
3284
+ if (count > 2) {
3285
+ questions.push(
3286
+ `Could elements from different sketches be combined to create something stronger?`
3287
+ );
3288
+ }
3289
+ return questions;
3290
+ }
3291
+ function gatherRelevantSkills(aspects) {
3292
+ const aspectToCategory = {
3293
+ composition: ["composition"],
3294
+ color: ["color"],
3295
+ rhythm: ["composition"],
3296
+ unity: ["composition", "color"],
3297
+ expression: ["process"]
3298
+ };
3299
+ const seen = /* @__PURE__ */ new Set();
3300
+ const result = [];
3301
+ for (const aspect of aspects) {
3302
+ const categories = aspectToCategory[aspect];
3303
+ for (const cat of categories) {
3304
+ const skills = registry3.list(cat);
3305
+ for (const skill of skills) {
3306
+ if (!seen.has(skill.id)) {
3307
+ seen.add(skill.id);
3308
+ result.push({ id: skill.id, name: skill.name, relevantTo: aspect });
3309
+ }
3310
+ }
3311
+ }
3312
+ }
3313
+ return result;
2969
3314
  }
2970
3315
 
2971
- // src/tools/design.ts
2972
- function requireSketchId(state, args) {
2973
- return args.sketchId ?? state.requireSelectedSketchId();
3316
+ // src/tools/series.ts
3317
+ import { writeFile as writeFile7 } from "fs/promises";
3318
+ import { basename as basename8, dirname as dirname6, resolve as resolve3 } from "path";
3319
+ import {
3320
+ serializeGenart as serializeGenart5,
3321
+ serializeWorkspace as serializeWorkspace4
3322
+ } from "@genart-dev/core";
3323
+ function now6() {
3324
+ return (/* @__PURE__ */ new Date()).toISOString();
2974
3325
  }
2975
- var BLEND_MODES = [
2976
- "normal",
2977
- "multiply",
2978
- "screen",
3326
+ var KEBAB_RE2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3327
+ function validateKebabId2(id) {
3328
+ if (!KEBAB_RE2.test(id)) {
3329
+ throw new Error(
3330
+ "ID must be kebab-case: lowercase letters, numbers, hyphens"
3331
+ );
3332
+ }
3333
+ }
3334
+ var VALID_STAGES = [
3335
+ "studies",
3336
+ "drafts",
3337
+ "refinements",
3338
+ "finals"
3339
+ ];
3340
+ var STAGE_TO_LEVEL = {
3341
+ studies: "study",
3342
+ drafts: "sketch",
3343
+ refinements: "developed",
3344
+ finals: "exhibition"
3345
+ };
3346
+ var LEVEL_SCALE = {
3347
+ study: 1,
3348
+ sketch: 1,
3349
+ developed: 1.5,
3350
+ exhibition: 2
3351
+ };
3352
+ async function createSeries(state, input) {
3353
+ const ws = state.requireWorkspace();
3354
+ const id = input.label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
3355
+ if (!id) {
3356
+ throw new Error("Could not derive a valid ID from the label");
3357
+ }
3358
+ if (ws.series?.some((s) => s.id === id)) {
3359
+ throw new Error(`Series with ID '${id}' already exists in workspace`);
3360
+ }
3361
+ const stages = input.stages ?? [...VALID_STAGES];
3362
+ for (const stage of stages) {
3363
+ if (!VALID_STAGES.includes(stage)) {
3364
+ throw new Error(
3365
+ `Invalid stage: '${stage}'. Valid stages: ${VALID_STAGES.join(", ")}`
3366
+ );
3367
+ }
3368
+ }
3369
+ const sketchFiles = input.sketchFiles ?? [];
3370
+ for (const file of sketchFiles) {
3371
+ const found = ws.sketches.some((s) => s.file === file);
3372
+ if (!found) {
3373
+ throw new Error(
3374
+ `Sketch file '${file}' not found in workspace`
3375
+ );
3376
+ }
3377
+ }
3378
+ const series = {
3379
+ id,
3380
+ label: input.label,
3381
+ narrative: input.narrative,
3382
+ intent: input.intent,
3383
+ ...input.progression ? { progression: input.progression } : {},
3384
+ stages,
3385
+ sketchFiles
3386
+ };
3387
+ state.workspace = {
3388
+ ...ws,
3389
+ modified: now6(),
3390
+ series: [...ws.series ?? [], series]
3391
+ };
3392
+ const workspaceJson = serializeWorkspace4(state.workspace);
3393
+ if (!state.remoteMode) {
3394
+ await writeFile7(state.workspacePath, workspaceJson, "utf-8");
3395
+ }
3396
+ state.emitMutation("workspace:updated", { seriesAdded: id });
3397
+ return {
3398
+ success: true,
3399
+ series: {
3400
+ id,
3401
+ label: input.label,
3402
+ narrative: input.narrative,
3403
+ intent: input.intent,
3404
+ stages,
3405
+ sketchCount: sketchFiles.length
3406
+ },
3407
+ workspaceContent: workspaceJson
3408
+ };
3409
+ }
3410
+ async function developConcept(_state, input) {
3411
+ const medium = input.medium ?? "p5";
3412
+ return {
3413
+ success: true,
3414
+ conceptPlan: {
3415
+ concept: input.concept,
3416
+ medium,
3417
+ mood: {
3418
+ instruction: "Define the emotional quality this concept should evoke.",
3419
+ prompts: [
3420
+ "What feeling should the viewer experience?",
3421
+ "Is this contemplative, energetic, unsettling, serene?",
3422
+ "What time of day, season, or environment does this concept suggest?"
3423
+ ]
3424
+ },
3425
+ palette: {
3426
+ instruction: "Design a color strategy that serves the mood.",
3427
+ prompts: [
3428
+ "What color temperature dominates (warm/cool)?",
3429
+ "How many distinct hues are needed?",
3430
+ "Should saturation be high (bold, graphic) or low (subtle, atmospheric)?",
3431
+ "What value range (light-to-dark contrast) supports the concept?"
3432
+ ]
3433
+ },
3434
+ composition: {
3435
+ instruction: "Plan the spatial structure.",
3436
+ prompts: [
3437
+ "Where should the viewer's eye land first?",
3438
+ "Is the composition centered, asymmetric, or edge-driven?",
3439
+ "How does negative space contribute to the concept?",
3440
+ "What rhythm (regular, progressive, chaotic) serves the idea?"
3441
+ ]
3442
+ },
3443
+ skills: {
3444
+ instruction: "Identify design skills to load for this concept.",
3445
+ prompts: [
3446
+ "Which composition skill applies (rule-of-thirds, golden-ratio, gestalt)?",
3447
+ "Which color skill applies (color-harmony, color-temperature, simultaneous-contrast)?",
3448
+ "Are there process skills needed (layering-strategy, iterative-refinement, thumbnail-studies)?",
3449
+ "Consider using `suggest_skills` with the concept as context."
3450
+ ]
3451
+ },
3452
+ seriesStructure: {
3453
+ instruction: "Plan the body of work.",
3454
+ prompts: [
3455
+ "How many studies should explore the core idea (3-6 recommended)?",
3456
+ "What aspect varies between studies (color, density, rhythm, scale)?",
3457
+ "Which studies should be developed further into drafts?",
3458
+ "What progression tells the most compelling story?"
3459
+ ],
3460
+ recommendedStages: ["studies", "drafts", "refinements", "finals"]
3461
+ }
3462
+ },
3463
+ nextSteps: [
3464
+ "1. Use `create_series` with a label, narrative, and intent derived from this plan.",
3465
+ "2. Create 3-6 study-level sketches using `create_sketch` with compositionLevel: 'study'.",
3466
+ "3. Use `critique_sketch` on each study to evaluate against the concept.",
3467
+ "4. Use `promote_sketch` to advance the best studies to drafts.",
3468
+ "5. Iterate: critique \u2192 refine \u2192 promote through stages.",
3469
+ "6. Use `series_summary` to capture the full progression."
3470
+ ]
3471
+ };
3472
+ }
3473
+ async function seriesSummary(state, input) {
3474
+ const ws = state.requireWorkspace();
3475
+ const series = ws.series?.find((s) => s.id === input.seriesId);
3476
+ if (!series) {
3477
+ throw new Error(`Series '${input.seriesId}' not found in workspace`);
3478
+ }
3479
+ const sketchInfos = [];
3480
+ const loadedIds = [];
3481
+ for (const file of series.sketchFiles) {
3482
+ let found = false;
3483
+ for (const [id, loaded] of state.sketches) {
3484
+ if (basename8(loaded.path) === file) {
3485
+ const def = loaded.definition;
3486
+ sketchInfos.push({
3487
+ id,
3488
+ title: def.title,
3489
+ file,
3490
+ compositionLevel: def.compositionLevel ?? "sketch",
3491
+ lineage: def.lineage ?? null,
3492
+ renderer: def.renderer.type,
3493
+ canvas: `${def.canvas.width}x${def.canvas.height}`,
3494
+ seed: def.state.seed,
3495
+ parameterCount: def.parameters.length,
3496
+ colorCount: def.colors.length,
3497
+ philosophy: def.philosophy ?? null
3498
+ });
3499
+ loadedIds.push(id);
3500
+ found = true;
3501
+ break;
3502
+ }
3503
+ }
3504
+ if (!found) {
3505
+ sketchInfos.push({ file, status: "not loaded" });
3506
+ }
3507
+ }
3508
+ let previews;
3509
+ if (input.captureScreenshots !== false && loadedIds.length > 0) {
3510
+ const batchResult = await captureBatch(state, {
3511
+ sketchIds: loadedIds,
3512
+ previewSize: input.previewSize ?? 300
3513
+ });
3514
+ previews = batchResult.items.map((item) => ({
3515
+ sketchId: item.metadata["sketchId"],
3516
+ inlineJpegBase64: item.inlineJpegBase64
3517
+ }));
3518
+ }
3519
+ const metadata = {
3520
+ success: true,
3521
+ series: {
3522
+ id: series.id,
3523
+ label: series.label,
3524
+ narrative: series.narrative,
3525
+ intent: series.intent,
3526
+ progression: series.progression ?? null,
3527
+ stages: series.stages ?? null
3528
+ },
3529
+ sketches: sketchInfos,
3530
+ summary: {
3531
+ totalSketches: series.sketchFiles.length,
3532
+ loadedSketches: loadedIds.length,
3533
+ compositionLevels: countBy(
3534
+ sketchInfos.filter((s) => s["compositionLevel"]).map((s) => s["compositionLevel"])
3535
+ )
3536
+ },
3537
+ instructions: [
3538
+ "Review the series progression from studies through finals.",
3539
+ "Evaluate whether the narrative and intent are reflected in the body of work.",
3540
+ "Consider: does each sketch build on its predecessors? Is there a clear evolution?",
3541
+ "Identify the strongest and weakest pieces. What makes them succeed or fail?",
3542
+ "Document insights and decisions in the series narrative."
3543
+ ]
3544
+ };
3545
+ return { metadata, previews };
3546
+ }
3547
+ async function promoteSketch(state, input) {
3548
+ const ws = state.requireWorkspace();
3549
+ const source = state.requireSketch(input.sketchId);
3550
+ const sourceDef = source.definition;
3551
+ if (!VALID_STAGES.includes(input.toStage)) {
3552
+ throw new Error(
3553
+ `Invalid stage: '${input.toStage}'. Valid stages: ${VALID_STAGES.join(", ")}`
3554
+ );
3555
+ }
3556
+ const targetLevel = STAGE_TO_LEVEL[input.toStage];
3557
+ const scale = LEVEL_SCALE[targetLevel];
3558
+ const newId = input.newId ?? `${input.sketchId}-${input.toStage.replace(/s$/, "")}`;
3559
+ validateKebabId2(newId);
3560
+ if (state.getSketch(newId)) {
3561
+ throw new Error(`Sketch with ID '${newId}' already exists`);
3562
+ }
3563
+ const newWidth = Math.round(sourceDef.canvas.width * scale);
3564
+ const newHeight = Math.round(sourceDef.canvas.height * scale);
3565
+ const sourceGeneration = sourceDef.lineage?.generation ?? 1;
3566
+ const title = input.title ?? `${sourceDef.title} (${input.toStage.replace(/s$/, "")})`;
3567
+ const ts = now6();
3568
+ const promotedDef = {
3569
+ genart: "1.1",
3570
+ id: newId,
3571
+ title,
3572
+ created: ts,
3573
+ modified: ts,
3574
+ renderer: sourceDef.renderer,
3575
+ canvas: { width: newWidth, height: newHeight },
3576
+ parameters: [...sourceDef.parameters],
3577
+ colors: [...sourceDef.colors],
3578
+ state: {
3579
+ seed: sourceDef.state.seed,
3580
+ params: { ...sourceDef.state.params },
3581
+ colorPalette: [...sourceDef.state.colorPalette]
3582
+ },
3583
+ algorithm: sourceDef.algorithm,
3584
+ compositionLevel: targetLevel,
3585
+ lineage: {
3586
+ parentId: input.sketchId,
3587
+ parentTitle: sourceDef.title,
3588
+ generation: sourceGeneration + 1
3589
+ },
3590
+ ...sourceDef.philosophy ? { philosophy: sourceDef.philosophy } : {},
3591
+ ...sourceDef.themes ? { themes: [...sourceDef.themes] } : {},
3592
+ ...sourceDef.skills ? { skills: [...sourceDef.skills] } : {},
3593
+ ...sourceDef.components ? { components: sourceDef.components } : {},
3594
+ ...sourceDef.symbols ? { symbols: sourceDef.symbols } : {},
3595
+ ...input.agent ? { agent: input.agent } : {},
3596
+ ...input.model ? { model: input.model } : {}
3597
+ };
3598
+ const sourceDir = dirname6(source.path);
3599
+ const newPath = resolve3(sourceDir, `${newId}.genart`);
3600
+ const json = serializeGenart5(promotedDef);
3601
+ if (!state.remoteMode) {
3602
+ await writeFile7(newPath, json, "utf-8");
3603
+ }
3604
+ state.sketches.set(newId, { definition: promotedDef, path: newPath });
3605
+ const sourceRef = ws.sketches.find(
3606
+ (s) => s.file === basename8(source.path)
3607
+ );
3608
+ const position = sourceRef ? { x: sourceRef.position.x, y: sourceRef.position.y + sourceDef.canvas.height + 200 } : { x: 0, y: 0 };
3609
+ const file = basename8(newPath);
3610
+ state.workspace = {
3611
+ ...ws,
3612
+ modified: ts,
3613
+ sketches: [...ws.sketches, { file, position }]
3614
+ };
3615
+ if (input.seriesId) {
3616
+ const seriesIndex = state.workspace.series?.findIndex(
3617
+ (s) => s.id === input.seriesId
3618
+ );
3619
+ if (seriesIndex !== void 0 && seriesIndex >= 0 && state.workspace.series) {
3620
+ const series = state.workspace.series[seriesIndex];
3621
+ const updatedSeries = {
3622
+ ...series,
3623
+ sketchFiles: [...series.sketchFiles, file]
3624
+ };
3625
+ state.workspace = {
3626
+ ...state.workspace,
3627
+ series: state.workspace.series.map(
3628
+ (s, i) => i === seriesIndex ? updatedSeries : s
3629
+ )
3630
+ };
3631
+ }
3632
+ }
3633
+ const workspaceJson = serializeWorkspace4(state.workspace);
3634
+ if (!state.remoteMode) {
3635
+ await writeFile7(state.workspacePath, workspaceJson, "utf-8");
3636
+ }
3637
+ state.emitMutation("sketch:created", { id: newId, path: newPath });
3638
+ state.emitMutation("workspace:updated", { added: file });
3639
+ return {
3640
+ success: true,
3641
+ sourceId: input.sketchId,
3642
+ promotedSketch: {
3643
+ id: newId,
3644
+ title,
3645
+ path: newPath,
3646
+ compositionLevel: targetLevel,
3647
+ stage: input.toStage,
3648
+ canvas: { width: newWidth, height: newHeight },
3649
+ position,
3650
+ lineage: promotedDef.lineage
3651
+ },
3652
+ ...scale > 1 ? {
3653
+ canvasUpscaled: `Canvas scaled ${scale}x: ${sourceDef.canvas.width}x${sourceDef.canvas.height} \u2192 ${newWidth}x${newHeight}`
3654
+ } : {},
3655
+ fileContent: json,
3656
+ workspaceContent: workspaceJson
3657
+ };
3658
+ }
3659
+ function countBy(items) {
3660
+ const counts = {};
3661
+ for (const item of items) {
3662
+ counts[item] = (counts[item] ?? 0) + 1;
3663
+ }
3664
+ return counts;
3665
+ }
3666
+
3667
+ // src/tools/reference.ts
3668
+ import { copyFile, mkdir, readFile as readFile5 } from "fs/promises";
3669
+ import { basename as basename9, dirname as dirname7, extname, resolve as resolve4 } from "path";
3670
+ import {
3671
+ serializeGenart as serializeGenart6,
3672
+ serializeWorkspace as serializeWorkspace5
3673
+ } from "@genart-dev/core";
3674
+ import { writeFile as writeFile8 } from "fs/promises";
3675
+ function now7() {
3676
+ return (/* @__PURE__ */ new Date()).toISOString();
3677
+ }
3678
+ var KEBAB_RE3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3679
+ function validateKebabId3(id) {
3680
+ if (!KEBAB_RE3.test(id)) {
3681
+ throw new Error(
3682
+ "ID must be kebab-case: lowercase letters, numbers, hyphens"
3683
+ );
3684
+ }
3685
+ }
3686
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
3687
+ ".png",
3688
+ ".jpg",
3689
+ ".jpeg",
3690
+ ".gif",
3691
+ ".webp",
3692
+ ".bmp",
3693
+ ".tiff",
3694
+ ".svg"
3695
+ ]);
3696
+ function isImageFile(path) {
3697
+ return IMAGE_EXTENSIONS.has(extname(path).toLowerCase());
3698
+ }
3699
+ var VALID_REFERENCE_TYPES = [
3700
+ "image",
3701
+ "artwork",
3702
+ "photograph",
3703
+ "texture",
3704
+ "palette"
3705
+ ];
3706
+ async function addReference(state, input) {
3707
+ const ws = state.requireWorkspace();
3708
+ if (!isImageFile(input.image)) {
3709
+ throw new Error(
3710
+ `Not a recognized image file: ${input.image}. Supported: ${[...IMAGE_EXTENSIONS].join(", ")}`
3711
+ );
3712
+ }
3713
+ const id = input.id ?? basename9(input.image, extname(input.image)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
3714
+ if (!id) {
3715
+ throw new Error("Could not derive a valid ID from the image filename");
3716
+ }
3717
+ validateKebabId3(id);
3718
+ const refType = input.type ?? "image";
3719
+ if (!VALID_REFERENCE_TYPES.includes(refType)) {
3720
+ throw new Error(
3721
+ `Invalid reference type: '${refType}'. Valid types: ${VALID_REFERENCE_TYPES.join(", ")}`
3722
+ );
3723
+ }
3724
+ const workspaceDir = dirname7(state.workspacePath);
3725
+ const refsDir = resolve4(workspaceDir, "references");
3726
+ await mkdir(refsDir, { recursive: true });
3727
+ const ext = extname(input.image);
3728
+ const destFilename = `${id}${ext}`;
3729
+ const destPath = resolve4(refsDir, destFilename);
3730
+ const relativePath = `references/${destFilename}`;
3731
+ if (!state.remoteMode) {
3732
+ await copyFile(resolve4(input.image), destPath);
3733
+ }
3734
+ const ref = {
3735
+ id,
3736
+ type: refType,
3737
+ path: relativePath,
3738
+ ...input.source ? { source: input.source } : {}
3739
+ };
3740
+ let attachedTo;
3741
+ let workspaceJson;
3742
+ let sketchJson;
3743
+ if (input.sketchId) {
3744
+ const loaded = state.requireSketch(input.sketchId);
3745
+ const existingRefs = loaded.definition.references ?? [];
3746
+ if (existingRefs.some((r) => r.id === id)) {
3747
+ throw new Error(
3748
+ `Reference with ID '${id}' already exists on sketch '${input.sketchId}'`
3749
+ );
3750
+ }
3751
+ const updatedDef = {
3752
+ ...loaded.definition,
3753
+ modified: now7(),
3754
+ references: [...existingRefs, ref]
3755
+ };
3756
+ state.sketches.set(input.sketchId, {
3757
+ definition: updatedDef,
3758
+ path: loaded.path
3759
+ });
3760
+ sketchJson = serializeGenart6(updatedDef);
3761
+ if (!state.remoteMode) {
3762
+ await writeFile8(loaded.path, sketchJson, "utf-8");
3763
+ }
3764
+ attachedTo = `sketch:${input.sketchId}`;
3765
+ state.emitMutation("sketch:updated", { id: input.sketchId });
3766
+ } else if (input.seriesId) {
3767
+ const seriesIndex = ws.series?.findIndex((s) => s.id === input.seriesId);
3768
+ if (seriesIndex === void 0 || seriesIndex < 0 || !ws.series) {
3769
+ throw new Error(`Series '${input.seriesId}' not found in workspace`);
3770
+ }
3771
+ const series = ws.series[seriesIndex];
3772
+ const existingRefs = series.references ?? [];
3773
+ if (existingRefs.some((r) => r.id === id)) {
3774
+ throw new Error(
3775
+ `Reference with ID '${id}' already exists on series '${input.seriesId}'`
3776
+ );
3777
+ }
3778
+ const updatedSeries = {
3779
+ ...series,
3780
+ references: [...existingRefs, ref]
3781
+ };
3782
+ state.workspace = {
3783
+ ...ws,
3784
+ modified: now7(),
3785
+ series: ws.series.map(
3786
+ (s, i) => i === seriesIndex ? updatedSeries : s
3787
+ )
3788
+ };
3789
+ workspaceJson = serializeWorkspace5(state.workspace);
3790
+ if (!state.remoteMode) {
3791
+ await writeFile8(state.workspacePath, workspaceJson, "utf-8");
3792
+ }
3793
+ attachedTo = `series:${input.seriesId}`;
3794
+ state.emitMutation("workspace:updated", { referenceAdded: id });
3795
+ } else {
3796
+ throw new Error("Either seriesId or sketchId must be specified");
3797
+ }
3798
+ return {
3799
+ success: true,
3800
+ reference: {
3801
+ id,
3802
+ type: refType,
3803
+ path: relativePath,
3804
+ source: input.source ?? null
3805
+ },
3806
+ attachedTo,
3807
+ ...sketchJson ? { fileContent: sketchJson } : {},
3808
+ ...workspaceJson ? { workspaceContent: workspaceJson } : {}
3809
+ };
3810
+ }
3811
+ async function analyzeReference(state, input) {
3812
+ state.requireWorkspace();
3813
+ const { ref, location } = findReference(state, input.referenceId, input.seriesId, input.sketchId);
3814
+ const workspaceDir = dirname7(state.workspacePath);
3815
+ const imagePath = resolve4(workspaceDir, ref.path);
3816
+ let previewJpegBase64;
3817
+ try {
3818
+ const imageBuffer = await readFile5(imagePath);
3819
+ const ext = extname(ref.path).toLowerCase();
3820
+ const mimeMap = {
3821
+ ".png": "image/png",
3822
+ ".jpg": "image/jpeg",
3823
+ ".jpeg": "image/jpeg",
3824
+ ".gif": "image/gif",
3825
+ ".webp": "image/webp",
3826
+ ".svg": "image/svg+xml"
3827
+ };
3828
+ previewJpegBase64 = imageBuffer.toString("base64");
3829
+ } catch {
3830
+ }
3831
+ const metadata = {
3832
+ success: true,
3833
+ referenceId: ref.id,
3834
+ type: ref.type,
3835
+ path: ref.path,
3836
+ source: ref.source ?? null,
3837
+ location,
3838
+ existingAnalysis: ref.analysis ?? null,
3839
+ analysisFramework: {
3840
+ composition: {
3841
+ instruction: "Analyze the compositional structure of this reference.",
3842
+ prompts: [
3843
+ "What is the primary compositional structure (centered, asymmetric, diagonal, radial)?",
3844
+ "Where does the eye land first? What creates the focal point?",
3845
+ "How is negative space used \u2014 actively or passively?",
3846
+ "What is the relationship between foreground, middle ground, and background?",
3847
+ "How do the edges and corners of the frame interact with the subject?"
3848
+ ]
3849
+ },
3850
+ palette: {
3851
+ instruction: "Identify the color strategy.",
3852
+ prompts: [
3853
+ "What are the dominant colors (3-5 hex values)?",
3854
+ "What color temperature dominates \u2014 warm, cool, or neutral?",
3855
+ "What is the value range \u2014 high contrast or compressed?",
3856
+ "Is the palette analogous, complementary, triadic, or something else?",
3857
+ "How does saturation vary across the composition?"
3858
+ ]
3859
+ },
3860
+ rhythm: {
3861
+ instruction: "Identify rhythmic and pattern qualities.",
3862
+ prompts: [
3863
+ "Is there a repeating motif or interval?",
3864
+ "Is the rhythm regular, progressive, alternating, or irregular?",
3865
+ "At how many scales does pattern appear (fractal quality)?",
3866
+ "How do density variations create movement?",
3867
+ "Where are the moments of rest vs. activity?"
3868
+ ]
3869
+ },
3870
+ mood: {
3871
+ instruction: "Identify the emotional and atmospheric qualities.",
3872
+ prompts: [
3873
+ "What is the overall mood \u2014 contemplative, energetic, serene, unsettling?",
3874
+ "How do color, light, and space contribute to that mood?",
3875
+ "Is there a sense of time \u2014 moment, duration, timelessness?",
3876
+ "What emotional response does the work invite?"
3877
+ ]
3878
+ },
3879
+ technique: {
3880
+ instruction: "Identify technical and material qualities worth studying.",
3881
+ prompts: [
3882
+ "What medium or technique is used?",
3883
+ "How is mark-making contributing to expression?",
3884
+ "Are there layering or transparency effects?",
3885
+ "What level of control vs. chance is visible?",
3886
+ "What technical approach could be translated to generative art?"
3887
+ ]
3888
+ }
3889
+ },
3890
+ instructions: [
3891
+ "Study the reference image carefully using the framework above.",
3892
+ "For each category, answer the prompts and synthesize your observations.",
3893
+ "After analysis, use update_reference_analysis to save the structured analysis.",
3894
+ "The analysis should inform how you create study sketches inspired by this reference.",
3895
+ "Focus on qualities that can be translated to generative art \u2014 don't try to replicate literally."
3896
+ ]
3897
+ };
3898
+ return { metadata, previewJpegBase64 };
3899
+ }
3900
+ async function updateReferenceAnalysis(state, input) {
3901
+ const ws = state.requireWorkspace();
3902
+ const { ref, location } = findReference(
3903
+ state,
3904
+ input.referenceId,
3905
+ input.seriesId,
3906
+ input.sketchId
3907
+ );
3908
+ const updatedRef = {
3909
+ ...ref,
3910
+ analysis: input.analysis
3911
+ };
3912
+ let workspaceJson;
3913
+ let sketchJson;
3914
+ if (location.startsWith("sketch:")) {
3915
+ const sketchId = location.replace("sketch:", "");
3916
+ const loaded = state.requireSketch(sketchId);
3917
+ const updatedDef = {
3918
+ ...loaded.definition,
3919
+ modified: now7(),
3920
+ references: (loaded.definition.references ?? []).map(
3921
+ (r) => r.id === input.referenceId ? updatedRef : r
3922
+ )
3923
+ };
3924
+ state.sketches.set(sketchId, {
3925
+ definition: updatedDef,
3926
+ path: loaded.path
3927
+ });
3928
+ sketchJson = serializeGenart6(updatedDef);
3929
+ if (!state.remoteMode) {
3930
+ await writeFile8(loaded.path, sketchJson, "utf-8");
3931
+ }
3932
+ state.emitMutation("sketch:updated", { id: sketchId });
3933
+ } else {
3934
+ const seriesId = location.replace("series:", "");
3935
+ const seriesIndex = ws.series.findIndex((s) => s.id === seriesId);
3936
+ const series = ws.series[seriesIndex];
3937
+ const updatedSeries = {
3938
+ ...series,
3939
+ references: (series.references ?? []).map(
3940
+ (r) => r.id === input.referenceId ? updatedRef : r
3941
+ )
3942
+ };
3943
+ state.workspace = {
3944
+ ...ws,
3945
+ modified: now7(),
3946
+ series: ws.series.map(
3947
+ (s, i) => i === seriesIndex ? updatedSeries : s
3948
+ )
3949
+ };
3950
+ workspaceJson = serializeWorkspace5(state.workspace);
3951
+ if (!state.remoteMode) {
3952
+ await writeFile8(state.workspacePath, workspaceJson, "utf-8");
3953
+ }
3954
+ state.emitMutation("workspace:updated", { referenceAnalyzed: input.referenceId });
3955
+ }
3956
+ return {
3957
+ success: true,
3958
+ referenceId: input.referenceId,
3959
+ location,
3960
+ analysis: input.analysis,
3961
+ ...sketchJson ? { fileContent: sketchJson } : {},
3962
+ ...workspaceJson ? { workspaceContent: workspaceJson } : {}
3963
+ };
3964
+ }
3965
+ async function extractPalette(state, input) {
3966
+ state.requireWorkspace();
3967
+ const { ref, location } = findReference(
3968
+ state,
3969
+ input.referenceId,
3970
+ input.seriesId,
3971
+ input.sketchId
3972
+ );
3973
+ const count = input.count ?? 6;
3974
+ const workspaceDir = dirname7(state.workspacePath);
3975
+ const imagePath = resolve4(workspaceDir, ref.path);
3976
+ let previewJpegBase64;
3977
+ try {
3978
+ const imageBuffer = await readFile5(imagePath);
3979
+ previewJpegBase64 = imageBuffer.toString("base64");
3980
+ } catch {
3981
+ }
3982
+ const metadata = {
3983
+ success: true,
3984
+ referenceId: ref.id,
3985
+ type: ref.type,
3986
+ path: ref.path,
3987
+ location,
3988
+ requestedColors: count,
3989
+ existingPalette: ref.analysis?.palette ?? null,
3990
+ instructions: [
3991
+ `Extract ${count} dominant colors from the reference image as hex values.`,
3992
+ "Order them from most dominant to least dominant.",
3993
+ "Include both saturated and neutral colors if present in the image.",
3994
+ "Consider the role of each color \u2014 is it a background, accent, or primary element?",
3995
+ "After extraction, use update_reference_analysis to save the palette.",
3996
+ "You can also apply the extracted palette to a sketch using set_colors or create a new theme."
3997
+ ],
3998
+ extractionGuidelines: {
3999
+ dominance: "Prioritize colors by the area they occupy, not just their saturation.",
4000
+ variety: "Include the full value range (lights, midtones, darks) if present.",
4001
+ harmony: `Look for ${count <= 4 ? "core harmony" : "extended palette including transitional colors"}.`,
4002
+ neutrals: "Don't ignore grays, blacks, and whites \u2014 they often define the character of a palette."
4003
+ }
4004
+ };
4005
+ return { metadata, previewJpegBase64 };
4006
+ }
4007
+ function findReference(state, referenceId, seriesId, sketchId) {
4008
+ if (sketchId) {
4009
+ const loaded = state.requireSketch(sketchId);
4010
+ const ref = (loaded.definition.references ?? []).find(
4011
+ (r) => r.id === referenceId
4012
+ );
4013
+ if (ref) return { ref, location: `sketch:${sketchId}` };
4014
+ throw new Error(
4015
+ `Reference '${referenceId}' not found on sketch '${sketchId}'`
4016
+ );
4017
+ }
4018
+ if (seriesId) {
4019
+ const ws2 = state.requireWorkspace();
4020
+ const series = ws2.series?.find((s) => s.id === seriesId);
4021
+ if (!series) {
4022
+ throw new Error(`Series '${seriesId}' not found in workspace`);
4023
+ }
4024
+ const ref = (series.references ?? []).find((r) => r.id === referenceId);
4025
+ if (ref) return { ref, location: `series:${seriesId}` };
4026
+ throw new Error(
4027
+ `Reference '${referenceId}' not found on series '${seriesId}'`
4028
+ );
4029
+ }
4030
+ const ws = state.requireWorkspace();
4031
+ if (ws.series) {
4032
+ for (const series of ws.series) {
4033
+ const ref = (series.references ?? []).find((r) => r.id === referenceId);
4034
+ if (ref) return { ref, location: `series:${series.id}` };
4035
+ }
4036
+ }
4037
+ for (const [id, loaded] of state.sketches) {
4038
+ const ref = (loaded.definition.references ?? []).find(
4039
+ (r) => r.id === referenceId
4040
+ );
4041
+ if (ref) return { ref, location: `sketch:${id}` };
4042
+ }
4043
+ throw new Error(
4044
+ `Reference '${referenceId}' not found in any series or sketch`
4045
+ );
4046
+ }
4047
+
4048
+ // src/tools/export.ts
4049
+ import { createWriteStream } from "fs";
4050
+ import { stat as stat4, writeFile as writeFile9 } from "fs/promises";
4051
+ import { dirname as dirname8 } from "path";
4052
+ import archiver from "archiver";
4053
+ import {
4054
+ createDefaultRegistry as createDefaultRegistry3,
4055
+ serializeGenart as serializeGenart7
4056
+ } from "@genart-dev/core";
4057
+ var registry4 = createDefaultRegistry3();
4058
+ async function validateOutputPath(outputPath) {
4059
+ const parentDir = dirname8(outputPath);
4060
+ try {
4061
+ const s = await stat4(parentDir);
4062
+ if (!s.isDirectory()) {
4063
+ throw new Error(`Parent directory does not exist: ${parentDir}`);
4064
+ }
4065
+ } catch (e) {
4066
+ if (e instanceof Error && e.message.startsWith("Parent directory")) throw e;
4067
+ throw new Error(`Parent directory does not exist: ${parentDir}`);
4068
+ }
4069
+ try {
4070
+ await stat4(outputPath);
4071
+ throw new Error(
4072
+ `File already exists at ${outputPath}. Delete it first or use a different path.`
4073
+ );
4074
+ } catch (e) {
4075
+ if (e instanceof Error && e.message.startsWith("File already exists")) throw e;
4076
+ }
4077
+ }
4078
+ function algorithmExtension(rendererType) {
4079
+ return rendererType === "glsl" ? ".glsl" : ".js";
4080
+ }
4081
+ function applyOverrides2(sketch, overrides) {
4082
+ if (overrides.seed === void 0 && overrides.params === void 0) {
4083
+ return sketch;
4084
+ }
4085
+ const newState = {
4086
+ seed: overrides.seed ?? sketch.state.seed,
4087
+ params: overrides.params ? { ...sketch.state.params, ...overrides.params } : sketch.state.params,
4088
+ colorPalette: sketch.state.colorPalette
4089
+ };
4090
+ return { ...sketch, state: newState };
4091
+ }
4092
+ async function exportSketch(state, input) {
4093
+ state.requireWorkspace();
4094
+ const loaded = state.requireSketch(input.sketchId);
4095
+ const sketch = applyOverrides2(loaded.definition, {
4096
+ seed: input.seed,
4097
+ params: input.params
4098
+ });
4099
+ await validateOutputPath(input.outputPath);
4100
+ const adapter = registry4.resolve(sketch.renderer.type);
4101
+ if (!adapter) {
4102
+ throw new Error(
4103
+ `Unsupported renderer type: '${sketch.renderer.type}'`
4104
+ );
4105
+ }
4106
+ switch (input.format) {
4107
+ case "html":
4108
+ return await exportHtml(sketch, input.outputPath);
4109
+ case "png":
4110
+ return await exportPng(sketch, input);
4111
+ case "svg":
4112
+ return await exportSvg(sketch, input);
4113
+ case "algorithm":
4114
+ return await exportAlgorithm(sketch, input.outputPath);
4115
+ case "zip":
4116
+ return await exportZip(sketch, input);
4117
+ default:
4118
+ throw new Error(`Unsupported export format: '${input.format}'`);
4119
+ }
4120
+ }
4121
+ async function exportHtml(sketch, outputPath) {
4122
+ const adapter = registry4.resolve(sketch.renderer.type);
4123
+ const html = adapter.generateStandaloneHTML(sketch);
4124
+ const content = Buffer.from(html, "utf-8");
4125
+ await writeFile9(outputPath, content);
4126
+ return {
4127
+ success: true,
4128
+ sketchId: sketch.id,
4129
+ format: "html",
4130
+ outputPath,
4131
+ fileSize: content.byteLength,
4132
+ renderer: sketch.renderer.type
4133
+ };
4134
+ }
4135
+ async function exportPng(sketch, input) {
4136
+ const adapter = registry4.resolve(sketch.renderer.type);
4137
+ const html = adapter.generateStandaloneHTML(sketch);
4138
+ const width = input.width ?? sketch.canvas.width;
4139
+ const height = input.height ?? sketch.canvas.height;
4140
+ const result = await captureHtml({ html, width, height });
4141
+ await writeFile9(input.outputPath, result.bytes);
4142
+ return {
4143
+ success: true,
4144
+ sketchId: sketch.id,
4145
+ format: "png",
4146
+ outputPath: input.outputPath,
4147
+ fileSize: result.bytes.byteLength,
4148
+ renderer: sketch.renderer.type
4149
+ };
4150
+ }
4151
+ async function exportSvg(sketch, input) {
4152
+ const width = input.width ?? sketch.canvas.width;
4153
+ const height = input.height ?? sketch.canvas.height;
4154
+ if (sketch.renderer.type === "svg") {
4155
+ const content2 = Buffer.from(sketch.algorithm, "utf-8");
4156
+ await writeFile9(input.outputPath, content2);
4157
+ return {
4158
+ success: true,
4159
+ sketchId: sketch.id,
4160
+ format: "svg",
4161
+ outputPath: input.outputPath,
4162
+ fileSize: content2.byteLength,
4163
+ renderer: sketch.renderer.type,
4164
+ notice: null
4165
+ };
4166
+ }
4167
+ const adapter = registry4.resolve(sketch.renderer.type);
4168
+ const html = adapter.generateStandaloneHTML(sketch);
4169
+ const result = await captureHtml({ html, width, height });
4170
+ const b64 = Buffer.from(result.bytes).toString("base64");
4171
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
4172
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
4173
+ width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
4174
+ <image width="${width}" height="${height}"
4175
+ href="data:image/png;base64,${b64}"/>
4176
+ </svg>`;
4177
+ const content = Buffer.from(svg, "utf-8");
4178
+ await writeFile9(input.outputPath, content);
4179
+ return {
4180
+ success: true,
4181
+ sketchId: sketch.id,
4182
+ format: "svg",
4183
+ outputPath: input.outputPath,
4184
+ fileSize: content.byteLength,
4185
+ renderer: sketch.renderer.type,
4186
+ notice: "Non-SVG renderer \u2014 rasterized PNG embedded in SVG container"
4187
+ };
4188
+ }
4189
+ async function exportAlgorithm(sketch, outputPath) {
4190
+ const content = Buffer.from(sketch.algorithm, "utf-8");
4191
+ await writeFile9(outputPath, content);
4192
+ return {
4193
+ success: true,
4194
+ sketchId: sketch.id,
4195
+ format: "algorithm",
4196
+ outputPath,
4197
+ fileSize: content.byteLength,
4198
+ renderer: sketch.renderer.type
4199
+ };
4200
+ }
4201
+ async function exportZip(sketch, input) {
4202
+ const adapter = registry4.resolve(sketch.renderer.type);
4203
+ const width = input.width ?? sketch.canvas.width;
4204
+ const height = input.height ?? sketch.canvas.height;
4205
+ const html = adapter.generateStandaloneHTML(sketch);
4206
+ const genartJson = serializeGenart7(sketch);
4207
+ const algorithm = sketch.algorithm;
4208
+ const algExt = algorithmExtension(sketch.renderer.type);
4209
+ const captureResult = await captureHtml({ html, width, height });
4210
+ const output = createWriteStream(input.outputPath);
4211
+ const archive = archiver("zip", { zlib: { level: 9 } });
4212
+ const finished = new Promise((resolve5, reject) => {
4213
+ output.on("close", resolve5);
4214
+ archive.on("error", reject);
4215
+ });
4216
+ archive.pipe(output);
4217
+ archive.append(html, { name: `${sketch.id}.html` });
4218
+ archive.append(Buffer.from(captureResult.bytes), { name: `${sketch.id}.png` });
4219
+ archive.append(algorithm, { name: `${sketch.id}${algExt}` });
4220
+ archive.append(genartJson, { name: `${sketch.id}.genart` });
4221
+ await archive.finalize();
4222
+ await finished;
4223
+ const s = await stat4(input.outputPath);
4224
+ return {
4225
+ success: true,
4226
+ sketchId: sketch.id,
4227
+ format: "zip",
4228
+ outputPath: input.outputPath,
4229
+ fileSize: s.size,
4230
+ renderer: sketch.renderer.type,
4231
+ contents: [
4232
+ `${sketch.id}.html`,
4233
+ `${sketch.id}.png`,
4234
+ `${sketch.id}${algExt}`,
4235
+ `${sketch.id}.genart`
4236
+ ]
4237
+ };
4238
+ }
4239
+
4240
+ // src/tools/design.ts
4241
+ function requireSketchId(state, args) {
4242
+ return args.sketchId ?? state.requireSelectedSketchId();
4243
+ }
4244
+ var BLEND_MODES = [
4245
+ "normal",
4246
+ "multiply",
4247
+ "screen",
2979
4248
  "overlay",
2980
4249
  "darken",
2981
4250
  "lighten",
@@ -2997,8 +4266,8 @@ async function designAddLayer(state, args) {
2997
4266
  const sketchId = requireSketchId(state, args);
2998
4267
  const loaded = state.requireSketch(sketchId);
2999
4268
  const stack = state.getLayerStack(sketchId);
3000
- const registry4 = state.pluginRegistry;
3001
- const layerTypeDef = registry4?.resolveLayerType(args.type);
4269
+ const registry5 = state.pluginRegistry;
4270
+ const layerTypeDef = registry5?.resolveLayerType(args.type);
3002
4271
  if (!layerTypeDef) {
3003
4272
  throw new Error(
3004
4273
  `Unknown layer type: '${args.type}'. Use design_list_layers types from registered plugins.`
@@ -3105,10 +4374,7 @@ async function designUpdateLayer(state, args) {
3105
4374
  stack.updateProperties(args.layerId, updates);
3106
4375
  }
3107
4376
  if (args.name !== void 0) {
3108
- const current = stack.get(args.layerId);
3109
- stack.updateProperties(args.layerId, { ...current.properties });
3110
- const mutableLayer = stack.get(args.layerId);
3111
- mutableLayer.name = args.name;
4377
+ stack.updateMeta(args.layerId, { name: args.name });
3112
4378
  }
3113
4379
  await state.saveSketch(sketchId);
3114
4380
  return { updated: true, layerId: args.layerId, sketchId };
@@ -3206,9 +4472,7 @@ async function designToggleVisibility(state, args) {
3206
4472
  throw new Error(`Layer '${args.layerId}' not found in sketch '${sketchId}'.`);
3207
4473
  }
3208
4474
  const newVisible = args.visible ?? !layer.visible;
3209
- const mutableLayer = layer;
3210
- mutableLayer.visible = newVisible;
3211
- stack.updateProperties(args.layerId, { ...layer.properties });
4475
+ stack.updateMeta(args.layerId, { visible: newVisible });
3212
4476
  await state.saveSketch(sketchId);
3213
4477
  return {
3214
4478
  layerId: args.layerId,
@@ -3224,9 +4488,7 @@ async function designLockLayer(state, args) {
3224
4488
  throw new Error(`Layer '${args.layerId}' not found in sketch '${sketchId}'.`);
3225
4489
  }
3226
4490
  const newLocked = args.locked ?? !layer.locked;
3227
- const mutableLayer = layer;
3228
- mutableLayer.locked = newLocked;
3229
- stack.updateProperties(args.layerId, { ...layer.properties });
4491
+ stack.updateMeta(args.layerId, { locked: newLocked });
3230
4492
  await state.saveSketch(sketchId);
3231
4493
  return {
3232
4494
  layerId: args.layerId,
@@ -3247,8 +4509,8 @@ async function designCaptureComposite(state, args) {
3247
4509
  }
3248
4510
 
3249
4511
  // src/tools/design-plugins.ts
3250
- function registerPluginMcpTools(server, registry4, state) {
3251
- for (const tool of registry4.getMcpTools()) {
4512
+ function registerPluginMcpTools(server, registry5, state) {
4513
+ for (const tool of registry5.getMcpTools()) {
3252
4514
  const inputSchema = tool.definition.inputSchema;
3253
4515
  server.tool(
3254
4516
  tool.name,
@@ -3296,7 +4558,7 @@ function registerPluginMcpTools(server, registry4, state) {
3296
4558
  import {
3297
4559
  CANVAS_PRESETS,
3298
4560
  createDefaultRegistry as createDefaultRegistry4,
3299
- createDefaultSkillRegistry as createDefaultSkillRegistry2
4561
+ createDefaultSkillRegistry as createDefaultSkillRegistry3
3300
4562
  } from "@genart-dev/core";
3301
4563
  function registerResources(server, state) {
3302
4564
  registerSkillsResource(server);
@@ -3305,7 +4567,7 @@ function registerResources(server, state) {
3305
4567
  registerRenderersResource(server);
3306
4568
  }
3307
4569
  function registerSkillsResource(server) {
3308
- const skillRegistry = createDefaultSkillRegistry2();
4570
+ const skillRegistry = createDefaultSkillRegistry3();
3309
4571
  server.resource(
3310
4572
  "skills",
3311
4573
  "genart://skills",
@@ -3413,7 +4675,7 @@ function registerGalleryResource(server, state) {
3413
4675
  );
3414
4676
  }
3415
4677
  function registerRenderersResource(server) {
3416
- const registry4 = createDefaultRegistry4();
4678
+ const registry5 = createDefaultRegistry4();
3417
4679
  server.resource(
3418
4680
  "renderers",
3419
4681
  "genart://renderers",
@@ -3422,9 +4684,9 @@ function registerRenderersResource(server) {
3422
4684
  mimeType: "application/json"
3423
4685
  },
3424
4686
  async () => {
3425
- const types = registry4.list();
4687
+ const types = registry5.list();
3426
4688
  const renderers = types.map((type) => {
3427
- const adapter = registry4.resolve(type);
4689
+ const adapter = registry5.resolve(type);
3428
4690
  return {
3429
4691
  type: adapter.type,
3430
4692
  displayName: adapter.displayName,
@@ -3436,7 +4698,7 @@ function registerRenderersResource(server) {
3436
4698
  }))
3437
4699
  };
3438
4700
  });
3439
- const defaultAdapter = registry4.getDefault();
4701
+ const defaultAdapter = registry5.getDefault();
3440
4702
  return {
3441
4703
  contents: [
3442
4704
  {
@@ -3463,6 +4725,9 @@ function registerPrompts(server, state) {
3463
4725
  registerCreateGenerativeArt(server);
3464
4726
  registerExploreVariations(server, state);
3465
4727
  registerApplyDesignTheory(server, state);
4728
+ registerCritiqueAndIterate(server, state);
4729
+ registerDevelopArtisticConcept(server, state);
4730
+ registerStudyReference(server, state);
3466
4731
  }
3467
4732
  function registerCreateGenerativeArt(server) {
3468
4733
  server.prompt(
@@ -3743,21 +5008,200 @@ function registerApplyDesignTheory(server, state) {
3743
5008
  content: {
3744
5009
  type: "text",
3745
5010
  text: [
3746
- `Apply design theory to improve a generative art sketch.`,
5011
+ `Apply design theory to improve a generative art sketch.`,
5012
+ ``,
5013
+ sketchContext,
5014
+ ``,
5015
+ theoryGuides[args.theory],
5016
+ ``,
5017
+ `## Workflow`,
5018
+ `1. Use \`get_selection\` or \`open_sketch\` to examine the current sketch`,
5019
+ `2. Analyze how the theory applies to the existing algorithm`,
5020
+ `3. Use \`fork_sketch\` to create a theory-applied variant`,
5021
+ `4. Modify the fork's algorithm and parameters using the theory principles above`,
5022
+ `5. Use \`capture_screenshot\` to compare before and after`,
5023
+ `6. Update the philosophy field to document the design rationale`,
5024
+ ``,
5025
+ `**Attribution:** Always pass your \`agent\` name and \`model\` identifier when calling tools that create or modify sketches.`
5026
+ ].join("\n")
5027
+ }
5028
+ }
5029
+ ]
5030
+ };
5031
+ }
5032
+ );
5033
+ }
5034
+ function registerCritiqueAndIterate(server, state) {
5035
+ server.prompt(
5036
+ "critique-and-iterate",
5037
+ "Capture a sketch, self-critique it, identify improvements, fork, apply changes, compare, and document the iteration",
5038
+ {
5039
+ sketchId: z.string().describe("ID of the sketch to critique and iterate on"),
5040
+ aspects: z.string().optional().describe("Comma-separated aspects to focus on (composition, color, rhythm, unity, expression). Default: all"),
5041
+ iterations: z.string().optional().describe("Number of improvement iterations (default: 1)")
5042
+ },
5043
+ async (args) => {
5044
+ const sketch = state.getSketch(args.sketchId);
5045
+ const iterations = args.iterations ? parseInt(args.iterations, 10) : 1;
5046
+ const aspectList = args.aspects ? args.aspects.split(",").map((a) => a.trim()) : ["composition", "color", "rhythm", "unity", "expression"];
5047
+ let sketchContext = "";
5048
+ if (sketch) {
5049
+ const def = sketch.definition;
5050
+ sketchContext = [
5051
+ `## Current Sketch: "${def.title}"`,
5052
+ `- **ID:** ${def.id}`,
5053
+ `- **Renderer:** ${def.renderer.type}`,
5054
+ `- **Canvas:** ${def.canvas.width}\xD7${def.canvas.height}`,
5055
+ `- **Composition Level:** ${def.compositionLevel ?? "sketch"}`,
5056
+ def.philosophy ? `- **Philosophy:** ${def.philosophy}` : `- **Philosophy:** not set`,
5057
+ `- **Parameters:** ${def.parameters?.length ?? 0} defined`,
5058
+ `- **Colors:** ${def.colors?.length ?? 0} defined`
5059
+ ].join("\n");
5060
+ } else {
5061
+ sketchContext = `## Sketch: ${args.sketchId}
5062
+ *(Not currently loaded \u2014 use open_sketch first)*`;
5063
+ }
5064
+ return {
5065
+ messages: [
5066
+ {
5067
+ role: "user",
5068
+ content: {
5069
+ type: "text",
5070
+ text: [
5071
+ `Perform a structured critique-and-iterate cycle on a generative art sketch.`,
3747
5072
  ``,
3748
5073
  sketchContext,
3749
5074
  ``,
3750
- theoryGuides[args.theory],
5075
+ `## Focus Aspects`,
5076
+ aspectList.map((a) => `- ${a}`).join("\n"),
3751
5077
  ``,
3752
- `## Workflow`,
3753
- `1. Use \`get_selection\` or \`open_sketch\` to examine the current sketch`,
3754
- `2. Analyze how the theory applies to the existing algorithm`,
3755
- `3. Use \`fork_sketch\` to create a theory-applied variant`,
3756
- `4. Modify the fork's algorithm and parameters using the theory principles above`,
3757
- `5. Use \`capture_screenshot\` to compare before and after`,
3758
- `6. Update the philosophy field to document the design rationale`,
5078
+ `## Iterations: ${iterations}`,
3759
5079
  ``,
3760
- `**Attribution:** Always pass your \`agent\` name and \`model\` identifier when calling tools that create or modify sketches.`
5080
+ `## Process`,
5081
+ ``,
5082
+ `For each iteration:`,
5083
+ ``,
5084
+ `### Step 1: Capture & Critique`,
5085
+ `1. Use \`critique_sketch\` with sketchId="${args.sketchId}" and aspects=[${aspectList.map((a) => `"${a}"`).join(", ")}]`,
5086
+ `2. Study the returned screenshot carefully`,
5087
+ `3. Answer each framework question honestly \u2014 what works and what doesn't`,
5088
+ `4. Note the severity calibration for this composition level`,
5089
+ ``,
5090
+ `### Step 2: Identify Improvements`,
5091
+ `Based on the critique, identify 2-3 specific, actionable improvements:`,
5092
+ `- Rank them by expected visual impact`,
5093
+ `- Be precise: "shift the focal cluster from center to upper-left third" not "improve composition"`,
5094
+ `- Consider which improvements can be achieved via parameter changes vs algorithm changes`,
5095
+ ``,
5096
+ `### Step 3: Fork & Apply`,
5097
+ `1. Use \`fork_sketch\` to create a new version (preserve the original for comparison)`,
5098
+ `2. Apply the identified improvements:`,
5099
+ ` - Use \`set_parameters\` or \`set_colors\` for parameter-level changes`,
5100
+ ` - Use \`update_algorithm\` for algorithmic changes`,
5101
+ `3. Use \`capture_screenshot\` to verify each change visually`,
5102
+ ``,
5103
+ `### Step 4: Compare`,
5104
+ `1. Use \`compare_sketches\` with the original and improved sketch IDs`,
5105
+ `2. Evaluate: did each intended improvement actually improve the piece?`,
5106
+ `3. Note any unintended consequences \u2014 improvements in one aspect sometimes degrade another`,
5107
+ ``,
5108
+ `### Step 5: Document`,
5109
+ `After all iterations:`,
5110
+ `1. Update the improved sketch's philosophy field to document what changed and why`,
5111
+ `2. Summarize the iteration journey: what was tried, what worked, what was learned`,
5112
+ `3. If the original was better in some aspects, note what to preserve in future iterations`,
5113
+ ``,
5114
+ `## Guidelines`,
5115
+ `- Be your own harshest (but fairest) critic \u2014 the goal is genuine improvement`,
5116
+ `- Small, focused changes are better than sweeping rewrites`,
5117
+ `- If a change doesn't work, revert it before trying the next improvement`,
5118
+ `- The final piece should feel like a natural evolution, not a different sketch`,
5119
+ `- Always pass your \`agent\` name and \`model\` identifier when calling tools that create or modify sketches`
5120
+ ].join("\n")
5121
+ }
5122
+ }
5123
+ ]
5124
+ };
5125
+ }
5126
+ );
5127
+ }
5128
+ function registerDevelopArtisticConcept(server, _state) {
5129
+ server.prompt(
5130
+ "develop-artistic-concept",
5131
+ "Develop an artistic concept through a full studio workflow: concept planning, studies, development, critique, iteration, and documentation",
5132
+ {
5133
+ concept: z.string().describe("The artistic concept or theme to explore"),
5134
+ medium: z.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Preferred renderer/medium (default: p5)"),
5135
+ depth: z.enum(["quick", "standard", "deep"]).optional().describe("How deeply to explore: quick (3 studies), standard (6 studies), deep (9+ studies). Default: standard")
5136
+ },
5137
+ async (args) => {
5138
+ const medium = args.medium ?? "p5";
5139
+ const depth = args.depth ?? "standard";
5140
+ const studyCount = depth === "quick" ? 3 : depth === "deep" ? 9 : 6;
5141
+ return {
5142
+ messages: [
5143
+ {
5144
+ role: "user",
5145
+ content: {
5146
+ type: "text",
5147
+ text: [
5148
+ `Develop the following artistic concept through a full studio workflow.`,
5149
+ ``,
5150
+ `## Concept`,
5151
+ `${args.concept}`,
5152
+ ``,
5153
+ `## Medium: ${medium}`,
5154
+ `## Depth: ${depth} (${studyCount} studies)`,
5155
+ ``,
5156
+ `## Phase 1: Conceptual Planning`,
5157
+ `1. Use \`develop_concept\` with your concept and medium to get a structured plan`,
5158
+ `2. Define: mood, color strategy, compositional approach, and relevant skills`,
5159
+ `3. Create a series with \`create_series\` \u2014 write a narrative and intent statement`,
5160
+ ``,
5161
+ `## Phase 2: Thumbnail Studies`,
5162
+ `1. Create ${studyCount} quick study-level sketches with \`create_sketch\` (compositionLevel: "study")`,
5163
+ `2. Each study should explore a different aspect of the concept:`,
5164
+ ` - Vary composition (centered vs asymmetric vs edge-driven)`,
5165
+ ` - Vary color (warm vs cool, saturated vs muted)`,
5166
+ ` - Vary rhythm (regular vs progressive vs chaotic)`,
5167
+ ` - Vary density (sparse vs dense vs gradient)`,
5168
+ `3. Use small canvases (600x600 or similar) \u2014 studies are fast explorations`,
5169
+ `4. Use \`capture_batch\` to see all studies at once`,
5170
+ ``,
5171
+ `## Phase 3: Selection & Critique`,
5172
+ `1. Use \`series_summary\` to see the full set of studies with screenshots`,
5173
+ `2. Use \`critique_sketch\` on the 2-3 most promising studies`,
5174
+ `3. Identify which studies best capture the concept's intent`,
5175
+ `4. Note what works in each \u2014 composition choices, color relationships, rhythmic qualities`,
5176
+ ``,
5177
+ `## Phase 4: Development`,
5178
+ `1. Use \`promote_sketch\` to advance the best 1-2 studies to "drafts" stage`,
5179
+ `2. Refine the promoted sketches:`,
5180
+ ` - Add more parameters for fine control`,
5181
+ ` - Develop the color palette with more nuance`,
5182
+ ` - Strengthen compositional structure`,
5183
+ ` - Load relevant skills with \`load_skill\` for guidance`,
5184
+ `3. Use \`critique_sketch\` after each round of changes`,
5185
+ ``,
5186
+ `## Phase 5: Critique & Iteration`,
5187
+ `1. Use \`compare_sketches\` to evaluate drafts against each other`,
5188
+ `2. For the strongest draft, use the critique-and-iterate workflow:`,
5189
+ ` - Critique \u2192 identify improvements \u2192 fork \u2192 apply \u2192 compare`,
5190
+ `3. Promote the best iteration to "refinements" stage`,
5191
+ `4. Continue refining until the piece feels resolved`,
5192
+ ``,
5193
+ `## Phase 6: Final & Documentation`,
5194
+ `1. Promote the best refinement to "finals" stage (canvas will upscale)`,
5195
+ `2. Update the philosophy field with the full artistic statement`,
5196
+ `3. Use \`series_summary\` to capture the complete progression`,
5197
+ `4. Document: what was the concept? How did it evolve? What was discovered?`,
5198
+ ``,
5199
+ `## Guidelines`,
5200
+ `- Each phase should feel like a natural progression, not a checklist`,
5201
+ `- Trust the studies \u2014 let unexpected results redirect the exploration`,
5202
+ `- The final piece should feel inevitable, like it couldn't have been any other way`,
5203
+ `- Always pass your \`agent\` name and \`model\` identifier when calling tools`,
5204
+ `- Use \`auto_arrange\` periodically to keep the workspace organized`
3761
5205
  ].join("\n")
3762
5206
  }
3763
5207
  }
@@ -3766,6 +5210,83 @@ function registerApplyDesignTheory(server, state) {
3766
5210
  }
3767
5211
  );
3768
5212
  }
5213
+ function registerStudyReference(server, _state) {
5214
+ server.prompt(
5215
+ "study-reference",
5216
+ "Study a reference image: analyze it, identify key qualities, create a generative study sketch inspired by it, and document learnings",
5217
+ {
5218
+ referenceId: z.string().describe("ID of the reference to study"),
5219
+ seriesId: z.string().optional().describe("Series the reference belongs to (also where the study sketch will be added)"),
5220
+ sketchId: z.string().optional().describe("Sketch the reference belongs to"),
5221
+ medium: z.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Renderer for the study sketch (default: p5)"),
5222
+ focus: z.string().optional().describe("Specific quality to focus on: composition, palette, rhythm, mood, technique, or a custom focus")
5223
+ },
5224
+ async (args) => {
5225
+ const medium = args.medium ?? "p5";
5226
+ const focus = args.focus ?? "all key qualities";
5227
+ return {
5228
+ messages: [
5229
+ {
5230
+ role: "user",
5231
+ content: {
5232
+ type: "text",
5233
+ text: [
5234
+ `Study a reference image and create a generative art sketch inspired by it.`,
5235
+ ``,
5236
+ `## Reference: ${args.referenceId}`,
5237
+ args.seriesId ? `## Series: ${args.seriesId}` : "",
5238
+ `## Medium: ${medium}`,
5239
+ `## Focus: ${focus}`,
5240
+ ``,
5241
+ `## Phase 1: Analyze the Reference`,
5242
+ `1. Use \`analyze_reference\` with referenceId="${args.referenceId}"${args.seriesId ? ` seriesId="${args.seriesId}"` : ""}${args.sketchId ? ` sketchId="${args.sketchId}"` : ""} to get the analysis framework and image`,
5243
+ `2. Study the image carefully using the framework prompts`,
5244
+ `3. Answer each category: composition, palette, rhythm, mood, technique`,
5245
+ `4. Use \`update_reference_analysis\` to save your structured analysis`,
5246
+ ``,
5247
+ `## Phase 2: Extract Key Qualities`,
5248
+ `From your analysis, identify 2-4 key qualities that are most interesting for generative art:`,
5249
+ `- These could be: a specific compositional structure, a color relationship, a rhythmic pattern, a mood quality`,
5250
+ `- Focus on qualities that can be *translated* into code, not literally replicated`,
5251
+ `- Consider what makes this reference compelling \u2014 what would be lost if you removed each quality?`,
5252
+ ``,
5253
+ `## Phase 3: Extract Palette`,
5254
+ `1. Use \`extract_palette\` to study the reference's color strategy`,
5255
+ `2. Extract 5-8 hex colors that capture the essential palette`,
5256
+ `3. Save the palette in the reference analysis`,
5257
+ ``,
5258
+ `## Phase 4: Create Study Sketch`,
5259
+ `1. Use \`create_sketch\` with compositionLevel: "study" to create a quick exploration`,
5260
+ `2. Translate the key qualities into generative parameters and algorithm choices:`,
5261
+ ` - Composition \u2192 element placement, density distribution, negative space`,
5262
+ ` - Palette \u2192 color definitions, themes derived from the reference palette`,
5263
+ ` - Rhythm \u2192 repetition patterns, interval variations, scale relationships`,
5264
+ ` - Mood \u2192 overall tone, animation speed, mark quality`,
5265
+ ` - Technique \u2192 rendering approach, layering, transparency`,
5266
+ `3. Add the reference to the sketch with \`add_reference\``,
5267
+ `4. Document in the philosophy field how the reference influenced the study`,
5268
+ `5. Use \`capture_screenshot\` to verify the result`,
5269
+ ``,
5270
+ `## Phase 5: Compare & Document`,
5271
+ `1. Use \`analyze_reference\` again to see the reference alongside your study`,
5272
+ `2. Evaluate: which qualities translated well? Which were lost or transformed?`,
5273
+ `3. Note what you learned \u2014 what worked, what surprised you, what to try next`,
5274
+ `4. Update the study sketch's philosophy with these insights`,
5275
+ ``,
5276
+ `## Guidelines`,
5277
+ `- The goal is *inspiration*, not replication \u2014 a study should be recognizably generative`,
5278
+ `- A good study captures the *spirit* of the reference while being authentically algorithmic`,
5279
+ `- Use small canvases (600x600) \u2014 studies are explorations, not finished pieces`,
5280
+ `- If the reference suggests multiple interesting directions, create multiple studies`,
5281
+ `- Always pass your \`agent\` name and \`model\` identifier when calling tools`
5282
+ ].filter(Boolean).join("\n")
5283
+ }
5284
+ }
5285
+ ]
5286
+ };
5287
+ }
5288
+ );
5289
+ }
3769
5290
 
3770
5291
  // src/server.ts
3771
5292
  function jsonResult(data) {
@@ -3780,22 +5301,36 @@ function toolError(message) {
3780
5301
  };
3781
5302
  }
3782
5303
  async function initializePluginRegistry() {
3783
- const registry4 = createPluginRegistry({
5304
+ const registry5 = createPluginRegistry({
3784
5305
  surface: "mcp",
3785
5306
  supportsInteractiveTools: false,
3786
5307
  supportsRendering: false
3787
5308
  });
3788
- await registry4.register(typographyPlugin);
3789
- await registry4.register(filtersPlugin);
3790
- await registry4.register(shapesPlugin);
3791
- await registry4.register(layoutGuidesPlugin);
3792
- return registry4;
5309
+ await registry5.register(typographyPlugin);
5310
+ await registry5.register(filtersPlugin);
5311
+ await registry5.register(shapesPlugin);
5312
+ await registry5.register(layoutGuidesPlugin);
5313
+ await registry5.register(paintingPlugin);
5314
+ await registry5.register(texturesPlugin);
5315
+ await registry5.register(animationPlugin);
5316
+ await registry5.register(colorAdjustPlugin);
5317
+ await registry5.register(compositingPlugin);
5318
+ await registry5.register(constructionPlugin);
5319
+ await registry5.register(distributionPlugin);
5320
+ await registry5.register(figurePlugin);
5321
+ await registry5.register(layoutCompositionPlugin);
5322
+ await registry5.register(perspectivePlugin);
5323
+ await registry5.register(posesPlugin);
5324
+ await registry5.register(stylesPlugin);
5325
+ await registry5.register(symbolsPlugin);
5326
+ await registry5.register(tracePlugin);
5327
+ return registry5;
3793
5328
  }
3794
5329
  function createServer(state) {
3795
5330
  const server = new McpServer(
3796
5331
  {
3797
5332
  name: "@genart/mcp-server",
3798
- version: "0.3.0"
5333
+ version: "0.4.0"
3799
5334
  },
3800
5335
  {
3801
5336
  capabilities: {
@@ -3805,9 +5340,9 @@ function createServer(state) {
3805
5340
  }
3806
5341
  }
3807
5342
  );
3808
- const registryReady = initializePluginRegistry().then((registry4) => {
3809
- state.pluginRegistry = registry4;
3810
- registerPluginMcpTools(server, registry4, state);
5343
+ const registryReady = initializePluginRegistry().then((registry5) => {
5344
+ state.pluginRegistry = registry5;
5345
+ registerPluginMcpTools(server, registry5, state);
3811
5346
  });
3812
5347
  server._pluginsReady = registryReady;
3813
5348
  registerWorkspaceTools(server, state);
@@ -3822,6 +5357,9 @@ function createServer(state) {
3822
5357
  registerKnowledgeTools(server, state);
3823
5358
  registerDesignTools(server, state);
3824
5359
  registerCaptureTools(server, state);
5360
+ registerCritiqueTools(server, state);
5361
+ registerSeriesTools(server, state);
5362
+ registerReferenceTools(server, state);
3825
5363
  registerExportTools(server, state);
3826
5364
  registerResources(server, state);
3827
5365
  registerPrompts(server, state);
@@ -4586,6 +6124,276 @@ function registerCaptureTools(server, state) {
4586
6124
  }
4587
6125
  );
4588
6126
  }
6127
+ function registerCritiqueTools(server, state) {
6128
+ server.tool(
6129
+ "critique_sketch",
6130
+ "Capture a sketch screenshot and return a structured self-critique framework (questions, principles, pitfalls) per aspect. Severity calibrates to compositionLevel.",
6131
+ {
6132
+ sketchId: z2.string().optional().describe("Sketch to critique (default: selected sketch)"),
6133
+ aspects: z2.array(z2.enum(["composition", "color", "rhythm", "unity", "expression"])).optional().describe("Aspects to critique (default: all five)"),
6134
+ previewSize: z2.number().optional().describe("Max dimension for inline preview JPEG (default: 400)")
6135
+ },
6136
+ async (args) => {
6137
+ try {
6138
+ const result = await critiqueSketch(state, args);
6139
+ return {
6140
+ content: [
6141
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) },
6142
+ { type: "image", data: result.previewJpegBase64, mimeType: "image/jpeg" }
6143
+ ]
6144
+ };
6145
+ } catch (e) {
6146
+ return toolError(e instanceof Error ? e.message : String(e));
6147
+ }
6148
+ }
6149
+ );
6150
+ server.tool(
6151
+ "compare_sketches",
6152
+ "Side-by-side capture of 2-4 sketches with a structured comparison framework across specified aspects.",
6153
+ {
6154
+ sketchIds: z2.array(z2.string()).describe("IDs of 2-4 sketches to compare"),
6155
+ aspects: z2.array(z2.enum(["composition", "color", "rhythm", "unity", "expression"])).optional().describe("Aspects to compare (default: all five)"),
6156
+ previewSize: z2.number().optional().describe("Max dimension for inline preview JPEGs (default: 300)")
6157
+ },
6158
+ async (args) => {
6159
+ try {
6160
+ const result = await compareSketches(state, args);
6161
+ const content = [
6162
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
6163
+ ];
6164
+ for (const preview of result.previews) {
6165
+ content.push({
6166
+ type: "text",
6167
+ text: `--- Sketch: ${preview.sketchId} ---`
6168
+ });
6169
+ content.push({
6170
+ type: "image",
6171
+ data: preview.inlineJpegBase64,
6172
+ mimeType: "image/jpeg"
6173
+ });
6174
+ }
6175
+ return { content };
6176
+ } catch (e) {
6177
+ return toolError(e instanceof Error ? e.message : String(e));
6178
+ }
6179
+ }
6180
+ );
6181
+ }
6182
+ function registerSeriesTools(server, state) {
6183
+ server.tool(
6184
+ "create_series",
6185
+ "Create a new curated series of sketches with narrative, intent, and studio workflow stages",
6186
+ {
6187
+ label: z2.string().describe("Display label for the series"),
6188
+ narrative: z2.string().describe("Prose narrative describing the artistic exploration"),
6189
+ intent: z2.string().describe("Short statement of artistic intent"),
6190
+ progression: z2.string().optional().describe(
6191
+ "Series progression type (e.g. 'linear', 'branching', 'iterative')"
6192
+ ),
6193
+ stages: z2.array(z2.enum(["studies", "drafts", "refinements", "finals"])).optional().describe(
6194
+ "Ordered stages in the studio workflow (default: all four)"
6195
+ ),
6196
+ sketchFiles: z2.array(z2.string()).optional().describe("File names of existing sketches to include")
6197
+ },
6198
+ async (args) => {
6199
+ try {
6200
+ const result = await createSeries(state, args);
6201
+ return jsonResult(result);
6202
+ } catch (e) {
6203
+ return toolError(e instanceof Error ? e.message : String(e));
6204
+ }
6205
+ }
6206
+ );
6207
+ server.tool(
6208
+ "develop_concept",
6209
+ "Generate a structured concept development plan with mood, palette, composition, skills, and series structure recommendations",
6210
+ {
6211
+ concept: z2.string().describe("The artistic concept or theme to develop"),
6212
+ medium: z2.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Preferred renderer/medium (default: p5)")
6213
+ },
6214
+ async (args) => {
6215
+ try {
6216
+ const result = await developConcept(state, args);
6217
+ return jsonResult(result);
6218
+ } catch (e) {
6219
+ return toolError(e instanceof Error ? e.message : String(e));
6220
+ }
6221
+ }
6222
+ );
6223
+ server.tool(
6224
+ "series_summary",
6225
+ "Capture all sketches in a series with narrative context for holistic evaluation",
6226
+ {
6227
+ seriesId: z2.string().describe("ID of the series to summarize"),
6228
+ captureScreenshots: z2.boolean().optional().describe("Capture screenshots of each sketch (default: true)"),
6229
+ previewSize: z2.number().optional().describe("Preview image size in pixels (default: 300)")
6230
+ },
6231
+ async (args) => {
6232
+ try {
6233
+ const result = await seriesSummary(state, args);
6234
+ const content = [
6235
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
6236
+ ];
6237
+ if (result.previews) {
6238
+ for (const preview of result.previews) {
6239
+ content.push({
6240
+ type: "image",
6241
+ data: preview.inlineJpegBase64,
6242
+ mimeType: "image/jpeg"
6243
+ });
6244
+ }
6245
+ }
6246
+ return { content };
6247
+ } catch (e) {
6248
+ return toolError(e instanceof Error ? e.message : String(e));
6249
+ }
6250
+ }
6251
+ );
6252
+ server.tool(
6253
+ "promote_sketch",
6254
+ "Promote a sketch to the next studio workflow stage \u2014 fork, upscale canvas, update compositionLevel, and add to series",
6255
+ {
6256
+ sketchId: z2.string().describe("ID of the sketch to promote"),
6257
+ toStage: z2.enum(["studies", "drafts", "refinements", "finals"]).describe("Target stage to promote to"),
6258
+ seriesId: z2.string().optional().describe("Series to add the promoted sketch to"),
6259
+ newId: z2.string().optional().describe(
6260
+ "URL-safe kebab-case ID for the promoted sketch (default: auto-generated)"
6261
+ ),
6262
+ title: z2.string().optional().describe("Title for the promoted sketch (default: auto-generated)"),
6263
+ agent: z2.string().optional().describe("CLI agent name"),
6264
+ model: z2.string().optional().describe("AI model identifier")
6265
+ },
6266
+ async (args) => {
6267
+ try {
6268
+ const result = await promoteSketch(state, args);
6269
+ return jsonResult(result);
6270
+ } catch (e) {
6271
+ return toolError(e instanceof Error ? e.message : String(e));
6272
+ }
6273
+ }
6274
+ );
6275
+ }
6276
+ function registerReferenceTools(server, state) {
6277
+ server.tool(
6278
+ "add_reference",
6279
+ "Import an image as a reference for inspiration. Copies the image to the workspace references/ directory and attaches it to a series or sketch.",
6280
+ {
6281
+ image: z2.string().describe("Path to the reference image file"),
6282
+ type: z2.enum(["image", "artwork", "photograph", "texture", "palette"]).optional().describe("Reference type (default: image)"),
6283
+ source: z2.string().optional().describe("Source attribution (artist, URL, collection)"),
6284
+ seriesId: z2.string().optional().describe("Series to attach the reference to"),
6285
+ sketchId: z2.string().optional().describe("Sketch to attach the reference to"),
6286
+ id: z2.string().optional().describe("Custom reference ID (default: derived from filename)")
6287
+ },
6288
+ async (args) => {
6289
+ try {
6290
+ const result = await addReference(state, args);
6291
+ return jsonResult(result);
6292
+ } catch (e) {
6293
+ return toolError(e instanceof Error ? e.message : String(e));
6294
+ }
6295
+ }
6296
+ );
6297
+ server.tool(
6298
+ "analyze_reference",
6299
+ "Return a structured analysis framework for a reference image, with the image for visual inspection. The agent fills in the analysis using the framework prompts.",
6300
+ {
6301
+ referenceId: z2.string().describe("ID of the reference to analyze"),
6302
+ seriesId: z2.string().optional().describe("Series the reference belongs to (speeds up lookup)"),
6303
+ sketchId: z2.string().optional().describe("Sketch the reference belongs to (speeds up lookup)"),
6304
+ previewSize: z2.number().optional().describe("Max dimension for preview image (default: native)")
6305
+ },
6306
+ async (args) => {
6307
+ try {
6308
+ const result = await analyzeReference(state, args);
6309
+ const content = [
6310
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
6311
+ ];
6312
+ if (result.previewJpegBase64) {
6313
+ const ext = (result.metadata["path"] ?? ".png").split(".").pop() ?? "png";
6314
+ const mimeMap = {
6315
+ png: "image/png",
6316
+ jpg: "image/jpeg",
6317
+ jpeg: "image/jpeg",
6318
+ gif: "image/gif",
6319
+ webp: "image/webp",
6320
+ svg: "image/svg+xml"
6321
+ };
6322
+ content.push({
6323
+ type: "image",
6324
+ data: result.previewJpegBase64,
6325
+ mimeType: mimeMap[ext] ?? "image/png"
6326
+ });
6327
+ }
6328
+ return { content };
6329
+ } catch (e) {
6330
+ return toolError(e instanceof Error ? e.message : String(e));
6331
+ }
6332
+ }
6333
+ );
6334
+ server.tool(
6335
+ "update_reference_analysis",
6336
+ "Save a structured analysis (composition, palette, rhythm, mood, technique) back to a reference after studying it with analyze_reference.",
6337
+ {
6338
+ referenceId: z2.string().describe("ID of the reference to update"),
6339
+ seriesId: z2.string().optional().describe("Series the reference belongs to"),
6340
+ sketchId: z2.string().optional().describe("Sketch the reference belongs to"),
6341
+ analysis: z2.object({
6342
+ composition: z2.string().optional().describe("Compositional structure observations"),
6343
+ palette: z2.array(z2.string()).optional().describe("Dominant colors as hex values"),
6344
+ rhythm: z2.string().optional().describe("Visual rhythm and pattern observations"),
6345
+ mood: z2.string().optional().describe("Mood and emotional qualities"),
6346
+ technique: z2.string().optional().describe("Technique and medium observations"),
6347
+ keyQualities: z2.array(z2.string()).optional().describe("Key qualities worth studying")
6348
+ }).describe("Structured analysis to save")
6349
+ },
6350
+ async (args) => {
6351
+ try {
6352
+ const result = await updateReferenceAnalysis(state, args);
6353
+ return jsonResult(result);
6354
+ } catch (e) {
6355
+ return toolError(e instanceof Error ? e.message : String(e));
6356
+ }
6357
+ }
6358
+ );
6359
+ server.tool(
6360
+ "extract_palette",
6361
+ "Return a reference image for color palette extraction, with guidelines for identifying dominant colors. The agent extracts hex colors visually.",
6362
+ {
6363
+ referenceId: z2.string().describe("ID of the reference to extract palette from"),
6364
+ seriesId: z2.string().optional().describe("Series the reference belongs to"),
6365
+ sketchId: z2.string().optional().describe("Sketch the reference belongs to"),
6366
+ count: z2.number().optional().describe("Number of colors to extract (default: 6)")
6367
+ },
6368
+ async (args) => {
6369
+ try {
6370
+ const result = await extractPalette(state, args);
6371
+ const content = [
6372
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
6373
+ ];
6374
+ if (result.previewJpegBase64) {
6375
+ const ext = (result.metadata["path"] ?? ".png").split(".").pop() ?? "png";
6376
+ const mimeMap = {
6377
+ png: "image/png",
6378
+ jpg: "image/jpeg",
6379
+ jpeg: "image/jpeg",
6380
+ gif: "image/gif",
6381
+ webp: "image/webp",
6382
+ svg: "image/svg+xml"
6383
+ };
6384
+ content.push({
6385
+ type: "image",
6386
+ data: result.previewJpegBase64,
6387
+ mimeType: mimeMap[ext] ?? "image/png"
6388
+ });
6389
+ }
6390
+ return { content };
6391
+ } catch (e) {
6392
+ return toolError(e instanceof Error ? e.message : String(e));
6393
+ }
6394
+ }
6395
+ );
6396
+ }
4589
6397
  function registerExportTools(server, state) {
4590
6398
  server.tool(
4591
6399
  "export_sketch",
@@ -4850,7 +6658,7 @@ function registerDesignTools(server, state) {
4850
6658
  }
4851
6659
  );
4852
6660
  }
4853
- function registerKnowledgeTools(server, _state) {
6661
+ function registerKnowledgeTools(server, state) {
4854
6662
  server.tool(
4855
6663
  "list_skills",
4856
6664
  "List all available design knowledge skills (Phase 5)",
@@ -4886,7 +6694,7 @@ function registerKnowledgeTools(server, _state) {
4886
6694
  "get_guidelines",
4887
6695
  "Return design guidelines and best practices for a topic (Phase 5)",
4888
6696
  {
4889
- topic: z2.enum(["composition", "color", "parameters", "animation", "performance"]).describe("Guideline topic"),
6697
+ topic: z2.enum(["composition", "color", "process", "painting", "illustration", "parameters", "animation", "performance"]).describe("Guideline topic"),
4890
6698
  renderer: z2.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Renderer-specific guidance")
4891
6699
  },
4892
6700
  async (args) => {
@@ -4898,6 +6706,22 @@ function registerKnowledgeTools(server, _state) {
4898
6706
  }
4899
6707
  }
4900
6708
  );
6709
+ server.tool(
6710
+ "suggest_skills",
6711
+ "Recommend relevant design skills based on sketch context and/or free-text description",
6712
+ {
6713
+ sketchId: z2.string().optional().describe("ID of a loaded sketch to analyze for skill recommendations"),
6714
+ context: z2.string().optional().describe("Free-text description of what you're working on (e.g., 'atmospheric landscape with watercolor')")
6715
+ },
6716
+ async (args) => {
6717
+ try {
6718
+ const result = await suggestSkills(state, args);
6719
+ return jsonResult(result);
6720
+ } catch (e) {
6721
+ return toolError(e instanceof Error ? e.message : String(e));
6722
+ }
6723
+ }
6724
+ );
4901
6725
  }
4902
6726
 
4903
6727
  // src/index.ts