dsh-artifact-studio 0.3.2 → 0.7.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.
@@ -1,30 +1,39 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { isDesignInfo, scopeOfId } from '../../contract.js';
1
4
  import { PAGE_CSP, composePage } from '../../render.js';
2
- import { scopeOfId } from '../../contract.js';
5
+ import { DesignRenderer, PREVIEW_MAX_SIDE } from './design-render.js';
3
6
  import { clearWorkspaceDesignSystem, resolveDesignSystem, saveDesignSystem } from './design-system.js';
4
7
  import { ArtifactError } from './errors.js';
8
+ import { acquireEditor, releaseEditor } from './editor-leases.js';
5
9
  import { docToHtml, writeExport } from './export.js';
6
- import { libraryRoot, requireWorkspace, workspaceRoot, workspaceRootExisting } from './paths.js';
7
- import { ArtifactStore } from './store.js';
10
+ import { assertWithin, withLock, writeAtomic } from './fsutil.js';
11
+ import { assertPlainFile, libraryRoot, requireWorkspace, workspaceRoot, workspaceRootExisting } from './paths.js';
12
+ import { ArtifactStore, applyEdits, hashOf } from './store.js';
8
13
  /**
9
- * One facade over the store, the scope roots, the design system, and export.
10
- * The route and the tools both call it, so both scopes share every rule.
14
+ * One facade over the store, the scope roots, the design system, the design
15
+ * renderer, and export. The route and the tools both call it, so both scopes
16
+ * share every rule.
11
17
  */
