@project-ava-supernova/core 0.2.176 → 0.2.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/agent/agent.d.ts +3 -0
  2. package/dist/agent/agent.d.ts.map +1 -1
  3. package/dist/agent/agent.js +44 -11
  4. package/dist/agent/agent.js.map +1 -1
  5. package/dist/agent/social-craft.d.ts +30 -67
  6. package/dist/agent/social-craft.d.ts.map +1 -1
  7. package/dist/agent/social-craft.js +58 -185
  8. package/dist/agent/social-craft.js.map +1 -1
  9. package/dist/agent/system-prompt.d.ts +10 -3
  10. package/dist/agent/system-prompt.d.ts.map +1 -1
  11. package/dist/agent/system-prompt.js +1184 -1321
  12. package/dist/agent/system-prompt.js.map +1 -1
  13. package/dist/auto/aurora-router.d.ts +1 -1
  14. package/dist/auto/aurora-router.d.ts.map +1 -1
  15. package/dist/auto/aurora-router.js +4 -1
  16. package/dist/auto/aurora-router.js.map +1 -1
  17. package/dist/auto/auto-coordinator.d.ts.map +1 -1
  18. package/dist/auto/auto-coordinator.js +2 -1
  19. package/dist/auto/auto-coordinator.js.map +1 -1
  20. package/dist/auto/longxiang-router.d.ts.map +1 -1
  21. package/dist/auto/longxiang-router.js +1 -0
  22. package/dist/auto/longxiang-router.js.map +1 -1
  23. package/dist/auto/model-router.d.ts.map +1 -1
  24. package/dist/auto/model-router.js +1 -0
  25. package/dist/auto/model-router.js.map +1 -1
  26. package/dist/auto/supernova-router.d.ts.map +1 -1
  27. package/dist/auto/supernova-router.js +3 -0
  28. package/dist/auto/supernova-router.js.map +1 -1
  29. package/dist/auto/task-classifier.d.ts.map +1 -1
  30. package/dist/auto/task-classifier.js +8 -1
  31. package/dist/auto/task-classifier.js.map +1 -1
  32. package/dist/auto/types.d.ts +1 -1
  33. package/dist/auto/types.d.ts.map +1 -1
  34. package/dist/brand/brand-kits.d.ts +217 -0
  35. package/dist/brand/brand-kits.d.ts.map +1 -0
  36. package/dist/brand/brand-kits.js +681 -0
  37. package/dist/brand/brand-kits.js.map +1 -0
  38. package/dist/brand/kit-py.d.ts +7 -0
  39. package/dist/brand/kit-py.d.ts.map +1 -0
  40. package/dist/brand/kit-py.js +49 -0
  41. package/dist/brand/kit-py.js.map +1 -0
  42. package/dist/config/schema.d.ts +5 -0
  43. package/dist/config/schema.d.ts.map +1 -1
  44. package/dist/config/schema.js.map +1 -1
  45. package/dist/creative/folder-export.d.ts +72 -0
  46. package/dist/creative/folder-export.d.ts.map +1 -0
  47. package/dist/creative/folder-export.js +463 -0
  48. package/dist/creative/folder-export.js.map +1 -0
  49. package/dist/creative/library-folders.d.ts +171 -0
  50. package/dist/creative/library-folders.d.ts.map +1 -0
  51. package/dist/creative/library-folders.js +515 -0
  52. package/dist/creative/library-folders.js.map +1 -0
  53. package/dist/creative/library-upload.d.ts +23 -0
  54. package/dist/creative/library-upload.d.ts.map +1 -0
  55. package/dist/creative/library-upload.js +152 -0
  56. package/dist/creative/library-upload.js.map +1 -0
  57. package/dist/creative/making-report.d.ts +46 -0
  58. package/dist/creative/making-report.d.ts.map +1 -0
  59. package/dist/creative/making-report.js +244 -0
  60. package/dist/creative/making-report.js.map +1 -0
  61. package/dist/creative/pack-plan-status.d.ts +18 -0
  62. package/dist/creative/pack-plan-status.d.ts.map +1 -0
  63. package/dist/creative/pack-plan-status.js +58 -0
  64. package/dist/creative/pack-plan-status.js.map +1 -0
  65. package/dist/creative/store-profiles.d.ts +46 -0
  66. package/dist/creative/store-profiles.d.ts.map +1 -0
  67. package/dist/creative/store-profiles.js +486 -0
  68. package/dist/creative/store-profiles.js.map +1 -0
  69. package/dist/docs/data/tools.d.ts.map +1 -1
  70. package/dist/docs/data/tools.js +17 -0
  71. package/dist/docs/data/tools.js.map +1 -1
  72. package/dist/index.d.ts +32 -1
  73. package/dist/index.d.ts.map +1 -1
  74. package/dist/index.js +22 -0
  75. package/dist/index.js.map +1 -1
  76. package/dist/memory/config.d.ts +12 -0
  77. package/dist/memory/config.d.ts.map +1 -1
  78. package/dist/memory/config.js +12 -0
  79. package/dist/memory/config.js.map +1 -1
  80. package/dist/memory/memory-manager.d.ts +11 -0
  81. package/dist/memory/memory-manager.d.ts.map +1 -1
  82. package/dist/memory/memory-manager.js +90 -2
  83. package/dist/memory/memory-manager.js.map +1 -1
  84. package/dist/memory/project-brain.d.ts.map +1 -1
  85. package/dist/memory/project-brain.js +2 -1
  86. package/dist/memory/project-brain.js.map +1 -1
  87. package/dist/memory/tfidf.d.ts +10 -0
  88. package/dist/memory/tfidf.d.ts.map +1 -1
  89. package/dist/memory/tfidf.js +27 -0
  90. package/dist/memory/tfidf.js.map +1 -1
  91. package/dist/portability/bundle.d.ts.map +1 -1
  92. package/dist/portability/bundle.js +1 -0
  93. package/dist/portability/bundle.js.map +1 -1
  94. package/dist/portability/factory-reset.js +1 -1
  95. package/dist/portability/factory-reset.js.map +1 -1
  96. package/dist/social/index.d.ts +57 -0
  97. package/dist/social/index.d.ts.map +1 -1
  98. package/dist/social/index.js +54 -5
  99. package/dist/social/index.js.map +1 -1
  100. package/dist/social/tag-volume.d.ts +7 -0
  101. package/dist/social/tag-volume.d.ts.map +1 -1
  102. package/dist/social/tag-volume.js +27 -0
  103. package/dist/social/tag-volume.js.map +1 -1
  104. package/dist/tools/blender/build-model.d.ts +62 -0
  105. package/dist/tools/blender/build-model.d.ts.map +1 -0
  106. package/dist/tools/blender/build-model.js +501 -0
  107. package/dist/tools/blender/build-model.js.map +1 -0
  108. package/dist/tools/blender/find-blender.d.ts +43 -0
  109. package/dist/tools/blender/find-blender.d.ts.map +1 -0
  110. package/dist/tools/blender/find-blender.js +154 -0
  111. package/dist/tools/blender/find-blender.js.map +1 -0
  112. package/dist/tools/blender/model-brief.d.ts +64 -0
  113. package/dist/tools/blender/model-brief.d.ts.map +1 -0
  114. package/dist/tools/blender/model-brief.js +117 -0
  115. package/dist/tools/blender/model-brief.js.map +1 -0
  116. package/dist/tools/blender/model-history.d.ts +42 -0
  117. package/dist/tools/blender/model-history.d.ts.map +1 -0
  118. package/dist/tools/blender/model-history.js +145 -0
  119. package/dist/tools/blender/model-history.js.map +1 -0
  120. package/dist/tools/blender/paths.d.ts +20 -0
  121. package/dist/tools/blender/paths.d.ts.map +1 -0
  122. package/dist/tools/blender/paths.js +37 -0
  123. package/dist/tools/blender/paths.js.map +1 -0
  124. package/dist/tools/blender/runner-py.d.ts +2 -0
  125. package/dist/tools/blender/runner-py.d.ts.map +1 -0
  126. package/dist/tools/blender/runner-py.js +455 -0
  127. package/dist/tools/blender/runner-py.js.map +1 -0
  128. package/dist/tools/brief-store.d.ts +28 -0
  129. package/dist/tools/brief-store.d.ts.map +1 -0
  130. package/dist/tools/brief-store.js +76 -0
  131. package/dist/tools/brief-store.js.map +1 -0
  132. package/dist/tools/check-posts.d.ts.map +1 -1
  133. package/dist/tools/check-posts.js +21 -3
  134. package/dist/tools/check-posts.js.map +1 -1
  135. package/dist/tools/design-checkin.d.ts +28 -0
  136. package/dist/tools/design-checkin.d.ts.map +1 -0
  137. package/dist/tools/design-checkin.js +74 -0
  138. package/dist/tools/design-checkin.js.map +1 -0
  139. package/dist/tools/design-docs.d.ts +37 -0
  140. package/dist/tools/design-docs.d.ts.map +1 -0
  141. package/dist/tools/design-docs.js +367 -0
  142. package/dist/tools/design-docs.js.map +1 -0
  143. package/dist/tools/design-folder.d.ts +24 -0
  144. package/dist/tools/design-folder.d.ts.map +1 -0
  145. package/dist/tools/design-folder.js +277 -0
  146. package/dist/tools/design-folder.js.map +1 -0
  147. package/dist/tools/design-fonts.d.ts +58 -0
  148. package/dist/tools/design-fonts.d.ts.map +1 -0
  149. package/dist/tools/design-fonts.js +316 -0
  150. package/dist/tools/design-fonts.js.map +1 -0
  151. package/dist/tools/design-studio-tools.d.ts +16 -0
  152. package/dist/tools/design-studio-tools.d.ts.map +1 -1
  153. package/dist/tools/design-studio-tools.js +288 -43
  154. package/dist/tools/design-studio-tools.js.map +1 -1
  155. package/dist/tools/generation-manager.d.ts +1 -1
  156. package/dist/tools/generation-manager.d.ts.map +1 -1
  157. package/dist/tools/gimp/build-image.d.ts +161 -0
  158. package/dist/tools/gimp/build-image.d.ts.map +1 -0
  159. package/dist/tools/gimp/build-image.js +900 -0
  160. package/dist/tools/gimp/build-image.js.map +1 -0
  161. package/dist/tools/gimp/find-gimp.d.ts +32 -0
  162. package/dist/tools/gimp/find-gimp.d.ts.map +1 -0
  163. package/dist/tools/gimp/find-gimp.js +149 -0
  164. package/dist/tools/gimp/find-gimp.js.map +1 -0
  165. package/dist/tools/gimp/runner-py.d.ts +2 -0
  166. package/dist/tools/gimp/runner-py.d.ts.map +1 -0
  167. package/dist/tools/gimp/runner-py.js +750 -0
  168. package/dist/tools/gimp/runner-py.js.map +1 -0
  169. package/dist/tools/making-record.d.ts +80 -0
  170. package/dist/tools/making-record.d.ts.map +1 -0
  171. package/dist/tools/making-record.js +221 -0
  172. package/dist/tools/making-record.js.map +1 -0
  173. package/dist/tools/propose-brief.d.ts.map +1 -1
  174. package/dist/tools/propose-brief.js +6 -1
  175. package/dist/tools/propose-brief.js.map +1 -1
  176. package/dist/tools/research-post.d.ts +1 -1
  177. package/dist/tools/research-post.d.ts.map +1 -1
  178. package/dist/tools/research-post.js +20 -9
  179. package/dist/tools/research-post.js.map +1 -1
  180. package/dist/tools/review-post.d.ts +25 -0
  181. package/dist/tools/review-post.d.ts.map +1 -0
  182. package/dist/tools/review-post.js +63 -0
  183. package/dist/tools/review-post.js.map +1 -0
  184. package/dist/tools/tool-registry.d.ts.map +1 -1
  185. package/dist/tools/tool-registry.js +42 -1
  186. package/dist/tools/tool-registry.js.map +1 -1
  187. package/dist/tools/tool-request-words.d.ts +7 -0
  188. package/dist/tools/tool-request-words.d.ts.map +1 -0
  189. package/dist/tools/tool-request-words.js +39 -0
  190. package/dist/tools/tool-request-words.js.map +1 -0
  191. package/dist/tools/write-post.d.ts.map +1 -1
  192. package/dist/tools/write-post.js +38 -2
  193. package/dist/tools/write-post.js.map +1 -1
  194. package/dist/tools/write-video-post.d.ts.map +1 -1
  195. package/dist/tools/write-video-post.js +10 -1
  196. package/dist/tools/write-video-post.js.map +1 -1
  197. package/package.json +2 -1
