@genart-dev/mcp-server 0.3.0 → 0.4.1

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/lib.js CHANGED
@@ -6,6 +6,20 @@ import typographyPlugin from "@genart-dev/plugin-typography";
6
6
  import filtersPlugin from "@genart-dev/plugin-filters";
7
7
  import shapesPlugin from "@genart-dev/plugin-shapes";
8
8
  import layoutGuidesPlugin from "@genart-dev/plugin-layout-guides";
9
+ import paintingPlugin from "@genart-dev/plugin-painting";
10
+ import texturesPlugin from "@genart-dev/plugin-textures";
11
+ import animationPlugin from "@genart-dev/plugin-animation";
12
+ import colorAdjustPlugin from "@genart-dev/plugin-color-adjust";
13
+ import compositingPlugin from "@genart-dev/plugin-compositing";
14
+ import constructionPlugin from "@genart-dev/plugin-construction";
15
+ import distributionPlugin from "@genart-dev/plugin-distribution";
16
+ import figurePlugin from "@genart-dev/plugin-figure";
17
+ import layoutCompositionPlugin from "@genart-dev/plugin-layout-composition";
18
+ import perspectivePlugin from "@genart-dev/plugin-perspective";
19
+ import posesPlugin from "@genart-dev/plugin-poses";
20
+ import stylesPlugin from "@genart-dev/plugin-styles";
21
+ import symbolsPlugin from "@genart-dev/plugin-symbols";
22
+ import tracePlugin from "@genart-dev/plugin-trace";
9
23
 
10
24
  // src/tools/workspace.ts
11
25
  import { readFile, writeFile, stat } from "fs/promises";
@@ -443,8 +457,8 @@ async function createSketch(state, input) {
443
457
  }
444
458
  let algorithm = input.algorithm;
445
459
  if (!algorithm) {
446
- const registry4 = createDefaultRegistry();
447
- const adapter = registry4.resolve(rendererType);
460
+ const registry5 = createDefaultRegistry();
461
+ const adapter = registry5.resolve(rendererType);
448
462
  algorithm = adapter.getAlgorithmTemplate();
449
463
  }
450
464
  let resolvedComponents;
