dsh-artifact-studio 0.8.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +72 -10
  2. package/THIRD_PARTY_NOTICES.md +57 -0
  3. package/assets/canvas.engine.js +72 -72
  4. package/assets/canvas.viewer.js +6415 -0
  5. package/client.canvas.js +1 -1
  6. package/client.doc.js +67 -79
  7. package/client.js +313 -291
  8. package/client.sheet.js +218 -0
  9. package/dist/contract.js +32 -5
  10. package/dist/host/lib/assets.js +12 -0
  11. package/dist/host/lib/brief.js +127 -0
  12. package/dist/host/lib/checks.js +62 -8
  13. package/dist/host/lib/design-catalog.js +149 -0
  14. package/dist/host/lib/design-render.js +37 -0
  15. package/dist/host/lib/design-system.js +1 -1
  16. package/dist/host/lib/export.js +123 -5
  17. package/dist/host/lib/fsutil.js +41 -0
  18. package/dist/host/lib/generation.js +36 -0
  19. package/dist/host/lib/guide.js +130 -0
  20. package/dist/host/lib/paths.js +2 -1
  21. package/dist/host/lib/recipes.js +224 -0
  22. package/dist/host/lib/rpc.js +20 -5
  23. package/dist/host/lib/service.js +253 -24
  24. package/dist/host/lib/skill.js +59 -18
  25. package/dist/host/lib/store.js +107 -25
  26. package/dist/host/lib/svg-model.js +85 -0
  27. package/dist/host/lib/svg-viewer.js +380 -0
  28. package/dist/host/lib/tools.js +346 -35
  29. package/dist/host/lib/validate.js +24 -0
  30. package/dist/host/lib/viewer.js +150 -0
  31. package/dist/host/lib/xlsx.js +314 -0
  32. package/dist/host/worker/design-worker.js +71 -5
  33. package/dist/host/worker/page-model.js +169 -0
  34. package/dist/html-tags.js +51 -0
  35. package/dist/kit.js +224 -0
  36. package/dist/render.js +10 -3
  37. package/dist/sheet/formula.js +475 -0
  38. package/dist/sheet/functions.js +463 -0
  39. package/dist/sheet/index.js +9 -0
  40. package/dist/sheet/model.js +695 -0
  41. package/dist/sheet/operations.js +384 -0
  42. package/dist/sheet/output.js +182 -0
  43. package/package.json +15 -3
@@ -1,7 +1,9 @@
1
1
  import { checkPage } from './checks.js';
2
+ import { SheetError, applySheetOperations, checkSheetWorkbook, parseSheetWorkbook, serializeSheetWorkbook, sheetOverview } from '../../sheet/index.js';
3
+ import { MAX_INSTRUCTIONS } from './guide.js';
2
4
  import { ArtifactError } from './errors.js';
3
5
  import { requireWorkspace, workspaceForSession } from './paths.js';
