dsh-artifact-studio 0.7.3 → 0.9.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.
@@ -1,52 +1,113 @@
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
- import { workspaceForSession } from './paths.js';
4
- import { fieldsOf, optionalEdits, optionalInteger, optionalScope, optionalString, optionalType, requiredFormat, requiredInteger, requiredString, requiredType, } from './validate.js';
5
+ import { requireWorkspace, workspaceForSession } from './paths.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'],
8
10
  description: 'workspace (default) stores it under the Harness home for this workspace. library stores it in the user profile, shared by every project; use it only when the user asks for something reusable across projects.',
9
11
  };
12
+ const WORKSPACE_PARAM = {
13
+ type: 'string',
14
+ description: "Another registered project's workspace id, from an artifact reference. Omit for this session's project.",
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
+ };
10
25
  const PAGE_GUIDE = [
11
- '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.',
12
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.',
13
- 'Style pages with the injected variables: --artifact-color-primary, -accent, -surface, -text, -muted; --artifact-font-family, -display, -mono; and the size, space, and radius scales in the skill.',
28
+ 'Pages build on the artifact kit and the injected --artifact-* variables that the brief lists.',
14
29
  'A doc is Markdown: headings, lists, task lists, tables, quotes, and fenced code.',
15
30
  'Each save is a version the user sees. Check before saving and batch fixes into one update.',
16
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
+ };
17
36
  /**
18
37
  * Warnings for the version an update wrote. Full content is checked directly.
19
38
  * Edits are checked against that exact saved version; the version already
20
- * landed, so a failed read reports no warnings instead of failing the write.
39
+ * landed, so a failed read reports that validation is incomplete.
21
40
  */
22
- 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
+ }
23
64
  if (type !== 'page')
24
65
  return [];
66
+ const options = recipe === undefined ? {} : { recipe };
25
67
  if (content !== undefined)
26
- return checkPage(content);
68
+ return checkPage(content, options);
27
69
  if (readEdited === undefined)
28
70
  return [];
29
71
  try {
30
- return checkPage((await readEdited()).content);
72
+ return checkPage((await readEdited()).content, options);
31
73
  }
32
74
  catch (error) {
33
75
  if (error instanceof ArtifactError)
34
- 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.'];
35
77
  throw error;
36
78
  }
37
79
  }
38
80
  /** Static page warnings for a written version; documents have none. */
39
- function warningsFor(type, content) {
40
- 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 [];
41
93
  }
42
94
  /**
43
- * The scope context of a call: the session's workspace, plus an explicit scope.
95
+ * The scope context of a call: the session's workspace, or an explicitly named
96
+ * registered workspace, plus an explicit scope.
44
97
  * @param host the tool host.
45
98
  * @param exec the execution.
46
99
  * @param scope an explicit scope.
100
+ * @param workspaceId another registered workspace, when the call names one.
47
101
  * @returns the target.
48
102
  */