@@ -669,8 +683,8 @@ async function updateAlgorithm(state, input) {
669
683
  const shouldValidate = input.validate !== false;
670
684
  let validationPassed = true;
671
685
  if (shouldValidate) {
672
- const registry4 = createDefaultRegistry();
673
- const adapter = registry4.resolve(def.renderer.type);
686
+ const registry5 = createDefaultRegistry();
687
+ const adapter = registry5.resolve(def.renderer.type);
674
688
  const result = adapter.validate(input.algorithm);
675
689
  if (!result.valid) {
676
690
  throw new Error(
@@ -793,6 +807,12 @@ async function forkSketch(state, input) {
793
807
  const seed = generateNewSeed ? Math.floor(Math.random() * 1e5) : sourceDef.state.seed;
794
808
  const title = input.title ?? `${sourceDef.title} (fork)`;
795
809
  const ts = now2();
810
+ const sourceGeneration = sourceDef.lineage?.generation ?? 1;
811
+ const lineage = {
812
+ parentId: input.sourceId,
813
+ parentTitle: sourceDef.title,
814
+ generation: sourceGeneration + 1
815
+ };
796
816
  const forkedDef = {
797
817
  genart: "1.1",
798
818
  id: input.newId,
@@ -805,6 +825,8 @@ async function forkSketch(state, input) {
805
825
  colors,
806
826
  state: buildState(parameters, colors, seed),
807
827
  algorithm,
828
+ ...sourceDef.compositionLevel ? { compositionLevel: sourceDef.compositionLevel } : {},
829
+ lineage,
808
830
  ...philosophy ? { philosophy } : {},
809
831
  ...sourceDef.themes ? { themes: [...sourceDef.themes] } : {},
810
832
  ...sourceDef.skills ? { skills: [...sourceDef.skills] } : {},
@@ -1770,6 +1792,13 @@ ${s.philosophy}`);
1770
1792
  params[p.key] = p.default;
1771
1793
  }
1772
1794
  const colorPalette = colors.map((c) => c.default);
1795
+ const maxGeneration = Math.max(
1796
+ ...sources.map((s) => s.lineage?.generation ?? 1)
1797
+ );
1798
+ const lineage = {
1799
+ blendSources: input.sourceIds,
1800
+ generation: maxGeneration + 1
1801
+ };
1773
1802
  const timestamp = now5();
1774
1803
  const newDef = {
1775
1804
  genart: "1.1",
@@ -1778,6 +1807,7 @@ ${s.philosophy}`);
1778
1807
  created: timestamp,
1779
1808
  modified: timestamp,
1780
1809
  ...skills.length > 0 ? { skills } : {},
1810
+ lineage,
1781
1811
  renderer: { type: renderer, version: sources[0].renderer.version },
1782
1812
  canvas: { width: canvasWidth, height: canvasHeight },
1783
1813
  ...philosophy ? { philosophy } : {},
@@ -2004,14 +2034,25 @@ async function getGuidelines(input) {
2004
2034
  color: "color",
2005
2035
  colours: "color",
2006
2036
  layout: "composition",
2007
- palette: "color"
2037
+ palette: "color",
2038
+ painting: "painting",
2039
+ watercolor: "painting",
2040
+ ink: "illustration",
2041
+ illustration: "illustration",
2042
+ "mixed-media": "illustration",
2043
+ "mixed media": "illustration",
2044
+ process: "process",
2045
+ layering: "process",
2046
+ "mark-making": "process",
2047
+ refinement: "process",
2048
+ constraints: "process"
2008
2049
  };
2009
2050
  const category = categoryMap[topic];
2010
2051
  if (!category) {
2011
2052
  return {
2012
2053
  success: false,
2013
2054
  topic,
2014
- error: `No guidelines found for topic: '${topic}'. Available topics: composition, color, parameters, animation, performance`,
2055
+ error: `No guidelines found for topic: '${topic}'. Available topics: composition, color, painting, illustration, process, parameters, animation, performance`,
2015
2056
  guidelines: null,
2016
2057
  relatedSkills: []
2017
2058
  };
@@ -2038,6 +2079,138 @@ ${guidelines}`,
2038
2079
  }))
2039
2080
  };
2040
2081
  }
2082
+ var CONTEXT_KEYWORDS = {
2083
+ // Composition keywords
2084
+ layout: ["golden-ratio", "rule-of-thirds", "visual-weight", "gestalt-grouping"],
2085
+ balance: ["visual-weight", "golden-ratio", "rule-of-thirds"],
2086
+ grid: ["rule-of-thirds", "gestalt-grouping", "rhythm-movement"],
2087
+ flow: ["rhythm-movement", "gestalt-grouping"],
2088
+ movement: ["rhythm-movement", "mark-making"],
2089
+ rhythm: ["rhythm-movement", "mark-making"],
2090
+ focal: ["rule-of-thirds", "visual-weight", "figure-ground"],
2091
+ negative: ["figure-ground", "visual-weight"],
2092
+ space: ["figure-ground", "visual-weight", "atmospheric-depth"],
2093
+ // Color keywords
2094
+ palette: ["color-harmony", "palette-generation", "color-mixing-strategy"],
2095
+ color: ["color-harmony", "color-temperature", "itten-contrasts", "color-mixing-strategy"],
2096
+ warm: ["color-temperature", "atmospheric-depth"],
2097
+ cool: ["color-temperature", "atmospheric-depth"],
2098
+ contrast: ["simultaneous-contrast", "itten-contrasts", "value-structure"],
2099
+ value: ["value-structure", "itten-contrasts", "layering-strategy"],
2100
+ gray: ["color-mixing-strategy", "value-structure"],
2101
+ // Painting keywords
2102
+ watercolor: ["watercolor-techniques", "layering-strategy", "material-behavior"],
2103
+ ink: ["ink-illustration", "mark-making", "material-behavior"],
2104
+ oil: ["painting-foundations", "layering-strategy", "material-behavior"],
2105
+ charcoal: ["material-behavior", "mark-making"],
2106
+ brush: ["mark-making", "material-behavior"],
2107
+ layer: ["layering-strategy", "mixed-media-workflow", "iterative-refinement"],
2108
+ texture: ["material-behavior", "mark-making"],
2109
+ // Process keywords
2110
+ study: ["thumbnail-studies", "creative-constraints", "iterative-refinement"],
2111
+ thumbnail: ["thumbnail-studies", "creative-constraints"],
2112
+ refine: ["iterative-refinement", "layering-strategy"],
2113
+ iterate: ["iterative-refinement", "thumbnail-studies"],
2114
+ depth: ["atmospheric-depth", "color-temperature", "value-structure"],
2115
+ atmosphere: ["atmospheric-depth", "color-temperature"],
2116
+ perspective: ["atmospheric-depth"],
2117
+ constraint: ["creative-constraints"],
2118
+ limit: ["creative-constraints", "color-mixing-strategy"],
2119
+ hatch: ["mark-making", "ink-illustration"],
2120
+ stipple: ["mark-making"],
2121
+ gestural: ["mark-making", "iterative-refinement"],
2122
+ mix: ["color-mixing-strategy", "mixed-media-workflow"],
2123
+ glaze: ["layering-strategy", "material-behavior"]
2124
+ };
2125
+ async function suggestSkills(state, input) {
2126
+ const allSkills = registry.list();
2127
+ const scored = /* @__PURE__ */ new Map();
2128
+ for (const skill of allSkills) {
2129
+ scored.set(skill.id, { score: 0, reasons: [] });
2130
+ }
2131
+ if (input.sketchId) {
2132
+ const loaded = state.getSketch(input.sketchId);
2133
+ if (loaded) {
2134
+ const sketch = loaded.definition;
2135
+ const usedSkills = new Set(sketch.skills ?? []);
2136
+ for (const skill of allSkills) {
2137
+ if (!usedSkills.has(skill.id)) {
2138
+ const entry = scored.get(skill.id);
2139
+ entry.score += 1;
2140
+ entry.reasons.push("not yet used in this sketch");
2141
+ }
2142
+ }
2143
+ const level = sketch.compositionLevel;
2144
+ if (level) {
2145
+ const levelSkills = {
2146
+ study: ["thumbnail-studies", "creative-constraints", "iterative-refinement"],
2147
+ sketch: ["iterative-refinement", "mark-making", "layering-strategy", "color-mixing-strategy"],
2148
+ developed: ["layering-strategy", "material-behavior", "atmospheric-depth", "color-mixing-strategy"],
2149
+ exhibition: ["layering-strategy", "material-behavior", "atmospheric-depth", "iterative-refinement", "mark-making"]
2150
+ };
2151
+ for (const id of levelSkills[level] ?? []) {
2152
+ const entry = scored.get(id);
2153
+ if (entry) {
2154
+ entry.score += 3;
2155
+ entry.reasons.push(`recommended for ${level}-level work`);
2156
+ }
2157
+ }
2158
+ }
2159
+ if (sketch.layers && sketch.layers.length > 0) {
2160
+ const layerTypes = sketch.layers.map((l) => l.type);
2161
+ if (layerTypes.some((t) => t.startsWith("painting:"))) {
2162
+ for (const id of ["layering-strategy", "material-behavior", "iterative-refinement"]) {
2163
+ const entry = scored.get(id);
2164
+ if (entry) {
2165
+ entry.score += 2;
2166
+ entry.reasons.push("sketch uses painting layers");
2167
+ }
2168
+ }
2169
+ }
2170
+ }
2171
+ }
2172
+ }
2173
+ if (input.context) {
2174
+ const words = input.context.toLowerCase().split(/\W+/);
2175
+ for (const word of words) {
2176
+ const matched = CONTEXT_KEYWORDS[word];
2177
+ if (matched) {
2178
+ for (const skillId of matched) {
2179
+ const entry = scored.get(skillId);
2180
+ if (entry) {
2181
+ entry.score += 2;
2182
+ if (!entry.reasons.includes(`matches context keyword "${word}"`)) {
2183
+ entry.reasons.push(`matches context keyword "${word}"`);
2184
+ }
2185
+ }
2186
+ }
2187
+ }
2188
+ }
2189
+ }
2190
+ if (!input.sketchId && !input.context) {
2191
+ for (const skill of allSkills) {
2192
+ if (skill.category === "process") {
2193
+ const entry = scored.get(skill.id);
2194
+ entry.score += 2;
2195
+ entry.reasons.push("process knowledge is broadly applicable");
2196
+ }
2197
+ }
2198
+ }
2199
+ const ranked = allSkills.map((skill) => ({
2200
+ id: skill.id,
2201
+ name: skill.name,
2202
+ category: skill.category,
2203
+ complexity: skill.complexity,
2204
+ description: skill.description,
2205
+ relevanceScore: scored.get(skill.id).score,
2206
+ rationale: scored.get(skill.id).reasons
2207
+ })).filter((s) => s.relevanceScore > 0).sort((a, b) => b.relevanceScore - a.relevanceScore).slice(0, 5);
2208
+ return {
2209
+ success: true,
2210
+ suggestions: ranked,
2211
+ total: ranked.length
2212
+ };
2213
+ }
2041
2214
 
2042
2215
  // src/tools/components.ts
2043
2216
  import { writeFile as writeFile4 } from "fs/promises";
@@ -2297,7 +2470,7 @@ async function captureHtml(options) {
2297
2470
  try {
2298
2471
  await page.setViewport({ width, height, deviceScaleFactor: 1 });
2299
2472
  await page.setContent(html, { waitUntil: "domcontentloaded", timeout: 3e4 });
2300
- await new Promise((resolve3) => setTimeout(resolve3, waitMs));
2473
+ await new Promise((resolve5) => setTimeout(resolve5, waitMs));
2301
2474
  const buffer = await page.screenshot({
2302
2475
  type: imageType,
2303
2476
  clip: { x: 0, y: 0, width, height },
@@ -2317,7 +2490,7 @@ async function captureHtmlMulti(options) {
2317
2490
  try {
2318
2491
  await page.setViewport({ width, height, deviceScaleFactor: 1 });
2319
2492
  await page.setContent(html, { waitUntil: "domcontentloaded", timeout: 3e4 });
2320
- await new Promise((resolve3) => setTimeout(resolve3, waitMs));
2493
+ await new Promise((resolve5) => setTimeout(resolve5, waitMs));
2321
2494
  const pngBuffer = await page.screenshot({
2322
2495
  type: "png",
2323
2496
  clip: { x: 0, y: 0, width, height }
@@ -2327,7 +2500,7 @@ async function captureHtmlMulti(options) {
2327
2500
  const inlineWidth = Math.round(width * scale);
2328
2501
  const inlineHeight = Math.round(height * scale);
2329
2502
  await page.setViewport({ width: inlineWidth, height: inlineHeight, deviceScaleFactor: 1 });
2330
- await new Promise((resolve3) => setTimeout(resolve3, 100));
2503
+ await new Promise((resolve5) => setTimeout(resolve5, 100));
2331
2504
  const jpegBuffer = await page.screenshot({
2332
2505
  type: "jpeg",
2333
2506
  quality: jpegQuality,
@@ -2488,216 +2661,1281 @@ async function captureBatch(state, input) {
2488
2661
  };
2489
2662
  }
2490
2663
 
2491
- // src/tools/export.ts
2492
- import { createWriteStream } from "fs";
2493
- import { stat as stat4, writeFile as writeFile6 } from "fs/promises";
2494
- import { dirname as dirname5 } from "path";
2495
- import archiver from "archiver";
2496
- import {
2497
- createDefaultRegistry as createDefaultRegistry3,
2498
- serializeGenart as serializeGenart4
2499
- } from "@genart-dev/core";
2500
- var registry3 = createDefaultRegistry3();
2501
- async function validateOutputPath(outputPath) {
2502
- const parentDir = dirname5(outputPath);
2503
- try {
2504
- const s = await stat4(parentDir);
2505
- if (!s.isDirectory()) {
2506
- throw new Error(`Parent directory does not exist: ${parentDir}`);
2507
- }
2508
- } catch (e) {
2509
- if (e instanceof Error && e.message.startsWith("Parent directory")) throw e;
2510
- throw new Error(`Parent directory does not exist: ${parentDir}`);
2511
- }
2512
- try {
2513
- await stat4(outputPath);
2514
- throw new Error(
2515
- `File already exists at ${outputPath}. Delete it first or use a different path.`
2516
- );
2517
- } catch (e) {
2518
- if (e instanceof Error && e.message.startsWith("File already exists")) throw e;
2664
+ // src/tools/critique.ts
2665
+ import { createDefaultSkillRegistry as createDefaultSkillRegistry2 } from "@genart-dev/core";
2666
+ var registry3 = createDefaultSkillRegistry2();
2667
+ var ALL_ASPECTS = [
2668
+ "composition",
2669
+ "color",
2670
+ "rhythm",
2671
+ "unity",
2672
+ "expression"
2673
+ ];
2674
+ var SEVERITY = {
2675
+ study: {
2676
+ level: "study",
2677
+ description: "Fast, exploratory \u2014 value the energy of discovery over polish",
2678
+ focus: "Is the core idea visible? Does the sketch capture a single insight?",
2679
+ tolerance: "High tolerance for roughness, imbalance, and incomplete resolution. Studies should feel alive, not finished."
2680
+ },
2681
+ sketch: {
2682
+ level: "sketch",
2683
+ description: "Intentional but rough \u2014 the idea should read clearly",
2684
+ focus: "Do composition and color serve the concept? Are parameters well-chosen?",
2685
+ tolerance: "Moderate tolerance. Unresolved edges and raw marks are fine, but the structure should be deliberate."
2686
+ },
2687
+ developed: {
2688
+ level: "developed",
2689
+ description: "Refined \u2014 every major decision should be justified",
2690
+ focus: "Do all elements work together? Is there a clear visual hierarchy? Does the palette feel cohesive?",
2691
+ tolerance: "Low tolerance for accidental imbalance. Rough areas should be intentional, not neglected."
2692
+ },
2693
+ exhibition: {
2694
+ level: "exhibition",
2695
+ description: "Polished \u2014 every element earns its place",
2696
+ focus: "Could you defend every choice? Does the piece hold up under sustained viewing? Is the concept fully realized?",
2697
+ tolerance: "Minimal tolerance. Each mark, color, and spatial relationship should feel inevitable."
2519
2698
  }
2699
+ };
2700
+ function buildCompositionFramework() {
2701
+ return {
2702
+ aspect: "composition",
2703
+ questions: [
2704
+ "Where does the eye land first? Is that the intended focal point?",
2705
+ "Is there a clear visual hierarchy (primary, secondary, tertiary)?",
2706
+ "How does the composition use the edges and corners of the canvas?",
2707
+ "Is negative space working actively or is it leftover?",
2708
+ "Does the arrangement feel balanced or intentionally unbalanced?"
2709
+ ],
2710
+ principles: [
2711
+ "Visual weight distribution \u2014 dense, dark, saturated, or detailed areas carry more weight",
2712
+ "Entry points and eye paths \u2014 the viewer needs a way in and a journey through the piece",
2713
+ "Edge tension \u2014 elements near canvas edges create tension; use this deliberately",
2714
+ "Rule of thirds / golden ratio \u2014 useful starting points, not rigid rules",
2715
+ "Figure-ground clarity \u2014 the relationship between positive and negative space"
2716
+ ],
2717
+ pitfalls: [
2718
+ "Centering everything \u2014 creates static compositions unless intentionally symmetrical",
2719
+ "Filling the canvas uniformly \u2014 denies the viewer rest areas and focal emphasis",
2720
+ "Tangent lines \u2014 elements barely touching edges or each other create visual discomfort",
2721
+ "Competing focal points \u2014 multiple areas of equal emphasis confuse the eye",
2722
+ "Ignoring the canvas aspect ratio \u2014 composition should respond to the format"
2723
+ ]
2724
+ };
2520
2725
  }
2521
- function algorithmExtension(rendererType) {
2522
- return rendererType === "glsl" ? ".glsl" : ".js";
2523
- }
2524
- function applyOverrides2(sketch, overrides) {
2525
- if (overrides.seed === void 0 && overrides.params === void 0) {
2526
- return sketch;
2527
- }
2528
- const newState = {
2529
- seed: overrides.seed ?? sketch.state.seed,
2530
- params: overrides.params ? { ...sketch.state.params, ...overrides.params } : sketch.state.params,
2531
- colorPalette: sketch.state.colorPalette
2726
+ function buildColorFramework() {
2727
+ return {
2728
+ aspect: "color",
2729
+ questions: [
2730
+ "Does the palette feel intentional or arbitrary?",
2731
+ "Is there a dominant color temperature (warm/cool) or a deliberate tension between them?",
2732
+ "How many distinct hues are active? Is that number serving the concept?",
2733
+ "Are value contrasts (light/dark) creating readable structure?",
2734
+ "Do any colors feel out of place \u2014 or is dissonance intentional?"
2735
+ ],
2736
+ principles: [
2737
+ "Color harmony \u2014 analogous, complementary, triadic, or split-complementary relationships",
2738
+ "Value structure \u2014 squint at the piece; the composition should read in grayscale",
2739
+ "Temperature as depth \u2014 warm advances, cool recedes (atmospheric perspective)",
2740
+ "Saturation as emphasis \u2014 high saturation draws the eye; use it sparingly for focus",
2741
+ "Color proportion \u2014 unequal amounts create interest (e.g., 60-30-10 ratio)"
2742
+ ],
2743
+ pitfalls: [
2744
+ "Too many fully saturated colors competing for attention",
2745
+ "No value range \u2014 all mid-tones flatten the piece",
2746
+ "Random color assignment \u2014 palette should derive from concept, not just randomness",
2747
+ "Ignoring simultaneous contrast \u2014 adjacent colors alter each other's appearance",
2748
+ "Uniform opacity everywhere \u2014 varying transparency adds depth and atmosphere"
2749
+ ]
2532
2750
  };
2533
- return { ...sketch, state: newState };
2534
2751
  }
2535
- async function exportSketch(state, input) {
2536
- state.requireWorkspace();
2537
- const loaded = state.requireSketch(input.sketchId);
2538
- const sketch = applyOverrides2(loaded.definition, {
2539
- seed: input.seed,
2540
- params: input.params
2541
- });
2542
- await validateOutputPath(input.outputPath);
2543
- const adapter = registry3.resolve(sketch.renderer.type);
2544
- if (!adapter) {
2545
- throw new Error(
2546
- `Unsupported renderer type: '${sketch.renderer.type}'`
2547
- );
2548
- }
2549
- switch (input.format) {
2550
- case "html":
2551
- return await exportHtml(sketch, input.outputPath);
2552
- case "png":
2553
- return await exportPng(sketch, input);
2554
- case "svg":
2555
- return await exportSvg(sketch, input);
2556
- case "algorithm":
2557
- return await exportAlgorithm(sketch, input.outputPath);
2558
- case "zip":
2559
- return await exportZip(sketch, input);
2560
- default:
2561
- throw new Error(`Unsupported export format: '${input.format}'`);
2562
- }
2752
+ function buildRhythmFramework() {
2753
+ return {
2754
+ aspect: "rhythm",
2755
+ questions: [
2756
+ "Is there a repeating visual motif or interval?",
2757
+ "Does the rhythm accelerate, decelerate, or remain steady?",
2758
+ "Are there moments of syncopation \u2014 unexpected breaks in the pattern?",
2759
+ "Does the rhythm contribute to or fight against the composition?",
2760
+ "Is there scale variation \u2014 does the motif appear at multiple sizes?"
2761
+ ],
2762
+ principles: [
2763
+ "Regular rhythm creates calm and order; irregular rhythm creates energy",
2764
+ "Progressive rhythm (gradual change) creates movement and depth",
2765
+ "Alternating rhythm adds complexity without chaos",
2766
+ "Rhythm at multiple scales (fractal repetition) creates richness",
2767
+ "Silence (empty intervals) is as important as sound (marked intervals)"
2768
+ ],
2769
+ pitfalls: [
2770
+ "Perfectly regular grids without variation feel mechanical, not generative",
2771
+ "Random distribution reads as noise, not rhythm",
2772
+ "Single-scale repetition feels monotonous \u2014 vary size, spacing, or density",
2773
+ "Rhythm that ignores the composition's focal structure",
2774
+ "Over-complexity \u2014 too many overlapping rhythms create visual noise"
2775
+ ]
2776
+ };
2563
2777
  }
2564
- async function exportHtml(sketch, outputPath) {
2565
- const adapter = registry3.resolve(sketch.renderer.type);
2566
- const html = adapter.generateStandaloneHTML(sketch);
2567
- const content = Buffer.from(html, "utf-8");
2568
- await writeFile6(outputPath, content);
2778
+ function buildUnityFramework() {
2569
2779
  return {
2570
- success: true,
2571
- sketchId: sketch.id,
2572
- format: "html",
2573
- outputPath,
2574
- fileSize: content.byteLength,
2575
- renderer: sketch.renderer.type
2780
+ aspect: "unity",
2781
+ questions: [
2782
+ "Does the piece feel like one cohesive work or disconnected parts?",
2783
+ "Is there a unifying visual language (consistent mark quality, shape vocabulary)?",
2784
+ "Do the parameters work together or do some feel bolted on?",
2785
+ "Would removing any element weaken the whole?",
2786
+ "Does the algorithm express a single clear idea?"
2787
+ ],
2788
+ principles: [
2789
+ "Unity through repetition \u2014 shared elements tie the composition together",
2790
+ "Unity through proximity \u2014 grouped elements feel related",
2791
+ "Unity through continuation \u2014 aligned elements create visual connections",
2792
+ "Variety within unity \u2014 enough variation to hold interest, enough consistency to cohere",
2793
+ "Conceptual unity \u2014 all visual decisions serve the stated philosophy"
2794
+ ],
2795
+ pitfalls: [
2796
+ "Feature accumulation \u2014 adding elements that don't serve the core concept",
2797
+ "Inconsistent mark quality \u2014 mixing precise geometry with organic marks without intention",
2798
+ "Disconnected color and form \u2014 palette that doesn't relate to the spatial structure",
2799
+ "Parameter sprawl \u2014 too many controls that don't interact meaningfully",
2800
+ "Style mixing without integration \u2014 combining techniques that don't speak to each other"
2801
+ ]
2576
2802
  };
2577
2803
  }
2578
- async function exportPng(sketch, input) {
2579
- const adapter = registry3.resolve(sketch.renderer.type);
2580
- const html = adapter.generateStandaloneHTML(sketch);
2581
- const width = input.width ?? sketch.canvas.width;
2582
- const height = input.height ?? sketch.canvas.height;
2583
- const result = await captureHtml({ html, width, height });
2584
- await writeFile6(input.outputPath, result.bytes);
2804
+ function buildExpressionFramework() {
2585
2805
  return {
2586
- success: true,
2587
- sketchId: sketch.id,
2588
- format: "png",
2589
- outputPath: input.outputPath,
2590
- fileSize: result.bytes.byteLength,
2591
- renderer: sketch.renderer.type
2806
+ aspect: "expression",
2807
+ questions: [
2808
+ "What mood or feeling does this piece evoke?",
2809
+ "Is the generative process visible in the output? Should it be?",
2810
+ "Does the algorithm's logic contribute to the emotional quality?",
2811
+ "Is there a sense of the unexpected \u2014 does the piece surprise even its creator?",
2812
+ "Does the philosophy statement match the visual experience?"
2813
+ ],
2814
+ principles: [
2815
+ "Generative art is a conversation between intention and emergence",
2816
+ "The algorithm is a medium \u2014 its constraints and affordances shape expression",
2817
+ "Controlled randomness creates life; pure randomness creates noise",
2818
+ "The seed is a collaborator \u2014 different seeds should produce meaningfully different moods",
2819
+ "Process and result are both the artwork \u2014 the code embodies artistic decisions"
2820
+ ],
2821
+ pitfalls: [
2822
+ "Over-control \u2014 leaving no room for generative surprise",
2823
+ "Under-control \u2014 no discernible artistic intention behind the randomness",
2824
+ "Technique as end \u2014 impressive code that produces emotionally flat output",
2825
+ "Derivative work \u2014 reproducing established generative art tropes without adding perspective",
2826
+ "Mismatched intent \u2014 the philosophy says one thing but the visual says another"
2827
+ ]
2592
2828
  };
2593
2829
  }
2594
- async function exportSvg(sketch, input) {
2595
- const width = input.width ?? sketch.canvas.width;
2596
- const height = input.height ?? sketch.canvas.height;
2597
- if (sketch.renderer.type === "svg") {
2598
- const content2 = Buffer.from(sketch.algorithm, "utf-8");
2599
- await writeFile6(input.outputPath, content2);
2600
- return {
2601
- success: true,
2602
- sketchId: sketch.id,
2603
- format: "svg",
2604
- outputPath: input.outputPath,
2605
- fileSize: content2.byteLength,
2606
- renderer: sketch.renderer.type,
2607
- notice: null
2608
- };
2830
+ var ASPECT_BUILDERS = {
2831
+ composition: buildCompositionFramework,
2832
+ color: buildColorFramework,
2833
+ rhythm: buildRhythmFramework,
2834
+ unity: buildUnityFramework,
2835
+ expression: buildExpressionFramework
2836
+ };
2837
+ async function critiqueSketch(state, input) {
2838
+ state.requireWorkspace();
2839
+ let sketchId;
2840
+ if (input.sketchId) {
2841
+ sketchId = input.sketchId;
2842
+ } else if (state.selection.size > 0) {
2843
+ sketchId = [...state.selection][0];
2844
+ } else {
2845
+ throw new Error("No sketch specified and nothing selected");
2609
2846
  }
2610
- const adapter = registry3.resolve(sketch.renderer.type);
2611
- const html = adapter.generateStandaloneHTML(sketch);
2612
- const result = await captureHtml({ html, width, height });
2613
- const b64 = Buffer.from(result.bytes).toString("base64");
2614
- const svg = `<?xml version="1.0" encoding="UTF-8"?>
2615
- <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
2616
- width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
2617
- <image width="${width}" height="${height}"
2618
- href="data:image/png;base64,${b64}"/>
2619
- </svg>`;
2620
- const content = Buffer.from(svg, "utf-8");
2621
- await writeFile6(input.outputPath, content);
2622
- return {
2847
+ const loaded = state.requireSketch(sketchId);
2848
+ const sketch = loaded.definition;
2849
+ const capture = await captureScreenshot(state, {
2850
+ target: "sketch",
2851
+ sketchId,
2852
+ previewSize: input.previewSize ?? 400
2853
+ });
2854
+ const aspects = input.aspects ?? [...ALL_ASPECTS];
2855
+ const frameworks = aspects.map((a) => ASPECT_BUILDERS[a]());
2856
+ const level = sketch.compositionLevel ?? "sketch";
2857
+ const severity = SEVERITY[level] ?? SEVERITY["sketch"];
2858
+ const relevantSkills = gatherRelevantSkills(aspects);
2859
+ const metadata = {
2623
2860
  success: true,
2624
- sketchId: sketch.id,
2625
- format: "svg",
2626
- outputPath: input.outputPath,
2627
- fileSize: content.byteLength,
2628
- renderer: sketch.renderer.type,
2629
- notice: "Non-SVG renderer \u2014 rasterized PNG embedded in SVG container"
2861
+ sketchId,
2862
+ title: sketch.title,
2863
+ compositionLevel: level,
2864
+ philosophy: sketch.philosophy ?? null,
2865
+ severity: {
2866
+ level: severity.level,
2867
+ description: severity.description,
2868
+ focus: severity.focus,
2869
+ tolerance: severity.tolerance
2870
+ },
2871
+ frameworks,
2872
+ relevantSkills,
2873
+ instructions: [
2874
+ "Use the image above and the frameworks below to perform a structured self-critique.",
2875
+ `Calibrate your critique to the ${severity.level} level: ${severity.description}`,
2876
+ "For each aspect, answer the questions, check the principles, and watch for the pitfalls.",
2877
+ "Be honest but constructive \u2014 identify what works as well as what could improve.",
2878
+ "End with 2-3 specific, actionable improvements ranked by impact."
2879
+ ]
2630
2880
  };
2631
- }
2632
- async function exportAlgorithm(sketch, outputPath) {
2633
- const content = Buffer.from(sketch.algorithm, "utf-8");
2634
- await writeFile6(outputPath, content);
2635
2881
  return {
2636
- success: true,
2637
- sketchId: sketch.id,
2638
- format: "algorithm",
2639
- outputPath,
2640
- fileSize: content.byteLength,
2641
- renderer: sketch.renderer.type
2882
+ metadata,
2883
+ previewJpegBase64: capture.previewJpegBase64
2642
2884
  };
2643
2885
  }
2644
- async function exportZip(sketch, input) {
2645
- const adapter = registry3.resolve(sketch.renderer.type);
2646
- const width = input.width ?? sketch.canvas.width;
2647
- const height = input.height ?? sketch.canvas.height;
2648
- const html = adapter.generateStandaloneHTML(sketch);
2649
- const genartJson = serializeGenart4(sketch);
2650
- const algorithm = sketch.algorithm;
2651
- const algExt = algorithmExtension(sketch.renderer.type);
2652
- const captureResult = await captureHtml({ html, width, height });
2653
- const output = createWriteStream(input.outputPath);
2654
- const archive = archiver("zip", { zlib: { level: 9 } });
2655
- const finished = new Promise((resolve3, reject) => {
2656
- output.on("close", resolve3);
2657
- archive.on("error", reject);
2886
+ async function compareSketches(state, input) {
2887
+ state.requireWorkspace();
2888
+ const ids = input.sketchIds;
2889
+ if (ids.length < 2) {
2890
+ throw new Error("compare_sketches requires at least 2 sketch IDs");
2891
+ }
2892
+ if (ids.length > 4) {
2893
+ throw new Error("compare_sketches supports a maximum of 4 sketches");
2894
+ }
2895
+ const sketchInfos = ids.map((id) => {
2896
+ const loaded = state.requireSketch(id);
2897
+ return {
2898
+ id,
2899
+ title: loaded.definition.title,
2900
+ compositionLevel: loaded.definition.compositionLevel ?? "sketch",
2901
+ philosophy: loaded.definition.philosophy ?? null,
2902
+ renderer: loaded.definition.renderer.type,
2903
+ seed: loaded.definition.state.seed
2904
+ };
2658
2905
  });
2659
- archive.pipe(output);
2660
- archive.append(html, { name: `${sketch.id}.html` });
2661
- archive.append(Buffer.from(captureResult.bytes), { name: `${sketch.id}.png` });
2662
- archive.append(algorithm, { name: `${sketch.id}${algExt}` });
2663
- archive.append(genartJson, { name: `${sketch.id}.genart` });
2664
- await archive.finalize();
2665
- await finished;
2666
- const s = await stat4(input.outputPath);
2667
- return {
2906
+ const batchResult = await captureBatch(state, {
2907
+ sketchIds: ids,
2908
+ previewSize: input.previewSize ?? 300
2909
+ });
2910
+ const previews = batchResult.items.map((item) => ({
2911
+ sketchId: item.metadata["sketchId"],
2912
+ inlineJpegBase64: item.inlineJpegBase64
2913
+ }));
2914
+ const aspects = input.aspects ?? [...ALL_ASPECTS];
2915
+ const frameworks = aspects.map((a) => ASPECT_BUILDERS[a]());
2916
+ const comparisonQuestions = aspects.map((aspect) => ({
2917
+ aspect,
2918
+ questions: buildComparisonQuestions(aspect, sketchInfos.length)
2919
+ }));
2920
+ const metadata = {
2668
2921
  success: true,
2669
- sketchId: sketch.id,
2670
- format: "zip",
2671
- outputPath: input.outputPath,
2672
- fileSize: s.size,
2673
- renderer: sketch.renderer.type,
2674
- contents: [
2675
- `${sketch.id}.html`,
2676
- `${sketch.id}.png`,
2677
- `${sketch.id}${algExt}`,
2678
- `${sketch.id}.genart`
2922
+ sketches: sketchInfos,
2923
+ aspects,
2924
+ frameworks,
2925
+ comparisonQuestions,
2926
+ instructions: [
2927
+ `Compare the ${ids.length} sketches shown above across the specified aspects.`,
2928
+ "For each aspect, use the framework questions and comparison questions to analyze differences.",
2929
+ "Identify which sketch handles each aspect most effectively and why.",
2930
+ "Note where sketches complement each other \u2014 techniques from one could improve another.",
2931
+ "End with a ranking per aspect and overall, with specific observations justifying each placement."
2932
+ ]
2933
+ };
2934
+ return { metadata, previews };
2935
+ }
2936
+ function buildComparisonQuestions(aspect, count) {
2937
+ const base = {
2938
+ composition: [
2939
+ "Which sketch has the strongest focal point?",
2940
+ "How do the compositions differ in their use of space?",
2941
+ "Which creates the most effective visual hierarchy?"
2942
+ ],
2943
+ color: [
2944
+ "Which palette feels most intentional?",
2945
+ "How do the value ranges compare \u2014 which has the strongest lights and darks?",
2946
+ "Which color temperature creates the most effective mood?"
2947
+ ],
2948
+ rhythm: [
2949
+ "Which sketch has the most engaging visual rhythm?",
2950
+ "How do the rhythmic structures differ \u2014 regular vs progressive vs irregular?",
2951
+ "Which achieves the best balance of repetition and variation?"
2952
+ ],
2953
+ unity: [
2954
+ "Which sketch feels most cohesive as a single work?",
2955
+ "Where does unity break down in each \u2014 what elements feel disconnected?",
2956
+ "Which has the tightest relationship between concept and execution?"
2957
+ ],
2958
+ expression: [
2959
+ "Which sketch evokes the strongest emotional response?",
2960
+ "How does each sketch's generative process contribute to its expression?",
2961
+ "Which most successfully balances intention with emergence?"
2679
2962
  ]
2680
2963
  };
2964
+ const questions = [...base[aspect]];
2965
+ if (count > 2) {
2966
+ questions.push(
2967
+ `Could elements from different sketches be combined to create something stronger?`
2968
+ );
2969
+ }
2970
+ return questions;
2971
+ }
2972
+ function gatherRelevantSkills(aspects) {
2973
+ const aspectToCategory = {
2974
+ composition: ["composition"],
2975
+ color: ["color"],
2976
+ rhythm: ["composition"],
2977
+ unity: ["composition", "color"],
2978
+ expression: ["process"]
2979
+ };
2980
+ const seen = /* @__PURE__ */ new Set();
2981
+ const result = [];
2982
+ for (const aspect of aspects) {
2983
+ const categories = aspectToCategory[aspect];
2984
+ for (const cat of categories) {
2985
+ const skills = registry3.list(cat);
2986
+ for (const skill of skills) {
2987
+ if (!seen.has(skill.id)) {
2988
+ seen.add(skill.id);
2989
+ result.push({ id: skill.id, name: skill.name, relevantTo: aspect });
2990
+ }
2991
+ }
2992
+ }
2993
+ }
2994
+ return result;
2681
2995
  }
2682
2996
 
2683
- // src/tools/design.ts
2684
- function requireSketchId(state, args) {
2685
- return args.sketchId ?? state.requireSelectedSketchId();
2997
+ // src/tools/series.ts
2998
+ import { writeFile as writeFile6 } from "fs/promises";
2999
+ import { basename as basename8, dirname as dirname5, resolve as resolve2 } from "path";
3000
+ import {
3001
+ serializeGenart as serializeGenart4,
3002
+ serializeWorkspace as serializeWorkspace3
3003
+ } from "@genart-dev/core";
3004
+ function now6() {
3005
+ return (/* @__PURE__ */ new Date()).toISOString();
2686
3006
  }
2687
- var BLEND_MODES = [
2688
- "normal",
2689
- "multiply",
2690
- "screen",
2691
- "overlay",
2692
- "darken",
2693
- "lighten",
2694
- "color-dodge",
2695
- "color-burn",
2696
- "hard-light",
2697
- "soft-light",
2698
- "difference",
2699
- "exclusion",
2700
- "hue",
3007
+ var KEBAB_RE2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3008
+ function validateKebabId2(id) {
3009
+ if (!KEBAB_RE2.test(id)) {
3010
+ throw new Error(
3011
+ "ID must be kebab-case: lowercase letters, numbers, hyphens"
3012
+ );
3013
+ }
3014
+ }
3015
+ var VALID_STAGES = [
3016
+ "studies",
3017
+ "drafts",
3018
+ "refinements",
3019
+ "finals"
3020
+ ];
3021
+ var STAGE_TO_LEVEL = {
3022
+ studies: "study",
3023
+ drafts: "sketch",
3024
+ refinements: "developed",
3025
+ finals: "exhibition"
3026
+ };
3027
+ var LEVEL_SCALE = {
3028
+ study: 1,
3029
+ sketch: 1,
3030
+ developed: 1.5,
3031
+ exhibition: 2
3032
+ };
3033
+ async function createSeries(state, input) {
3034
+ const ws = state.requireWorkspace();
3035
+ const id = input.label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
3036
+ if (!id) {
3037
+ throw new Error("Could not derive a valid ID from the label");
3038
+ }
3039
+ if (ws.series?.some((s) => s.id === id)) {
3040
+ throw new Error(`Series with ID '${id}' already exists in workspace`);
3041
+ }
3042
+ const stages = input.stages ?? [...VALID_STAGES];
3043
+ for (const stage of stages) {
3044
+ if (!VALID_STAGES.includes(stage)) {
3045
+ throw new Error(
3046
+ `Invalid stage: '${stage}'. Valid stages: ${VALID_STAGES.join(", ")}`
3047
+ );
3048
+ }
3049
+ }
3050
+ const sketchFiles = input.sketchFiles ?? [];
3051
+ for (const file of sketchFiles) {
3052
+ const found = ws.sketches.some((s) => s.file === file);
3053
+ if (!found) {
3054
+ throw new Error(
3055
+ `Sketch file '${file}' not found in workspace`
3056
+ );
3057
+ }
3058
+ }
3059
+ const series = {
3060
+ id,
3061
+ label: input.label,
3062
+ narrative: input.narrative,
3063
+ intent: input.intent,
3064
+ ...input.progression ? { progression: input.progression } : {},
3065
+ stages,
3066
+ sketchFiles
3067
+ };
3068
+ state.workspace = {
3069
+ ...ws,
3070
+ modified: now6(),
3071
+ series: [...ws.series ?? [], series]
3072
+ };
3073
+ const workspaceJson = serializeWorkspace3(state.workspace);
3074
+ if (!state.remoteMode) {
3075
+ await writeFile6(state.workspacePath, workspaceJson, "utf-8");
3076
+ }
3077
+ state.emitMutation("workspace:updated", { seriesAdded: id });
3078
+ return {
3079
+ success: true,
3080
+ series: {
3081
+ id,
3082
+ label: input.label,
3083
+ narrative: input.narrative,
3084
+ intent: input.intent,
3085
+ stages,
3086
+ sketchCount: sketchFiles.length
3087
+ },
3088
+ workspaceContent: workspaceJson
3089
+ };
3090
+ }
3091
+ async function developConcept(_state, input) {
3092
+ const medium = input.medium ?? "p5";
3093
+ return {
3094
+ success: true,
3095
+ conceptPlan: {
3096
+ concept: input.concept,
3097
+ medium,
3098
+ mood: {
3099
+ instruction: "Define the emotional quality this concept should evoke.",
3100
+ prompts: [
3101
+ "What feeling should the viewer experience?",
3102
+ "Is this contemplative, energetic, unsettling, serene?",
3103
+ "What time of day, season, or environment does this concept suggest?"
3104
+ ]
3105
+ },
3106
+ palette: {
3107
+ instruction: "Design a color strategy that serves the mood.",
3108
+ prompts: [
3109
+ "What color temperature dominates (warm/cool)?",
3110
+ "How many distinct hues are needed?",
3111
+ "Should saturation be high (bold, graphic) or low (subtle, atmospheric)?",
3112
+ "What value range (light-to-dark contrast) supports the concept?"
3113
+ ]
3114
+ },
3115
+ composition: {
3116
+ instruction: "Plan the spatial structure.",
3117
+ prompts: [
3118
+ "Where should the viewer's eye land first?",
3119
+ "Is the composition centered, asymmetric, or edge-driven?",
3120
+ "How does negative space contribute to the concept?",
3121
+ "What rhythm (regular, progressive, chaotic) serves the idea?"
3122
+ ]
3123
+ },
3124
+ skills: {
3125
+ instruction: "Identify design skills to load for this concept.",
3126
+ prompts: [
3127
+ "Which composition skill applies (rule-of-thirds, golden-ratio, gestalt)?",
3128
+ "Which color skill applies (color-harmony, color-temperature, simultaneous-contrast)?",
3129
+ "Are there process skills needed (layering-strategy, iterative-refinement, thumbnail-studies)?",
3130
+ "Consider using `suggest_skills` with the concept as context."
3131
+ ]
3132
+ },
3133
+ seriesStructure: {
3134
+ instruction: "Plan the body of work.",
3135
+ prompts: [
3136
+ "How many studies should explore the core idea (3-6 recommended)?",
3137
+ "What aspect varies between studies (color, density, rhythm, scale)?",
3138
+ "Which studies should be developed further into drafts?",
3139
+ "What progression tells the most compelling story?"
3140
+ ],
3141
+ recommendedStages: ["studies", "drafts", "refinements", "finals"]
3142
+ }
3143
+ },
3144
+ nextSteps: [
3145
+ "1. Use `create_series` with a label, narrative, and intent derived from this plan.",
3146
+ "2. Create 3-6 study-level sketches using `create_sketch` with compositionLevel: 'study'.",
3147
+ "3. Use `critique_sketch` on each study to evaluate against the concept.",
3148
+ "4. Use `promote_sketch` to advance the best studies to drafts.",
3149
+ "5. Iterate: critique \u2192 refine \u2192 promote through stages.",
3150
+ "6. Use `series_summary` to capture the full progression."
3151
+ ]
3152
+ };
3153
+ }
3154
+ async function seriesSummary(state, input) {
3155
+ const ws = state.requireWorkspace();
3156
+ const series = ws.series?.find((s) => s.id === input.seriesId);
3157
+ if (!series) {
3158
+ throw new Error(`Series '${input.seriesId}' not found in workspace`);
3159
+ }
3160
+ const sketchInfos = [];
3161
+ const loadedIds = [];
3162
+ for (const file of series.sketchFiles) {
3163
+ let found = false;
3164
+ for (const [id, loaded] of state.sketches) {
3165
+ if (basename8(loaded.path) === file) {
3166
+ const def = loaded.definition;
3167
+ sketchInfos.push({
3168
+ id,
3169
+ title: def.title,
3170
+ file,
3171
+ compositionLevel: def.compositionLevel ?? "sketch",
3172
+ lineage: def.lineage ?? null,
3173
+ renderer: def.renderer.type,
3174
+ canvas: `${def.canvas.width}x${def.canvas.height}`,
3175
+ seed: def.state.seed,
3176
+ parameterCount: def.parameters.length,
3177
+ colorCount: def.colors.length,
3178
+ philosophy: def.philosophy ?? null
3179
+ });
3180
+ loadedIds.push(id);
3181
+ found = true;
3182
+ break;
3183
+ }
3184
+ }
3185
+ if (!found) {
3186
+ sketchInfos.push({ file, status: "not loaded" });
3187
+ }
3188
+ }
3189
+ let previews;
3190
+ if (input.captureScreenshots !== false && loadedIds.length > 0) {
3191
+ const batchResult = await captureBatch(state, {
3192
+ sketchIds: loadedIds,
3193
+ previewSize: input.previewSize ?? 300
3194
+ });
3195
+ previews = batchResult.items.map((item) => ({
3196
+ sketchId: item.metadata["sketchId"],
3197
+ inlineJpegBase64: item.inlineJpegBase64
3198
+ }));
3199
+ }
3200
+ const metadata = {
3201
+ success: true,
3202
+ series: {
3203
+ id: series.id,
3204
+ label: series.label,
3205
+ narrative: series.narrative,
3206
+ intent: series.intent,
3207
+ progression: series.progression ?? null,
3208
+ stages: series.stages ?? null
3209
+ },
3210
+ sketches: sketchInfos,
3211
+ summary: {
3212
+ totalSketches: series.sketchFiles.length,
3213
+ loadedSketches: loadedIds.length,
3214
+ compositionLevels: countBy(
3215
+ sketchInfos.filter((s) => s["compositionLevel"]).map((s) => s["compositionLevel"])
3216
+ )
3217
+ },
3218
+ instructions: [
3219
+ "Review the series progression from studies through finals.",
3220
+ "Evaluate whether the narrative and intent are reflected in the body of work.",
3221
+ "Consider: does each sketch build on its predecessors? Is there a clear evolution?",
3222
+ "Identify the strongest and weakest pieces. What makes them succeed or fail?",
3223
+ "Document insights and decisions in the series narrative."
3224
+ ]
3225
+ };
3226
+ return { metadata, previews };
3227
+ }
3228
+ async function promoteSketch(state, input) {
3229
+ const ws = state.requireWorkspace();
3230
+ const source = state.requireSketch(input.sketchId);
3231
+ const sourceDef = source.definition;
3232
+ if (!VALID_STAGES.includes(input.toStage)) {
3233
+ throw new Error(
3234
+ `Invalid stage: '${input.toStage}'. Valid stages: ${VALID_STAGES.join(", ")}`
3235
+ );
3236
+ }
3237
+ const targetLevel = STAGE_TO_LEVEL[input.toStage];
3238
+ const scale = LEVEL_SCALE[targetLevel];
3239
+ const newId = input.newId ?? `${input.sketchId}-${input.toStage.replace(/s$/, "")}`;
3240
+ validateKebabId2(newId);
3241
+ if (state.getSketch(newId)) {
3242
+ throw new Error(`Sketch with ID '${newId}' already exists`);
3243
+ }
3244
+ const newWidth = Math.round(sourceDef.canvas.width * scale);
3245
+ const newHeight = Math.round(sourceDef.canvas.height * scale);
3246
+ const sourceGeneration = sourceDef.lineage?.generation ?? 1;
3247
+ const title = input.title ?? `${sourceDef.title} (${input.toStage.replace(/s$/, "")})`;
3248
+ const ts = now6();
3249
+ const promotedDef = {
3250
+ genart: "1.1",
3251
+ id: newId,
3252
+ title,
3253
+ created: ts,
3254
+ modified: ts,
3255
+ renderer: sourceDef.renderer,
3256
+ canvas: { width: newWidth, height: newHeight },
3257
+ parameters: [...sourceDef.parameters],
3258
+ colors: [...sourceDef.colors],
3259
+ state: {
3260
+ seed: sourceDef.state.seed,
3261
+ params: { ...sourceDef.state.params },
3262
+ colorPalette: [...sourceDef.state.colorPalette]
3263
+ },
3264
+ algorithm: sourceDef.algorithm,
3265
+ compositionLevel: targetLevel,
3266
+ lineage: {
3267
+ parentId: input.sketchId,
3268
+ parentTitle: sourceDef.title,
3269
+ generation: sourceGeneration + 1
3270
+ },
3271
+ ...sourceDef.philosophy ? { philosophy: sourceDef.philosophy } : {},
3272
+ ...sourceDef.themes ? { themes: [...sourceDef.themes] } : {},
3273
+ ...sourceDef.skills ? { skills: [...sourceDef.skills] } : {},
3274
+ ...sourceDef.components ? { components: sourceDef.components } : {},
3275
+ ...sourceDef.symbols ? { symbols: sourceDef.symbols } : {},
3276
+ ...input.agent ? { agent: input.agent } : {},
3277
+ ...input.model ? { model: input.model } : {}
3278
+ };
3279
+ const sourceDir = dirname5(source.path);
3280
+ const newPath = resolve2(sourceDir, `${newId}.genart`);
3281
+ const json = serializeGenart4(promotedDef);
3282
+ if (!state.remoteMode) {
3283
+ await writeFile6(newPath, json, "utf-8");
3284
+ }
3285
+ state.sketches.set(newId, { definition: promotedDef, path: newPath });
3286
+ const sourceRef = ws.sketches.find(
3287
+ (s) => s.file === basename8(source.path)
3288
+ );
3289
+ const position = sourceRef ? { x: sourceRef.position.x, y: sourceRef.position.y + sourceDef.canvas.height + 200 } : { x: 0, y: 0 };
3290
+ const file = basename8(newPath);
3291
+ state.workspace = {
3292
+ ...ws,
3293
+ modified: ts,
3294
+ sketches: [...ws.sketches, { file, position }]
3295
+ };
3296
+ if (input.seriesId) {
3297
+ const seriesIndex = state.workspace.series?.findIndex(
3298
+ (s) => s.id === input.seriesId
3299
+ );
3300
+ if (seriesIndex !== void 0 && seriesIndex >= 0 && state.workspace.series) {
3301
+ const series = state.workspace.series[seriesIndex];
3302
+ const updatedSeries = {
3303
+ ...series,
3304
+ sketchFiles: [...series.sketchFiles, file]
3305
+ };
3306
+ state.workspace = {
3307
+ ...state.workspace,
3308
+ series: state.workspace.series.map(
3309
+ (s, i) => i === seriesIndex ? updatedSeries : s
3310
+ )
3311
+ };
3312
+ }
3313
+ }
3314
+ const workspaceJson = serializeWorkspace3(state.workspace);
3315
+ if (!state.remoteMode) {
3316
+ await writeFile6(state.workspacePath, workspaceJson, "utf-8");
3317
+ }
3318
+ state.emitMutation("sketch:created", { id: newId, path: newPath });
3319
+ state.emitMutation("workspace:updated", { added: file });
3320
+ return {
3321
+ success: true,
3322
+ sourceId: input.sketchId,
3323
+ promotedSketch: {
3324
+ id: newId,
3325
+ title,
3326
+ path: newPath,
3327
+ compositionLevel: targetLevel,
3328
+ stage: input.toStage,
3329
+ canvas: { width: newWidth, height: newHeight },
3330
+ position,
3331
+ lineage: promotedDef.lineage
3332
+ },
3333
+ ...scale > 1 ? {
3334
+ canvasUpscaled: `Canvas scaled ${scale}x: ${sourceDef.canvas.width}x${sourceDef.canvas.height} \u2192 ${newWidth}x${newHeight}`
3335
+ } : {},
3336
+ fileContent: json,
3337
+ workspaceContent: workspaceJson
3338
+ };
3339
+ }
3340
+ function countBy(items) {
3341
+ const counts = {};
3342
+ for (const item of items) {
3343
+ counts[item] = (counts[item] ?? 0) + 1;
3344
+ }
3345
+ return counts;
3346
+ }
3347
+
3348
+ // src/tools/reference.ts
3349
+ import { copyFile, mkdir, readFile as readFile4 } from "fs/promises";
3350
+ import { basename as basename9, dirname as dirname6, extname, resolve as resolve3 } from "path";
3351
+ import {
3352
+ serializeGenart as serializeGenart5,
3353
+ serializeWorkspace as serializeWorkspace4
3354
+ } from "@genart-dev/core";
3355
+ import { writeFile as writeFile7 } from "fs/promises";
3356
+ function now7() {
3357
+ return (/* @__PURE__ */ new Date()).toISOString();
3358
+ }
3359
+ var KEBAB_RE3 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3360
+ function validateKebabId3(id) {
3361
+ if (!KEBAB_RE3.test(id)) {
3362
+ throw new Error(
3363
+ "ID must be kebab-case: lowercase letters, numbers, hyphens"
3364
+ );
3365
+ }
3366
+ }
3367
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
3368
+ ".png",
3369
+ ".jpg",
3370
+ ".jpeg",
3371
+ ".gif",
3372
+ ".webp",
3373
+ ".bmp",
3374
+ ".tiff",
3375
+ ".svg"
3376
+ ]);
3377
+ function isImageFile(path) {
3378
+ return IMAGE_EXTENSIONS.has(extname(path).toLowerCase());
3379
+ }
3380
+ var VALID_REFERENCE_TYPES = [
3381
+ "image",
3382
+ "artwork",
3383
+ "photograph",
3384
+ "texture",
3385
+ "palette"
3386
+ ];
3387
+ async function addReference(state, input) {
3388
+ const ws = state.requireWorkspace();
3389
+ if (!isImageFile(input.image)) {
3390
+ throw new Error(
3391
+ `Not a recognized image file: ${input.image}. Supported: ${[...IMAGE_EXTENSIONS].join(", ")}`
3392
+ );
3393
+ }
3394
+ const id = input.id ?? basename9(input.image, extname(input.image)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
3395
+ if (!id) {
3396
+ throw new Error("Could not derive a valid ID from the image filename");
3397
+ }
3398
+ validateKebabId3(id);
3399
+ const refType = input.type ?? "image";
3400
+ if (!VALID_REFERENCE_TYPES.includes(refType)) {
3401
+ throw new Error(
3402
+ `Invalid reference type: '${refType}'. Valid types: ${VALID_REFERENCE_TYPES.join(", ")}`
3403
+ );
3404
+ }
3405
+ const workspaceDir = dirname6(state.workspacePath);
3406
+ const refsDir = resolve3(workspaceDir, "references");
3407
+ await mkdir(refsDir, { recursive: true });
3408
+ const ext = extname(input.image);
3409
+ const destFilename = `${id}${ext}`;
3410
+ const destPath = resolve3(refsDir, destFilename);
3411
+ const relativePath = `references/${destFilename}`;
3412
+ if (!state.remoteMode) {
3413
+ await copyFile(resolve3(input.image), destPath);
3414
+ }
3415
+ const ref = {
3416
+ id,
3417
+ type: refType,
3418
+ path: relativePath,
3419
+ ...input.source ? { source: input.source } : {}
3420
+ };
3421
+ let attachedTo;
3422
+ let workspaceJson;
3423
+ let sketchJson;
3424
+ if (input.sketchId) {
3425
+ const loaded = state.requireSketch(input.sketchId);
3426
+ const existingRefs = loaded.definition.references ?? [];
3427
+ if (existingRefs.some((r) => r.id === id)) {
3428
+ throw new Error(
3429
+ `Reference with ID '${id}' already exists on sketch '${input.sketchId}'`
3430
+ );
3431
+ }
3432
+ const updatedDef = {
3433
+ ...loaded.definition,
3434
+ modified: now7(),
3435
+ references: [...existingRefs, ref]
3436
+ };
3437
+ state.sketches.set(input.sketchId, {
3438
+ definition: updatedDef,
3439
+ path: loaded.path
3440
+ });
3441
+ sketchJson = serializeGenart5(updatedDef);
3442
+ if (!state.remoteMode) {
3443
+ await writeFile7(loaded.path, sketchJson, "utf-8");
3444
+ }
3445
+ attachedTo = `sketch:${input.sketchId}`;
3446
+ state.emitMutation("sketch:updated", { id: input.sketchId });
3447
+ } else if (input.seriesId) {
3448
+ const seriesIndex = ws.series?.findIndex((s) => s.id === input.seriesId);
3449
+ if (seriesIndex === void 0 || seriesIndex < 0 || !ws.series) {
3450
+ throw new Error(`Series '${input.seriesId}' not found in workspace`);
3451
+ }
3452
+ const series = ws.series[seriesIndex];
3453
+ const existingRefs = series.references ?? [];
3454
+ if (existingRefs.some((r) => r.id === id)) {
3455
+ throw new Error(
3456
+ `Reference with ID '${id}' already exists on series '${input.seriesId}'`
3457
+ );
3458
+ }
3459
+ const updatedSeries = {
3460
+ ...series,
3461
+ references: [...existingRefs, ref]
3462
+ };
3463
+ state.workspace = {
3464
+ ...ws,
3465
+ modified: now7(),
3466
+ series: ws.series.map(
3467
+ (s, i) => i === seriesIndex ? updatedSeries : s
3468
+ )
3469
+ };
3470
+ workspaceJson = serializeWorkspace4(state.workspace);
3471
+ if (!state.remoteMode) {
3472
+ await writeFile7(state.workspacePath, workspaceJson, "utf-8");
3473
+ }
3474
+ attachedTo = `series:${input.seriesId}`;
3475
+ state.emitMutation("workspace:updated", { referenceAdded: id });
3476
+ } else {
3477
+ throw new Error("Either seriesId or sketchId must be specified");
3478
+ }
3479
+ return {
3480
+ success: true,
3481
+ reference: {
3482
+ id,
3483
+ type: refType,
3484
+ path: relativePath,
3485
+ source: input.source ?? null
3486
+ },
3487
+ attachedTo,
3488
+ ...sketchJson ? { fileContent: sketchJson } : {},
3489
+ ...workspaceJson ? { workspaceContent: workspaceJson } : {}
3490
+ };
3491
+ }
3492
+ async function analyzeReference(state, input) {
3493
+ state.requireWorkspace();
3494
+ const { ref, location } = findReference(state, input.referenceId, input.seriesId, input.sketchId);
3495
+ const workspaceDir = dirname6(state.workspacePath);
3496
+ const imagePath = resolve3(workspaceDir, ref.path);
3497
+ let previewJpegBase64;
3498
+ try {
3499
+ const imageBuffer = await readFile4(imagePath);
3500
+ const ext = extname(ref.path).toLowerCase();
3501
+ const mimeMap = {
3502
+ ".png": "image/png",
3503
+ ".jpg": "image/jpeg",
3504
+ ".jpeg": "image/jpeg",
3505
+ ".gif": "image/gif",
3506
+ ".webp": "image/webp",
3507
+ ".svg": "image/svg+xml"
3508
+ };
3509
+ previewJpegBase64 = imageBuffer.toString("base64");
3510
+ } catch {
3511
+ }
3512
+ const metadata = {
3513
+ success: true,
3514
+ referenceId: ref.id,
3515
+ type: ref.type,
3516
+ path: ref.path,
3517
+ source: ref.source ?? null,
3518
+ location,
3519
+ existingAnalysis: ref.analysis ?? null,
3520
+ analysisFramework: {
3521
+ composition: {
3522
+ instruction: "Analyze the compositional structure of this reference.",
3523
+ prompts: [
3524
+ "What is the primary compositional structure (centered, asymmetric, diagonal, radial)?",
3525
+ "Where does the eye land first? What creates the focal point?",
3526
+ "How is negative space used \u2014 actively or passively?",
3527
+ "What is the relationship between foreground, middle ground, and background?",
3528
+ "How do the edges and corners of the frame interact with the subject?"
3529
+ ]
3530
+ },
3531
+ palette: {
3532
+ instruction: "Identify the color strategy.",
3533
+ prompts: [
3534
+ "What are the dominant colors (3-5 hex values)?",
3535
+ "What color temperature dominates \u2014 warm, cool, or neutral?",
3536
+ "What is the value range \u2014 high contrast or compressed?",
3537
+ "Is the palette analogous, complementary, triadic, or something else?",
3538
+ "How does saturation vary across the composition?"
3539
+ ]
3540
+ },
3541
+ rhythm: {
3542
+ instruction: "Identify rhythmic and pattern qualities.",
3543
+ prompts: [
3544
+ "Is there a repeating motif or interval?",
3545
+ "Is the rhythm regular, progressive, alternating, or irregular?",
3546
+ "At how many scales does pattern appear (fractal quality)?",
3547
+ "How do density variations create movement?",
3548
+ "Where are the moments of rest vs. activity?"
3549
+ ]
3550
+ },
3551
+ mood: {
3552
+ instruction: "Identify the emotional and atmospheric qualities.",
3553
+ prompts: [
3554
+ "What is the overall mood \u2014 contemplative, energetic, serene, unsettling?",
3555
+ "How do color, light, and space contribute to that mood?",
3556
+ "Is there a sense of time \u2014 moment, duration, timelessness?",
3557
+ "What emotional response does the work invite?"
3558
+ ]
3559
+ },
3560
+ technique: {
3561
+ instruction: "Identify technical and material qualities worth studying.",
3562
+ prompts: [
3563
+ "What medium or technique is used?",
3564
+ "How is mark-making contributing to expression?",
3565
+ "Are there layering or transparency effects?",
3566
+ "What level of control vs. chance is visible?",
3567
+ "What technical approach could be translated to generative art?"
3568
+ ]
3569
+ }
3570
+ },
3571
+ instructions: [
3572
+ "Study the reference image carefully using the framework above.",
3573
+ "For each category, answer the prompts and synthesize your observations.",
3574
+ "After analysis, use update_reference_analysis to save the structured analysis.",
3575
+ "The analysis should inform how you create study sketches inspired by this reference.",
3576
+ "Focus on qualities that can be translated to generative art \u2014 don't try to replicate literally."
3577
+ ]
3578
+ };
3579
+ return { metadata, previewJpegBase64 };
3580
+ }
3581
+ async function updateReferenceAnalysis(state, input) {
3582
+ const ws = state.requireWorkspace();
3583
+ const { ref, location } = findReference(
3584
+ state,
3585
+ input.referenceId,
3586
+ input.seriesId,
3587
+ input.sketchId
3588
+ );
3589
+ const updatedRef = {
3590
+ ...ref,
3591
+ analysis: input.analysis
3592
+ };
3593
+ let workspaceJson;
3594
+ let sketchJson;
3595
+ if (location.startsWith("sketch:")) {
3596
+ const sketchId = location.replace("sketch:", "");
3597
+ const loaded = state.requireSketch(sketchId);
3598
+ const updatedDef = {
3599
+ ...loaded.definition,
3600
+ modified: now7(),
3601
+ references: (loaded.definition.references ?? []).map(
3602
+ (r) => r.id === input.referenceId ? updatedRef : r
3603
+ )
3604
+ };
3605
+ state.sketches.set(sketchId, {
3606
+ definition: updatedDef,
3607
+ path: loaded.path
3608
+ });
3609
+ sketchJson = serializeGenart5(updatedDef);
3610
+ if (!state.remoteMode) {
3611
+ await writeFile7(loaded.path, sketchJson, "utf-8");
3612
+ }
3613
+ state.emitMutation("sketch:updated", { id: sketchId });
3614
+ } else {
3615
+ const seriesId = location.replace("series:", "");
3616
+ const seriesIndex = ws.series.findIndex((s) => s.id === seriesId);
3617
+ const series = ws.series[seriesIndex];
3618
+ const updatedSeries = {
3619
+ ...series,
3620
+ references: (series.references ?? []).map(
3621
+ (r) => r.id === input.referenceId ? updatedRef : r
3622
+ )
3623
+ };
3624
+ state.workspace = {
3625
+ ...ws,
3626
+ modified: now7(),
3627
+ series: ws.series.map(
3628
+ (s, i) => i === seriesIndex ? updatedSeries : s
3629
+ )
3630
+ };
3631
+ workspaceJson = serializeWorkspace4(state.workspace);
3632
+ if (!state.remoteMode) {
3633
+ await writeFile7(state.workspacePath, workspaceJson, "utf-8");
3634
+ }
3635
+ state.emitMutation("workspace:updated", { referenceAnalyzed: input.referenceId });
3636
+ }
3637
+ return {
3638
+ success: true,
3639
+ referenceId: input.referenceId,
3640
+ location,
3641
+ analysis: input.analysis,
3642
+ ...sketchJson ? { fileContent: sketchJson } : {},
3643
+ ...workspaceJson ? { workspaceContent: workspaceJson } : {}
3644
+ };
3645
+ }
3646
+ async function extractPalette(state, input) {
3647
+ state.requireWorkspace();
3648
+ const { ref, location } = findReference(
3649
+ state,
3650
+ input.referenceId,
3651
+ input.seriesId,
3652
+ input.sketchId
3653
+ );
3654
+ const count = input.count ?? 6;
3655
+ const workspaceDir = dirname6(state.workspacePath);
3656
+ const imagePath = resolve3(workspaceDir, ref.path);
3657
+ let previewJpegBase64;
3658
+ try {
3659
+ const imageBuffer = await readFile4(imagePath);
3660
+ previewJpegBase64 = imageBuffer.toString("base64");
3661
+ } catch {
3662
+ }
3663
+ const metadata = {
3664
+ success: true,
3665
+ referenceId: ref.id,
3666
+ type: ref.type,
3667
+ path: ref.path,
3668
+ location,
3669
+ requestedColors: count,
3670
+ existingPalette: ref.analysis?.palette ?? null,
3671
+ instructions: [
3672
+ `Extract ${count} dominant colors from the reference image as hex values.`,
3673
+ "Order them from most dominant to least dominant.",
3674
+ "Include both saturated and neutral colors if present in the image.",
3675
+ "Consider the role of each color \u2014 is it a background, accent, or primary element?",
3676
+ "After extraction, use update_reference_analysis to save the palette.",
3677
+ "You can also apply the extracted palette to a sketch using set_colors or create a new theme."
3678
+ ],
3679
+ extractionGuidelines: {
3680
+ dominance: "Prioritize colors by the area they occupy, not just their saturation.",
3681
+ variety: "Include the full value range (lights, midtones, darks) if present.",
3682
+ harmony: `Look for ${count <= 4 ? "core harmony" : "extended palette including transitional colors"}.`,
3683
+ neutrals: "Don't ignore grays, blacks, and whites \u2014 they often define the character of a palette."
3684
+ }
3685
+ };
3686
+ return { metadata, previewJpegBase64 };
3687
+ }
3688
+ function findReference(state, referenceId, seriesId, sketchId) {
3689
+ if (sketchId) {
3690
+ const loaded = state.requireSketch(sketchId);
3691
+ const ref = (loaded.definition.references ?? []).find(
3692
+ (r) => r.id === referenceId
3693
+ );
3694
+ if (ref) return { ref, location: `sketch:${sketchId}` };
3695
+ throw new Error(
3696
+ `Reference '${referenceId}' not found on sketch '${sketchId}'`
3697
+ );
3698
+ }
3699
+ if (seriesId) {
3700
+ const ws2 = state.requireWorkspace();
3701
+ const series = ws2.series?.find((s) => s.id === seriesId);
3702
+ if (!series) {
3703
+ throw new Error(`Series '${seriesId}' not found in workspace`);
3704
+ }
3705
+ const ref = (series.references ?? []).find((r) => r.id === referenceId);
3706
+ if (ref) return { ref, location: `series:${seriesId}` };
3707
+ throw new Error(
3708
+ `Reference '${referenceId}' not found on series '${seriesId}'`
3709
+ );
3710
+ }
3711
+ const ws = state.requireWorkspace();
3712
+ if (ws.series) {
3713
+ for (const series of ws.series) {
3714
+ const ref = (series.references ?? []).find((r) => r.id === referenceId);
3715
+ if (ref) return { ref, location: `series:${series.id}` };
3716
+ }
3717
+ }
3718
+ for (const [id, loaded] of state.sketches) {
3719
+ const ref = (loaded.definition.references ?? []).find(
3720
+ (r) => r.id === referenceId
3721
+ );
3722
+ if (ref) return { ref, location: `sketch:${id}` };
3723
+ }
3724
+ throw new Error(
3725
+ `Reference '${referenceId}' not found in any series or sketch`
3726
+ );
3727
+ }
3728
+
3729
+ // src/tools/export.ts
3730
+ import { createWriteStream } from "fs";
3731
+ import { stat as stat4, writeFile as writeFile8 } from "fs/promises";
3732
+ import { dirname as dirname7 } from "path";
3733
+ import archiver from "archiver";
3734
+ import {
3735
+ createDefaultRegistry as createDefaultRegistry3,
3736
+ serializeGenart as serializeGenart6
3737
+ } from "@genart-dev/core";
3738
+ var registry4 = createDefaultRegistry3();
3739
+ async function validateOutputPath(outputPath) {
3740
+ const parentDir = dirname7(outputPath);
3741
+ try {
3742
+ const s = await stat4(parentDir);
3743
+ if (!s.isDirectory()) {
3744
+ throw new Error(`Parent directory does not exist: ${parentDir}`);
3745
+ }
3746
+ } catch (e) {
3747
+ if (e instanceof Error && e.message.startsWith("Parent directory")) throw e;
3748
+ throw new Error(`Parent directory does not exist: ${parentDir}`);
3749
+ }
3750
+ try {
3751
+ await stat4(outputPath);
3752
+ throw new Error(
3753
+ `File already exists at ${outputPath}. Delete it first or use a different path.`
3754
+ );
3755
+ } catch (e) {
3756
+ if (e instanceof Error && e.message.startsWith("File already exists")) throw e;
3757
+ }
3758
+ }
3759
+ function algorithmExtension(rendererType) {
3760
+ return rendererType === "glsl" ? ".glsl" : ".js";
3761
+ }
3762
+ function applyOverrides2(sketch, overrides) {
3763
+ if (overrides.seed === void 0 && overrides.params === void 0) {
3764
+ return sketch;
3765
+ }
3766
+ const newState = {
3767
+ seed: overrides.seed ?? sketch.state.seed,
3768
+ params: overrides.params ? { ...sketch.state.params, ...overrides.params } : sketch.state.params,
3769
+ colorPalette: sketch.state.colorPalette
3770
+ };
3771
+ return { ...sketch, state: newState };
3772
+ }
3773
+ async function exportSketch(state, input) {
3774
+ state.requireWorkspace();
3775
+ const loaded = state.requireSketch(input.sketchId);
3776
+ const sketch = applyOverrides2(loaded.definition, {
3777
+ seed: input.seed,
3778
+ params: input.params
3779
+ });
3780
+ await validateOutputPath(input.outputPath);
3781
+ const adapter = registry4.resolve(sketch.renderer.type);
3782
+ if (!adapter) {
3783
+ throw new Error(
3784
+ `Unsupported renderer type: '${sketch.renderer.type}'`
3785
+ );
3786
+ }
3787
+ switch (input.format) {
3788
+ case "html":
3789
+ return await exportHtml(sketch, input.outputPath);
3790
+ case "png":
3791
+ return await exportPng(sketch, input);
3792
+ case "svg":
3793
+ return await exportSvg(sketch, input);
3794
+ case "algorithm":
3795
+ return await exportAlgorithm(sketch, input.outputPath);
3796
+ case "zip":
3797
+ return await exportZip(sketch, input);
3798
+ default:
3799
+ throw new Error(`Unsupported export format: '${input.format}'`);
3800
+ }
3801
+ }
3802
+ async function exportHtml(sketch, outputPath) {
3803
+ const adapter = registry4.resolve(sketch.renderer.type);
3804
+ const html = adapter.generateStandaloneHTML(sketch);
3805
+ const content = Buffer.from(html, "utf-8");
3806
+ await writeFile8(outputPath, content);
3807
+ return {
3808
+ success: true,
3809
+ sketchId: sketch.id,
3810
+ format: "html",
3811
+ outputPath,
3812
+ fileSize: content.byteLength,
3813
+ renderer: sketch.renderer.type
3814
+ };
3815
+ }
3816
+ async function exportPng(sketch, input) {
3817
+ const adapter = registry4.resolve(sketch.renderer.type);
3818
+ const html = adapter.generateStandaloneHTML(sketch);
3819
+ const width = input.width ?? sketch.canvas.width;
3820
+ const height = input.height ?? sketch.canvas.height;
3821
+ const result = await captureHtml({ html, width, height });
3822
+ await writeFile8(input.outputPath, result.bytes);
3823
+ return {
3824
+ success: true,
3825
+ sketchId: sketch.id,
3826
+ format: "png",
3827
+ outputPath: input.outputPath,
3828
+ fileSize: result.bytes.byteLength,
3829
+ renderer: sketch.renderer.type
3830
+ };
3831
+ }
3832
+ async function exportSvg(sketch, input) {
3833
+ const width = input.width ?? sketch.canvas.width;
3834
+ const height = input.height ?? sketch.canvas.height;
3835
+ if (sketch.renderer.type === "svg") {
3836
+ const content2 = Buffer.from(sketch.algorithm, "utf-8");
3837
+ await writeFile8(input.outputPath, content2);
3838
+ return {
3839
+ success: true,
3840
+ sketchId: sketch.id,
3841
+ format: "svg",
3842
+ outputPath: input.outputPath,
3843
+ fileSize: content2.byteLength,
3844
+ renderer: sketch.renderer.type,
3845
+ notice: null
3846
+ };
3847
+ }
3848
+ const adapter = registry4.resolve(sketch.renderer.type);
3849
+ const html = adapter.generateStandaloneHTML(sketch);
3850
+ const result = await captureHtml({ html, width, height });
3851
+ const b64 = Buffer.from(result.bytes).toString("base64");
3852
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
3853
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
3854
+ width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
3855
+ <image width="${width}" height="${height}"
3856
+ href="data:image/png;base64,${b64}"/>
3857
+ </svg>`;
3858
+ const content = Buffer.from(svg, "utf-8");
3859
+ await writeFile8(input.outputPath, content);
3860
+ return {
3861
+ success: true,
3862
+ sketchId: sketch.id,
3863
+ format: "svg",
3864
+ outputPath: input.outputPath,
3865
+ fileSize: content.byteLength,
3866
+ renderer: sketch.renderer.type,
3867
+ notice: "Non-SVG renderer \u2014 rasterized PNG embedded in SVG container"
3868
+ };
3869
+ }
3870
+ async function exportAlgorithm(sketch, outputPath) {
3871
+ const content = Buffer.from(sketch.algorithm, "utf-8");
3872
+ await writeFile8(outputPath, content);
3873
+ return {
3874
+ success: true,
3875
+ sketchId: sketch.id,
3876
+ format: "algorithm",
3877
+ outputPath,
3878
+ fileSize: content.byteLength,
3879
+ renderer: sketch.renderer.type
3880
+ };
3881
+ }
3882
+ async function exportZip(sketch, input) {
3883
+ const adapter = registry4.resolve(sketch.renderer.type);
3884
+ const width = input.width ?? sketch.canvas.width;
3885
+ const height = input.height ?? sketch.canvas.height;
3886
+ const html = adapter.generateStandaloneHTML(sketch);
3887
+ const genartJson = serializeGenart6(sketch);
3888
+ const algorithm = sketch.algorithm;
3889
+ const algExt = algorithmExtension(sketch.renderer.type);
3890
+ const captureResult = await captureHtml({ html, width, height });
3891
+ const output = createWriteStream(input.outputPath);
3892
+ const archive = archiver("zip", { zlib: { level: 9 } });
3893
+ const finished = new Promise((resolve5, reject) => {
3894
+ output.on("close", resolve5);
3895
+ archive.on("error", reject);
3896
+ });
3897
+ archive.pipe(output);
3898
+ archive.append(html, { name: `${sketch.id}.html` });
3899
+ archive.append(Buffer.from(captureResult.bytes), { name: `${sketch.id}.png` });
3900
+ archive.append(algorithm, { name: `${sketch.id}${algExt}` });
3901
+ archive.append(genartJson, { name: `${sketch.id}.genart` });
3902
+ await archive.finalize();
3903
+ await finished;
3904
+ const s = await stat4(input.outputPath);
3905
+ return {
3906
+ success: true,
3907
+ sketchId: sketch.id,
3908
+ format: "zip",
3909
+ outputPath: input.outputPath,
3910
+ fileSize: s.size,
3911
+ renderer: sketch.renderer.type,
3912
+ contents: [
3913
+ `${sketch.id}.html`,
3914
+ `${sketch.id}.png`,
3915
+ `${sketch.id}${algExt}`,
3916
+ `${sketch.id}.genart`
3917
+ ]
3918
+ };
3919
+ }
3920
+
3921
+ // src/tools/design.ts
3922
+ function requireSketchId(state, args) {
3923
+ return args.sketchId ?? state.requireSelectedSketchId();
3924
+ }
3925
+ var BLEND_MODES = [
3926
+ "normal",
3927
+ "multiply",
3928
+ "screen",
3929
+ "overlay",
3930
+ "darken",
3931
+ "lighten",
3932
+ "color-dodge",
3933
+ "color-burn",
3934
+ "hard-light",
3935
+ "soft-light",
3936
+ "difference",
3937
+ "exclusion",
3938
+ "hue",
2701
3939
  "saturation",
2702
3940
  "color",
2703
3941
  "luminosity"
@@ -2709,8 +3947,8 @@ async function designAddLayer(state, args) {
2709
3947
  const sketchId = requireSketchId(state, args);
2710
3948
  const loaded = state.requireSketch(sketchId);
2711
3949
  const stack = state.getLayerStack(sketchId);
2712
- const registry4 = state.pluginRegistry;
2713
- const layerTypeDef = registry4?.resolveLayerType(args.type);
3950
+ const registry5 = state.pluginRegistry;
3951
+ const layerTypeDef = registry5?.resolveLayerType(args.type);
2714
3952
  if (!layerTypeDef) {
2715
3953
  throw new Error(
2716
3954
  `Unknown layer type: '${args.type}'. Use design_list_layers types from registered plugins.`
@@ -2817,10 +4055,7 @@ async function designUpdateLayer(state, args) {
2817
4055
  stack.updateProperties(args.layerId, updates);
2818
4056
  }
2819
4057
  if (args.name !== void 0) {
2820
- const current = stack.get(args.layerId);
2821
- stack.updateProperties(args.layerId, { ...current.properties });
2822
- const mutableLayer = stack.get(args.layerId);
2823
- mutableLayer.name = args.name;
4058
+ stack.updateMeta(args.layerId, { name: args.name });
2824
4059
  }
2825
4060
  await state.saveSketch(sketchId);
2826
4061
  return { updated: true, layerId: args.layerId, sketchId };
@@ -2918,9 +4153,7 @@ async function designToggleVisibility(state, args) {
2918
4153
  throw new Error(`Layer '${args.layerId}' not found in sketch '${sketchId}'.`);
2919
4154
  }
2920
4155
  const newVisible = args.visible ?? !layer.visible;
2921
- const mutableLayer = layer;
2922
- mutableLayer.visible = newVisible;
2923
- stack.updateProperties(args.layerId, { ...layer.properties });
4156
+ stack.updateMeta(args.layerId, { visible: newVisible });
2924
4157
  await state.saveSketch(sketchId);
2925
4158
  return {
2926
4159
  layerId: args.layerId,
@@ -2936,9 +4169,7 @@ async function designLockLayer(state, args) {
2936
4169
  throw new Error(`Layer '${args.layerId}' not found in sketch '${sketchId}'.`);
2937
4170
  }
2938
4171
  const newLocked = args.locked ?? !layer.locked;
2939
- const mutableLayer = layer;
2940
- mutableLayer.locked = newLocked;
2941
- stack.updateProperties(args.layerId, { ...layer.properties });
4172
+ stack.updateMeta(args.layerId, { locked: newLocked });
2942
4173
  await state.saveSketch(sketchId);
2943
4174
  return {
2944
4175
  layerId: args.layerId,
@@ -2959,8 +4190,8 @@ async function designCaptureComposite(state, args) {
2959
4190
  }
2960
4191
 
2961
4192
  // src/tools/design-plugins.ts
2962
- function registerPluginMcpTools(server, registry4, state) {
2963
- for (const tool of registry4.getMcpTools()) {
4193
+ function registerPluginMcpTools(server, registry5, state) {
4194
+ for (const tool of registry5.getMcpTools()) {
2964
4195
  const inputSchema = tool.definition.inputSchema;
2965
4196
  server.tool(
2966
4197
  tool.name,
@@ -3008,7 +4239,7 @@ function registerPluginMcpTools(server, registry4, state) {
3008
4239
  import {
3009
4240
  CANVAS_PRESETS,
3010
4241
  createDefaultRegistry as createDefaultRegistry4,
3011
- createDefaultSkillRegistry as createDefaultSkillRegistry2
4242
+ createDefaultSkillRegistry as createDefaultSkillRegistry3
3012
4243
  } from "@genart-dev/core";
3013
4244
  function registerResources(server, state) {
3014
4245
  registerSkillsResource(server);
@@ -3017,7 +4248,7 @@ function registerResources(server, state) {
3017
4248
  registerRenderersResource(server);
3018
4249
  }
3019
4250
  function registerSkillsResource(server) {
3020
- const skillRegistry = createDefaultSkillRegistry2();
4251
+ const skillRegistry = createDefaultSkillRegistry3();
3021
4252
  server.resource(
3022
4253
  "skills",
3023
4254
  "genart://skills",
@@ -3125,7 +4356,7 @@ function registerGalleryResource(server, state) {
3125
4356
  );
3126
4357
  }
3127
4358
  function registerRenderersResource(server) {
3128
- const registry4 = createDefaultRegistry4();
4359
+ const registry5 = createDefaultRegistry4();
3129
4360
  server.resource(
3130
4361
  "renderers",
3131
4362
  "genart://renderers",
@@ -3134,9 +4365,9 @@ function registerRenderersResource(server) {
3134
4365
  mimeType: "application/json"
3135
4366
  },
3136
4367
  async () => {
3137
- const types = registry4.list();
4368
+ const types = registry5.list();
3138
4369
  const renderers = types.map((type) => {
3139
- const adapter = registry4.resolve(type);
4370
+ const adapter = registry5.resolve(type);
3140
4371
  return {
3141
4372
  type: adapter.type,
3142
4373
  displayName: adapter.displayName,
@@ -3148,7 +4379,7 @@ function registerRenderersResource(server) {
3148
4379
  }))
3149
4380
  };
3150
4381
  });
3151
- const defaultAdapter = registry4.getDefault();
4382
+ const defaultAdapter = registry5.getDefault();
3152
4383
  return {
3153
4384
  contents: [
3154
4385
  {
@@ -3175,6 +4406,9 @@ function registerPrompts(server, state) {
3175
4406
  registerCreateGenerativeArt(server);
3176
4407
  registerExploreVariations(server, state);
3177
4408
  registerApplyDesignTheory(server, state);
4409
+ registerCritiqueAndIterate(server, state);
4410
+ registerDevelopArtisticConcept(server, state);
4411
+ registerStudyReference(server, state);
3178
4412
  }
3179
4413
  function registerCreateGenerativeArt(server) {
3180
4414
  server.prompt(
@@ -3455,21 +4689,200 @@ function registerApplyDesignTheory(server, state) {
3455
4689
  content: {
3456
4690
  type: "text",
3457
4691
  text: [
3458
- `Apply design theory to improve a generative art sketch.`,
4692
+ `Apply design theory to improve a generative art sketch.`,
4693
+ ``,
4694
+ sketchContext,
4695
+ ``,
4696
+ theoryGuides[args.theory],
4697
+ ``,
4698
+ `## Workflow`,
4699
+ `1. Use \`get_selection\` or \`open_sketch\` to examine the current sketch`,
4700
+ `2. Analyze how the theory applies to the existing algorithm`,
4701
+ `3. Use \`fork_sketch\` to create a theory-applied variant`,
4702
+ `4. Modify the fork's algorithm and parameters using the theory principles above`,
4703
+ `5. Use \`capture_screenshot\` to compare before and after`,
4704
+ `6. Update the philosophy field to document the design rationale`,
4705
+ ``,
4706
+ `**Attribution:** Always pass your \`agent\` name and \`model\` identifier when calling tools that create or modify sketches.`
4707
+ ].join("\n")
4708
+ }
4709
+ }
4710
+ ]
4711
+ };
4712
+ }
4713
+ );
4714
+ }
4715
+ function registerCritiqueAndIterate(server, state) {
4716
+ server.prompt(
4717
+ "critique-and-iterate",
4718
+ "Capture a sketch, self-critique it, identify improvements, fork, apply changes, compare, and document the iteration",
4719
+ {
4720
+ sketchId: z.string().describe("ID of the sketch to critique and iterate on"),
4721
+ aspects: z.string().optional().describe("Comma-separated aspects to focus on (composition, color, rhythm, unity, expression). Default: all"),
4722
+ iterations: z.string().optional().describe("Number of improvement iterations (default: 1)")
4723
+ },
4724
+ async (args) => {
4725
+ const sketch = state.getSketch(args.sketchId);
4726
+ const iterations = args.iterations ? parseInt(args.iterations, 10) : 1;
4727
+ const aspectList = args.aspects ? args.aspects.split(",").map((a) => a.trim()) : ["composition", "color", "rhythm", "unity", "expression"];
4728
+ let sketchContext = "";
4729
+ if (sketch) {
4730
+ const def = sketch.definition;
4731
+ sketchContext = [
4732
+ `## Current Sketch: "${def.title}"`,
4733
+ `- **ID:** ${def.id}`,
4734
+ `- **Renderer:** ${def.renderer.type}`,
4735
+ `- **Canvas:** ${def.canvas.width}\xD7${def.canvas.height}`,
4736
+ `- **Composition Level:** ${def.compositionLevel ?? "sketch"}`,
4737
+ def.philosophy ? `- **Philosophy:** ${def.philosophy}` : `- **Philosophy:** not set`,
4738
+ `- **Parameters:** ${def.parameters?.length ?? 0} defined`,
4739
+ `- **Colors:** ${def.colors?.length ?? 0} defined`
4740
+ ].join("\n");
4741
+ } else {
4742
+ sketchContext = `## Sketch: ${args.sketchId}
4743
+ *(Not currently loaded \u2014 use open_sketch first)*`;
4744
+ }
4745
+ return {
4746
+ messages: [
4747
+ {
4748
+ role: "user",
4749
+ content: {
4750
+ type: "text",
4751
+ text: [
4752
+ `Perform a structured critique-and-iterate cycle on a generative art sketch.`,
3459
4753
  ``,
3460
4754
  sketchContext,
3461
4755
  ``,
3462
- theoryGuides[args.theory],
4756
+ `## Focus Aspects`,
4757
+ aspectList.map((a) => `- ${a}`).join("\n"),
3463
4758
  ``,
3464
- `## Workflow`,
3465
- `1. Use \`get_selection\` or \`open_sketch\` to examine the current sketch`,
3466
- `2. Analyze how the theory applies to the existing algorithm`,
3467
- `3. Use \`fork_sketch\` to create a theory-applied variant`,
3468
- `4. Modify the fork's algorithm and parameters using the theory principles above`,
3469
- `5. Use \`capture_screenshot\` to compare before and after`,
3470
- `6. Update the philosophy field to document the design rationale`,
4759
+ `## Iterations: ${iterations}`,
3471
4760
  ``,
3472
- `**Attribution:** Always pass your \`agent\` name and \`model\` identifier when calling tools that create or modify sketches.`
4761
+ `## Process`,
4762
+ ``,
4763
+ `For each iteration:`,
4764
+ ``,
4765
+ `### Step 1: Capture & Critique`,
4766
+ `1. Use \`critique_sketch\` with sketchId="${args.sketchId}" and aspects=[${aspectList.map((a) => `"${a}"`).join(", ")}]`,
4767
+ `2. Study the returned screenshot carefully`,
4768
+ `3. Answer each framework question honestly \u2014 what works and what doesn't`,
4769
+ `4. Note the severity calibration for this composition level`,
4770
+ ``,
4771
+ `### Step 2: Identify Improvements`,
4772
+ `Based on the critique, identify 2-3 specific, actionable improvements:`,
4773
+ `- Rank them by expected visual impact`,
4774
+ `- Be precise: "shift the focal cluster from center to upper-left third" not "improve composition"`,
4775
+ `- Consider which improvements can be achieved via parameter changes vs algorithm changes`,
4776
+ ``,
4777
+ `### Step 3: Fork & Apply`,
4778
+ `1. Use \`fork_sketch\` to create a new version (preserve the original for comparison)`,
4779
+ `2. Apply the identified improvements:`,
4780
+ ` - Use \`set_parameters\` or \`set_colors\` for parameter-level changes`,
4781
+ ` - Use \`update_algorithm\` for algorithmic changes`,
4782
+ `3. Use \`capture_screenshot\` to verify each change visually`,
4783
+ ``,
4784
+ `### Step 4: Compare`,
4785
+ `1. Use \`compare_sketches\` with the original and improved sketch IDs`,
4786
+ `2. Evaluate: did each intended improvement actually improve the piece?`,
4787
+ `3. Note any unintended consequences \u2014 improvements in one aspect sometimes degrade another`,
4788
+ ``,
4789
+ `### Step 5: Document`,
4790
+ `After all iterations:`,
4791
+ `1. Update the improved sketch's philosophy field to document what changed and why`,
4792
+ `2. Summarize the iteration journey: what was tried, what worked, what was learned`,
4793
+ `3. If the original was better in some aspects, note what to preserve in future iterations`,
4794
+ ``,
4795
+ `## Guidelines`,
4796
+ `- Be your own harshest (but fairest) critic \u2014 the goal is genuine improvement`,
4797
+ `- Small, focused changes are better than sweeping rewrites`,
4798
+ `- If a change doesn't work, revert it before trying the next improvement`,
4799
+ `- The final piece should feel like a natural evolution, not a different sketch`,
4800
+ `- Always pass your \`agent\` name and \`model\` identifier when calling tools that create or modify sketches`
4801
+ ].join("\n")
4802
+ }
4803
+ }
4804
+ ]
4805
+ };
4806
+ }
4807
+ );
4808
+ }
4809
+ function registerDevelopArtisticConcept(server, _state) {
4810
+ server.prompt(
4811
+ "develop-artistic-concept",
4812
+ "Develop an artistic concept through a full studio workflow: concept planning, studies, development, critique, iteration, and documentation",
4813
+ {
4814
+ concept: z.string().describe("The artistic concept or theme to explore"),
4815
+ medium: z.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Preferred renderer/medium (default: p5)"),
4816
+ depth: z.enum(["quick", "standard", "deep"]).optional().describe("How deeply to explore: quick (3 studies), standard (6 studies), deep (9+ studies). Default: standard")
4817
+ },
4818
+ async (args) => {
4819
+ const medium = args.medium ?? "p5";
4820
+ const depth = args.depth ?? "standard";
4821
+ const studyCount = depth === "quick" ? 3 : depth === "deep" ? 9 : 6;
4822
+ return {
4823
+ messages: [
4824
+ {
4825
+ role: "user",
4826
+ content: {
4827
+ type: "text",
4828
+ text: [
4829
+ `Develop the following artistic concept through a full studio workflow.`,
4830
+ ``,
4831
+ `## Concept`,
4832
+ `${args.concept}`,
4833
+ ``,
4834
+ `## Medium: ${medium}`,
4835
+ `## Depth: ${depth} (${studyCount} studies)`,
4836
+ ``,
4837
+ `## Phase 1: Conceptual Planning`,
4838
+ `1. Use \`develop_concept\` with your concept and medium to get a structured plan`,
4839
+ `2. Define: mood, color strategy, compositional approach, and relevant skills`,
4840
+ `3. Create a series with \`create_series\` \u2014 write a narrative and intent statement`,
4841
+ ``,
4842
+ `## Phase 2: Thumbnail Studies`,
4843
+ `1. Create ${studyCount} quick study-level sketches with \`create_sketch\` (compositionLevel: "study")`,
4844
+ `2. Each study should explore a different aspect of the concept:`,
4845
+ ` - Vary composition (centered vs asymmetric vs edge-driven)`,
4846
+ ` - Vary color (warm vs cool, saturated vs muted)`,
4847
+ ` - Vary rhythm (regular vs progressive vs chaotic)`,
4848
+ ` - Vary density (sparse vs dense vs gradient)`,
4849
+ `3. Use small canvases (600x600 or similar) \u2014 studies are fast explorations`,
4850
+ `4. Use \`capture_batch\` to see all studies at once`,
4851
+ ``,
4852
+ `## Phase 3: Selection & Critique`,
4853
+ `1. Use \`series_summary\` to see the full set of studies with screenshots`,
4854
+ `2. Use \`critique_sketch\` on the 2-3 most promising studies`,
4855
+ `3. Identify which studies best capture the concept's intent`,
4856
+ `4. Note what works in each \u2014 composition choices, color relationships, rhythmic qualities`,
4857
+ ``,
4858
+ `## Phase 4: Development`,
4859
+ `1. Use \`promote_sketch\` to advance the best 1-2 studies to "drafts" stage`,
4860
+ `2. Refine the promoted sketches:`,
4861
+ ` - Add more parameters for fine control`,
4862
+ ` - Develop the color palette with more nuance`,
4863
+ ` - Strengthen compositional structure`,
4864
+ ` - Load relevant skills with \`load_skill\` for guidance`,
4865
+ `3. Use \`critique_sketch\` after each round of changes`,
4866
+ ``,
4867
+ `## Phase 5: Critique & Iteration`,
4868
+ `1. Use \`compare_sketches\` to evaluate drafts against each other`,
4869
+ `2. For the strongest draft, use the critique-and-iterate workflow:`,
4870
+ ` - Critique \u2192 identify improvements \u2192 fork \u2192 apply \u2192 compare`,
4871
+ `3. Promote the best iteration to "refinements" stage`,
4872
+ `4. Continue refining until the piece feels resolved`,
4873
+ ``,
4874
+ `## Phase 6: Final & Documentation`,
4875
+ `1. Promote the best refinement to "finals" stage (canvas will upscale)`,
4876
+ `2. Update the philosophy field with the full artistic statement`,
4877
+ `3. Use \`series_summary\` to capture the complete progression`,
4878
+ `4. Document: what was the concept? How did it evolve? What was discovered?`,
4879
+ ``,
4880
+ `## Guidelines`,
4881
+ `- Each phase should feel like a natural progression, not a checklist`,
4882
+ `- Trust the studies \u2014 let unexpected results redirect the exploration`,
4883
+ `- The final piece should feel inevitable, like it couldn't have been any other way`,
4884
+ `- Always pass your \`agent\` name and \`model\` identifier when calling tools`,
4885
+ `- Use \`auto_arrange\` periodically to keep the workspace organized`
3473
4886
  ].join("\n")
3474
4887
  }
3475
4888
  }
@@ -3478,6 +4891,83 @@ function registerApplyDesignTheory(server, state) {
3478
4891
  }
3479
4892
  );
3480
4893
  }
4894
+ function registerStudyReference(server, _state) {
4895
+ server.prompt(
4896
+ "study-reference",
4897
+ "Study a reference image: analyze it, identify key qualities, create a generative study sketch inspired by it, and document learnings",
4898
+ {
4899
+ referenceId: z.string().describe("ID of the reference to study"),
4900
+ seriesId: z.string().optional().describe("Series the reference belongs to (also where the study sketch will be added)"),
4901
+ sketchId: z.string().optional().describe("Sketch the reference belongs to"),
4902
+ medium: z.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Renderer for the study sketch (default: p5)"),
4903
+ focus: z.string().optional().describe("Specific quality to focus on: composition, palette, rhythm, mood, technique, or a custom focus")
4904
+ },
4905
+ async (args) => {
4906
+ const medium = args.medium ?? "p5";
4907
+ const focus = args.focus ?? "all key qualities";
4908
+ return {
4909
+ messages: [
4910
+ {
4911
+ role: "user",
4912
+ content: {
4913
+ type: "text",
4914
+ text: [
4915
+ `Study a reference image and create a generative art sketch inspired by it.`,
4916
+ ``,
4917
+ `## Reference: ${args.referenceId}`,
4918
+ args.seriesId ? `## Series: ${args.seriesId}` : "",
4919
+ `## Medium: ${medium}`,
4920
+ `## Focus: ${focus}`,
4921
+ ``,
4922
+ `## Phase 1: Analyze the Reference`,
4923
+ `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`,
4924
+ `2. Study the image carefully using the framework prompts`,
4925
+ `3. Answer each category: composition, palette, rhythm, mood, technique`,
4926
+ `4. Use \`update_reference_analysis\` to save your structured analysis`,
4927
+ ``,
4928
+ `## Phase 2: Extract Key Qualities`,
4929
+ `From your analysis, identify 2-4 key qualities that are most interesting for generative art:`,
4930
+ `- These could be: a specific compositional structure, a color relationship, a rhythmic pattern, a mood quality`,
4931
+ `- Focus on qualities that can be *translated* into code, not literally replicated`,
4932
+ `- Consider what makes this reference compelling \u2014 what would be lost if you removed each quality?`,
4933
+ ``,
4934
+ `## Phase 3: Extract Palette`,
4935
+ `1. Use \`extract_palette\` to study the reference's color strategy`,
4936
+ `2. Extract 5-8 hex colors that capture the essential palette`,
4937
+ `3. Save the palette in the reference analysis`,
4938
+ ``,
4939
+ `## Phase 4: Create Study Sketch`,
4940
+ `1. Use \`create_sketch\` with compositionLevel: "study" to create a quick exploration`,
4941
+ `2. Translate the key qualities into generative parameters and algorithm choices:`,
4942
+ ` - Composition \u2192 element placement, density distribution, negative space`,
4943
+ ` - Palette \u2192 color definitions, themes derived from the reference palette`,
4944
+ ` - Rhythm \u2192 repetition patterns, interval variations, scale relationships`,
4945
+ ` - Mood \u2192 overall tone, animation speed, mark quality`,
4946
+ ` - Technique \u2192 rendering approach, layering, transparency`,
4947
+ `3. Add the reference to the sketch with \`add_reference\``,
4948
+ `4. Document in the philosophy field how the reference influenced the study`,
4949
+ `5. Use \`capture_screenshot\` to verify the result`,
4950
+ ``,
4951
+ `## Phase 5: Compare & Document`,
4952
+ `1. Use \`analyze_reference\` again to see the reference alongside your study`,
4953
+ `2. Evaluate: which qualities translated well? Which were lost or transformed?`,
4954
+ `3. Note what you learned \u2014 what worked, what surprised you, what to try next`,
4955
+ `4. Update the study sketch's philosophy with these insights`,
4956
+ ``,
4957
+ `## Guidelines`,
4958
+ `- The goal is *inspiration*, not replication \u2014 a study should be recognizably generative`,
4959
+ `- A good study captures the *spirit* of the reference while being authentically algorithmic`,
4960
+ `- Use small canvases (600x600) \u2014 studies are explorations, not finished pieces`,
4961
+ `- If the reference suggests multiple interesting directions, create multiple studies`,
4962
+ `- Always pass your \`agent\` name and \`model\` identifier when calling tools`
4963
+ ].filter(Boolean).join("\n")
4964
+ }
4965
+ }
4966
+ ]
4967
+ };
4968
+ }
4969
+ );
4970
+ }
3481
4971
 
3482
4972
  // src/server.ts
3483
4973
  function jsonResult(data) {
@@ -3492,22 +4982,36 @@ function toolError(message) {
3492
4982
  };
3493
4983
  }
3494
4984
  async function initializePluginRegistry() {
3495
- const registry4 = createPluginRegistry({
4985
+ const registry5 = createPluginRegistry({
3496
4986
  surface: "mcp",
3497
4987
  supportsInteractiveTools: false,
3498
4988
  supportsRendering: false
3499
4989
  });
3500
- await registry4.register(typographyPlugin);
3501
- await registry4.register(filtersPlugin);
3502
- await registry4.register(shapesPlugin);
3503
- await registry4.register(layoutGuidesPlugin);
3504
- return registry4;
4990
+ await registry5.register(typographyPlugin);
4991
+ await registry5.register(filtersPlugin);
4992
+ await registry5.register(shapesPlugin);
4993
+ await registry5.register(layoutGuidesPlugin);
4994
+ await registry5.register(paintingPlugin);
4995
+ await registry5.register(texturesPlugin);
4996
+ await registry5.register(animationPlugin);
4997
+ await registry5.register(colorAdjustPlugin);
4998
+ await registry5.register(compositingPlugin);
4999
+ await registry5.register(constructionPlugin);
5000
+ await registry5.register(distributionPlugin);
5001
+ await registry5.register(figurePlugin);
5002
+ await registry5.register(layoutCompositionPlugin);
5003
+ await registry5.register(perspectivePlugin);
5004
+ await registry5.register(posesPlugin);
5005
+ await registry5.register(stylesPlugin);
5006
+ await registry5.register(symbolsPlugin);
5007
+ await registry5.register(tracePlugin);
5008
+ return registry5;
3505
5009
  }
3506
5010
  function createServer(state) {
3507
5011
  const server = new McpServer(
3508
5012
  {
3509
5013
  name: "@genart/mcp-server",
3510
- version: "0.3.0"
5014
+ version: "0.4.0"
3511
5015
  },
3512
5016
  {
3513
5017
  capabilities: {
@@ -3517,9 +5021,9 @@ function createServer(state) {
3517
5021
  }
3518
5022
  }
3519
5023
  );
3520
- const registryReady = initializePluginRegistry().then((registry4) => {
3521
- state.pluginRegistry = registry4;
3522
- registerPluginMcpTools(server, registry4, state);
5024
+ const registryReady = initializePluginRegistry().then((registry5) => {
5025
+ state.pluginRegistry = registry5;
5026
+ registerPluginMcpTools(server, registry5, state);
3523
5027
  });
3524
5028
  server._pluginsReady = registryReady;
3525
5029
  registerWorkspaceTools(server, state);
@@ -3534,6 +5038,9 @@ function createServer(state) {
3534
5038
  registerKnowledgeTools(server, state);
3535
5039
  registerDesignTools(server, state);
3536
5040
  registerCaptureTools(server, state);
5041
+ registerCritiqueTools(server, state);
5042
+ registerSeriesTools(server, state);
5043
+ registerReferenceTools(server, state);
3537
5044
  registerExportTools(server, state);
3538
5045
  registerResources(server, state);
3539
5046
  registerPrompts(server, state);
@@ -4298,6 +5805,276 @@ function registerCaptureTools(server, state) {
4298
5805
  }
4299
5806
  );
4300
5807
  }
5808
+ function registerCritiqueTools(server, state) {
5809
+ server.tool(
5810
+ "critique_sketch",
5811
+ "Capture a sketch screenshot and return a structured self-critique framework (questions, principles, pitfalls) per aspect. Severity calibrates to compositionLevel.",
5812
+ {
5813
+ sketchId: z2.string().optional().describe("Sketch to critique (default: selected sketch)"),
5814
+ aspects: z2.array(z2.enum(["composition", "color", "rhythm", "unity", "expression"])).optional().describe("Aspects to critique (default: all five)"),
5815
+ previewSize: z2.number().optional().describe("Max dimension for inline preview JPEG (default: 400)")
5816
+ },
5817
+ async (args) => {
5818
+ try {
5819
+ const result = await critiqueSketch(state, args);
5820
+ return {
5821
+ content: [
5822
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) },
5823
+ { type: "image", data: result.previewJpegBase64, mimeType: "image/jpeg" }
5824
+ ]
5825
+ };
5826
+ } catch (e) {
5827
+ return toolError(e instanceof Error ? e.message : String(e));
5828
+ }
5829
+ }
5830
+ );
5831
+ server.tool(
5832
+ "compare_sketches",
5833
+ "Side-by-side capture of 2-4 sketches with a structured comparison framework across specified aspects.",
5834
+ {
5835
+ sketchIds: z2.array(z2.string()).describe("IDs of 2-4 sketches to compare"),
5836
+ aspects: z2.array(z2.enum(["composition", "color", "rhythm", "unity", "expression"])).optional().describe("Aspects to compare (default: all five)"),
5837
+ previewSize: z2.number().optional().describe("Max dimension for inline preview JPEGs (default: 300)")
5838
+ },
5839
+ async (args) => {
5840
+ try {
5841
+ const result = await compareSketches(state, args);
5842
+ const content = [
5843
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
5844
+ ];
5845
+ for (const preview of result.previews) {
5846
+ content.push({
5847
+ type: "text",
5848
+ text: `--- Sketch: ${preview.sketchId} ---`
5849
+ });
5850
+ content.push({
5851
+ type: "image",
5852
+ data: preview.inlineJpegBase64,
5853
+ mimeType: "image/jpeg"
5854
+ });
5855
+ }
5856
+ return { content };
5857
+ } catch (e) {
5858
+ return toolError(e instanceof Error ? e.message : String(e));
5859
+ }
5860
+ }
5861
+ );
5862
+ }
5863
+ function registerSeriesTools(server, state) {
5864
+ server.tool(
5865
+ "create_series",
5866
+ "Create a new curated series of sketches with narrative, intent, and studio workflow stages",
5867
+ {
5868
+ label: z2.string().describe("Display label for the series"),
5869
+ narrative: z2.string().describe("Prose narrative describing the artistic exploration"),
5870
+ intent: z2.string().describe("Short statement of artistic intent"),
5871
+ progression: z2.string().optional().describe(
5872
+ "Series progression type (e.g. 'linear', 'branching', 'iterative')"
5873
+ ),
5874
+ stages: z2.array(z2.enum(["studies", "drafts", "refinements", "finals"])).optional().describe(
5875
+ "Ordered stages in the studio workflow (default: all four)"
5876
+ ),
5877
+ sketchFiles: z2.array(z2.string()).optional().describe("File names of existing sketches to include")
5878
+ },
5879
+ async (args) => {
5880
+ try {
5881
+ const result = await createSeries(state, args);
5882
+ return jsonResult(result);
5883
+ } catch (e) {
5884
+ return toolError(e instanceof Error ? e.message : String(e));
5885
+ }
5886
+ }
5887
+ );
5888
+ server.tool(
5889
+ "develop_concept",
5890
+ "Generate a structured concept development plan with mood, palette, composition, skills, and series structure recommendations",
5891
+ {
5892
+ concept: z2.string().describe("The artistic concept or theme to develop"),
5893
+ medium: z2.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Preferred renderer/medium (default: p5)")
5894
+ },
5895
+ async (args) => {
5896
+ try {
5897
+ const result = await developConcept(state, args);
5898
+ return jsonResult(result);
5899
+ } catch (e) {
5900
+ return toolError(e instanceof Error ? e.message : String(e));
5901
+ }
5902
+ }
5903
+ );
5904
+ server.tool(
5905
+ "series_summary",
5906
+ "Capture all sketches in a series with narrative context for holistic evaluation",
5907
+ {
5908
+ seriesId: z2.string().describe("ID of the series to summarize"),
5909
+ captureScreenshots: z2.boolean().optional().describe("Capture screenshots of each sketch (default: true)"),
5910
+ previewSize: z2.number().optional().describe("Preview image size in pixels (default: 300)")
5911
+ },
5912
+ async (args) => {
5913
+ try {
5914
+ const result = await seriesSummary(state, args);
5915
+ const content = [
5916
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
5917
+ ];
5918
+ if (result.previews) {
5919
+ for (const preview of result.previews) {
5920
+ content.push({
5921
+ type: "image",
5922
+ data: preview.inlineJpegBase64,
5923
+ mimeType: "image/jpeg"
5924
+ });
5925
+ }
5926
+ }
5927
+ return { content };
5928
+ } catch (e) {
5929
+ return toolError(e instanceof Error ? e.message : String(e));
5930
+ }
5931
+ }
5932
+ );
5933
+ server.tool(
5934
+ "promote_sketch",
5935
+ "Promote a sketch to the next studio workflow stage \u2014 fork, upscale canvas, update compositionLevel, and add to series",
5936
+ {
5937
+ sketchId: z2.string().describe("ID of the sketch to promote"),
5938
+ toStage: z2.enum(["studies", "drafts", "refinements", "finals"]).describe("Target stage to promote to"),
5939
+ seriesId: z2.string().optional().describe("Series to add the promoted sketch to"),
5940
+ newId: z2.string().optional().describe(
5941
+ "URL-safe kebab-case ID for the promoted sketch (default: auto-generated)"
5942
+ ),
5943
+ title: z2.string().optional().describe("Title for the promoted sketch (default: auto-generated)"),
5944
+ agent: z2.string().optional().describe("CLI agent name"),
5945
+ model: z2.string().optional().describe("AI model identifier")
5946
+ },
5947
+ async (args) => {
5948
+ try {
5949
+ const result = await promoteSketch(state, args);
5950
+ return jsonResult(result);
5951
+ } catch (e) {
5952
+ return toolError(e instanceof Error ? e.message : String(e));
5953
+ }
5954
+ }
5955
+ );
5956
+ }
5957
+ function registerReferenceTools(server, state) {
5958
+ server.tool(
5959
+ "add_reference",
5960
+ "Import an image as a reference for inspiration. Copies the image to the workspace references/ directory and attaches it to a series or sketch.",
5961
+ {
5962
+ image: z2.string().describe("Path to the reference image file"),
5963
+ type: z2.enum(["image", "artwork", "photograph", "texture", "palette"]).optional().describe("Reference type (default: image)"),
5964
+ source: z2.string().optional().describe("Source attribution (artist, URL, collection)"),
5965
+ seriesId: z2.string().optional().describe("Series to attach the reference to"),
5966
+ sketchId: z2.string().optional().describe("Sketch to attach the reference to"),
5967
+ id: z2.string().optional().describe("Custom reference ID (default: derived from filename)")
5968
+ },
5969
+ async (args) => {
5970
+ try {
5971
+ const result = await addReference(state, args);
5972
+ return jsonResult(result);
5973
+ } catch (e) {
5974
+ return toolError(e instanceof Error ? e.message : String(e));
5975
+ }
5976
+ }
5977
+ );
5978
+ server.tool(
5979
+ "analyze_reference",
5980
+ "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.",
5981
+ {
5982
+ referenceId: z2.string().describe("ID of the reference to analyze"),
5983
+ seriesId: z2.string().optional().describe("Series the reference belongs to (speeds up lookup)"),
5984
+ sketchId: z2.string().optional().describe("Sketch the reference belongs to (speeds up lookup)"),
5985
+ previewSize: z2.number().optional().describe("Max dimension for preview image (default: native)")
5986
+ },
5987
+ async (args) => {
5988
+ try {
5989
+ const result = await analyzeReference(state, args);
5990
+ const content = [
5991
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
5992
+ ];
5993
+ if (result.previewJpegBase64) {
5994
+ const ext = (result.metadata["path"] ?? ".png").split(".").pop() ?? "png";
5995
+ const mimeMap = {
5996
+ png: "image/png",
5997
+ jpg: "image/jpeg",
5998
+ jpeg: "image/jpeg",
5999
+ gif: "image/gif",
6000
+ webp: "image/webp",
6001
+ svg: "image/svg+xml"
6002
+ };
6003
+ content.push({
6004
+ type: "image",
6005
+ data: result.previewJpegBase64,
6006
+ mimeType: mimeMap[ext] ?? "image/png"
6007
+ });
6008
+ }
6009
+ return { content };
6010
+ } catch (e) {
6011
+ return toolError(e instanceof Error ? e.message : String(e));
6012
+ }
6013
+ }
6014
+ );
6015
+ server.tool(
6016
+ "update_reference_analysis",
6017
+ "Save a structured analysis (composition, palette, rhythm, mood, technique) back to a reference after studying it with analyze_reference.",
6018
+ {
6019
+ referenceId: z2.string().describe("ID of the reference to update"),
6020
+ seriesId: z2.string().optional().describe("Series the reference belongs to"),
6021
+ sketchId: z2.string().optional().describe("Sketch the reference belongs to"),
6022
+ analysis: z2.object({
6023
+ composition: z2.string().optional().describe("Compositional structure observations"),
6024
+ palette: z2.array(z2.string()).optional().describe("Dominant colors as hex values"),
6025
+ rhythm: z2.string().optional().describe("Visual rhythm and pattern observations"),
6026
+ mood: z2.string().optional().describe("Mood and emotional qualities"),
6027
+ technique: z2.string().optional().describe("Technique and medium observations"),
6028
+ keyQualities: z2.array(z2.string()).optional().describe("Key qualities worth studying")
6029
+ }).describe("Structured analysis to save")
6030
+ },
6031
+ async (args) => {
6032
+ try {
6033
+ const result = await updateReferenceAnalysis(state, args);
6034
+ return jsonResult(result);
6035
+ } catch (e) {
6036
+ return toolError(e instanceof Error ? e.message : String(e));
6037
+ }
6038
+ }
6039
+ );
6040
+ server.tool(
6041
+ "extract_palette",
6042
+ "Return a reference image for color palette extraction, with guidelines for identifying dominant colors. The agent extracts hex colors visually.",
6043
+ {
6044
+ referenceId: z2.string().describe("ID of the reference to extract palette from"),
6045
+ seriesId: z2.string().optional().describe("Series the reference belongs to"),
6046
+ sketchId: z2.string().optional().describe("Sketch the reference belongs to"),
6047
+ count: z2.number().optional().describe("Number of colors to extract (default: 6)")
6048
+ },
6049
+ async (args) => {
6050
+ try {
6051
+ const result = await extractPalette(state, args);
6052
+ const content = [
6053
+ { type: "text", text: JSON.stringify(result.metadata, null, 2) }
6054
+ ];
6055
+ if (result.previewJpegBase64) {
6056
+ const ext = (result.metadata["path"] ?? ".png").split(".").pop() ?? "png";
6057
+ const mimeMap = {
6058
+ png: "image/png",
6059
+ jpg: "image/jpeg",
6060
+ jpeg: "image/jpeg",
6061
+ gif: "image/gif",
6062
+ webp: "image/webp",
6063
+ svg: "image/svg+xml"
6064
+ };
6065
+ content.push({
6066
+ type: "image",
6067
+ data: result.previewJpegBase64,
6068
+ mimeType: mimeMap[ext] ?? "image/png"
6069
+ });
6070
+ }
6071
+ return { content };
6072
+ } catch (e) {
6073
+ return toolError(e instanceof Error ? e.message : String(e));
6074
+ }
6075
+ }
6076
+ );
6077
+ }
4301
6078
  function registerExportTools(server, state) {
4302
6079
  server.tool(
4303
6080
  "export_sketch",
@@ -4562,7 +6339,7 @@ function registerDesignTools(server, state) {
4562
6339
  }
4563
6340
  );
4564
6341
  }
4565
- function registerKnowledgeTools(server, _state) {
6342
+ function registerKnowledgeTools(server, state) {
4566
6343
  server.tool(
4567
6344
  "list_skills",
4568
6345
  "List all available design knowledge skills (Phase 5)",
@@ -4598,7 +6375,7 @@ function registerKnowledgeTools(server, _state) {
4598
6375
  "get_guidelines",
4599
6376
  "Return design guidelines and best practices for a topic (Phase 5)",
4600
6377
  {
4601
- topic: z2.enum(["composition", "color", "parameters", "animation", "performance"]).describe("Guideline topic"),
6378
+ topic: z2.enum(["composition", "color", "process", "painting", "illustration", "parameters", "animation", "performance"]).describe("Guideline topic"),
4602
6379
  renderer: z2.enum(["p5", "three", "glsl", "canvas2d", "svg"]).optional().describe("Renderer-specific guidance")
4603
6380
  },
4604
6381
  async (args) => {
@@ -4610,12 +6387,28 @@ function registerKnowledgeTools(server, _state) {
4610
6387
  }
4611
6388
  }
4612
6389
  );
6390
+ server.tool(
6391
+ "suggest_skills",
6392
+ "Recommend relevant design skills based on sketch context and/or free-text description",
6393
+ {
6394
+ sketchId: z2.string().optional().describe("ID of a loaded sketch to analyze for skill recommendations"),
6395
+ context: z2.string().optional().describe("Free-text description of what you're working on (e.g., 'atmospheric landscape with watercolor')")
6396
+ },
6397
+ async (args) => {
6398
+ try {
6399
+ const result = await suggestSkills(state, args);
6400
+ return jsonResult(result);
6401
+ } catch (e) {
6402
+ return toolError(e instanceof Error ? e.message : String(e));
6403
+ }
6404
+ }
6405
+ );
4613
6406
  }
4614
6407
 
4615
6408
  // src/state.ts
4616
6409
  import { EventEmitter } from "events";
4617
- import { readFile as readFile4 } from "fs/promises";
4618
- import { dirname as dirname6, isAbsolute, resolve as resolve2 } from "path";
6410
+ import { readFile as readFile5 } from "fs/promises";
6411
+ import { dirname as dirname8, isAbsolute, resolve as resolve4 } from "path";
4619
6412
 
4620
6413
  // src/sidecar.ts
4621
6414
  function isSidecarMode() {
@@ -4633,11 +6426,11 @@ function notifyMutation(type, payload) {
4633
6426
  import {
4634
6427
  parseGenart as parseGenart4,
4635
6428
  parseWorkspace as parseWorkspace2,
4636
- serializeGenart as serializeGenart5,
4637
- serializeWorkspace as serializeWorkspace3,
6429
+ serializeGenart as serializeGenart7,
6430
+ serializeWorkspace as serializeWorkspace5,
4638
6431
  createLayerStack
4639
6432
  } from "@genart-dev/core";
4640
- import { writeFile as writeFile7 } from "fs/promises";
6433
+ import { writeFile as writeFile9 } from "fs/promises";
4641
6434
  var EditorState = class extends EventEmitter {
4642
6435
  /** Absolute path to the active .genart-workspace file, or null. */
4643
6436
  workspacePath = null;
@@ -4686,10 +6479,10 @@ var EditorState = class extends EventEmitter {
4686
6479
  }
4687
6480
  if ((file.startsWith("~/") || file === "~") && !this.basePath) {
4688
6481
  const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
4689
- return resolve2(home, file.slice(2));
6482
+ return resolve4(home, file.slice(2));
4690
6483
  }
4691
6484
  const base = this.basePath ?? process.cwd();
4692
- const resolved = resolve2(base, file);
6485
+ const resolved = resolve4(base, file);
4693
6486
  if (this.basePath && !resolved.startsWith(this.basePath)) {
4694
6487
  throw new Error(`Path escapes sandbox: ${resolved}`);
4695
6488
  }
@@ -4705,11 +6498,11 @@ var EditorState = class extends EventEmitter {
4705
6498
  }
4706
6499
  if (!this.workspacePath) {
4707
6500
  if (this.basePath) {
4708
- return resolve2(this.basePath, file);
6501
+ return resolve4(this.basePath, file);
4709
6502
  }
4710
6503
  throw new Error("No workspace is currently open");
4711
6504
  }
4712
- const resolved = resolve2(dirname6(this.workspacePath), file);
6505
+ const resolved = resolve4(dirname8(this.workspacePath), file);
4713
6506
  if (this.basePath && !resolved.startsWith(this.basePath)) {
4714
6507
  throw new Error(`Path escapes sandbox: ${resolved}`);
4715
6508
  }
@@ -4720,7 +6513,7 @@ var EditorState = class extends EventEmitter {
4720
6513
  if (this.basePath && !absPath.startsWith(this.basePath)) {
4721
6514
  throw new Error(`Path escapes sandbox: ${absPath}`);
4722
6515
  }
4723
- const raw = await readFile4(absPath, "utf-8");
6516
+ const raw = await readFile5(absPath, "utf-8");
4724
6517
  const json = JSON.parse(raw);
4725
6518
  const ws = parseWorkspace2(json);
4726
6519
  this.workspacePath = absPath;
@@ -4739,7 +6532,7 @@ var EditorState = class extends EventEmitter {
4739
6532
  if (this.basePath && !absPath.startsWith(this.basePath)) {
4740
6533
  throw new Error(`Path escapes sandbox: ${absPath}`);
4741
6534
  }
4742
- const raw = await readFile4(absPath, "utf-8");
6535
+ const raw = await readFile5(absPath, "utf-8");
4743
6536
  const json = JSON.parse(raw);
4744
6537
  const definition = parseGenart4(json);
4745
6538
  this.sketches.set(definition.id, { definition, path: absPath });
@@ -4777,18 +6570,18 @@ var EditorState = class extends EventEmitter {
4777
6570
  if (!this.workspace || !this.workspacePath) {
4778
6571
  throw new Error("No workspace is currently open");
4779
6572
  }
4780
- const json = serializeWorkspace3(this.workspace);
6573
+ const json = serializeWorkspace5(this.workspace);
4781
6574
  if (!this.remoteMode) {
4782
- await writeFile7(this.workspacePath, json, "utf-8");
6575
+ await writeFile9(this.workspacePath, json, "utf-8");
4783
6576
  }
4784
6577
  this.emitMutation("workspace:saved", { path: this.workspacePath });
4785
6578
  }
4786
6579
  /** Save a sketch to disk. */
4787
6580
  async saveSketch(id) {
4788
6581
  const loaded = this.requireSketch(id);
4789
- const json = serializeGenart5(loaded.definition);
6582
+ const json = serializeGenart7(loaded.definition);
4790
6583
  if (!this.remoteMode) {
4791
- await writeFile7(loaded.path, json, "utf-8");
6584
+ await writeFile9(loaded.path, json, "utf-8");
4792
6585
  }
4793
6586
  this.emitMutation("sketch:saved", { id, path: loaded.path });
4794
6587
  }
@@ -4860,9 +6653,40 @@ var EditorState = class extends EventEmitter {
4860
6653
  canvasHeight: def.canvas.height,
4861
6654
  rendererId: def.renderer.type
4862
6655
  };
6656
+ const sketch = {
6657
+ getSymbols() {
6658
+ return loaded.definition.symbols ?? {};
6659
+ },
6660
+ setSymbols(symbols) {
6661
+ loaded.definition = { ...loaded.definition, symbols };
6662
+ },
6663
+ getComponents() {
6664
+ return loaded.definition.components ?? {};
6665
+ },
6666
+ setComponents(components) {
6667
+ loaded.definition = { ...loaded.definition, components };
6668
+ },
6669
+ getThirdParty() {
6670
+ const def2 = loaded.definition;
6671
+ return def2["thirdParty"] ?? [];
6672
+ },
6673
+ setThirdParty(notices) {
6674
+ loaded.definition["thirdParty"] = notices;
6675
+ },
6676
+ getRenderer() {
6677
+ return loaded.definition.renderer.type;
6678
+ },
6679
+ getGenartVersion() {
6680
+ return loaded.definition.genart;
6681
+ },
6682
+ setGenartVersion(version) {
6683
+ loaded.definition = { ...loaded.definition, genart: version };
6684
+ }
6685
+ };
4863
6686
  return {
4864
6687
  layers: layerStack,
4865
6688
  sketchState,
6689
+ sketch,
4866
6690
  canvasWidth: def.canvas.width,
4867
6691
  canvasHeight: def.canvas.height,
4868
6692
  async resolveAsset(_assetId) {