4
- import { fieldsOf, optionalEdits, optionalInteger, optionalScope, optionalString, optionalType, requiredFormat, requiredInteger, requiredString, requiredType, } from './validate.js';
6
+ import { fieldsOf, designSelection, designSaveOptions, optionalEdits, optionalInteger, optionalScope, optionalString, optionalType, requiredFormat, requiredInteger, requiredString, requiredType, } from './validate.js';
5
7
  const SCOPE_PARAM = {
6
8
  type: 'string',
7
9
  enum: ['workspace', 'library'],
@@ -11,37 +13,83 @@ const WORKSPACE_PARAM = {
11
13
  type: 'string',
12
14
  description: "Another registered project's workspace id, from an artifact reference. Omit for this session's project.",
13
15
  };
16
+ const DESIGN_SELECTION = {
17
+ systemId: { type: 'string', description: 'Named design system ID from design_system_list. Omit for the scope default.' },
18
+ systemScope: { type: 'string', enum: ['workspace', 'library'], description: 'Scope of the selected named system.' },
19
+ systemRevision: { type: 'integer', minimum: 1, description: 'Exact named system revision. Omit for its latest revision.' },
20
+ };
21
+ const DESIGN_IDENTITY = {
22
+ system: { oneOf: [{ type: 'object' }, { type: 'null' }] },
23
+ catalogRevision: { oneOf: [{ type: 'integer' }, { type: 'null' }] },
24
+ };
14
25
  const PAGE_GUIDE = [
15
- 'Load the artifact-design skill first if not loaded yet. Precedence: the user\'s request, then the design system, then your own choices.',
26
+ 'Load the artifact-design skill, then call artifact_brief and follow it. Precedence: the user\'s request, then saved conventions, then the recipe, then the design system, then your own choices.',
16
27
  'A page is one self-contained HTML document in a sandbox with no network or browser storage: inline all CSS and JavaScript, draw charts with inline SVG or canvas, and use data: URIs for images. Keep the layout fluid for a 380 to 700 px panel.',
17
- 'Use injected --artifact-* color, font, size, space, and radius variables. The skill covers semantic roles and the packaged page reference.',
28
+ 'Pages build on the artifact kit and the injected --artifact-* variables that the brief lists.',
18
29
  'A doc is Markdown: headings, lists, task lists, tables, quotes, and fenced code.',
19
30
  'Each save is a version the user sees. Check before saving and batch fixes into one update.',
20
31
  ].join('\n');
32
+ const RECIPE_PARAM = {
33
+ type: 'string',
34
+ description: 'The recipe id from artifact_brief: the content structure for this intent, such as client-scope or feature-spec. It is stored with the artifact and drives the structure checks.',
35
+ };
21
36
  /**
22
37
  * Warnings for the version an update wrote. Full content is checked directly.
23
38
  * Edits are checked against that exact saved version; the version already
24
- * landed, so a failed read reports no warnings instead of failing the write.
39
+ * landed, so a failed read reports that validation is incomplete.
25
40
  */
26
- async function writtenWarnings(type, content, readEdited) {
41
+ async function writtenWarnings(type, content, readEdited, recipe) {
42
+ if (type === 'sheet') {
43
+ const check = (text) => {
44
+ try {
45
+ return checkSheetWorkbook(parseSheetWorkbook(text));
46
+ }
47
+ catch {
48
+ return [];
49
+ }
50
+ };
51
+ if (content !== undefined)
52
+ return check(content);
53
+ if (readEdited === undefined)
54
+ return [];
55
+ try {
56
+ return check((await readEdited()).content);
57
+ }
58
+ catch (error) {
59
+ if (error instanceof ArtifactError)
60
+ return ['checks-unavailable: the version was saved, but its content could not be read for checks. Do not retry the write; read the saved version.'];
61
+ throw error;
62
+ }
63
+ }
27
64
  if (type !== 'page')
28
65
  return [];
66
+ const options = recipe === undefined ? {} : { recipe };
29
67
  if (content !== undefined)
30
- return checkPage(content);
68
+ return checkPage(content, options);
31
69
  if (readEdited === undefined)
32
70
  return [];
33
71
  try {
34
- return checkPage((await readEdited()).content);
72
+ return checkPage((await readEdited()).content, options);
35
73
  }
36
74
  catch (error) {
37
75
  if (error instanceof ArtifactError)
38
- return [];
76
+ return ['checks-unavailable: the version was saved, but its content could not be read for checks. Do not retry the write; read the saved version.'];
39
77
  throw error;
40
78
  }
41
79
  }
42
80
  /** Static page warnings for a written version; documents have none. */
43
- function warningsFor(type, content) {
44
- return type === 'page' && content !== undefined ? checkPage(content) : [];
81
+ function warningsFor(type, content, recipe) {
82
+ if (type === 'page' && content !== undefined)
83
+ return checkPage(content, recipe === undefined ? {} : { recipe });
84
+ if (type === 'sheet' && content !== undefined) {
85
+ try {
86
+ return checkSheetWorkbook(parseSheetWorkbook(content));
87
+ }
88
+ catch {
89
+ return [];
90
+ }
91
+ }
92
+ return [];
45
93
  }
46
94
  /**
47
95
  * The scope context of a call: the session's workspace, or an explicitly named
@@ -121,6 +169,8 @@ function summary(manifest, target) {
121
169
  updatedAt: manifest.updatedAt,
122
170
  contentBytes: manifest.contentBytes,
123
171
  workspaceId: manifest.scope === 'workspace' ? (target.workspaceId ?? null) : null,
172
+ recipe: manifest.recipe ?? null,
173
+ generation: manifest.generation ? { ...manifest.generation, system: manifest.generation.system ? { ...manifest.generation.system } : null } : null,
124
174
  };
125
175
  }
126
176
  /** The text the model reads after a write, with any page warnings. */
@@ -133,16 +183,18 @@ function writeText(value, verb) {
133
183
  const SUMMARY_SCHEMA = {
134
184
  type: 'object',
135
185
  additionalProperties: false,
136
- required: ['id', 'scope', 'type', 'title', 'version', 'updatedAt', 'contentBytes', 'workspaceId'],
186
+ required: ['id', 'scope', 'type', 'title', 'version', 'updatedAt', 'contentBytes', 'workspaceId', 'recipe'],
137
187
  properties: {
138
188
  id: { type: 'string' },
139
189
  scope: { type: 'string', enum: ['workspace', 'library'] },
140
- type: { type: 'string', enum: ['page', 'doc', 'design'] },
190
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
141
191
  title: { type: 'string' },
142
192
  version: { type: 'integer' },
143
193
  updatedAt: { type: 'string' },
144
194
  contentBytes: { type: 'integer' },
145
195
  workspaceId: { oneOf: [{ type: 'string' }, { type: 'null' }] },
196
+ recipe: { oneOf: [{ type: 'string' }, { type: 'null' }] },
197
+ generation: { oneOf: [{ type: 'object' }, { type: 'null' }] },
146
198
  },
147
199
  };
148
200
  /**
@@ -153,7 +205,8 @@ const SUMMARY_SCHEMA = {
153
205
  */
154
206
  function line(value, verb) {
155
207
  const fields = record(value);
156
- return `${verb} ${String(fields.type)} "${String(fields.title)}" id=${String(fields.id)} scope=${String(fields.scope)} version=${String(fields.version)}.`;
208
+ const recipe = typeof fields.recipe === 'string' ? ` recipe=${fields.recipe}` : '';
209
+ return `${verb} ${String(fields.type)} "${String(fields.title)}" id=${String(fields.id)} scope=${String(fields.scope)} version=${String(fields.version)}${recipe}.`;
157
210
  }
158
211
  const WRITE_SCHEMA = {
159
212
  ...SUMMARY_SCHEMA,
@@ -180,9 +233,11 @@ export function createTools(host) {
180
233
  additionalProperties: false,
181
234
  required: ['type', 'title', 'content'],
182
235
  properties: {
183
- type: { type: 'string', enum: ['page', 'doc', 'design'], description: 'page for HTML, doc for Markdown, design for OpenPencil Design JSX. A mockup or wireframe is always design. For a design, load the artifact-design skill first: no imports, no HTML. If a design fails for a reason other than its source, report the error; never redo it as a page.' },
236
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'], description: 'page for HTML, doc for Markdown, design for OpenPencil Design JSX, sheet for a JSON workbook. A mockup or wireframe is always design. For a design, load the artifact-design skill first: no imports, no HTML. If a design fails for a reason other than its source, report the error; never redo it as a page.' },
184
237
  title: { type: 'string', description: 'Short title, 1 to 120 characters.' },
185
- content: { type: 'string', description: 'The full HTML document, Markdown text, or Design JSX source, up to 2 MiB.' },
238
+ content: { type: 'string', description: 'The full HTML document, Markdown text, Design JSX source, or sheet workbook JSON, up to 2 MiB.' },
239
+ recipe: RECIPE_PARAM,
240
+ ...DESIGN_SELECTION,
186
241
  scope: SCOPE_PARAM,
187
242
  workspaceId: WORKSPACE_PARAM,
188
243
  },
@@ -197,15 +252,19 @@ export function createTools(host) {
197
252
  const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
198
253
  const type = requiredType(fields);
199
254
  const content = optionalString(fields, 'content') ?? '';
255
+ const recipeId = optionalString(fields, 'recipe');
256
+ const recipe = recipeId === undefined ? undefined : await service.recipe(target, recipeId, type);
200
257
  const manifest = await service.create(target, {
201
258
  type,
202
259
  title: requiredString(fields, 'title'),
203
260
  content,
261
+ ...(recipeId === undefined ? {} : { recipe: recipeId }),
262
+ design: designSelection(fields),
204
263
  source: { origin: 'agent', action: 'create', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
205
264
  });
206
265
  const warnings = type === 'design'
207
266
  ? (await service.read(target, manifest.id)).designInfo?.warnings ?? []
208
- : warningsFor(type, content);
267
+ : warningsFor(type, content, recipe);
209
268
  return { ...summary(manifest, target), warnings };
210
269
  },
211
270
  };
@@ -235,12 +294,21 @@ export function createTools(host) {
235
294
  type: 'object',
236
295
  description: 'The compiled summary of a design: pages, nodes, type counts, fonts, and warnings.',
237
296
  },
297
+ sheetInfo: {
298
+ type: 'array',
299
+ description: 'Per-sheet size and counts for a sheet artifact.',
300
+ items: { type: 'object' },
301
+ },
238
302
  },
239
303
  },
240
304
  render: (_args, value) => {
241
305
  const fields = record(value);
242
306
  const artifact = record(fields.artifact ?? null);
243
307
  const info = record(fields.designInfo ?? null);
308
+ const sheetRows = Array.isArray(fields.sheetInfo) ? fields.sheetInfo.map(record) : [];
309
+ const sheetLine = sheetRows.length === 0
310
+ ? ''
311
+ : '\n\nSheets: ' + sheetRows.map((row) => String(row.name) + ' (' + String(row.rows) + ' x ' + String(row.columns) + ', ' + String(row.cells) + ' cells)').join('; ') + '.';
244
312
  const summaryLine = info.nodes === undefined
245
313
  ? ''
246
314
  : `\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'}.`
@@ -248,7 +316,7 @@ export function createTools(host) {
248
316
  return [
249
317
  {
250
318
  type: 'text',
251
- text: `${line(artifact, 'Artifact')} Showing version ${String(fields.readVersion)}.${summaryLine}\n\n${String(fields.content)}`,
319
+ text: `${line(artifact, 'Artifact')} Showing version ${String(fields.readVersion)}.${summaryLine}${sheetLine}\n\n${String(fields.content)}`,
252
320
  },
253
321
  ];
254
322
  },
@@ -266,6 +334,9 @@ export function createTools(host) {
266
334
  ...(info === undefined
267
335
  ? {}
268
336
  : { designInfo: { pages: info.pages, nodes: info.nodes, types: info.types, fonts: info.fonts, warnings: info.warnings } }),
337
+ ...(result.manifest.type === 'sheet'
338
+ ? { sheetInfo: sheetOverview(parseSheetWorkbook(result.content)).map((item) => ({ name: item.name, rows: item.rows, columns: item.columns, cells: item.cells, formulas: item.formulas })) }
339
+ : {}),
269
340
  };
270
341
  },
271
342
  };
@@ -274,8 +345,9 @@ export function createTools(host) {
274
345
  description: [
275
346
  '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.',
276
347
  '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.',
277
- '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.',
348
+ 'A layout or styling change follows the artifact-design skill and the same precedence: the user\'s request, then saved conventions, then the recipe, then the design system, then your own choices. Send recipe to set or change it.',
278
349
  '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.',
350
+ 'For a sheet, prefer artifact_sheet_update with cell operations; send the complete workbook JSON as content only when you rewrite most of it.',
279
351
  '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.',
280
352
  ].join('\n'),
281
353
  parameters: {
@@ -285,7 +357,7 @@ export function createTools(host) {
285
357
  properties: {
286
358
  id: { type: 'string' },
287
359
  baseVersion: { type: 'integer', description: 'The version your change is based on.' },
288
- content: { type: 'string', description: 'Complete replacement content. Use this or edits. For a design, send the complete Design JSX source.' },
360
+ content: { type: 'string', description: 'Complete replacement content. Use this or edits. For a design, send the complete Design JSX source; for a sheet, prefer artifact_sheet_update.' },
289
361
  edits: {
290
362
  type: 'array',
291
363
  description: 'Replace-once edits applied in order. Each oldText must occur exactly once.',
@@ -297,6 +369,7 @@ export function createTools(host) {
297
369
  },
298
370
  },
299
371
  title: { type: 'string', description: 'A new title.' },
372
+ recipe: { ...RECIPE_PARAM, description: 'Set or change the recipe, for example on an artifact made before recipes existed.' },
300
373
  workspaceId: WORKSPACE_PARAM,
301
374
  },
302
375
  },
@@ -312,22 +385,103 @@ export function createTools(host) {
312
385
  const content = optionalString(fields, 'content');
313
386
  const edits = optionalEdits(fields);
314
387
  const title = optionalString(fields, 'title');
315
- if (content === undefined && edits === undefined && title === undefined) {
316
- throw new ArtifactError('artifact/bad-request', 'Send content, edits, or a title.');
388
+ const recipeId = optionalString(fields, 'recipe');
389
+ if (content === undefined && edits === undefined && title === undefined && recipeId === undefined) {
390
+ throw new ArtifactError('artifact/bad-request', 'Send content, edits, a title, or a recipe.');
317
391
  }
392
+ const current = await service.store.manifest(await service.root(target, id), id);
393
+ const recipe = recipeId === undefined
394
+ ? await service.recipeOf(target, current)
395
+ : await service.recipe({ ...target, scope: current.scope }, recipeId, current.type);
318
396
  const manifest = await service.update(target, id, {
319
397
  baseVersion: requiredInteger(fields, 'baseVersion'),
320
398
  content,
321
399
  edits,
322
400
  title,
401
+ ...(recipeId === undefined ? {} : { recipe: recipeId }),
323
402
  source: { origin: 'agent', action: 'update', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
324
403
  });
325
404
  const warnings = manifest.type === 'design'
326
405
  ? (await service.read(target, id, manifest.version)).designInfo?.warnings ?? []
327
- : await writtenWarnings(manifest.type, content, edits === undefined ? undefined : () => service.read(target, id, manifest.version));
406
+ : await writtenWarnings(manifest.type, content, edits === undefined && recipeId === undefined ? undefined : () => service.read(target, id, manifest.version), recipe);
328
407
  return { ...summary(manifest, target), warnings };
329
408
  },
330
409
  };
410
+ const sheetUpdate = {
411
+ name: 'artifact_sheet_update',
412
+ description: [
413
+ 'Edit a sheet artifact\'s cells and structure without rewriting the whole workbook JSON. Read the artifact first when the user may have edited it, then send one operations array with the current baseVersion.',
414
+ 'Operations run in order: set one cell, write a block, clear a range, format a range, add, rename, or delete a sheet, or set a column width. A string that starts with "=" is a formula in a written block. The whole workbook is validated before it is saved, and formula warnings come back with the result.',
415
+ 'Use artifact_read for the current workbook and artifact_update when you rewrite most of it, change its title, or change the sheet structure in one batch.',
416
+ ].join('\n'),
417
+ parameters: {
418
+ type: 'object',
419
+ additionalProperties: false,
420
+ required: ['id', 'baseVersion', 'operations'],
421
+ properties: {
422
+ id: { type: 'string', description: 'Sheet artifact id.' },
423
+ baseVersion: { type: 'integer', description: 'The version you read; a stale value is refused.' },
424
+ operations: {
425
+ type: 'array',
426
+ description: 'Ordered edits. set {op,sheet?,ref,value?|formula?,style?}; write {op,sheet?,ref,values}; clear {op,sheet?,range}; format {op,sheet?,range,style}; add-sheet {op,name}; rename-sheet {op,from,to}; delete-sheet {op,name}; set-column-width {op,sheet?,column,width}.',
427
+ items: { type: 'object' },
428
+ },
429
+ workspaceId: WORKSPACE_PARAM,
430
+ },
431
+ },
432
+ output: {
433
+ schema: {
434
+ ...WRITE_SCHEMA,
435
+ properties: {
436
+ ...WRITE_SCHEMA.properties,
437
+ notes: { type: 'array', items: { type: 'string' } },
438
+ sheets: { type: 'array', items: { type: 'object' } },
439
+ },
440
+ required: [...WRITE_SCHEMA.required, 'notes', 'sheets'],
441
+ },
442
+ render: (_args, value) => {
443
+ const fields = record(value);
444
+ const notes = Array.isArray(fields.notes) ? fields.notes.map(String) : [];
445
+ const sheetRows = Array.isArray(fields.sheets) ? fields.sheets.map(record) : [];
446
+ const sheetLine = sheetRows.length === 0
447
+ ? ''
448
+ : '\nSheets: ' + sheetRows.map((row) => String(row.name) + ' (' + String(row.cells) + ' cells)').join('; ') + '.';
449
+ const noteLines = notes.length === 0 ? '' : '\n' + notes.map((note) => '- ' + note).join('\n');
450
+ return [{ type: 'text', text: writeText(value, 'Updated') + sheetLine + noteLines }];
451
+ },
452
+ presentationMeta: (_args, value) => cardMeta(value),
453
+ },
454
+ async execute(args, exec) {
455
+ const fields = fieldsOf(args);
456
+ const id = requiredString(fields, 'id');
457
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
458
+ const current = await service.read(target, id);
459
+ if (current.manifest.type !== 'sheet') {
460
+ throw new ArtifactError('artifact/unsupported-type', 'artifact_sheet_update works only on sheet artifacts.', { type: current.manifest.type });
461
+ }
462
+ let applied;
463
+ try {
464
+ applied = applySheetOperations(current.content, fields.operations);
465
+ }
466
+ catch (error) {
467
+ if (error instanceof SheetError)
468
+ throw new ArtifactError('artifact/invalid-sheet', error.message, { message: error.message });
469
+ throw error;
470
+ }
471
+ const content = serializeSheetWorkbook(applied.workbook);
472
+ const manifest = await service.update(target, id, {
473
+ baseVersion: requiredInteger(fields, 'baseVersion'),
474
+ content,
475
+ source: { origin: 'agent', action: 'update', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
476
+ });
477
+ return {
478
+ ...summary(manifest, target),
479
+ warnings: checkSheetWorkbook(applied.workbook),
480
+ notes: applied.notes,
481
+ sheets: sheetOverview(applied.workbook).map((item) => ({ name: item.name, rows: item.rows, columns: item.columns, cells: item.cells, formulas: item.formulas })),
482
+ };
483
+ },
484
+ };
331
485
  const list = {
332
486
  name: 'artifact_list',
333
487
  description: 'List artifacts in this project or the profile library, newest first, at most 50 per call. Pass workspaceId to list another project.',
@@ -337,8 +491,9 @@ export function createTools(host) {
337
491
  properties: {
338
492
  scope: { type: 'string', enum: ['workspace', 'library'], description: 'Defaults to workspace.' },
339
493
  workspaceId: WORKSPACE_PARAM,
340
- type: { type: 'string', enum: ['page', 'doc', 'design'] },
494
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
341
495
  query: { type: 'string', description: 'Title substring, case-insensitive.' },
496
+ recipe: { type: 'string', description: 'Only artifacts that follow this recipe.' },
342
497
  offset: { type: 'integer' },
343
498
  },
344
499
  },
@@ -354,7 +509,8 @@ export function createTools(host) {
354
509
  const items = Array.isArray(fields.items) ? fields.items : [];
355
510
  const lines = items.map((item) => {
356
511
  const row = record(item);
357
- return `- ${String(row.id)} ${String(row.type)} v${String(row.version)} "${String(row.title)}" (updated ${String(row.updatedAt)})`;
512
+ const recipe = typeof row.recipe === 'string' ? ` [${row.recipe}]` : '';
513
+ return `- ${String(row.id)} ${String(row.type)}${recipe} v${String(row.version)} "${String(row.title)}" (updated ${String(row.updatedAt)})`;
358
514
  });
359
515
  const head = `${items.length} of ${String(fields.total)} artifacts${fields.hasMore === true ? '; more with a higher offset' : ''}.`;
360
516
  return [{ type: 'text', text: [head, ...lines].join('\n') }];
@@ -366,6 +522,7 @@ export function createTools(host) {
366
522
  const page = await service.list(target, {
367
523
  query: optionalString(fields, 'query'),
368
524
  type: optionalType(fields),
525
+ recipe: optionalString(fields, 'recipe'),
369
526
  offset: optionalInteger(fields, 'offset'),
370
527
  });
371
528
  return { items: page.items.map((item) => summary(item, target)), total: page.total, hasMore: page.hasMore };
@@ -394,12 +551,12 @@ export function createTools(host) {
394
551
  };
395
552
  const exportTool = {
396
553
  name: 'artifact_export',
397
- 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.',
554
+ 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, .fig, a self-contained view-only html viewer, or a smaller html page with an svg scene and selectable text; a sheet exports as csv (first sheet) or xlsx (every sheet).',
398
555
  parameters: {
399
556
  type: 'object',
400
557
  additionalProperties: false,
401
558
  required: ['id', 'format'],
402
- properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig'] },
559
+ properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig', 'html-svg', 'csv', 'xlsx'] },
403
560
  version: { type: 'integer', minimum: 1, description: 'Saved version to export. Omit for the current version.' },
404
561
  workspaceId: WORKSPACE_PARAM },
405
562
  },
@@ -415,26 +572,58 @@ export function createTools(host) {
415
572
  return { path: file.path, bytes: file.bytes };
416
573
  },
417
574
  };
575
+ const importTool = {
576
+ name: 'artifact_import',
577
+ description: 'Import a Figma .fig file as a new design the user calls a mockup. The file\'s first page with elements becomes the editable Design JSX source; later pages are skipped and named in warnings. Pass the absolute file path the user named. Use it when the user points at a .fig file instead of asking for a fresh mockup.',
578
+ parameters: {
579
+ type: 'object',
580
+ additionalProperties: false,
581
+ required: ['path'],
582
+ properties: {
583
+ path: { type: 'string', description: 'Absolute path of the .fig file to read.' },
584
+ title: { type: 'string', description: 'Short title, 1 to 120 characters. Defaults to the file name.' },
585
+ ...DESIGN_SELECTION,
586
+ scope: SCOPE_PARAM,
587
+ workspaceId: WORKSPACE_PARAM,
588
+ },
589
+ },
590
+ output: {
591
+ schema: { type: 'object', additionalProperties: false, required: [...WRITE_SCHEMA.required, 'warnings'], properties: { ...WRITE_SCHEMA.properties, warnings: { type: 'array', items: { type: 'string' } } } },
592
+ render: (_args, value) => [{ type: 'text', text: writeText(value, 'Imported') }],
593
+ presentationMeta: (_args, value) => cardMeta(value),
594
+ },
595
+ async execute(args, exec) {
596
+ const fields = fieldsOf(args);
597
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
598
+ const manifest = await service.importDesign(target, {
599
+ path: requiredString(fields, 'path'),
600
+ title: optionalString(fields, 'title'),
601
+ source: { origin: 'agent', action: 'create', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
602
+ });
603
+ const warnings = (await service.read(target, manifest.id)).designInfo?.warnings ?? [];
604
+ return { ...summary(manifest, target), warnings };
605
+ },
606
+ };
418
607
  const designRead = {
419
608
  name: 'design_system_read',
420
609
  description: 'Read the design tokens that pages and docs in this project inherit, and whether they come from the project, the profile library, or the built-in default.',
421
- parameters: { type: 'object', additionalProperties: false, properties: { workspaceId: WORKSPACE_PARAM } },
610
+ parameters: { type: 'object', additionalProperties: false, properties: { workspaceId: WORKSPACE_PARAM, scope: SCOPE_PARAM, ...DESIGN_SELECTION } },
422
611
  output: {
423
- schema: { type: 'object', additionalProperties: false, required: ['source', 'tokens'], properties: { source: { type: 'string' }, tokens: { type: 'string' } } },
612
+ schema: { type: 'object', additionalProperties: false, required: ['source', 'tokens'], properties: { source: { type: 'string' }, tokens: { type: 'string' }, ...DESIGN_IDENTITY } },
424
613
  render: (_args, value) => [{ type: 'text', text: `Design system from ${String(record(value).source)}:\n${String(record(value).tokens)}` }],
425
614
  },
426
615
  async execute(args, exec) {
427
616
  const fields = fieldsOf(args);
428
617
  const workspaceId = optionalString(fields, 'workspaceId');
429
- const target = await targetFor(host, exec, undefined, workspaceId).catch((error) => {
618
+ const target = await targetFor(host, exec, optionalScope(fields), workspaceId).catch((error) => {
430
619
  // A session outside every workspace can still read the library. A named
431
620
  // workspace that does not resolve is a real failure.
432
621
  if (workspaceId === undefined && error instanceof ArtifactError && error.code === 'artifact/no-workspace')
433
622
  return {};
434
623
  throw error;
435
624
  });
436
- const resolved = await service.designSystem(target);
437
- return { source: resolved.source, tokens: JSON.stringify(resolved.tokens, null, 2) };
625
+ const resolved = await service.designSystem(target, designSelection(fields));
626
+ return { source: resolved.source, tokens: JSON.stringify(resolved.tokens, null, 2), system: resolved.system ? { ...resolved.system } : null, catalogRevision: resolved.catalogRevision ?? null };
438
627
  },
439
628
  };
440
629
  const designUpdate = {
@@ -445,6 +634,10 @@ export function createTools(host) {
445
634
  additionalProperties: false,
446
635
  required: ['tokens'],
447
636
  properties: {
637
+ systemId: DESIGN_SELECTION.systemId,
638
+ expectedRevision: { type: 'integer', minimum: 0, description: 'Catalog revision from design_system_list, required for named saves.' },
639
+ createNew: { type: 'boolean', description: 'Save a new named system, leaving existing systems unchanged.' },
640
+ makeDefault: { type: 'boolean', description: 'Select this system for future artifacts. Existing pinned artifacts do not change.' },
448
641
  tokens: {
449
642
  type: 'object',
450
643
  description: 'Partial tokens: name, notes, colors and colorsDark {primary, accent, surface, text, muted, background, raised, border, control, action, actionText, focus, success, warning, danger}, typography {fontFamily, displayFamily, monoFamily, scale[]}, spacing {unit, scale[]}, radius {sm, md, lg}. Sizes are pixels.',
@@ -458,15 +651,133 @@ export function createTools(host) {
458
651
  },
459
652
  },
460
653
  output: {
461
- schema: { type: 'object', additionalProperties: false, required: ['scope', 'tokens'], properties: { scope: { type: 'string' }, tokens: { type: 'string' } } },
654
+ schema: { type: 'object', additionalProperties: false, required: ['scope', 'tokens'], properties: { scope: { type: 'string' }, tokens: { type: 'string' }, ...DESIGN_IDENTITY } },
462
655
  render: (_args, value) => [{ type: 'text', text: `Saved ${String(record(value).scope)} design system:\n${String(record(value).tokens)}` }],
463
656
  },
464
657
  async execute(args, exec) {
465
658
  const fields = fieldsOf(args);
466
659
  const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
467
- const saved = await service.saveDesignSystem(target, fields.tokens);
468
- return { scope: saved.scope, tokens: JSON.stringify(saved.tokens, null, 2) };
660
+ const saved = await service.saveDesignSystem(target, fields.tokens, designSaveOptions(fields));
661
+ return { scope: saved.scope, tokens: JSON.stringify(saved.tokens, null, 2), system: saved.system ? { ...saved.system } : null, catalogRevision: saved.catalogRevision ?? null };
662
+ },
663
+ };
664
+ const brief = {
665
+ name: 'artifact_brief',
666
+ description: [
667
+ 'Get the brief for a new artifact before artifact_create: the project conventions, the user\'s preferences, the recipe sections and rules, earlier artifacts to match, the design system, and for a page the component kit. Follow it, then pass the same recipe to artifact_create.',
668
+ 'Call it without recipe to list the recipes for the type, choose the one that fits the reader and purpose, and call it again with that id. Also call it before restyling an artifact that has a recipe.',
669
+ ].join('\n'),
670
+ parameters: {
671
+ type: 'object',
672
+ additionalProperties: false,
673
+ required: ['type'],
674
+ properties: {
675
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
676
+ recipe: { type: 'string', description: 'A recipe id. Omit to list the recipes for this type.' },
677
+ ...DESIGN_SELECTION,
678
+ scope: SCOPE_PARAM,
679
+ workspaceId: WORKSPACE_PARAM,
680
+ },
681
+ },
682
+ output: {
683
+ schema: {
684
+ type: 'object',
685
+ additionalProperties: false,
686
+ required: ['brief', 'recipe'],
687
+ properties: { brief: { type: 'string' }, recipe: { oneOf: [{ type: 'string' }, { type: 'null' }] } },
688
+ },
689
+ render: (_args, value) => [{ type: 'text', text: String(record(value).brief) }],
690
+ },
691
+ async execute(args, exec) {
692
+ const fields = fieldsOf(args);
693
+ const workspaceId = optionalString(fields, 'workspaceId');
694
+ const scope = optionalScope(fields);
695
+ const target = await targetFor(host, exec, scope, workspaceId).catch((error) => {
696
+ // Outside every workspace the library guide and recipes still apply.
697
+ if (workspaceId === undefined && scope !== 'workspace' && error instanceof ArtifactError && error.code === 'artifact/no-workspace')
698
+ return { scope: 'library' };
699
+ throw error;
700
+ });
701
+ const result = await service.brief(target, requiredType(fields), optionalString(fields, 'recipe'), designSelection(fields));
702
+ return { brief: result.brief, recipe: result.recipe?.id ?? null };
703
+ },
704
+ };
705
+ const guideUpdate = {
706
+ name: 'artifact_guide_update',
707
+ description: [
708
+ 'Save conventions the user wants every future artifact to follow, or a reusable recipe. Call it only when the user asks to remember a preference, a convention, or a structure; never for a one-off request.',
709
+ 'scope workspace (default) is this project\'s conventions. scope library is the user\'s preferences in every project. instructions replaces that scope\'s whole text, so read the current text in artifact_brief and send the full result.',
710
+ 'A recipe with the id of a built-in or wider recipe replaces it in this scope.',
711
+ ].join('\n'),
712
+ parameters: {
713
+ type: 'object',
714
+ additionalProperties: false,
715
+ properties: {
716
+ instructions: { type: 'string', description: `The complete conventions text for this scope, up to ${MAX_INSTRUCTIONS} characters. Short, concrete, checkable rules.` },
717
+ recipe: {
718
+ type: 'object',
719
+ description: 'A recipe to add or replace: { id, name, types: ["page"|"doc"|"design"], audience, purpose, sections: [{ key, title, purpose, required }], rules: [string] }.',
720
+ },
721
+ removeRecipe: { type: 'string', description: 'The id of a recipe in this scope to remove.' },
722
+ scope: SCOPE_PARAM,
723
+ workspaceId: WORKSPACE_PARAM,
724
+ },
725
+ },
726
+ output: {
727
+ schema: {
728
+ type: 'object',
729
+ additionalProperties: false,
730
+ required: ['scope', 'instructions', 'recipes'],
731
+ properties: { scope: { type: 'string' }, instructions: { type: 'string' }, recipes: { type: 'array', items: { type: 'string' } } },
732
+ },
733
+ render: (_args, value) => {
734
+ const fields = record(value);
735
+ const recipes = Array.isArray(fields.recipes) && fields.recipes.length > 0 ? fields.recipes.map(String).join(', ') : 'none';
736
+ return [{ type: 'text', text: `Saved the ${String(fields.scope)} guide. Recipes in this scope: ${recipes}.` }];
737
+ },
738
+ },
739
+ async execute(args, exec) {
740
+ const fields = fieldsOf(args);
741
+ const instructions = optionalString(fields, 'instructions');
742
+ const removeRecipe = optionalString(fields, 'removeRecipe');
743
+ const recipe = fields.recipe ?? undefined;
744
+ if (instructions === undefined && removeRecipe === undefined && recipe === undefined) {
745
+ throw new ArtifactError('artifact/bad-request', 'Send instructions, a recipe, or removeRecipe.');
746
+ }
747
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
748
+ const patch = {
749
+ ...(instructions === undefined ? {} : { instructions }),
750
+ ...(recipe === undefined ? {} : { recipe }),
751
+ ...(removeRecipe === undefined ? {} : { removeRecipe }),
752
+ };
753
+ const saved = await service.saveGuide(target, patch);
754
+ return { scope: saved.scope, instructions: saved.guide.instructions, recipes: saved.guide.recipes.map((item) => item.id) };
755
+ },
756
+ };
757
+ const designList = {
758
+ name: 'design_system_list',
759
+ description: 'List named design systems in one scope, its default ID, and catalog revision. Read before creating or updating a named system. Library and workspace catalogs are separate.',
760
+ parameters: { type: 'object', additionalProperties: false, properties: { scope: SCOPE_PARAM, workspaceId: WORKSPACE_PARAM } },
761
+ output: { schema: { type: 'object', properties: { scope: { type: 'string' }, revision: { type: 'integer' }, defaultId: { oneOf: [{ type: 'string' }, { type: 'null' }] }, systems: { type: 'array', items: { type: 'object' } } } }, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
762
+ async execute(args, exec) {
763
+ const fields = fieldsOf(args);
764
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
765
+ const catalog = await service.listDesignSystems(target);
766
+ return { ...catalog, systems: catalog.systems.map(system => ({ ...system })) };
767
+ },
768
+ };
769
+ const rebase = {
770
+ name: 'artifact_rebase',
771
+ description: 'Explicitly adopt current or selected design-system and recipe settings for a Page or Document, appending one version without changing content. Ordinary edits preserve pinned settings. Call only when the user requests a design/recipe refresh. Read first and pass baseVersion.',
772
+ parameters: { type: 'object', additionalProperties: false, required: ['id', 'baseVersion'], properties: { id: { type: 'string' }, baseVersion: { type: 'integer' }, recipe: RECIPE_PARAM, ...DESIGN_SELECTION, workspaceId: WORKSPACE_PARAM } },
773
+ output: { schema: WRITE_SCHEMA, render: (_args, value) => [{ type: 'text', text: writeText(value, 'Rebased') }], presentationMeta: (_args, value) => cardMeta(value) },
774
+ async execute(args, exec) {
775
+ const fields = fieldsOf(args);
776
+ const id = requiredString(fields, 'id');
777
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
778
+ const manifest = await service.rebase(target, id, { baseVersion: requiredInteger(fields, 'baseVersion'), recipe: optionalString(fields, 'recipe'), design: designSelection(fields), source: { origin: 'agent', action: 'rebase', ...(exec.agent ? { sessionId: exec.agent.id } : {}) } });
779
+ return { ...summary(manifest, target), warnings: [] };
469
780
  },
470
781
  };
471
- return [create, read, update, list, remove, exportTool, designRead, designUpdate];
782
+ return [create, read, update, sheetUpdate, list, remove, importTool, exportTool, designRead, designUpdate, brief, guideUpdate, designList, rebase];
472
783
  }
@@ -125,3 +125,27 @@ export function optionalEdits(fields) {
125
125
  return { oldText, newText };
126
126
  });
127
127
  }
128
+ export function optionalBoolean(fields, key) {
129
+ const value = fields[key];
130
+ if (value === undefined)
131
+ return undefined;
132
+ if (typeof value !== 'boolean')
133
+ throw new ArtifactError('artifact/bad-request', key + ' must be a boolean.');
134
+ return value;
135
+ }
136
+ export function designSelection(fields) {
137
+ return { systemId: optionalString(fields, 'systemId'),
138
+ systemScope: optionalEnum(fields, 'systemScope', SCOPES, 'artifact/unknown-scope'),
139
+ revision: optionalInteger(fields, 'systemRevision') };
140
+ }
141
+ export function designSaveOptions(fields) {
142
+ const systemId = optionalString(fields, 'systemId');
143
+ const expectedRevision = optionalInteger(fields, 'expectedRevision');
144
+ const createNew = optionalBoolean(fields, 'createNew');
145
+ const makeDefault = optionalBoolean(fields, 'makeDefault');
146
+ if (systemId === undefined && expectedRevision === undefined && createNew === undefined && makeDefault === undefined)
147
+ return undefined;
148
+ if (expectedRevision === undefined)
149
+ throw new ArtifactError('artifact/bad-request', 'Named system saves require expectedRevision from design_system_list.');
150
+ return { systemId, expectedRevision, createNew, makeDefault };
151
+ }