12
18
  export class ArtifactService {
13
19
  store;
14
20
  config;
15
21
  registry;
16
22
  now;
23
+ designs;
17
24
  /**
18
25
  * @param config root locations.
19
26
  * @param registry the workspace registry.
20
27
  * @param store the store.
21
28
  * @param now the clock.
29
+ * @param designs the design renderer.
22
30
  */
23
- constructor(config, registry, store = new ArtifactStore(), now = () => new Date()) {
31
+ constructor(config, registry, store = new ArtifactStore(), now = () => new Date(), designs = new DesignRenderer()) {
24
32
  this.config = config;
25
33
  this.registry = registry;
26
34
  this.store = store;
27
35
  this.now = now;
36
+ this.designs = designs;
28
37
  }
29
38
  /**
30
39
  * Resolve a scope root. An id decides its own scope; a workspace scope needs a workspace id.
@@ -91,20 +100,100 @@ export class ArtifactService {
91
100
  await clearWorkspaceDesignSystem(await this.root({ ...target, scope: 'workspace' }));
92
101
  return this.designSystem(target);
93
102
  }
103
+ /**
104
+ * Create an artifact. A design is compiled before anything is written, so an
105
+ * invalid source never creates a directory or a version.
106
+ * @param target the caller's context.
107
+ * @param input type, title, content, and source.
108
+ * @returns the manifest.
109
+ */
94
110
  async create(target, input) {
95
- return this.store.create(await this.root(target), input);
111
+ const root = await this.root(target);
112
+ const info = input.type === 'design' ? await this.designs.inspect(input.content) : undefined;
113
+ const manifest = await this.store.create(root, input);
114
+ if (info !== undefined)
115
+ await this.writeInfo(root, manifest.id, input.content, info);
116
+ return manifest;
96
117
  }
118
+ /**
119
+ * Read an artifact. A design carries its compiled summary when one can be
120
+ * produced; a failure there never hides the source.
121
+ * @param target the caller's context.
122
+ * @param id the artifact id.
123
+ * @param version an earlier version, when the caller named one.
124
+ * @returns the payload.
125
+ */
97
126
  async read(target, id, version) {
98
- const result = await this.store.read(await this.root(target, id), id, version);
127
+ const root = await this.root(target, id);
128
+ const result = await this.store.read(root, id, version);
99
129
  const design = await this.designSystem(target);
100
- return { ...result, designCss: design.css, design: design.tokens };
130
+ const payload = {
131
+ ...result,
132
+ designCss: design.css,
133
+ design: design.tokens,
134
+ };
135
+ if (result.manifest.type === 'design') {
136
+ const info = await this.infoFor(root, id, result.content);
137
+ if (info !== undefined)
138
+ payload.designInfo = info;
139
+ }
140
+ return payload;
101
141
  }
142
+ /**
143
+ * Save a new version. A design update resolves the final source first, so
144
+ * edits are validated after they are applied and the committed content is
145
+ * exactly what the renderer accepted.
146
+ * @param target the caller's context.
147
+ * @param id the artifact id.
148
+ * @param input the update.
149
+ * @returns the new manifest.
150
+ */
102
151
  async update(target, id, input) {
103
- return this.store.update(await this.root(target, id), id, input);
152
+ const root = await this.root(target, id);
153
+ const current = await this.store.manifest(root, id);
154
+ if (current.type !== 'design')
155
+ return this.store.update(root, id, input);
156
+ const existing = await this.store.read(root, id);
157
+ let next = input.content;
158
+ if (next === undefined && input.edits !== undefined)
159
+ next = applyEdits(existing.content, input.edits);
160
+ if (next === undefined)
161
+ return this.store.update(root, id, input);
162
+ const info = await this.designs.inspect(next);
163
+ const manifest = await this.store.update(root, id, { ...input, content: next, edits: undefined });
164
+ await this.writeInfo(root, id, next, info);
165
+ return manifest;
104
166
  }
167
+ /**
168
+ * Restore an earlier version.
169
+ * @param target the caller's context.
170
+ * @param id the artifact id.
171
+ * @param version the version to restore.
172
+ * @param source who restored it.
173
+ * @param baseVersion the version the caller saw, if it checks.
174
+ * @returns the new manifest.
175
+ */
105
176
  async restore(target, id, version, source, baseVersion) {
106
177
  return this.store.restore(await this.root(target, id), id, version, source, baseVersion);
107
178
  }
179
+ async openEditor(target, id, token) {
180
+ const root = await this.root(target, id);
181
+ const key = path.join(root.root, id);
182
+ await acquireEditor(key, token, async () => { await this.store.manifest(root, id); });
183
+ }
184
+ async closeEditor(target, id, token) {
185
+ const root = await this.root(target, id);
186
+ await releaseEditor(path.join(root.root, id), token);
187
+ }
188
+ async move(target, id, destinationWorkspaceId, baseVersion, ownToken) {
189
+ if (scopeOfId(id) !== 'workspace' || target.workspaceId === undefined || destinationWorkspaceId === target.workspaceId) {
190
+ throw new ArtifactError('artifact/bad-request', 'Choose a different workspace for a workspace artifact.');
191
+ }
192
+ requireWorkspace(this.registry, destinationWorkspaceId);
193
+ const source = await this.root({ scope: 'workspace', workspaceId: target.workspaceId }, id);
194
+ const destination = await this.root({ scope: 'workspace', workspaceId: destinationWorkspaceId });
195
+ return this.store.move(source, destination, id, baseVersion, ownToken);
196
+ }
108
197
  async history(target, id) {
109
198
  return this.store.history(await this.root(target, id), id);
110
199
  }
@@ -122,15 +211,206 @@ export class ArtifactService {
122
211
  */
123
212
  async printable(target, id, version) {
124
213
  const { manifest, content } = await this.store.read(await this.root(target, id), id, version);
214
+ if (manifest.type === 'design') {
215
+ throw new ArtifactError('artifact/unsupported-format', 'A design cannot be printed.', { type: manifest.type });
216
+ }
125
217
  const design = await this.designSystem(target);
126
218
  return { html: manifest.type === 'page'
127
219
  ? composePage(content, design.css, PAGE_CSP, manifest.title)
128
220
  : docToHtml(manifest.title, content, design.css, true) };
129
221
  }
222
+ /**
223
+ * Export a saved version. A design is rendered from its source at that
224
+ * version; the preview cache is never used as the export source.
225
+ * @param target the caller's context.
226
+ * @param id the artifact id.
227
+ * @param format the format.
228
+ * @param version the version, when the caller named one.
229
+ * @returns the exported file.
230
+ */
130
231
  async export(target, id, format, version) {
131
232
  const root = await this.root(target, id);
132
233
  const { manifest, content, version: readVersion } = await this.store.read(root, id, version);
133
234
  const design = await this.designSystem(target);
134
- return writeExport(root, { ...manifest, version: readVersion }, content, format, design, this.now());
235
+ return writeExport(root, { ...manifest, version: readVersion }, content, format, design, this.now(), this.designs);
236
+ }
237
+ /**
238
+ * Render a design, or return its cached preview for the same source.
239
+ * @param target the caller's context.
240
+ * @param id the artifact id.
241
+ * @param version the version, when the caller named one.
242
+ * @returns the preview.
243
+ */
244
+ async preview(target, id, version) {
245
+ const root = await this.root(target, id);
246
+ const { manifest, content } = await this.store.read(root, id, version);
247
+ if (manifest.type !== 'design') {
248
+ throw new ArtifactError('artifact/unsupported-type', 'Only a design has a rendered preview.', { type: manifest.type });
249
+ }
250
+ const cached = await this.readPreview(root, id, content);
251
+ if (cached !== undefined)
252
+ return cached;
253
+ const rendered = await this.designs.preview(content, PREVIEW_MAX_SIDE);
254
+ await this.writePreview(root, id, content, rendered.info, rendered.width, rendered.height, rendered.bytes);
255
+ return {
256
+ mediaType: 'image/png',
257
+ data: rendered.bytes.toString('base64'),
258
+ width: rendered.width,
259
+ height: rendered.height,
260
+ info: rendered.info,
261
+ };
262
+ }
263
+ /**
264
+ * The cache location of a source's preview.
265
+ * @param root the scope root.
266
+ * @param id the artifact id.
267
+ * @param content the design source.
268
+ * @returns the paths.
269
+ */
270
+ previewPaths(root, id, content) {
271
+ const dir = path.join(root.root, id, 'preview');
272
+ const key = hashOf(content).slice('sha256:'.length);
273
+ return { dir, png: path.join(dir, `${key}.png`), meta: path.join(dir, `${key}.json`) };
274
+ }
275
+ /**
276
+ * Read a cached preview, when both files are plain and agree on the size.
277
+ * @param root the scope root.
278
+ * @param id the artifact id.
279
+ * @param content the design source.
280
+ * @returns the preview, or undefined.
281
+ */
282
+ async readPreview(root, id, content) {
283
+ try {
284
+ const paths = this.previewPaths(root, id, content);
285
+ await assertWithin(root.root, paths.dir);
286
+ if (!(await assertPlainFile(paths.png)) || !(await assertPlainFile(paths.meta)))
287
+ return undefined;
288
+ const parsed = JSON.parse(await fs.readFile(paths.meta, 'utf8'));
289
+ if (parsed === null || typeof parsed !== 'object')
290
+ return undefined;
291
+ const fields = { ...parsed };
292
+ if (!isDesignInfo(fields.info) || typeof fields.width !== 'number' || typeof fields.height !== 'number')
293
+ return undefined;
294
+ const bytes = await fs.readFile(paths.png);
295
+ return {
296
+ mediaType: 'image/png',
297
+ data: bytes.toString('base64'),
298
+ width: fields.width,
299
+ height: fields.height,
300
+ info: fields.info,
301
+ };
302
+ }
303
+ catch {
304
+ return undefined;
305
+ }
306
+ }
307
+ /**
308
+ * The summary of a design, from the cache or a compile.
309
+ * @param root the scope root.
310
+ * @param id the artifact id.
311
+ * @param content the design source.
312
+ * @returns the summary, or undefined when the renderer is unavailable.
313
+ */
314
+ async infoFor(root, id, content) {
315
+ const cached = await this.readCachedInfo(root, id, content);
316
+ if (cached !== undefined)
317
+ return cached;
318
+ try {
319
+ const info = await this.designs.inspect(content);
320
+ await this.writeInfo(root, id, content, info);
321
+ return info;
322
+ }
323
+ catch (error) {
324
+ console.warn('[dsh-artifact-studio] design summary failed', id, error instanceof Error ? error.message : error);
325
+ return undefined;
326
+ }
327
+ }
328
+ /**
329
+ * Read a cached summary.
330
+ * @param root the scope root.
331
+ * @param id the artifact id.
332
+ * @param content the design source.
333
+ * @returns the summary, or undefined.
334
+ */
335
+ async readCachedInfo(root, id, content) {
336
+ try {
337
+ const paths = this.previewPaths(root, id, content);
338
+ await assertWithin(root.root, paths.dir);
339
+ if (!(await assertPlainFile(paths.meta)))
340
+ return undefined;
341
+ const parsed = JSON.parse(await fs.readFile(paths.meta, 'utf8'));
342
+ if (parsed === null || typeof parsed !== 'object')
343
+ return undefined;
344
+ const fields = { ...parsed };
345
+ return isDesignInfo(fields.info) ? fields.info : undefined;
346
+ }
347
+ catch {
348
+ return undefined;
349
+ }
350
+ }
351
+ /**
352
+ * Cache a summary for a source hash.
353
+ * @param root the scope root.
354
+ * @param id the artifact id.
355
+ * @param content the design source.
356
+ * @param info the summary.
357
+ */
358
+ async writeInfo(root, id, content, info) {
359
+ try {
360
+ const paths = this.previewPaths(root, id, content);
361
+ await assertWithin(root.root, paths.dir);
362
+ await withLock(paths.dir, async () => {
363
+ await fs.mkdir(paths.dir, { recursive: true });
364
+ await assertWithin(root.root, paths.meta);
365
+ await writeAtomic(paths.meta, `${JSON.stringify({ info }, null, 2)}\n`);
366
+ await this.prunePreview(paths.dir, path.basename(paths.png));
367
+ });
368
+ }
369
+ catch (error) {
370
+ // The artifact is saved; a cache failure only costs the next reader a compile.
371
+ console.warn('[dsh-artifact-studio] design cache failed', id, error instanceof Error ? error.message : error);
372
+ }
373
+ }
374
+ /**
375
+ * Cache a rendered preview.
376
+ * @param root the scope root.
377
+ * @param id the artifact id.
378
+ * @param content the design source.
379
+ * @param info the summary.
380
+ * @param width the image width.
381
+ * @param height the image height.
382
+ * @param bytes the PNG bytes.
383
+ */
384
+ async writePreview(root, id, content, info, width, height, bytes) {
385
+ try {
386
+ const paths = this.previewPaths(root, id, content);
387
+ await assertWithin(root.root, paths.dir);
388
+ await withLock(paths.dir, async () => {
389
+ await fs.mkdir(paths.dir, { recursive: true });
390
+ await assertWithin(root.root, paths.png);
391
+ await writeAtomic(paths.png, bytes);
392
+ await assertWithin(root.root, paths.meta);
393
+ await writeAtomic(paths.meta, `${JSON.stringify({ info, width, height }, null, 2)}\n`);
394
+ await this.prunePreview(paths.dir, path.basename(paths.png));
395
+ });
396
+ }
397
+ catch (error) {
398
+ console.warn('[dsh-artifact-studio] design preview cache failed', id, error instanceof Error ? error.message : error);
399
+ }
400
+ }
401
+ /**
402
+ * Drop cache files that do not belong to the current source hash.
403
+ * @param dir the preview directory.
404
+ * @param keep the file name to keep.
405
+ */
406
+ async prunePreview(dir, keep) {
407
+ const prefix = keep.replace(/\.png$/, '');
408
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
409
+ if (!entry.isFile() || entry.isSymbolicLink())
410
+ continue;
411
+ if (entry.name.startsWith(prefix))
412
+ continue;
413
+ await fs.rm(path.join(dir, entry.name), { force: true });
414
+ }
135
415
  }
136
416
  }
@@ -5,7 +5,7 @@ Use this before you call \`artifact_create\`, and before an \`artifact_update\`
5
5
 
6
6
  ## When to use an artifact
7
7
 
8
- Use \`artifact_create\` when the user asks for an artifact, an artifact page, or an artifact doc. Pick \`page\` for an artifact page and \`doc\` for an artifact doc. Never write a file in the project instead. Write a project file only when the user asks for a file in the repo.
8
+ Use \`artifact_create\` when the user asks for an artifact, an artifact page, an artifact doc, or an artifact design. Pick \`page\` for an artifact page, \`doc\` for an artifact doc, and \`design\` for an OpenPencil design. Never write a file in the project instead. Write a project file only when the user asks for a file in the repo.
9
9
 
10
10
  ## Precedence
11
11
 
@@ -17,6 +17,25 @@ Use \`artifact_create\` when the user asks for an artifact, an artifact page, or
17
17
 
18
18
  - \`doc\` for prose: reports, briefs, plans, specs, notes. It is Markdown, edited in a rich-text editor, and exported to Word, Markdown, and HTML. Use headings, short paragraphs, lists, tables, task lists, quotes, and fenced code. Do not paste HTML into a doc.
19
19
  - \`page\` for anything visual or interactive: dashboards, one-pagers, explainers, calculators, diagrams, prototypes.
20
+ - \`design\` for a layout the user will open on a canvas: UI mockups, layout explorations, and screens that export as PNG, SVG, or a \`.fig\` document.
21
+
22
+ ## Designs (OpenPencil Design JSX)
23
+
24
+ A design is OpenPencil Design JSX, not React DOM and not HTML. There are no imports, no HTML tags, and no CSS classes. Icons use the bundled Material Design Icons set.
25
+
26
+ Call this artifact a mockup when you talk to the user. The tools still take type \`design\`.
27
+
28
+ - Elements: \`Frame\`, \`Text\`, \`Rectangle\`, \`Ellipse\`, \`Line\`, \`Star\`, \`Polygon\`, \`Vector\`, \`Group\`, \`Section\`.
29
+ - Layout props: \`w\`, \`h\`, \`p\`, \`px\`, \`py\`, \`gap\`, \`flex\` (\`row\` or \`col\`), \`items\`, \`justify\`, \`bg\`, \`rounded\`, \`stroke\`, \`strokeWidth\`, \`opacity\`.
30
+ - Use \`flex\`, not \`dir\`. \`dir\` is accepted and does nothing, so every child sits at the same origin. A frame with \`flex\` sizes itself to its children unless you give it \`w\` or \`h\`.
31
+ - Text props: \`size\`, \`weight\`, \`color\`, \`font\`, \`lineHeight\`, \`letterSpacing\`, \`textAlign\`, \`maxLines\`.
32
+ - Put a background on the outer \`Frame\`; the preview crops transparent space around the content.
33
+ - Example: \`<Frame w={720} p={40} bg="#ffffff" flex="col" gap={12}><Text size={40} weight={700} color="#16181d">Title</Text><Text size={16} color="#5b6170">One line of context.</Text></Frame>\`
34
+ - Icons: \`<Icon name="mdi:home" size={24} color="#1b1712" />\`. Only the \`mdi:\` set is bundled. Common names: \`home\`, \`search\`, \`user\`, \`heart\`, \`star\`, \`check\`, \`close\`, \`plus\`, \`arrow-right\`, \`settings\`, \`bell\`, \`calendar\`, \`mail\`, \`image\`, \`file\`, \`folder\`, \`trash\`, \`edit\`, \`download\`, \`lock\`, \`eye\`, \`cart\`, \`chart-bar\`, \`alert\`, \`clock\`, \`map-marker\`, \`menu\`, \`chevron-right\`. An unknown set or name refuses the save. Icons draw as vectors and keep their 24 unit box.
35
+ - Text uses Inter, Roboto, or Noto Naskh Arabic, which ship with the package. Any other family substitutes a default face and returns a warning.
36
+ - A design has no network and no external images. Use solid and gradient fills, shapes, and text.
37
+ - The stored artifact is the JSX source. Send the complete source as \`content\` when you update a design. The host compiles and validates before saving, so a compile error refuses the write and returns the compiler message.
38
+ - Export is PNG, SVG, or \`.fig\`. The user can open the \`.fig\` in OpenPencil for a full canvas editor.
20
39
 
21
40
  ## The page sandbox
22
41
 
@@ -81,7 +100,7 @@ Tell the user in one or two sentences what you made or changed. Do not repeat th
81
100
  /** The artifact design skill, registered by the \`dsh-artifact-studio/skill\` host plugin. */
82
101
  export const ARTIFACT_DESIGN_SKILL = {
83
102
  name: 'artifact-design',
84
- description: 'Design rules for artifact pages and documents: when to use an artifact, precedence, the page sandbox, design tokens, dark mode, layout, typography, and the update rule.',
103
+ description: 'Design rules for artifact pages, documents, and OpenPencil designs: when to use an artifact, precedence, the page sandbox, Design JSX, design tokens, dark mode, layout, typography, and the update rule.',
85
104
  whenToUse: 'Load before artifact_create, when the user asks for an artifact, and before an artifact_update that changes layout or styling.',
86
105
  source: 'bundled',
87
106
  content: CONTENT,
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { CONTENT_FILE, ID_PATTERN, MAX_LIST_LIMIT, MAX_TITLE, isArtifactType, isManifest, isVersionSource } from '../../contract.js';
5
5
  import { ArtifactError, errnoCode } from './errors.js';
6
+ import { assertNoEditors } from './editor-leases.js';
6
7
  import { assertWithin, withLock, writeAtomic } from './fsutil.js';
7
8
  import { artifactDir, assertPlainFile } from './paths.js';
8
9
  export const DEFAULT_LIMITS = {
@@ -329,6 +330,15 @@ export class ArtifactStore {
329
330
  }
330
331
  return manifest;
331
332
  }
333
+ /**
334
+ * Read only the manifest, without its content.
335
+ * @param root the scope root.
336
+ * @param id the artifact id.
337
+ * @returns the manifest.
338
+ */
339
+ async manifest(root, id) {
340
+ return this.readManifest(await artifactDir(root, id));
341
+ }
332
342
  /**
333
343
  * Read the manifest and content of the current or an earlier version.
334
344
  * @param root the scope root.
@@ -480,6 +490,53 @@ export class ArtifactStore {
480
490
  const items = filtered.slice(offset, offset + limit);
481
491
  return { items, total: filtered.length, hasMore: offset + items.length < filtered.length, truncated };
482
492
  }
493
+ /** Transfer saved files under source and destination locks. */
494
+ async move(source, destination, id, baseVersion, ownToken) {
495
+ if (source.scope !== 'workspace' || destination.scope !== 'workspace' || source.root === destination.root) {
496
+ throw new ArtifactError('artifact/bad-request', 'Choose a different workspace.');
497
+ }
498
+ const dir = await artifactDir(source, id);
499
+ const target = path.join(destination.root, id);
500
+ await assertWithin(destination.root, target);
501
+ const first = dir < target ? dir : target;
502
+ const second = dir < target ? target : dir;
503
+ return withLock(first, () => withLock(second, async () => {
504
+ await assertNoEditors(dir, ownToken);
505
+ const manifest = await this.readManifest(dir);
506
+ if (manifest.version !== baseVersion) {
507
+ throw new ArtifactError('artifact/stale-version', 'The artifact changed before it could be moved.', { current: manifest.version, baseVersion });
508
+ }
509
+ try {
510
+ await fs.lstat(target);
511
+ throw new ArtifactError('artifact/bad-request', 'The destination already contains this artifact.', { id });
512
+ }
513
+ catch (error) {
514
+ if (error instanceof ArtifactError || errnoCode(error) !== 'ENOENT')
515
+ throw error;
516
+ }
517
+ const inspect = async (entry) => {
518
+ await assertWithin(source.root, entry);
519
+ const stat = await fs.lstat(entry);
520
+ if (stat.isSymbolicLink() || (!stat.isFile() && !stat.isDirectory())) {
521
+ throw new ArtifactError('artifact/forbidden-path', 'An artifact contains an unsafe file.');
522
+ }
523
+ if (stat.isDirectory())
524
+ for (const name of await fs.readdir(entry))
525
+ await inspect(path.join(entry, name));
526
+ };
527
+ await inspect(dir);
528
+ await assertWithin(destination.root, target);
529
+ try {
530
+ await fs.rename(dir, target);
531
+ }
532
+ catch (error) {
533
+ if (errnoCode(error) === 'EXDEV')
534
+ throw new ArtifactError('artifact/storage-failure', 'Source and destination must be on the same filesystem. The artifact was not moved.');
535
+ throw error;
536
+ }
537
+ return manifest;
538
+ }));
539
+ }
483
540
  /**
484
541
  * Move an artifact into the scope's trash, then sweep trash entries past retention.
485
542
  * @param root the scope root.
@@ -124,7 +124,7 @@ const SUMMARY_SCHEMA = {
124
124
  properties: {
125
125
  id: { type: 'string' },
126
126
  scope: { type: 'string', enum: ['workspace', 'library'] },
127
- type: { type: 'string', enum: ['page', 'doc'] },
127
+ type: { type: 'string', enum: ['page', 'doc', 'design'] },
128
128
  title: { type: 'string' },
129
129
  version: { type: 'integer' },
130
130
  updatedAt: { type: 'string' },
@@ -167,9 +167,9 @@ export function createTools(host) {
167
167
  additionalProperties: false,
168
168
  required: ['type', 'title', 'content'],
169
169
  properties: {
170
- type: { type: 'string', enum: ['page', 'doc'], description: 'page for HTML, doc for Markdown.' },
170
+ type: { type: 'string', enum: ['page', 'doc', 'design'], description: 'page for HTML, doc for Markdown, design for OpenPencil Design JSX. For a design, load the artifact-design skill first: no imports, no HTML.' },
171
171
  title: { type: 'string', description: 'Short title, 1 to 120 characters.' },
172
- content: { type: 'string', description: 'The full HTML document or Markdown text, up to 2 MiB.' },
172
+ content: { type: 'string', description: 'The full HTML document, Markdown text, or Design JSX source, up to 2 MiB.' },
173
173
  scope: SCOPE_PARAM,
174
174
  },
175
175
  },
@@ -189,7 +189,10 @@ export function createTools(host) {
189
189
  content,
190
190
  source: { origin: 'agent', action: 'create', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
191
191
  });
192
- return { ...summary(manifest, target), warnings: warningsFor(type, content) };
192
+ const warnings = type === 'design'
193
+ ? (await service.read(target, manifest.id)).designInfo?.warnings ?? []
194
+ : warningsFor(type, content);
195
+ return { ...summary(manifest, target), warnings };
193
196
  },
194
197
  };
195
198
  const read = {
@@ -209,15 +212,28 @@ export function createTools(host) {
209
212
  type: 'object',
210
213
  additionalProperties: false,
211
214
  required: ['artifact', 'readVersion', 'content'],
212
- properties: { artifact: SUMMARY_SCHEMA, readVersion: { type: 'integer' }, content: { type: 'string' } },
215
+ properties: {
216
+ artifact: SUMMARY_SCHEMA,
217
+ readVersion: { type: 'integer' },
218
+ content: { type: 'string' },
219
+ designInfo: {
220
+ type: 'object',
221
+ description: 'The compiled summary of a design: pages, nodes, type counts, fonts, and warnings.',
222
+ },
223
+ },
213
224
  },
214
225
  render: (_args, value) => {
215
226
  const fields = record(value);
216
227
  const artifact = record(fields.artifact ?? null);
228
+ const info = record(fields.designInfo ?? null);
229
+ const summaryLine = info.nodes === undefined
230
+ ? ''
231
+ : `\n\nDesign: ${String(info.nodes)} nodes, ${String(info.pages)} page(s), fonts ${Array.isArray(info.fonts) && info.fonts.length > 0 ? info.fonts.map(String).join(', ') : 'none'}.`
232
+ + (Array.isArray(info.warnings) && info.warnings.length > 0 ? `\nWarnings:\n${info.warnings.map((item) => `- ${String(item)}`).join('\n')}` : '');
217
233
  return [
218
234
  {
219
235
  type: 'text',
220
- text: `${line(artifact, 'Artifact')} Showing version ${String(fields.readVersion)}.\n\n${String(fields.content)}`,
236
+ text: `${line(artifact, 'Artifact')} Showing version ${String(fields.readVersion)}.${summaryLine}\n\n${String(fields.content)}`,
221
237
  },
222
238
  ];
223
239
  },
@@ -227,7 +243,15 @@ export function createTools(host) {
227
243
  const id = requiredString(fields, 'id');
228
244
  const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined);
229
245
  const result = await service.read(target, id, optionalInteger(fields, 'version'));
230
- return { artifact: summary(result.manifest, target), readVersion: result.version, content: result.content };
246
+ const info = result.designInfo;
247
+ return {
248
+ artifact: summary(result.manifest, target),
249
+ readVersion: result.version,
250
+ content: result.content,
251
+ ...(info === undefined
252
+ ? {}
253
+ : { designInfo: { pages: info.pages, nodes: info.nodes, types: info.types, fonts: info.fonts, warnings: info.warnings } }),
254
+ };
231
255
  },
232
256
  };
233
257
  const update = {
@@ -236,6 +260,7 @@ export function createTools(host) {
236
260
  'Save a new version of an artifact. For a few local changes send edits; send complete content only when you rewrite most of it. Each edit oldText must occur exactly once.',
237
261
  'The update is refused when baseVersion is not the current version, for example after the user edited it; read it again and reapply your change. Never discard the user\'s edits.',
238
262
  'A layout or styling change follows the artifact-design skill and the same precedence: the user\'s request, then the design system, then your own choices.',
263
+ 'For a design, send the complete Design JSX source as content and read it first if you did not write it; edits are applied and validated too, but a design rewrite is usually smaller as one content value.',
239
264
  'Each call writes a version the user sees. Put every fix for one request, including all returned warnings, into one update; never send one update per finding.',
240
265
  ].join('\n'),
241
266
  parameters: {
@@ -245,7 +270,7 @@ export function createTools(host) {
245
270
  properties: {
246
271
  id: { type: 'string' },
247
272
  baseVersion: { type: 'integer', description: 'The version your change is based on.' },
248
- content: { type: 'string', description: 'Complete replacement content. Use this or edits.' },
273
+ content: { type: 'string', description: 'Complete replacement content. Use this or edits. For a design, send the complete Design JSX source.' },
249
274
  edits: {
250
275
  type: 'array',
251
276
  description: 'Replace-once edits applied in order. Each oldText must occur exactly once.',
@@ -281,7 +306,25 @@ export function createTools(host) {
281
306
  title,
282
307
  source: { origin: 'agent', action: 'update', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
283
308
  });
284
- return { ...summary(manifest, target), warnings: await writtenWarnings(manifest.type, content, edits === undefined ? undefined : () => service.read(target, id, manifest.version)) };
309
+ const warnings = manifest.type === 'design'
310
+ ? (await service.read(target, id, manifest.version)).designInfo?.warnings ?? []
311
+ : await writtenWarnings(manifest.type, content, edits === undefined ? undefined : () => service.read(target, id, manifest.version));
312
+ return { ...summary(manifest, target), warnings };
313
+ },
314
+ };
315
+ const move = {
316
+ name: 'artifact_move',
317
+ description: 'Move a saved workspace artifact to another registered workspace. Ask the user first. Close all editors for the artifact before moving it.',
318
+ parameters: { type: 'object', additionalProperties: false, required: ['id', 'destinationWorkspaceId', 'baseVersion'], properties: {
319
+ id: { type: 'string' }, destinationWorkspaceId: { type: 'string' }, baseVersion: { type: 'integer' },
320
+ } },
321
+ output: { schema: SUMMARY_SCHEMA, render: (_args, value) => [{ type: 'text', text: 'Moved artifact: ' + String(record(value).id) + ' to workspace ' + String(record(value).workspaceId) }] },
322
+ async execute(args, exec) {
323
+ const fields = fieldsOf(args);
324
+ const target = await targetFor(host, exec, undefined);
325
+ const destinationWorkspaceId = requiredString(fields, 'destinationWorkspaceId');
326
+ const manifest = await service.move(target, requiredString(fields, 'id'), destinationWorkspaceId, requiredInteger(fields, 'baseVersion'));
327
+ return summary(manifest, { scope: 'workspace', workspaceId: destinationWorkspaceId });
285
328
  },
286
329
  };
287
330
  const list = {
@@ -292,7 +335,7 @@ export function createTools(host) {
292
335
  additionalProperties: false,
293
336
  properties: {
294
337
  scope: { type: 'string', enum: ['workspace', 'library'], description: 'Defaults to workspace.' },
295
- type: { type: 'string', enum: ['page', 'doc'] },
338
+ type: { type: 'string', enum: ['page', 'doc', 'design'] },
296
339
  query: { type: 'string', description: 'Title substring, case-insensitive.' },
297
340
  offset: { type: 'integer' },
298
341
  },
@@ -349,12 +392,12 @@ export function createTools(host) {
349
392
  };
350
393
  const exportTool = {
351
394
  name: 'artifact_export',
352
- description: 'Write an artifact to a standalone file and return its path. A page exports as html; a doc exports as md, docx, or printable html.',
395
+ description: 'Write an artifact to a standalone file and return its path. A page exports as html; a doc exports as md, docx, or printable html; a design exports as png, svg, or .fig.',
353
396
  parameters: {
354
397
  type: 'object',
355
398
  additionalProperties: false,
356
399
  required: ['id', 'format'],
357
- properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx'] },
400
+ properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig'] },
358
401
  version: { type: 'integer', minimum: 1, description: 'Saved version to export. Omit for the current version.' } },
359
402
  },
360
403
  output: {
@@ -417,5 +460,5 @@ export function createTools(host) {
417
460
  return { scope: saved.scope, tokens: JSON.stringify(saved.tokens, null, 2) };
418
461
  },
419
462
  };
420
- return [create, read, update, list, remove, exportTool, designRead, designUpdate];
463
+ return [create, read, update, move, list, remove, exportTool, designRead, designUpdate];
421
464
  }