49
- async function targetFor(host, exec, scope) {
103
+ async function targetFor(host, exec, scope, workspaceId) {
104
+ if (workspaceId !== undefined) {
105
+ requireWorkspace(host.registry, workspaceId);
106
+ if (scope === 'library') {
107
+ throw new ArtifactError('artifact/bad-request', '"workspaceId" applies only to workspace artifacts.', { workspaceId });
108
+ }
109
+ return { workspaceId, scope: 'workspace' };
110
+ }
50
111
  if (exec.agent === undefined) {
51
112
  if (scope === 'library')
52
113
  return { scope };
@@ -108,6 +169,8 @@ function summary(manifest, target) {
108
169
  updatedAt: manifest.updatedAt,
109
170
  contentBytes: manifest.contentBytes,
110
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,
111
174
  };
112
175
  }
113
176
  /** The text the model reads after a write, with any page warnings. */
@@ -120,16 +183,18 @@ function writeText(value, verb) {
120
183
  const SUMMARY_SCHEMA = {
121
184
  type: 'object',
122
185
  additionalProperties: false,
123
- required: ['id', 'scope', 'type', 'title', 'version', 'updatedAt', 'contentBytes', 'workspaceId'],
186
+ required: ['id', 'scope', 'type', 'title', 'version', 'updatedAt', 'contentBytes', 'workspaceId', 'recipe'],
124
187
  properties: {
125
188
  id: { type: 'string' },
126
189
  scope: { type: 'string', enum: ['workspace', 'library'] },
127
- type: { type: 'string', enum: ['page', 'doc', 'design'] },
190
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
128
191
  title: { type: 'string' },
129
192
  version: { type: 'integer' },
130
193
  updatedAt: { type: 'string' },
131
194
  contentBytes: { type: 'integer' },
132
195
  workspaceId: { oneOf: [{ type: 'string' }, { type: 'null' }] },
196
+ recipe: { oneOf: [{ type: 'string' }, { type: 'null' }] },
197
+ generation: { oneOf: [{ type: 'object' }, { type: 'null' }] },
133
198
  },
134
199
  };
135
200
  /**
@@ -140,7 +205,8 @@ const SUMMARY_SCHEMA = {
140
205
  */
141
206
  function line(value, verb) {
142
207
  const fields = record(value);
143
- 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}.`;
144
210
  }
145
211
  const WRITE_SCHEMA = {
146
212
  ...SUMMARY_SCHEMA,
@@ -167,10 +233,13 @@ export function createTools(host) {
167
233
  additionalProperties: false,
168
234
  required: ['type', 'title', 'content'],
169
235
  properties: {
170
- 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.' },
171
237
  title: { type: 'string', description: 'Short title, 1 to 120 characters.' },
172
- 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,
173
241
  scope: SCOPE_PARAM,
242
+ workspaceId: WORKSPACE_PARAM,
174
243
  },
175
244
  },
176
245
  output: {
@@ -180,24 +249,28 @@ export function createTools(host) {
180
249
  },
181
250
  async execute(args, exec) {
182
251
  const fields = fieldsOf(args);
183
- const target = await targetFor(host, exec, optionalScope(fields));
252
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
184
253
  const type = requiredType(fields);
185
254
  const content = optionalString(fields, 'content') ?? '';
255
+ const recipeId = optionalString(fields, 'recipe');
256
+ const recipe = recipeId === undefined ? undefined : await service.recipe(target, recipeId, type);
186
257
  const manifest = await service.create(target, {
187
258
  type,
188
259
  title: requiredString(fields, 'title'),
189
260
  content,
261
+ ...(recipeId === undefined ? {} : { recipe: recipeId }),
262
+ design: designSelection(fields),
190
263
  source: { origin: 'agent', action: 'create', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
191
264
  });
192
265
  const warnings = type === 'design'
193
266
  ? (await service.read(target, manifest.id)).designInfo?.warnings ?? []
194
- : warningsFor(type, content);
267
+ : warningsFor(type, content, recipe);
195
268
  return { ...summary(manifest, target), warnings };
196
269
  },
197
270
  };
198
271
  const read = {
199
272
  name: 'artifact_read',
200
- description: 'Read an artifact\'s current content and version, or an earlier version. Read before updating an artifact the user may have edited.',
273
+ description: 'Read an artifact\'s current content and version, or an earlier version. Read before updating an artifact the user may have edited. Pass workspaceId for an artifact in another project.',
201
274
  parameters: {
202
275
  type: 'object',
203
276
  additionalProperties: false,
@@ -205,6 +278,7 @@ export function createTools(host) {
205
278
  properties: {
206
279
  id: { type: 'string', description: 'Artifact id from artifact_create or artifact_list.' },
207
280
  version: { type: 'integer', description: 'An earlier version to read. Omit for the current one.' },
281
+ workspaceId: WORKSPACE_PARAM,
208
282
  },
209
283
  },
210
284
  output: {
@@ -220,12 +294,21 @@ export function createTools(host) {
220
294
  type: 'object',
221
295
  description: 'The compiled summary of a design: pages, nodes, type counts, fonts, and warnings.',
222
296
  },
297
+ sheetInfo: {
298
+ type: 'array',
299
+ description: 'Per-sheet size and counts for a sheet artifact.',
300
+ items: { type: 'object' },
301
+ },
223
302
  },
224
303
  },
225
304
  render: (_args, value) => {
226
305
  const fields = record(value);
227
306
  const artifact = record(fields.artifact ?? null);
228
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('; ') + '.';
229
312
  const summaryLine = info.nodes === undefined
230
313
  ? ''
231
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'}.`
@@ -233,7 +316,7 @@ export function createTools(host) {
233
316
  return [
234
317
  {
235
318
  type: 'text',
236
- 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)}`,
237
320
  },
238
321
  ];
239
322
  },
@@ -241,7 +324,7 @@ export function createTools(host) {
241
324
  async execute(args, exec) {
242
325
  const fields = fieldsOf(args);
243
326
  const id = requiredString(fields, 'id');
244
- const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined);
327
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
245
328
  const result = await service.read(target, id, optionalInteger(fields, 'version'));
246
329
  const info = result.designInfo;
247
330
  return {
@@ -251,6 +334,9 @@ export function createTools(host) {
251
334
  ...(info === undefined
252
335
  ? {}
253
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
+ : {}),
254
340
  };
255
341
  },
256
342
  };
@@ -259,8 +345,9 @@ export function createTools(host) {
259
345
  description: [
260
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.',
261
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.',
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.',
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.',
263
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.',
264
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.',
265
352
  ].join('\n'),
266
353
  parameters: {
@@ -270,7 +357,7 @@ export function createTools(host) {
270
357
  properties: {
271
358
  id: { type: 'string' },
272
359
  baseVersion: { type: 'integer', description: 'The version your change is based on.' },
273
- 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.' },
274
361
  edits: {
275
362
  type: 'array',
276
363
  description: 'Replace-once edits applied in order. Each oldText must occur exactly once.',
@@ -282,6 +369,8 @@ export function createTools(host) {
282
369
  },
283
370
  },
284
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.' },
373
+ workspaceId: WORKSPACE_PARAM,
285
374
  },
286
375
  },
287
376
  output: {
@@ -292,36 +381,119 @@ export function createTools(host) {
292
381
  async execute(args, exec) {
293
382
  const fields = fieldsOf(args);
294
383
  const id = requiredString(fields, 'id');
295
- const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined);
384
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
296
385
  const content = optionalString(fields, 'content');
297
386
  const edits = optionalEdits(fields);
298
387
  const title = optionalString(fields, 'title');
299
- if (content === undefined && edits === undefined && title === undefined) {
300
- 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.');
301
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);
302
396
  const manifest = await service.update(target, id, {
303
397
  baseVersion: requiredInteger(fields, 'baseVersion'),
304
398
  content,
305
399
  edits,
306
400
  title,
401
+ ...(recipeId === undefined ? {} : { recipe: recipeId }),
307
402
  source: { origin: 'agent', action: 'update', ...(exec.agent === undefined ? {} : { sessionId: exec.agent.id }) },
308
403
  });
309
404
  const warnings = manifest.type === 'design'
310
405
  ? (await service.read(target, id, manifest.version)).designInfo?.warnings ?? []
311
- : 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);
312
407
  return { ...summary(manifest, target), warnings };
313
408
  },
314
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
+ };
315
485
  const list = {
316
486
  name: 'artifact_list',
317
- description: 'List artifacts in this project or the profile library, newest first, at most 50 per call.',
487
+ description: 'List artifacts in this project or the profile library, newest first, at most 50 per call. Pass workspaceId to list another project.',
318
488
  parameters: {
319
489
  type: 'object',
320
490
  additionalProperties: false,
321
491
  properties: {
322
492
  scope: { type: 'string', enum: ['workspace', 'library'], description: 'Defaults to workspace.' },
323
- type: { type: 'string', enum: ['page', 'doc', 'design'] },
493
+ workspaceId: WORKSPACE_PARAM,
494
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
324
495
  query: { type: 'string', description: 'Title substring, case-insensitive.' },
496
+ recipe: { type: 'string', description: 'Only artifacts that follow this recipe.' },
325
497
  offset: { type: 'integer' },
326
498
  },
327
499
  },
@@ -337,7 +509,8 @@ export function createTools(host) {
337
509
  const items = Array.isArray(fields.items) ? fields.items : [];
338
510
  const lines = items.map((item) => {
339
511
  const row = record(item);
340
- 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)})`;
341
514
  });
342
515
  const head = `${items.length} of ${String(fields.total)} artifacts${fields.hasMore === true ? '; more with a higher offset' : ''}.`;
343
516
  return [{ type: 'text', text: [head, ...lines].join('\n') }];
@@ -345,10 +518,11 @@ export function createTools(host) {
345
518
  },
346
519
  async execute(args, exec) {
347
520
  const fields = fieldsOf(args);
348
- const target = await targetFor(host, exec, optionalScope(fields));
521
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
349
522
  const page = await service.list(target, {
350
523
  query: optionalString(fields, 'query'),
351
524
  type: optionalType(fields),
525
+ recipe: optionalString(fields, 'recipe'),
352
526
  offset: optionalInteger(fields, 'offset'),
353
527
  });
354
528
  return { items: page.items.map((item) => summary(item, target)), total: page.total, hasMore: page.hasMore };
@@ -361,7 +535,7 @@ export function createTools(host) {
361
535
  type: 'object',
362
536
  additionalProperties: false,
363
537
  required: ['id'],
364
- properties: { id: { type: 'string' } },
538
+ properties: { id: { type: 'string' }, workspaceId: WORKSPACE_PARAM },
365
539
  },
366
540
  output: {
367
541
  schema: { type: 'object', additionalProperties: false, required: ['id', 'trashPath'], properties: { id: { type: 'string' }, trashPath: { type: 'string' } } },
@@ -370,20 +544,21 @@ export function createTools(host) {
370
544
  async execute(args, exec) {
371
545
  const fields = fieldsOf(args);
372
546
  const id = requiredString(fields, 'id');
373
- const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined);
547
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
374
548
  const result = await service.remove(target, id);
375
549
  return { id, trashPath: result.trashPath };
376
550
  },
377
551
  };
378
552
  const exportTool = {
379
553
  name: 'artifact_export',
380
- 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, or .fig; a sheet exports as csv (first sheet) or xlsx (every sheet).',
381
555
  parameters: {
382
556
  type: 'object',
383
557
  additionalProperties: false,
384
558
  required: ['id', 'format'],
385
- properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig'] },
386
- version: { type: 'integer', minimum: 1, description: 'Saved version to export. Omit for the current version.' } },
559
+ properties: { id: { type: 'string' }, format: { type: 'string', enum: ['html', 'md', 'docx', 'png', 'svg', 'fig', 'csv', 'xlsx'] },
560
+ version: { type: 'integer', minimum: 1, description: 'Saved version to export. Omit for the current version.' },
561
+ workspaceId: WORKSPACE_PARAM },
387
562
  },
388
563
  output: {
389
564
  schema: { type: 'object', additionalProperties: false, required: ['path', 'bytes'], properties: { path: { type: 'string' }, bytes: { type: 'integer' } } },
@@ -392,7 +567,7 @@ export function createTools(host) {
392
567
  async execute(args, exec) {
393
568
  const fields = fieldsOf(args);
394
569
  const id = requiredString(fields, 'id');
395
- const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined);
570
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
396
571
  const file = await service.export(target, id, requiredFormat(fields), optionalInteger(fields, 'version'));
397
572
  return { path: file.path, bytes: file.bytes };
398
573
  },
@@ -400,19 +575,23 @@ export function createTools(host) {
400
575
  const designRead = {
401
576
  name: 'design_system_read',
402
577
  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.',
403
- parameters: { type: 'object', additionalProperties: false, properties: {} },
578
+ parameters: { type: 'object', additionalProperties: false, properties: { workspaceId: WORKSPACE_PARAM, scope: SCOPE_PARAM, ...DESIGN_SELECTION } },
404
579
  output: {
405
- schema: { type: 'object', additionalProperties: false, required: ['source', 'tokens'], properties: { source: { type: 'string' }, tokens: { type: 'string' } } },
580
+ schema: { type: 'object', additionalProperties: false, required: ['source', 'tokens'], properties: { source: { type: 'string' }, tokens: { type: 'string' }, ...DESIGN_IDENTITY } },
406
581
  render: (_args, value) => [{ type: 'text', text: `Design system from ${String(record(value).source)}:\n${String(record(value).tokens)}` }],
407
582
  },
408
- async execute(_args, exec) {
409
- const target = await targetFor(host, exec, undefined).catch((error) => {
410
- if (error instanceof ArtifactError && error.code === 'artifact/no-workspace')
583
+ async execute(args, exec) {
584
+ const fields = fieldsOf(args);
585
+ const workspaceId = optionalString(fields, 'workspaceId');
586
+ const target = await targetFor(host, exec, optionalScope(fields), workspaceId).catch((error) => {
587
+ // A session outside every workspace can still read the library. A named
588
+ // workspace that does not resolve is a real failure.
589
+ if (workspaceId === undefined && error instanceof ArtifactError && error.code === 'artifact/no-workspace')
411
590
  return {};
412
591
  throw error;
413
592
  });
414
- const resolved = await service.designSystem(target);
415
- return { source: resolved.source, tokens: JSON.stringify(resolved.tokens, null, 2) };
593
+ const resolved = await service.designSystem(target, designSelection(fields));
594
+ return { source: resolved.source, tokens: JSON.stringify(resolved.tokens, null, 2), system: resolved.system ? { ...resolved.system } : null, catalogRevision: resolved.catalogRevision ?? null };
416
595
  },
417
596
  };
418
597
  const designUpdate = {
@@ -423,27 +602,150 @@ export function createTools(host) {
423
602
  additionalProperties: false,
424
603
  required: ['tokens'],
425
604
  properties: {
605
+ systemId: DESIGN_SELECTION.systemId,
606
+ expectedRevision: { type: 'integer', minimum: 0, description: 'Catalog revision from design_system_list, required for named saves.' },
607
+ createNew: { type: 'boolean', description: 'Save a new named system, leaving existing systems unchanged.' },
608
+ makeDefault: { type: 'boolean', description: 'Select this system for future artifacts. Existing pinned artifacts do not change.' },
426
609
  tokens: {
427
610
  type: 'object',
428
- description: 'Partial tokens: name, notes, colors and colorsDark {primary, accent, surface, text, muted}, typography {fontFamily, displayFamily, monoFamily, scale[]}, spacing {unit, scale[]}, radius {sm, md, lg}. Sizes are pixels.',
611
+ 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.',
429
612
  },
430
613
  scope: {
431
614
  type: 'string',
432
615
  enum: ['workspace', 'library'],
433
616
  description: 'workspace (default) overrides tokens for this project only. library changes the profile default every project inherits.',
434
617
  },
618
+ workspaceId: WORKSPACE_PARAM,
435
619
  },
436
620
  },
437
621
  output: {
438
- schema: { type: 'object', additionalProperties: false, required: ['scope', 'tokens'], properties: { scope: { type: 'string' }, tokens: { type: 'string' } } },
622
+ schema: { type: 'object', additionalProperties: false, required: ['scope', 'tokens'], properties: { scope: { type: 'string' }, tokens: { type: 'string' }, ...DESIGN_IDENTITY } },
439
623
  render: (_args, value) => [{ type: 'text', text: `Saved ${String(record(value).scope)} design system:\n${String(record(value).tokens)}` }],
440
624
  },
441
625
  async execute(args, exec) {
442
626
  const fields = fieldsOf(args);
443
- const target = await targetFor(host, exec, optionalScope(fields));
444
- const saved = await service.saveDesignSystem(target, fields.tokens);
445
- return { scope: saved.scope, tokens: JSON.stringify(saved.tokens, null, 2) };
627
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
628
+ const saved = await service.saveDesignSystem(target, fields.tokens, designSaveOptions(fields));
629
+ return { scope: saved.scope, tokens: JSON.stringify(saved.tokens, null, 2), system: saved.system ? { ...saved.system } : null, catalogRevision: saved.catalogRevision ?? null };
630
+ },
631
+ };
632
+ const brief = {
633
+ name: 'artifact_brief',
634
+ description: [
635
+ '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.',
636
+ '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.',
637
+ ].join('\n'),
638
+ parameters: {
639
+ type: 'object',
640
+ additionalProperties: false,
641
+ required: ['type'],
642
+ properties: {
643
+ type: { type: 'string', enum: ['page', 'doc', 'design', 'sheet'] },
644
+ recipe: { type: 'string', description: 'A recipe id. Omit to list the recipes for this type.' },
645
+ ...DESIGN_SELECTION,
646
+ scope: SCOPE_PARAM,
647
+ workspaceId: WORKSPACE_PARAM,
648
+ },
649
+ },
650
+ output: {
651
+ schema: {
652
+ type: 'object',
653
+ additionalProperties: false,
654
+ required: ['brief', 'recipe'],
655
+ properties: { brief: { type: 'string' }, recipe: { oneOf: [{ type: 'string' }, { type: 'null' }] } },
656
+ },
657
+ render: (_args, value) => [{ type: 'text', text: String(record(value).brief) }],
658
+ },
659
+ async execute(args, exec) {
660
+ const fields = fieldsOf(args);
661
+ const workspaceId = optionalString(fields, 'workspaceId');
662
+ const scope = optionalScope(fields);
663
+ const target = await targetFor(host, exec, scope, workspaceId).catch((error) => {
664
+ // Outside every workspace the library guide and recipes still apply.
665
+ if (workspaceId === undefined && scope !== 'workspace' && error instanceof ArtifactError && error.code === 'artifact/no-workspace')
666
+ return { scope: 'library' };
667
+ throw error;
668
+ });
669
+ const result = await service.brief(target, requiredType(fields), optionalString(fields, 'recipe'), designSelection(fields));
670
+ return { brief: result.brief, recipe: result.recipe?.id ?? null };
671
+ },
672
+ };
673
+ const guideUpdate = {
674
+ name: 'artifact_guide_update',
675
+ description: [
676
+ '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.',
677
+ '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.',
678
+ 'A recipe with the id of a built-in or wider recipe replaces it in this scope.',
679
+ ].join('\n'),
680
+ parameters: {
681
+ type: 'object',
682
+ additionalProperties: false,
683
+ properties: {
684
+ instructions: { type: 'string', description: `The complete conventions text for this scope, up to ${MAX_INSTRUCTIONS} characters. Short, concrete, checkable rules.` },
685
+ recipe: {
686
+ type: 'object',
687
+ description: 'A recipe to add or replace: { id, name, types: ["page"|"doc"|"design"], audience, purpose, sections: [{ key, title, purpose, required }], rules: [string] }.',
688
+ },
689
+ removeRecipe: { type: 'string', description: 'The id of a recipe in this scope to remove.' },
690
+ scope: SCOPE_PARAM,
691
+ workspaceId: WORKSPACE_PARAM,
692
+ },
693
+ },
694
+ output: {
695
+ schema: {
696
+ type: 'object',
697
+ additionalProperties: false,
698
+ required: ['scope', 'instructions', 'recipes'],
699
+ properties: { scope: { type: 'string' }, instructions: { type: 'string' }, recipes: { type: 'array', items: { type: 'string' } } },
700
+ },
701
+ render: (_args, value) => {
702
+ const fields = record(value);
703
+ const recipes = Array.isArray(fields.recipes) && fields.recipes.length > 0 ? fields.recipes.map(String).join(', ') : 'none';
704
+ return [{ type: 'text', text: `Saved the ${String(fields.scope)} guide. Recipes in this scope: ${recipes}.` }];
705
+ },
706
+ },
707
+ async execute(args, exec) {
708
+ const fields = fieldsOf(args);
709
+ const instructions = optionalString(fields, 'instructions');
710
+ const removeRecipe = optionalString(fields, 'removeRecipe');
711
+ const recipe = fields.recipe ?? undefined;
712
+ if (instructions === undefined && removeRecipe === undefined && recipe === undefined) {
713
+ throw new ArtifactError('artifact/bad-request', 'Send instructions, a recipe, or removeRecipe.');
714
+ }
715
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
716
+ const patch = {
717
+ ...(instructions === undefined ? {} : { instructions }),
718
+ ...(recipe === undefined ? {} : { recipe }),
719
+ ...(removeRecipe === undefined ? {} : { removeRecipe }),
720
+ };
721
+ const saved = await service.saveGuide(target, patch);
722
+ return { scope: saved.scope, instructions: saved.guide.instructions, recipes: saved.guide.recipes.map((item) => item.id) };
723
+ },
724
+ };
725
+ const designList = {
726
+ name: 'design_system_list',
727
+ 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.',
728
+ parameters: { type: 'object', additionalProperties: false, properties: { scope: SCOPE_PARAM, workspaceId: WORKSPACE_PARAM } },
729
+ 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) }] },
730
+ async execute(args, exec) {
731
+ const fields = fieldsOf(args);
732
+ const target = await targetFor(host, exec, optionalScope(fields), optionalString(fields, 'workspaceId'));
733
+ const catalog = await service.listDesignSystems(target);
734
+ return { ...catalog, systems: catalog.systems.map(system => ({ ...system })) };
735
+ },
736
+ };
737
+ const rebase = {
738
+ name: 'artifact_rebase',
739
+ 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.',
740
+ parameters: { type: 'object', additionalProperties: false, required: ['id', 'baseVersion'], properties: { id: { type: 'string' }, baseVersion: { type: 'integer' }, recipe: RECIPE_PARAM, ...DESIGN_SELECTION, workspaceId: WORKSPACE_PARAM } },
741
+ output: { schema: WRITE_SCHEMA, render: (_args, value) => [{ type: 'text', text: writeText(value, 'Rebased') }], presentationMeta: (_args, value) => cardMeta(value) },
742
+ async execute(args, exec) {
743
+ const fields = fieldsOf(args);
744
+ const id = requiredString(fields, 'id');
745
+ const target = await targetFor(host, exec, id.startsWith('art_lib_') ? 'library' : undefined, optionalString(fields, 'workspaceId'));
746
+ 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 } : {}) } });
747
+ return { ...summary(manifest, target), warnings: [] };
446
748
  },
447
749
  };
448
- return [create, read, update, list, remove, exportTool, designRead, designUpdate];
750
+ return [create, read, update, sheetUpdate, list, remove, exportTool, designRead, designUpdate, brief, guideUpdate, designList, rebase];
449
751
  }