@@ -0,0 +1,900 @@
1
+ /**
2
+ * Design Studio 2D — Ava makes images in GIMP with no window.
3
+ *
4
+ * The same shape as design_build_model (his call, 1 Nov 2026: GIMP is Phase 4,
5
+ * the same pattern as Blender). A piece of work lives in its own folder under
6
+ * ~/.ava/creative/gimp/<name>/: one layered .xcf per image, a PNG of each, and
7
+ * anything exported at exact sizes in exports/. A set is several images in one
8
+ * folder. Saved work is reopened, including what the person changed by hand in
9
+ * GIMP; a run that fails saves nothing; the last 5 versions of each image are
10
+ * kept; the brief is agreed on the card first.
11
+ *
12
+ * Generation is an aid here, never the maker (his direction, 3 Nov 2026): an
13
+ * image from Open Canvas can be brought in as a layer with ava_place, and the
14
+ * work stays in layers the person owns.
15
+ */
16
+ import { spawn } from 'node:child_process';
17
+ import { existsSync } from 'node:fs';
18
+ import { mkdir, writeFile, readFile, readdir, stat, rm, cp, copyFile } from 'node:fs/promises';
19
+ import { basename, join, resolve, sep } from 'node:path';
20
+ import { tmpdir } from 'node:os';
21
+ import { randomUUID } from 'node:crypto';
22
+ import { designRunRefusal, recordDesignRun } from '../design-checkin.js';
23
+ import { creativeDir, imagesDir, metadataFile, modelSlug } from '../blender/paths.js';
24
+ import { kitForProject, kitForScripts, kitPieceStates } from '../../brand/brand-kits.js';
25
+ import { briefStore } from '../brief-store.js';
26
+ import { appendMaking, avaContext, beforeChange, fontLicences, sourcesNow } from '../making-record.js';
27
+ import { fileLinkedWork } from '../../creative/library-folders.js';
28
+ import { findGimp, GIMP_DOWNLOAD_URL } from './find-gimp.js';
29
+ import { GIMP_RUNNER_PY } from './runner-py.js';
30
+ const DEFAULT_TIMEOUT_S = 180;
31
+ const MAX_TIMEOUT_S = 600;
32
+ const MAX_OUTPUT = 400_000;
33
+ // ── The brief ────────────────────────────────────────────────────────────────
34
+ export const IMAGE_BRIEF_FIELDS = [
35
+ ['what', 'What it is', 'e.g. "the stat icons for a sci-fi character screen"'],
36
+ ['where', 'Where it is used', 'e.g. "the stat panel, on a dark teal UI, read at a glance"'],
37
+ ['style', 'Style', 'the look — and why it suits where it lives'],
38
+ ['sizes', 'Exact sizes', 'pixel sizes and formats, e.g. "64×64 and 128×128 PNG, transparent"'],
39
+ ['set', 'The set', 'how many, and each item by name — or "just this one"'],
40
+ ['palette', 'Palette', 'the colours, as hex, taken from what it sits beside'],
41
+ ['references', 'References', 'what you found that shows how this kind of thing is done well'],
42
+ ['aid', 'Generation aid', 'whether a generated image helps here and for what — or "none, GIMP alone"'],
43
+ ['purpose', 'Purpose', 'their own project, or for sale'],
44
+ ];
45
+ const store = briefStore(imagesDir, () => IMAGE_BRIEF_FIELDS.map(([k]) => k), 'gimp');
46
+ export const readImageBrief = store.read;
47
+ export const agreeImageBrief = store.agree;
48
+ export const saveImageBriefEdits = store.saveEdits;
49
+ export const formatImageBrief = (b) => IMAGE_BRIEF_FIELDS.map(([k, label]) => `${label}: ${b[k] || '—'}`).join('\n');
50
+ const IMAGE_FILE = /\.(png|jpe?g|webp)$/i;
51
+ const MAX_ART_BYTES = 50 * 1024 * 1024;
52
+ /** A work makes dozens of tests and comparisons on the way to a few finished
53
+ * files. This list is what counts as the work, wherever it is offered. */
54
+ export async function readImageFinals(slug) {
55
+ try {
56
+ const parsed = JSON.parse(await readFile(join(imagesDir(), slug, 'finals.json'), 'utf-8'));
57
+ if (!Array.isArray(parsed))
58
+ return [];
59
+ return parsed.filter((f) => typeof f === 'string' && existsSync(join(imagesDir(), slug, f)));
60
+ }
61
+ catch {
62
+ return [];
63
+ }
64
+ }
65
+ const writeFinals = (slug, files) => writeFile(join(imagesDir(), slug, 'finals.json'), JSON.stringify(files, null, 2), 'utf-8');
66
+ /** Their click on the stage: this file isn't final after all. */
67
+ export async function removeImageFinal(slug, file) {
68
+ if (modelSlug(slug) !== slug)
69
+ return;
70
+ const finals = await readImageFinals(slug);
71
+ if (!finals.includes(file))
72
+ return;
73
+ await writeFinals(slug, finals.filter((f) => f !== file));
74
+ const dir = join(imagesDir(), slug);
75
+ await beforeChange(dir, 'gimp');
76
+ await appendMaking(dir, { event: 'final_removed', by: 'person', tool: 'gimp', file });
77
+ }
78
+ const PERSON = { by: 'person' };
79
+ export async function readImageOptions(slug) {
80
+ try {
81
+ return JSON.parse(await readFile(join(imagesDir(), slug, 'options.json'), 'utf-8'));
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ /** Their click on the stage. Only they choose: her tool can only ask. */
88
+ export async function pickImageOption(slug, index) {
89
+ if (modelSlug(slug) !== slug)
90
+ return null;
91
+ const current = await readImageOptions(slug);
92
+ const option = current?.status === 'waiting' ? current.options[index] : undefined;
93
+ if (!current || !option)
94
+ return null;
95
+ await writeFile(join(imagesDir(), slug, 'options.json'), JSON.stringify({ ...current, status: 'picked', picked: index }, null, 2), 'utf-8');
96
+ const dir = join(imagesDir(), slug);
97
+ await beforeChange(dir, 'gimp');
98
+ await appendMaking(dir, { event: 'option_picked', by: 'person', tool: 'gimp', question: current.question, label: option.label, file: option.file });
99
+ return option;
100
+ }
101
+ async function listImageReferences(slug) {
102
+ return (await readdir(join(imagesDir(), slug, 'references')).catch(() => [])).filter((f) => IMAGE_FILE.test(f)).sort();
103
+ }
104
+ /** A file they picked themselves in the Add your art dialog, copied into the
105
+ * work so her scripts can reach it. Her own tools have no way to do this. */
106
+ export async function addImageReference(slug, source) {
107
+ if (modelSlug(slug) !== slug || !existsSync(join(imagesDir(), slug)))
108
+ return { ok: false, error: 'That work could not be found.' };
109
+ if (!IMAGE_FILE.test(source))
110
+ return { ok: false, error: 'Use a PNG, JPEG or WebP image.' };
111
+ const size = (await stat(source).catch(() => null))?.size;
112
+ if (size === undefined)
113
+ return { ok: false, error: 'That file could not be read.' };
114
+ if (size > MAX_ART_BYTES)
115
+ return { ok: false, error: 'That image is over 50 MB.' };
116
+ const dir = join(imagesDir(), slug, 'references');
117
+ await mkdir(dir, { recursive: true });
118
+ const base = (basename(source).replace(/[^\w.-]+/g, '-').replace(/^[.-]+/, '')) || 'art.png';
119
+ await copyFile(source, join(dir, base));
120
+ const work = join(imagesDir(), slug);
121
+ await beforeChange(work, 'gimp');
122
+ await appendMaking(work, { event: 'brought_in', by: 'person', tool: 'gimp', file: `references/${base}`, original: basename(source), ...(await libraryOrigin(source)) });
123
+ return { ok: true, file: `references/${base}` };
124
+ }
125
+ /**
126
+ * Where a file they brought in came from, when the Library knows. Open Canvas
127
+ * records how each picture was made from 9 Nov 2026: 'generated' with the AI
128
+ * model, or 'composed' (built by code from shapes and fonts, like a logo).
129
+ * Anything saved earlier says it is unknown, rather than assuming either way.
130
+ */
131
+ async function libraryOrigin(source) {
132
+ try {
133
+ const items = JSON.parse(await readFile(metadataFile(), 'utf-8'));
134
+ const norm = (p) => resolve(p).toLowerCase();
135
+ const hit = items.find((i) => typeof i.absolutePath === 'string' && norm(i.absolutePath) === norm(source));
136
+ if (!hit)
137
+ return { fromLibrary: false };
138
+ if (hit.kind === 'gimp' || hit.kind === 'model')
139
+ return { fromLibrary: true, libraryKind: hit.kind };
140
+ const made = hit.origin === 'generated' || hit.origin === 'composed' || hit.origin === 'uploaded' ? hit.origin : 'unknown';
141
+ return {
142
+ fromLibrary: true, libraryKind: hit.kind, libraryTitle: hit.title ?? null, made,
143
+ aiModel: made === 'generated' ? hit.aiModel ?? null : null,
144
+ aiProvider: made === 'generated' ? hit.aiProvider ?? null : null,
145
+ prompt: hit.prompt ?? null,
146
+ };
147
+ }
148
+ catch {
149
+ return {};
150
+ }
151
+ }
152
+ // ── History ──────────────────────────────────────────────────────────────────
153
+ // Each step saves over the same .xcf, so without this "I preferred it before"
154
+ // means redoing it by hand. After every run the images and preview are copied to
155
+ // history/<number>/. Going back copies them home and counts as a step itself, so
156
+ // nothing later is lost and they can go forward again. Exports and finals are
157
+ // separate files and stay as they are.
158
+ const HISTORY_KEEP = 20;
159
+ const historyFile = (slug) => join(imagesDir(), slug, 'history.json');
160
+ const stepFolder = (slug, number) => join(imagesDir(), slug, 'history', String(number));
161
+ export async function readImageHistory(slug) {
162
+ try {
163
+ const parsed = JSON.parse(await readFile(historyFile(slug), 'utf-8'));
164
+ return Array.isArray(parsed) ? parsed : [];
165
+ }
166
+ catch {
167
+ return [];
168
+ }
169
+ }
170
+ const imagesIn = async (dir) => (await readdir(dir, { withFileTypes: true }).catch(() => [])).filter((e) => e.isFile() && e.name.endsWith('.xcf')).map((e) => e.name);
171
+ export async function recordImageStep(slug, label) {
172
+ const dir = join(imagesDir(), slug);
173
+ const images = await imagesIn(dir);
174
+ if (images.length === 0)
175
+ return null;
176
+ const steps = await readImageHistory(slug);
177
+ const number = (steps.at(-1)?.number ?? 0) + 1;
178
+ const folder = stepFolder(slug, number);
179
+ await mkdir(folder, { recursive: true });
180
+ for (const file of images)
181
+ await copyFile(join(dir, file), join(folder, file));
182
+ const hasPreview = existsSync(join(dir, 'preview.png'));
183
+ if (hasPreview)
184
+ await copyFile(join(dir, 'preview.png'), join(folder, 'preview.png'));
185
+ const step = {
186
+ number, label: label.trim().slice(0, 80) || `Step ${number}`, at: new Date().toISOString(),
187
+ preview: hasPreview ? `history/${number}/preview.png` : null,
188
+ };
189
+ steps.push(step);
190
+ while (steps.length > HISTORY_KEEP) {
191
+ const oldest = steps.shift();
192
+ await rm(stepFolder(slug, oldest.number), { recursive: true, force: true });
193
+ }
194
+ await writeFile(historyFile(slug), JSON.stringify(steps, null, 2), 'utf-8');
195
+ return step;
196
+ }
197
+ /** Put the work back as it was at a step. Null if there is no such step. */
198
+ export async function restoreImageStep(slug, number, who = PERSON) {
199
+ const step = (await readImageHistory(slug)).find((s) => s.number === number);
200
+ if (!step)
201
+ return null;
202
+ const dir = join(imagesDir(), slug);
203
+ const folder = stepFolder(slug, number);
204
+ const saved = await imagesIn(folder);
205
+ if (saved.length === 0)
206
+ return null;
207
+ await beforeChange(dir, 'gimp');
208
+ for (const file of await imagesIn(dir)) {
209
+ if (!saved.includes(file))
210
+ await rm(join(dir, file), { force: true });
211
+ }
212
+ for (const file of saved)
213
+ await copyFile(join(folder, file), join(dir, file));
214
+ if (existsSync(join(folder, 'preview.png')))
215
+ await copyFile(join(folder, 'preview.png'), join(dir, 'preview.png'));
216
+ await recordImageStep(slug, `Back to step ${number}`);
217
+ await appendMaking(dir, { ...who, event: 'restored', tool: 'gimp', step: number, label: step.label, sources: await sourcesNow(dir, 'gimp') });
218
+ return step;
219
+ }
220
+ // ── Versions ─────────────────────────────────────────────────────────────────
221
+ // When she makes several designs, what happens to each is theirs to decide, by
222
+ // clicking the design itself: on a sheet of unlabelled pictures, "the one on the
223
+ // right" meant a different file to her than it did to them, and the wrong one
224
+ // went into the kit.
225
+ const TEST_IMAGE = /^(test|compare|comparison|thumb|proof|tmp|temp|scratch|draft|check|trial)([-_ ]|$)/i;
226
+ const mainFile = (slug) => join(imagesDir(), slug, 'main.json');
227
+ export async function listImageVersions(slug) {
228
+ const dir = join(imagesDir(), slug);
229
+ return (await imagesIn(dir)).map((f) => f.slice(0, -4)).filter((n) => !TEST_IMAGE.test(n) && existsSync(join(dir, `${n}.png`))).sort();
230
+ }
231
+ export async function readImageMain(slug) {
232
+ try {
233
+ const name = JSON.parse(await readFile(mainFile(slug), 'utf-8'));
234
+ return typeof name === 'string' && (await listImageVersions(slug)).includes(name) ? name : null;
235
+ }
236
+ catch {
237
+ return null;
238
+ }
239
+ }
240
+ /** Their choice of main design. It goes on the stage and stays there. */
241
+ export async function chooseImageMain(slug, name) {
242
+ if (!(await listImageVersions(slug)).includes(name))
243
+ return false;
244
+ const dir = join(imagesDir(), slug);
245
+ await writeFile(mainFile(slug), JSON.stringify(name), 'utf-8');
246
+ await beforeChange(dir, 'gimp');
247
+ await appendMaking(dir, { event: 'main_chosen', by: 'person', tool: 'gimp', name });
248
+ if (!(await readImageFinals(slug)).length)
249
+ await copyFile(join(dir, `${name}.png`), join(dir, 'preview.png'));
250
+ return true;
251
+ }
252
+ /**
253
+ * Keep a design for later: it becomes its own piece of work, with the same brief,
254
+ * so it shows in the Library and can be opened and carried on with. It leaves
255
+ * this work, so what is left here is what they're deciding between.
256
+ */
257
+ export async function keepImageVersion(slug, name) {
258
+ if (!(await listImageVersions(slug)).includes(name))
259
+ return null;
260
+ const title = name.replace(/[-_]+/g, ' ').trim();
261
+ let kept = title;
262
+ for (let n = 2; existsSync(join(imagesDir(), modelSlug(kept))); n++)
263
+ kept = `${title} ${n}`;
264
+ const to = modelSlug(kept);
265
+ const from = join(imagesDir(), slug);
266
+ const dir = join(imagesDir(), to);
267
+ await beforeChange(from, 'gimp');
268
+ await mkdir(dir, { recursive: true });
269
+ // The kept design was made the same way as the work it leaves, up to here.
270
+ if (existsSync(join(from, 'making.jsonl')))
271
+ await copyFile(join(from, 'making.jsonl'), join(dir, 'making.jsonl'));
272
+ await copyFile(join(from, `${name}.xcf`), join(dir, `${name}.xcf`));
273
+ await copyFile(join(from, `${name}.png`), join(dir, `${name}.png`));
274
+ await copyFile(join(from, `${name}.png`), join(dir, 'preview.png'));
275
+ await writeFile(join(dir, 'finals.json'), JSON.stringify([`${name}.png`]), 'utf-8');
276
+ const brief = await readImageBrief(slug);
277
+ if (brief)
278
+ await store.write(to, { ...brief, name: kept });
279
+ await upsertLibraryEntry({ slug: to, name: kept, files: [`${name}.xcf`, `${name}.png`, 'preview.png'], gimpVersion: '', imageCount: 1 });
280
+ await removeVersionFiles(slug, name);
281
+ await appendMaking(dir, {
282
+ event: 'copied_from', by: 'person', tool: 'gimp', from: (await readImageBrief(slug))?.name ?? slug, version: name,
283
+ note: 'Kept as its own work. The lines above belong to the work it came from.', sources: await sourcesNow(dir, 'gimp'),
284
+ });
285
+ await appendMaking(from, { event: 'version_kept', by: 'person', tool: 'gimp', name, to: kept, sources: await sourcesNow(from, 'gimp') });
286
+ return kept;
287
+ }
288
+ export async function deleteImageVersion(slug, name) {
289
+ if (!(await listImageVersions(slug)).includes(name))
290
+ return false;
291
+ const dir = join(imagesDir(), slug);
292
+ await beforeChange(dir, 'gimp');
293
+ await removeVersionFiles(slug, name);
294
+ await appendMaking(dir, { event: 'version_deleted', by: 'person', tool: 'gimp', name, sources: await sourcesNow(dir, 'gimp') });
295
+ return true;
296
+ }
297
+ async function removeVersionFiles(slug, name) {
298
+ const dir = join(imagesDir(), slug);
299
+ const wasMain = (await readImageMain(slug)) === name;
300
+ await rm(join(dir, `${name}.xcf`), { force: true });
301
+ await rm(join(dir, `${name}.png`), { force: true });
302
+ if (wasMain)
303
+ await rm(mainFile(slug), { force: true });
304
+ }
305
+ /** Every piece of work — including one with a brief and nothing made yet. */
306
+ export async function listImageWork() {
307
+ const out = [];
308
+ for (const e of await readdir(imagesDir(), { withFileTypes: true }).catch(() => [])) {
309
+ if (!e.isDirectory())
310
+ continue;
311
+ const dir = join(imagesDir(), e.name);
312
+ const brief = await readImageBrief(e.name);
313
+ const preview = join(dir, 'preview.png');
314
+ const built = existsSync(preview);
315
+ const mtime = (await stat(built ? preview : dir).catch(() => null))?.mtime ?? new Date(0);
316
+ const briefTime = brief?.agreedAt || brief?.proposedAt;
317
+ const updatedAt = briefTime && new Date(briefTime) > mtime ? briefTime : mtime.toISOString();
318
+ const options = await readImageOptions(e.name);
319
+ out.push({
320
+ slug: e.name, name: brief?.name || e.name, brief, built, updatedAt,
321
+ options: options?.status === 'waiting' ? options : null,
322
+ references: await listImageReferences(e.name),
323
+ finals: await readImageFinals(e.name),
324
+ history: await readImageHistory(e.name),
325
+ versions: await listImageVersions(e.name),
326
+ main: await readImageMain(e.name),
327
+ });
328
+ }
329
+ return out.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
330
+ }
331
+ export class DesignProposeImageBriefTool {
332
+ name = 'design_propose_image_brief';
333
+ description = 'Propose the brief for an image or a set in GIMP — what it is, where it is used, style, exact sizes, the set, palette, references, generation aid, purpose — for the person to question and agree BEFORE anything is made.';
334
+ riskLevel = 'safe';
335
+ requiresConfirmation = false;
336
+ schema = {
337
+ name: 'design_propose_image_brief',
338
+ description: 'Put the BRIEF for an image or set on the card in the room, before anything is made. Research first, then propose YOUR point of view on every field with your reasoning — never hand the questions back to them. ' +
339
+ 'They question it, may edit it on the card, and agree it there; design_build_image will not run until they have. Call again with the full brief when the discussion changes it; a changed brief has to be agreed again. You cannot agree it yourself.',
340
+ parameters: {
341
+ type: 'object',
342
+ properties: {
343
+ name: { type: 'string', description: 'The name of the work, e.g. "Stat Icons". The same name is used for design_build_image.' },
344
+ ...Object.fromEntries(IMAGE_BRIEF_FIELDS.map(([k, label, hint]) => [k, { type: 'string', description: `${label} — ${hint}.` }])),
345
+ reasoning: { type: 'string', description: 'Why this brief: what you found, what you weighed and rejected. This is the part they learn from.' },
346
+ },
347
+ required: ['name', ...IMAGE_BRIEF_FIELDS.map(([k]) => k), 'reasoning'],
348
+ },
349
+ };
350
+ async execute(args, context) {
351
+ const str = (k) => (typeof args[k] === 'string' ? args[k].trim() : '');
352
+ const name = str('name');
353
+ const slug = modelSlug(name);
354
+ if (!slug)
355
+ return { success: false, output: 'Missing `name` — the name of the work.' };
356
+ const missing = IMAGE_BRIEF_FIELDS.filter(([k]) => !str(k)).map(([, label]) => label);
357
+ if (!str('reasoning'))
358
+ missing.push('your reasoning');
359
+ if (missing.length)
360
+ return { success: false, output: `The brief is missing: ${missing.join(', ')}. A hole here is filled by guesswork when it is made.` };
361
+ const wasAgreed = (await readImageBrief(slug))?.status === 'agreed';
362
+ await store.propose(slug, {
363
+ name,
364
+ ...Object.fromEntries(IMAGE_BRIEF_FIELDS.map(([k]) => [k, str(k)])),
365
+ reasoning: str('reasoning'),
366
+ status: 'proposed',
367
+ proposedAt: new Date().toISOString(),
368
+ }, context);
369
+ return {
370
+ success: true,
371
+ output: `Brief for "${name}" is on the card${wasAgreed ? ' — it changed, so it needs agreeing again before the next step' : ''}. Talk them through your reasoning, change it where they have a point. They agree it on the card; nothing is made until they do.`,
372
+ metadata: { work: slug },
373
+ };
374
+ }
375
+ }
376
+ // ── The script check ─────────────────────────────────────────────────────────
377
+ const SCRIPT_RULES = [
378
+ { re: /\bsubprocess\b|\bos\.(system|popen|exec\w*|spawn\w*|startfile|kill)\b/, why: 'it starts other programs' },
379
+ { re: /\b(socket|urllib|requests|http\.client|ftplib|smtplib)\b/, why: 'it uses the network' },
380
+ { re: /\b(ctypes|cffi|winreg|_winapi|msvcrt)\b/, why: 'it reaches native code or the registry' },
381
+ { re: /\bGimp\.(file_save|quit)\b/, why: 'it saves or closes GIMP itself — the tool saves your images after your script; use ava_export for exact sizes' },
382
+ { re: /\bexpanduser\b|Path\.home\b|\bos\.environ\b|\bgetenv\b/, why: 'it builds a path outside the work\'s folder' },
383
+ { re: /["'](?:[A-Za-z]:[\\/]|\\\\|~[\\/]|\/(?:Users|home|etc|tmp|var|Applications|mnt|opt)\b)/, why: 'it contains an absolute path — build every path from ASSET_DIR' },
384
+ { re: /\.\.[\\/]/, why: 'it climbs out of the folder with ".." — build every path from ASSET_DIR' },
385
+ ];
386
+ export function checkGimpScript(script) {
387
+ for (const rule of SCRIPT_RULES) {
388
+ const m = rule.re.exec(script);
389
+ if (m)
390
+ return `The script was not run: ${rule.why} (found "${m[0]}"). Scripts here only make the image and write inside its own folder.`;
391
+ }
392
+ return null;
393
+ }
394
+ // ── What a GIMP 2 habit means in GIMP 3 ─────────────────────────────────────
395
+ // A traceback says what broke, not what to write instead. Each of these cost a
396
+ // run on the first logo (4 Nov 2026).
397
+ const API_HINTS = [
398
+ [/select_(ellipse|rectangle)\(\) takes exactly/, 'GIMP 3 takes separate numbers, not a tuple: image.select_ellipse(op, x, y, w, h). Easier: ava_fill(layer, dict(ellipse=(x,y,w,h)), "#hex").'],
399
+ [/has no attribute 'select_all'/, 'Select all is Gimp.Selection.all(image), on Gimp.Selection, not on the image.'],
400
+ [/has no attribute 'ADD_EXCLUDE'/, 'ChannelOps is only ADD, SUBTRACT, REPLACE, INTERSECT. To cut a shape out, use ava_cut(layer, shape).'],
401
+ [/'Layer' object has no attribute 'name'/, 'Use layer.get_name() and layer.set_name("...").'],
402
+ [/has no attribute 'width'|has no attribute 'height'/, 'Use image.get_width() and image.get_height(); the same on a layer.'],
403
+ [/has no attribute 'layers'/, 'Use image.get_layers().'],
404
+ [/has no attribute 'duplicate'/, 'To copy a layer: ava_copy_layer(layer, "name"). Between images: ava_copy_layer(layer, into=other).'],
405
+ [/to wrong image/, 'A layer belongs to its image. Move one across with ava_copy_layer(layer, into=other), or derive it in place with ava_merged(image, layers, "name").'],
406
+ [/has no attribute '(lower_layer|raise_layer|reorder_layer|lower|raise)'/, 'To change the order: ava_move(layer, to="top"), to="bottom", above=other or below=other.'],
407
+ [/'Layer' object has no attribute 'remove'/, 'To delete a layer: ava_remove(layer).'],
408
+ [/'Layer' object has no attribute 'get_layers'/, 'A layer has no layers of its own. image.get_layers() lists them, top first, and they are not nested unless you made a group.'],
409
+ [/has no attribute 'get_children'/, 'Use image.get_layers().'],
410
+ [/has no attribute 'get_app'|has no attribute 'get_images'|'NoneType' object has no attribute 'get_layer/, 'Each run is a brand new GIMP with nothing open. Reach saved work with ava_image("name"); print(ava_images()) lists it.'],
411
+ [/flatten an image without any visible layer|Nothing is visible in this image/, 'Every layer is hidden there. Check set_visible on your copy; at least one must be on.'],
412
+ [/get_pixel|getv\(\)|get_components/, 'To read a colour, ava_pixel(image, x, y) gives the "#RRGGBB" you would really see. get_pixel reads one layer, in that layer\'s own coordinates and linear colour, which is rarely what you want.'],
413
+ [/too many values to unpack/, 'Several GIMP calls also return a success flag: ok, x, y = layer.get_offsets().'],
414
+ [/instances of a subclass Color/, 'Make a colour with Gegl.Color.new("#3FE8FF").'],
415
+ [/Unsupported|No such property|property .* not found|object has no property/i, 'That filter does not have that setting. Look up the GEGL operation\'s property names for this version; dashes in names become underscores in ava_filter.'],
416
+ ];
417
+ export function gimpApiHint(error) {
418
+ const hit = API_HINTS.find(([re]) => re.test(error));
419
+ return hit ? hit[1] : null;
420
+ }
421
+ // ── Library entry (one asset, one folder) ────────────────────────────────────
422
+ async function folderBytes(dir) {
423
+ let total = 0;
424
+ for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
425
+ const p = join(dir, entry.name);
426
+ if (entry.isDirectory())
427
+ total += await folderBytes(p);
428
+ else
429
+ total += (await stat(p).catch(() => ({ size: 0 }))).size;
430
+ }
431
+ return total;
432
+ }
433
+ async function upsertLibraryEntry(m) {
434
+ let items = [];
435
+ try {
436
+ const parsed = JSON.parse(await readFile(metadataFile(), 'utf-8'));
437
+ if (Array.isArray(parsed))
438
+ items = parsed;
439
+ }
440
+ catch { /* none yet */ }
441
+ const id = `gimp_${m.slug}`;
442
+ const existing = items.find((i) => i.id === id);
443
+ const folder = join(imagesDir(), m.slug);
444
+ const now = new Date().toISOString();
445
+ const entry = {
446
+ ...(existing ?? {}),
447
+ id, kind: 'gimp', designType: 'gimp',
448
+ path: `gimp/${m.slug}/preview.png`,
449
+ absolutePath: join(folder, 'preview.png'),
450
+ folder: `gimp/${m.slug}`,
451
+ absoluteFolder: folder,
452
+ files: m.files,
453
+ imageCount: m.imageCount,
454
+ prompt: m.description ?? existing?.prompt ?? '',
455
+ title: m.name,
456
+ gimpVersion: m.gimpVersion,
457
+ createdAt: existing?.createdAt ?? now,
458
+ updatedAt: now,
459
+ bytes: await folderBytes(folder),
460
+ };
461
+ await mkdir(creativeDir(), { recursive: true });
462
+ await writeFile(metadataFile(), JSON.stringify([entry, ...items.filter((i) => i.id !== id)], null, 2), 'utf-8');
463
+ }
464
+ function runGimp(exe, args, cwd, env, timeoutMs, signal) {
465
+ return new Promise((resolve) => {
466
+ const child = spawn(exe, args, { cwd, env, windowsHide: true });
467
+ let out = '', timedOut = false, aborted = false;
468
+ const take = (d) => { if (out.length < MAX_OUTPUT)
469
+ out += d; };
470
+ child.stdout.on('data', take);
471
+ child.stderr.on('data', take);
472
+ const timer = setTimeout(() => { timedOut = true; child.kill(); }, timeoutMs);
473
+ const onAbort = () => { aborted = true; child.kill(); };
474
+ signal?.addEventListener('abort', onAbort, { once: true });
475
+ const done = () => {
476
+ clearTimeout(timer);
477
+ signal?.removeEventListener('abort', onAbort);
478
+ resolve({ out, timedOut, aborted });
479
+ };
480
+ child.on('close', done);
481
+ child.on('error', (err) => { out += String(err); done(); });
482
+ });
483
+ }
484
+ /** Her own print() lines, without GIMP's start-up chatter. */
485
+ export function scriptOutput(out) {
486
+ const noise = /^(INFO:|GIMP-Message|GIMP-Warning|A new version|It is recommended|batch command|Welcome to GIMP|@@AVA_RESULT@@|\s*$|\(.*:\d+\): )/;
487
+ // GIMP says this every time the batch Python ends, on a good run too. It is
488
+ // not a crash, and reading it as one sent her after problems that weren't
489
+ // there. A real crash names another plug-in, and that line stays.
490
+ const ending = /gimp_wire_read\(\): unexpected EOF|Plug-in crashed: "python-eval|python-eval\.py\)\s*$|The dying plug-in may have messed up|GeglBuffer|EEEEeEeek/;
491
+ return out.split(/\r?\n/).filter((l) => !noise.test(l) && !ending.test(l)).slice(-30).join('\n').slice(-3000);
492
+ }
493
+ // ── design_build_image ───────────────────────────────────────────────────────
494
+ export class DesignBuildImageTool {
495
+ name = 'design_build_image';
496
+ description = 'Make or change an image or a set in GIMP with no window: run your Python on it, save the layered source, export it and see a preview. Free — GIMP runs on their own computer.';
497
+ riskLevel = 'write';
498
+ requiresConfirmation = false;
499
+ schema = {
500
+ name: 'design_build_image',
501
+ description: 'Run YOUR GIMP 3 Python on a piece of work and get back a preview image. Gimp, Gegl, Gio and ASSET_DIR are predefined, plus these helpers: ' +
502
+ 'ava_image(name, width, height) opens that image — its saved .xcf, INCLUDING anything the person changed by hand in GIMP — or makes a new transparent one the first time. A SET is several names in the same work. ' +
503
+ 'ava_layer(image, name, fill="#hex") adds a layer. ava_place(image, path, name) brings a file in as a layer (a Blender render, a generated reference; path relative to ASSET_DIR). ' +
504
+ 'ava_filter(layer, "gegl:dropshadow", x=0.0, y=6.0, radius=14.0) runs a GEGL filter and keeps the result. ava_export(image, "name-64.png", size=(64, 64)) writes an exact size into exports/. ' +
505
+ 'DRAWING — use these, they are the verified GIMP 3.2 calls: ava_fill(layer, shape, "#hex") and ava_cut(layer, shape) (real transparency, for negative space). A shape is a flat point list [x1,y1,x2,y2,...], dict(rect=(x,y,w,h), radius=12), dict(ellipse=(x,y,w,h)), or dict(svg="M 10 10 C 40 0, 60 0, 90 10 Z") for SMOOTH CURVES; several shapes in a tuple act together. ava_gradient(layer, shape, "#top", "#bottom", y0, y1) fills with a vertical gradient. ' +
506
+ 'LOOK: ava_show(image_or_file, crop=(x,y,w,h), on="#hex" or a picture, label="...") brings it back to you at up to 1024px, up to 4 per run; with none, you see the images this run touched. ava_proof(image_or_file, on=("#f4f4f4","#101014"), widths=(256,120,64)) makes the proof sheet: large on each background, plus its real small sizes. Use these and judge by eye; never measure pixels to find out whether something shows. ' +
507
+ 'LAYERS: ava_copy_layer(layer, "name", into=other_image), ava_remove(layer), ava_move(layer, to="top"|"bottom", above=other, below=other). ava_merged(image, layers, "name") is a merged copy as one new layer in the same image, originals untouched. ava_glow(image, layers, radius=24.0, opacity=50.0, colour="#hex", name="Glow") is a real switchable glow; call twice for bloom plus halo. ava_pixel(image, x, y) reads the true "#RRGGBB" there. ava_images() lists the saved images. os is predefined. ' +
508
+ 'Layer OPACITY IS 0-100: set_opacity(55.0), never 0.55. ' +
509
+ 'BRAND: KIT is the brand kit for this project: KIT.colour("primary"), KIT.font("heading") for ava_text, KIT.logo("mark") for a real file to ava_place, KIT.name. If (not KIT) there is none: ask them. ' +
510
+ 'FINISH: ava_final(image, "name.png", size=(w, h)) makes the finished file in final/: the real thing, shown on the stage and in the Library, and what brand kits offer. Exports are working files; every piece ends with at least one final, once they are happy. ' +
511
+ 'TEXT: ava_text(image, "Words", font="Sans-serif Bold", size=96, colour="#hex", x=0, y=0, spacing=0.0) makes a real editable text layer; print(ava_fonts("match")) lists installed fonts (hundreds are available). ' +
512
+ 'After your script the tool saves every image you touched as layered .xcf, writes a PNG of each, renders preview.png, and reports every layer with anything that looks wrong. Each run is a new GIMP with nothing open: ava_image is the only way to reach saved work, and ava_image() with no name opens the main image. Write ONLY this step: saved work is reopened, never rebuild it. Keep layers named and separate: the person owns this file and may open it. ' +
513
+ 'If you go below the helpers, this is GIMP 3, not 2: image.select_ellipse(op, x, y, w, h) takes separate numbers, not a tuple; ChannelOps is ADD, SUBTRACT, REPLACE, INTERSECT; select all is Gimp.Selection.all(image); a layer\'s name is layer.get_name(). ava_layer layers already have transparency, so never add_alpha. ' +
514
+ 'Absolute paths, "..", other programs, network and native code are refused. If the script errors, nothing is saved and you get the traceback. The GIMP Python API differs from 2.10; the result tells you the version, check its docs when unsure.',
515
+ parameters: {
516
+ type: 'object',
517
+ properties: {
518
+ name: { type: 'string', description: 'The name of the work, e.g. "Stat Icons". The same name continues the same work.' },
519
+ script: { type: 'string', description: 'GIMP 3 Python for THIS step only.' },
520
+ description: { type: 'string', description: 'One line for the Library card.' },
521
+ timeout_seconds: { type: 'number', description: `How long GIMP may run. Default ${DEFAULT_TIMEOUT_S}, most ${MAX_TIMEOUT_S}.` },
522
+ },
523
+ required: ['name', 'script'],
524
+ },
525
+ };
526
+ async execute(args, context) {
527
+ const wait = designRunRefusal(context);
528
+ if (wait)
529
+ return { success: false, output: wait };
530
+ const jobs = context.sharedState?.generationManager;
531
+ let jobId;
532
+ const started = (name, slug, assetDir) => {
533
+ jobId = `gimp_${randomUUID()}`;
534
+ jobs?.create({ id: jobId, type: 'gimp', prompt: name, filename: slug, targetPath: assetDir });
535
+ jobs?.update(jobId, { status: 'generating' });
536
+ };
537
+ try {
538
+ const res = await this.step(args, context, started);
539
+ if (jobId) {
540
+ if (res.success)
541
+ jobs?.complete(jobId);
542
+ else
543
+ jobs?.fail(jobId, res.output.split('\n')[0]);
544
+ // Runs Blender/GIMP actually made. A refusal is not a run.
545
+ const checkIn = recordDesignRun(context, res.success);
546
+ if (checkIn)
547
+ res.output += `\n\n${checkIn}`;
548
+ }
549
+ return res;
550
+ }
551
+ catch (err) {
552
+ if (jobId)
553
+ jobs?.fail(jobId, err instanceof Error ? err.message : String(err));
554
+ throw err;
555
+ }
556
+ }
557
+ async step(args, context, started) {
558
+ const name = String(args.name ?? '').trim();
559
+ const script = String(args.script ?? '');
560
+ const slug = modelSlug(name);
561
+ if (!slug)
562
+ return { success: false, output: 'Missing `name` — the name of the work.' };
563
+ if (!script.trim())
564
+ return { success: false, output: 'Missing `script` — the GIMP Python for this step.' };
565
+ const brief = await readImageBrief(slug);
566
+ if (!brief) {
567
+ return { success: false, output: `Nothing was made: "${name}" has no brief yet. Research it, then propose the brief with design_propose_image_brief — the person agrees it on the card first.` };
568
+ }
569
+ if (brief.status !== 'agreed') {
570
+ return {
571
+ success: false,
572
+ output: `Nothing was made: the brief for "${name}" is still waiting for the person to agree it on the card` +
573
+ `${brief.editedByPerson ? ' (they edited it — read their changes in the room context and talk them through)' : ''}.`,
574
+ };
575
+ }
576
+ const refused = checkGimpScript(script);
577
+ if (refused)
578
+ return { success: false, output: refused };
579
+ const gimp = await findGimp();
580
+ if (!gimp) {
581
+ return { success: false, output: `GIMP 3 isn't installed on this computer, or I can't find it. It's free from ${GIMP_DOWNLOAD_URL} — if it's somewhere unusual, its path can be set in Settings.` };
582
+ }
583
+ const assetDir = join(imagesDir(), slug);
584
+ await mkdir(join(assetDir, 'scripts'), { recursive: true });
585
+ // Before anything changes: start the record, or note hand edits since the last step.
586
+ await beforeChange(assetDir, 'gimp');
587
+ await writeFile(join(assetDir, 'script.py'), script, 'utf-8');
588
+ const scriptFile = `scripts/${new Date().toISOString().replace(/[:.]/g, '-')}.py`;
589
+ await writeFile(join(assetDir, scriptFile), script, 'utf-8');
590
+ const runId = randomUUID();
591
+ const runnerPath = join(tmpdir(), `ava-gimp-runner-${runId}.py`);
592
+ const jobPath = join(tmpdir(), `ava-gimp-job-${runId}.json`);
593
+ await writeFile(runnerPath, GIMP_RUNNER_PY, 'utf-8');
594
+ await writeFile(jobPath, JSON.stringify({ assetDir, name, kit: await kitForScripts(context.sharedState?.designProject?.()) }), 'utf-8');
595
+ const timeoutS = Math.min(MAX_TIMEOUT_S, Math.max(30, Number(args.timeout_seconds) || DEFAULT_TIMEOUT_S));
596
+ // -n: a GIMP the person has open must not swallow the batch. JSON.stringify
597
+ // gives a valid Python string for any path, whatever it contains.
598
+ const gimpArgs = ['-n', '-i', '--batch-interpreter', 'python-fu-eval', '-b', `exec(open(${JSON.stringify(runnerPath)}, encoding='utf-8').read())`, '--quit'];
599
+ started(name, slug, assetDir);
600
+ let run;
601
+ try {
602
+ run = await runGimp(gimp.path, gimpArgs, assetDir, { ...process.env, AVA_GIMP_JOB: jobPath }, timeoutS * 1000, context.signal);
603
+ }
604
+ finally {
605
+ await rm(runnerPath, { force: true }).catch(() => { });
606
+ await rm(jobPath, { force: true }).catch(() => { });
607
+ }
608
+ if (run.aborted)
609
+ return { success: false, output: 'Stopped before GIMP finished. Nothing new was saved.' };
610
+ if (run.timedOut)
611
+ return { success: false, output: `GIMP was stopped after ${timeoutS}s and nothing new was saved. The very first run on a machine can take about 35 seconds while GIMP sets itself up. Make the step smaller, or raise timeout_seconds.` };
612
+ const marker = run.out.lastIndexOf('@@AVA_RESULT@@');
613
+ if (marker < 0) {
614
+ return { success: false, output: `GIMP closed without finishing the run, so nothing new was saved. Its last output:\n${run.out.split(/\r?\n/).slice(-25).join('\n')}` };
615
+ }
616
+ let result;
617
+ try {
618
+ result = JSON.parse(run.out.slice(marker + '@@AVA_RESULT@@'.length).split(/\r?\n/)[0]);
619
+ }
620
+ catch {
621
+ return { success: false, output: 'GIMP finished, but its report could not be read.' };
622
+ }
623
+ const printed = scriptOutput(run.out);
624
+ if (!result.ok) {
625
+ return {
626
+ success: false,
627
+ output: `Your script stopped with an error in GIMP ${gimp.version}. Nothing was saved — "${name}" is exactly as it was before this run.\n\n${(result.error ?? '').trim()}` +
628
+ (gimpApiHint(`${result.error ?? ''}\n${printed}`) ? `\n\nHint: ${gimpApiHint(`${result.error ?? ''}\n${printed}`)}` : '') +
629
+ (printed ? `\n\nWhat the script printed:\n${printed}` : '') + '\n\nFix it and run the step again.',
630
+ };
631
+ }
632
+ const xcfCount = result.files.filter((f) => f.endsWith('.xcf')).length;
633
+ await upsertLibraryEntry({
634
+ slug, name, description: typeof args.description === 'string' ? args.description : undefined,
635
+ files: result.files, gimpVersion: gimp.version, imageCount: xcfCount,
636
+ }).catch(() => { });
637
+ const saved = await recordImageStep(slug, typeof args.description === 'string' ? args.description : '').catch(() => null);
638
+ // A pack plan that names this work files it into its place in the pack.
639
+ await fileLinkedWork('gimp', slug);
640
+ // The making record: written here, by the tool, never by her.
641
+ const who = avaContext(context);
642
+ await appendMaking(assetDir, {
643
+ event: 'step', by: 'ava', ai: who.ai, ask: who.ask, tool: 'gimp', app: `GIMP ${gimp.version}`,
644
+ description: typeof args.description === 'string' ? args.description : null,
645
+ script: scriptFile, historyStep: saved?.number ?? null,
646
+ images: result.images.map((i) => i.name), files: result.files, newFinals: result.newFinals ?? [],
647
+ fonts: await fontLicences(Object.values(result.fonts ?? {}).flat()),
648
+ fontsByImage: result.fonts ?? {}, placed: result.placed ?? [], kitLogos: result.kit_logos ?? [],
649
+ sources: await sourcesNow(assetDir, 'gimp'),
650
+ });
651
+ const lines = [
652
+ `Done on "${name}" in ${result.seconds ?? '?'}s with GIMP ${gimp.version}. ${xcfCount} image${xcfCount === 1 ? '' : 's'} in this work.${saved ? ` Saved as step ${saved.number}.` : ''}`,
653
+ `This step: ${result.images.map((i) => `${i.name} ${i.width}×${i.height} (${i.layers} layer${i.layers === 1 ? '' : 's'})`).join(', ')}.`,
654
+ `Files in ${assetDir}: ${result.files.join(', ')}.`,
655
+ ];
656
+ if (!(await readImageFinals(slug)).length) {
657
+ lines.push('NO FINAL YET: this work has working files but no finished one, and only a final counts as the work. Keep going until it is right; when they are happy, make it with ava_final(image, "name.png", size=(w, h)). Don\'t leave a piece without one.');
658
+ }
659
+ if (result.newFinals?.length) {
660
+ const inUse = await kitForProject(context.sharedState?.designProject?.());
661
+ const open = inUse.kit ? kitPieceStates(inUse.kit).filter((p) => p.state !== 'agreed' && p.room !== 'kit') : [];
662
+ if (inUse.kit && open.length)
663
+ lines.push(`KIT: if this is one of "${inUse.kit.name}"'s pieces (${open.map((p) => `${p.label} [${p.id}]`).join(', ')}), ask whether to save it to the kit, then call design_save_to_kit once they say yes.`);
664
+ }
665
+ if (result.report?.length)
666
+ lines.push(`The file now:\n${result.report.join('\n')}`);
667
+ if (result.warnings?.length)
668
+ lines.push(`CHECK THESE:\n${result.warnings.map((w) => `- ${w}`).join('\n')}`);
669
+ if (printed)
670
+ lines.push(`What the script printed:\n${printed}`);
671
+ // What she sees: what she asked for with ava_show or ava_proof, else what
672
+ // this run touched. preview.png stays the sheet for the Library and stage.
673
+ const looks = [];
674
+ for (const look of result.looks ?? []) {
675
+ try {
676
+ looks.push((await readFile(join(assetDir, '.look', look.file))).toString('base64'));
677
+ }
678
+ catch { /* the next one may be there */ }
679
+ }
680
+ if (!looks.length && result.files.includes('preview.png')) {
681
+ try {
682
+ looks.push((await readFile(join(assetDir, 'preview.png'))).toString('base64'));
683
+ }
684
+ catch { /* none */ }
685
+ }
686
+ lines.push(`The agreed brief:\n${formatImageBrief(brief)}`);
687
+ if (result.looks?.length)
688
+ lines.push(`You are looking at, in order: ${result.looks.map((l) => l.label).join('; ')}.`);
689
+ lines.push(looks.length
690
+ ? 'LOOK at it now and check it against the brief: does it read at its real size, does it sit with the rest of the set, is the style right? Believe your eyes over your reasoning; to see anything else, ava_show or ava_proof it. Say plainly what is off and fix it in the next step; saved work is reopened, so write only the change.'
691
+ : 'There is no image to look at this time — say so rather than describing what you think it looks like.');
692
+ return {
693
+ success: true,
694
+ output: lines.join('\n'),
695
+ metadata: {
696
+ work: slug, folder: assetDir, files: result.files, gimpVersion: gimp.version,
697
+ ...(looks.length ? { base64_image: looks[0], mime_type: 'image/png', more_images: looks.slice(1) } : {}),
698
+ },
699
+ };
700
+ }
701
+ }
702
+ // ── design_restore_image ─────────────────────────────────────────────────────
703
+ export class DesignRestoreImageTool {
704
+ name = 'design_restore_image';
705
+ description = 'Put a piece of GIMP work back as it was at an earlier step, when they ask.';
706
+ riskLevel = 'write';
707
+ requiresConfirmation = false;
708
+ schema = {
709
+ name: 'design_restore_image',
710
+ description: 'Put a piece of work back to an earlier step, when they say they preferred it. The steps are numbered in each ' +
711
+ 'run\'s report and on the strip in the room. Later steps stay in the history, so they can go forward again. ' +
712
+ 'Exports and finals are not changed.',
713
+ parameters: {
714
+ type: 'object',
715
+ properties: {
716
+ name: { type: 'string', description: 'The name of the work.' },
717
+ step: { type: 'number', description: 'The step to go back to.' },
718
+ },
719
+ required: ['name', 'step'],
720
+ },
721
+ };
722
+ async execute(args, context) {
723
+ const slug = modelSlug(String(args.name ?? ''));
724
+ const number = Number(args.step);
725
+ const steps = slug ? await readImageHistory(slug) : [];
726
+ const step = await restoreImageStep(slug, number, { by: 'ava', ...avaContext(context) }).catch(() => null);
727
+ if (!step) {
728
+ return { success: false, output: `There is no step ${args.step} on "${args.name}". Steps here: ${steps.map((s) => s.number).join(', ') || 'none yet'}.` };
729
+ }
730
+ const preview = await readFile(join(imagesDir(), slug, 'preview.png')).catch(() => null);
731
+ return {
732
+ success: true,
733
+ output: `"${args.name}" is back as it was at step ${number} (${step.label}). Later steps are still in the history. LOOK at it and carry on from here.`,
734
+ metadata: { work: slug, ...(preview ? { base64_image: preview.toString('base64'), mime_type: 'image/png' } : {}) },
735
+ };
736
+ }
737
+ }
738
+ // ── design_mark_final ────────────────────────────────────────────────────────
739
+ export class DesignMarkFinalTool {
740
+ name = 'design_mark_final';
741
+ description = 'Mark which files in a piece of work are the finished ones, after asking the person.';
742
+ riskLevel = 'write';
743
+ requiresConfirmation = false;
744
+ schema = {
745
+ name: 'design_mark_final',
746
+ description: 'Mark files as FINAL: the finished pieces the person will use, which is what the Library and brand kits offer. Tests, comparisons and proof sheets are never final. ' +
747
+ 'ALWAYS ask them first, and only call this once they have said yes. It adds to the list; they can remove any from the stage.',
748
+ parameters: {
749
+ type: 'object',
750
+ properties: {
751
+ name: { type: 'string', description: 'The name of the work.' },
752
+ files: { type: 'array', items: { type: 'string' }, description: 'The images, relative to the work, e.g. ["exports/logo-2x.png"].' },
753
+ },
754
+ required: ['name', 'files'],
755
+ },
756
+ };
757
+ async execute(args, context) {
758
+ const name = String(args.name ?? '').trim();
759
+ const slug = modelSlug(name);
760
+ const files = Array.isArray(args.files) ? args.files.map(String) : [];
761
+ if (!slug || !existsSync(join(imagesDir(), slug)))
762
+ return { success: false, output: `There is no work called "${name}".` };
763
+ if (!files.length)
764
+ return { success: false, output: 'Name the files to mark in `files`.' };
765
+ const root = resolve(imagesDir(), slug);
766
+ const clean = [];
767
+ for (const raw of files) {
768
+ const file = raw.replace(/\\/g, '/').replace(/^\.\//, '');
769
+ const full = resolve(root, file);
770
+ if (!full.startsWith(root + sep) || !IMAGE_FILE.test(file))
771
+ return { success: false, output: `"${file}" is not an image inside this work.` };
772
+ if (!existsSync(full))
773
+ return { success: false, output: `There is no file at ${file}. The files are listed in your last run.` };
774
+ clean.push(file);
775
+ }
776
+ const all = [...new Set([...(await readImageFinals(slug)), ...clean])];
777
+ await writeFinals(slug, all);
778
+ const who = avaContext(context);
779
+ await beforeChange(root, 'gimp');
780
+ await appendMaking(root, { event: 'marked_final', by: 'ava', ai: who.ai, ask: who.ask, tool: 'gimp', files: clean });
781
+ return { success: true, output: `Marked final: ${clean.join(', ')}. "${name}" now has ${all.length} final file${all.length === 1 ? '' : 's'}.` };
782
+ }
783
+ }
784
+ // ── design_show_options ──────────────────────────────────────────────────────
785
+ export class DesignShowOptionsTool {
786
+ name = 'design_show_options';
787
+ description = 'Put two to four versions on the stage for the person to choose between by eye.';
788
+ riskLevel = 'write';
789
+ requiresConfirmation = false;
790
+ schema = {
791
+ name: 'design_show_options',
792
+ description: 'Put 2 to 4 versions of a piece on the stage, side by side, for the person to pick by clicking one. For real DESIGN choices that are best judged by eye: a typeface, a composition, a colour direction. Export each version first (ava_export), then point at the files. ' +
793
+ 'Then STOP and wait: their pick comes back as their next message. Never use it for technical choices; those are yours to solve.',
794
+ parameters: {
795
+ type: 'object',
796
+ properties: {
797
+ name: { type: 'string', description: 'The name of the work.' },
798
+ question: { type: 'string', description: 'What they are choosing, in plain words.' },
799
+ options: {
800
+ type: 'array',
801
+ description: '2 to 4 versions.',
802
+ items: {
803
+ type: 'object',
804
+ properties: {
805
+ label: { type: 'string', description: 'A short name, e.g. "Geometric".' },
806
+ file: { type: 'string', description: 'The image, relative to the work, e.g. "exports/option-a.png".' },
807
+ note: { type: 'string', description: 'One line on what this version does.' },
808
+ },
809
+ required: ['label', 'file'],
810
+ },
811
+ },
812
+ },
813
+ required: ['name', 'question', 'options'],
814
+ },
815
+ };
816
+ async execute(args, context) {
817
+ const name = String(args.name ?? '').trim();
818
+ const slug = modelSlug(name);
819
+ const question = String(args.question ?? '').trim();
820
+ const raw = Array.isArray(args.options) ? args.options : [];
821
+ if (!slug || !existsSync(join(imagesDir(), slug)))
822
+ return { success: false, output: `There is no work called "${name}".` };
823
+ if (!question)
824
+ return { success: false, output: 'Say what they are choosing, in `question`.' };
825
+ if (raw.length < 2 || raw.length > 4)
826
+ return { success: false, output: 'Show 2 to 4 options.' };
827
+ const root = resolve(imagesDir(), slug);
828
+ const options = [];
829
+ for (const o of raw) {
830
+ const file = String(o.file ?? '').replace(/\\/g, '/').replace(/^\.\//, '');
831
+ const full = resolve(root, file);
832
+ if (!full.startsWith(root + sep) || !IMAGE_FILE.test(file))
833
+ return { success: false, output: `"${file}" is not an image inside this work. Use a path like exports/option-a.png.` };
834
+ if (!existsSync(full))
835
+ return { success: false, output: `There is no file at ${file}. Export it first with ava_export; the files are listed in your last run.` };
836
+ options.push({ label: String(o.label ?? '').trim() || `Option ${options.length + 1}`, file, ...(o.note ? { note: String(o.note).trim() } : {}) });
837
+ }
838
+ const record = { question, options, status: 'waiting', proposedAt: new Date().toISOString() };
839
+ await writeFile(join(root, 'options.json'), JSON.stringify(record, null, 2), 'utf-8');
840
+ const who = avaContext(context);
841
+ await beforeChange(root, 'gimp');
842
+ await appendMaking(root, { event: 'options_shown', by: 'ava', ai: who.ai, ask: who.ask, tool: 'gimp', question, options });
843
+ return { success: true, output: `${options.length} options are on the stage for "${name}". Stop here and wait: tell them in a line or two what you'd pick and why, then end your turn. Their click comes back as their next message.` };
844
+ }
845
+ }
846
+ // ── design_duplicate_image ───────────────────────────────────────────────────
847
+ export class DesignDuplicateImageTool {
848
+ name = 'design_duplicate_image';
849
+ description = 'Copy a piece of GIMP work to a new name, so an idea can be tried on the copy while the original stays untouched.';
850
+ riskLevel = 'write';
851
+ requiresConfirmation = false;
852
+ schema = {
853
+ name: 'design_duplicate_image',
854
+ description: 'Duplicate work made with design_build_image under a new name, for trying something without touching the original. Then continue on the copy with the NEW name.',
855
+ parameters: {
856
+ type: 'object',
857
+ properties: {
858
+ from: { type: 'string', description: 'The existing work\'s name.' },
859
+ to: { type: 'string', description: 'The new name.' },
860
+ },
861
+ required: ['from', 'to'],
862
+ },
863
+ };
864
+ async execute(args, context) {
865
+ const fromName = String(args.from ?? '').trim();
866
+ const toName = String(args.to ?? '').trim();
867
+ const from = modelSlug(fromName);
868
+ const to = modelSlug(toName);
869
+ if (!from || !to)
870
+ return { success: false, output: 'Give both names: `from` and `to`.' };
871
+ if (from === to)
872
+ return { success: false, output: 'The new name must be different from the original.' };
873
+ const src = join(imagesDir(), from);
874
+ const dst = join(imagesDir(), to);
875
+ if (!existsSync(src))
876
+ return { success: false, output: `There is no work called "${fromName}".` };
877
+ if (existsSync(dst))
878
+ return { success: false, output: `Work called "${toName}" already exists. Pick another name.` };
879
+ // Its making record travels with it: the copy was made the same way, up to here.
880
+ await beforeChange(src, 'gimp');
881
+ await cp(src, dst, { recursive: true, filter: (p) => !/[\\/](versions|scripts)([\\/]|$)/.test(p.slice(src.length)) });
882
+ const brief = await readImageBrief(to);
883
+ if (brief) {
884
+ brief.name = toName;
885
+ await store.write(to, brief);
886
+ }
887
+ const who = avaContext(context);
888
+ await appendMaking(dst, {
889
+ event: 'copied_from', by: 'ava', ai: who.ai, ask: who.ask, tool: 'gimp', from: fromName,
890
+ note: 'The lines above belong to the original; its step scripts stay with it.',
891
+ sources: await sourcesNow(dst, 'gimp'),
892
+ });
893
+ const files = (await readdir(dst, { withFileTypes: true })).filter((e) => e.isFile() && e.name !== 'brief.json').map((e) => e.name);
894
+ if (existsSync(join(dst, 'preview.png'))) {
895
+ await upsertLibraryEntry({ slug: to, name: toName, files, gimpVersion: '', imageCount: files.filter((f) => f.endsWith('.xcf')).length }).catch(() => { });
896
+ }
897
+ return { success: true, output: `Copied "${fromName}" to "${toName}". The original is untouched. Continue on the copy with design_build_image, name "${toName}".`, metadata: { work: to, folder: dst } };
898
+ }
899
+ }
900
+ //# sourceMappingURL=build-image.js.map