@aqian0/dsh-renderer 0.1.0 → 0.2.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.
package/lib/config.js CHANGED
@@ -36,11 +36,15 @@ export const Config = z.object({
36
36
  enableArtifactTool: z
37
37
  .boolean()
38
38
  .default(DEFAULT_RENDERER_CONFIG.enableArtifactTool)
39
- .description('Register the render_artifact tool and prompt guidance so models emit complex documents directly as cards.'),
39
+ .description('Register the render_artifact tool and prompt guidance so models emit visual/interactive documents directly as cards.'),
40
+ enableArtifactSkill: z
41
+ .boolean()
42
+ .default(DEFAULT_RENDERER_CONFIG.enableArtifactSkill)
43
+ .description('Register the bundled visual-artifact skill in DSH so models load diagram/UI craft guidance on demand and users can invoke /visual-artifact.'),
40
44
  autoOpenArtifact: z
41
45
  .boolean()
42
46
  .default(DEFAULT_RENDERER_CONFIG.autoOpenArtifact)
43
- .description('Automatically open settled render_artifact results in the right Sidebar instead of waiting for a click.'),
47
+ .description('Automatically open newly completed live render_artifact results in the right Sidebar (historical replays remain click-to-open).'),
44
48
  enableTurnMediaFallback: z
45
49
  .boolean()
46
50
  .default(DEFAULT_RENDERER_CONFIG.enableTurnMediaFallback)
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Bundled DSH runtime skill (`visual-artifact`) registered on `ctx.skills`.
3
+ *
4
+ * Keeps the always-on system prompt minimal while surfacing a clear, discoverable
5
+ * entry in DSH's `<available_skills>` catalog and enabling direct user invocation
6
+ * via `/visual-artifact`. When loaded on demand, it gives the model concrete craft
7
+ * rules for self-contained SVG diagrams, interactive HTML apps/charts, and long
8
+ * structured documents rendered through `render_artifact`.
9
+ *
10
+ * @module dsh-renderer/host/artifact-skill
11
+ */
12
+ /** Kebab-case skill name registered with DSH's `ctx.skills` service. */
13
+ export const ARTIFACT_SKILL_NAME = 'visual-artifact';
14
+ const ARTIFACT_SKILL_BODY = [
15
+ '# Visual artifact authoring guide',
16
+ '',
17
+ 'Use `render_artifact` to deliver rich visual, interactive, or long self-contained content directly in the conversation card and right Sidebar without creating temporary files in the workspace.',
18
+ '',
19
+ '## Choosing `kind`',
20
+ '',
21
+ '- `svg`: architecture diagrams, flowcharts, sequence/state diagrams, ER schemas, system topologies, timelines, concept maps, and crisp vector illustrations. Prefer clean `svg` over ASCII art or raw Mermaid blocks.',
22
+ '- `html`: interactive demos, data charts/dashboards, calculators, algorithm step-through visualizers, UI prototypes, or any view needing hover tooltips, filters, tabs, or animation.',
23
+ '- `code`: long self-contained specifications, reports, comparison matrices, SQL/JSON/YAML schemas, or standalone scripts meant for reading and copying rather than saving into the project.',
24
+ '',
25
+ '## Craft rules for `svg`',
26
+ '',
27
+ '- Always include `xmlns="http://www.w3.org/2000/svg"` and an explicit `viewBox="0 0 W H"` with comfortable outer padding (at least 24px).',
28
+ '- Avoid external fonts, remote images, or `<script>` tags (SVG renders statically in an isolated `<img>` context).',
29
+ '- Use a clean system font stack (`system-ui, -apple-system, "PingFang SC", "Segoe UI", sans-serif`), generous node padding, non-overlapping labels, clear visual hierarchy, and high-contrast strokes/fills that remain legible on both light and dark surfaces (or include an explicit rounded background `<rect>`).',
30
+ '',
31
+ '## Craft rules for `html`',
32
+ '',
33
+ '- Emit one complete, self-contained HTML document (`<!doctype html>`) with inline `<style>` and `<script>`. Do not depend on external CDN scripts, stylesheets, or web fonts because external network requests are blocked by default.',
34
+ '- Adapt gracefully to both light and dark themes (`@media (prefers-color-scheme: dark)` or clean neutral surfaces with strong contrast) and use responsive layout that works well inside a 420px–960px Sidebar pane as well as fullscreen.',
35
+ '- Avoid trapping content in fixed `100vh` overflow-hidden containers unless intentionally building a full-canvas interactive widget; ensure scrolling and controls work smoothly.',
36
+ '- Draw charts/graphs with inline SVG or `<canvas>` directly rather than importing third-party charting CDNs.',
37
+ '',
38
+ '## Delivery etiquette',
39
+ '',
40
+ '- Pass `title`, `kind` (and `lang` when `kind` is `"code"`) before `content` so the streaming card displays its header immediately.',
41
+ '- After calling `render_artifact`, provide a brief explanation or key takeaways in chat prose instead of repeating the full source code in a Markdown fence.',
42
+ '- If the user explicitly asked to create or edit project files on disk, use `write`/`edit` (and `present` when appropriate) instead of `render_artifact`.',
43
+ ].join('\n');
44
+ /** Bundled runtime skill registration accepted by DSH `ctx.skills.register`. */
45
+ export const ARTIFACT_SKILL_REGISTRATION = {
46
+ name: ARTIFACT_SKILL_NAME,
47
+ description: 'Create visual diagrams (architecture, flow, sequence, ER), interactive HTML demos/charts/prototypes, or long standalone documents rendered directly in the conversation and right Sidebar via render_artifact.',
48
+ whenToUse: 'Use when a diagram, chart, interactive visualization, UI prototype, or long standalone document communicates the answer better than plain text or ASCII art.',
49
+ source: 'bundled',
50
+ invocation: {
51
+ modelInvocable: true,
52
+ userInvocable: true,
53
+ },
54
+ content: ARTIFACT_SKILL_BODY,
55
+ };
@@ -16,8 +16,13 @@ import { utf8ByteLength } from '../shared/sanitize.js';
16
16
  export const ARTIFACT_TOOL_NAME = 'render_artifact';
17
17
  /** System-prompt section name registered on `ctx.systemPrompt`. */
18
18
  export const ARTIFACT_PROMPT_SECTION_NAME = 'dsh-renderer:artifact';
19
- /** Placement order beside built-in tool guidance (`TOOL_REPORT: 2900` .. `MCP_SERVERS: 3100`). */
20
- const ARTIFACT_PROMPT_ORDER = 2950;
19
+ /**
20
+ * Placement order immediately after DSH's `DELIVERABLE_FILE_REFERENCES` (9000)
21
+ * and before `STRUCTURED_OUTPUT` (9900) / `HARNESS_SOURCE` (10000), so artifact
22
+ * guidance is not overshadowed by workspace file-delivery rules while remaining
23
+ * inside the reusable KV-cache prompt prefix.
24
+ */
25
+ export const ARTIFACT_PROMPT_ORDER = 9050;
21
26
  const VALID_KINDS = new Set(['html', 'svg', 'code']);
22
27
  /** Validate and normalize raw `render_artifact` tool arguments. */
23
28
  function parseArtifactArgs(raw, maxContentBytes) {
@@ -57,7 +62,7 @@ function parseArtifactArgs(raw, maxContentBytes) {
57
62
  export function createRenderArtifactToolDefinition(options) {
58
63
  return {
59
64
  name: ARTIFACT_TOOL_NAME,
60
- description: 'Publish a standalone interactive HTML document, complex SVG diagram, or long self-contained code/Markdown document as a clickable card that opens in the right Sidebar. Provide title, kind (and lang for code) before content so the card shows its header immediately while streaming.',
65
+ description: 'Render a visual diagram (SVG), interactive web view/chart/prototype (HTML), or long self-contained document/code artifact directly as a prominent card in chat and in the right Sidebar, without writing workspace files. Pass title, kind (and lang for code) before content so the card streams with its header immediately.',
61
66
  parameters: {
62
67
  type: 'object',
63
68
  additionalProperties: false,
@@ -133,9 +138,40 @@ export function createRenderArtifactToolDefinition(options) {
133
138
  },
134
139
  };
135
140
  }
136
- /** Concise system-prompt section steering the model to use `render_artifact` for heavy standalone output. */
141
+ /** Prompt guidance steering natural, intent-driven use of `render_artifact`. */
142
+ export const ARTIFACT_PROMPT_TEXT = [
143
+ 'Use `render_artifact` proactively whenever a visual, interactive, or long self-contained artifact communicates the answer better than plain chat prose — even when the user does not mention HTML, SVG, or `render_artifact` explicitly:',
144
+ '- Diagrams (architecture, flowcharts, sequence/state machines, ER schemas, topologies, timelines, wireframes): prefer a crisp self-contained `svg` (or interactive `html`) artifact over ASCII art or raw Mermaid fences.',
145
+ '- Data visualizations, dashboards, calculators, simulations, algorithm visualizers, and UI prototypes: render a single-file self-contained `html` artifact.',
146
+ '- Long standalone specs, comparison reports, or multi-section code/Markdown documents meant for inspection in chat rather than saving to the project: render a `code` artifact.',
147
+ 'Use `write`/`edit` (and `present` when delivering files) only for actual workspace files; use `render_artifact` for in-conversation visualization and exploration without cluttering the repository. Keep short snippets inline in Markdown, and do not repeat an artifact’s full source in a chat code fence after calling `render_artifact`.',
148
+ ].join('\n');
149
+ /** Static system-prompt section retained for callers and tests inspecting the constant directly. */
137
150
  export const ARTIFACT_PROMPT_SECTION = {
138
151
  name: ARTIFACT_PROMPT_SECTION_NAME,
139
152
  order: ARTIFACT_PROMPT_ORDER,
140
- text: 'When the user asks for a standalone interactive HTML page/app, a detailed SVG diagram, or a long self-contained code/Markdown document to inspect rather than save to the workspace, call `render_artifact` instead of printing a large code fence in chat prose. Keep short snippets and inline explanations in regular Markdown.',
153
+ text: ARTIFACT_PROMPT_TEXT,
154
+ interpolate: false,
141
155
  };
156
+ /**
157
+ * Create a tool-aware system-prompt section for `render_artifact`.
158
+ *
159
+ * Omits guidance automatically when `render_artifact` is restricted or shadowed
160
+ * for the assembling agent scope (`ctx.tools.get(name, scope, toolSet)`).
161
+ */
162
+ export function createArtifactPromptSection(getTools) {
163
+ return {
164
+ name: ARTIFACT_PROMPT_SECTION_NAME,
165
+ order: ARTIFACT_PROMPT_ORDER,
166
+ interpolate: false,
167
+ text(context) {
168
+ const tools = getTools?.();
169
+ if (tools !== undefined && typeof tools.get === 'function') {
170
+ const visible = tools.get(ARTIFACT_TOOL_NAME, context.scope, context.toolSet);
171
+ if (visible === undefined)
172
+ return '';
173
+ }
174
+ return ARTIFACT_PROMPT_TEXT;
175
+ },
176
+ };
177
+ }
package/lib/index.js CHANGED
@@ -13,7 +13,8 @@
13
13
  * @module dsh-renderer
14
14
  */
15
15
  import { Config, DEFAULT_RENDERER_CONFIG, RENDERER_CONFIG_GLOBAL, SUPPORTED_FENCE_LANGUAGES, normalizeClientConfig, resolveConfig, } from './config.js';
16
- import { ARTIFACT_PROMPT_SECTION, createRenderArtifactToolDefinition, } from './host/artifact-tool.js';
16
+ import { ARTIFACT_SKILL_REGISTRATION } from './host/artifact-skill.js';
17
+ import { createArtifactPromptSection, createRenderArtifactToolDefinition, } from './host/artifact-tool.js';
17
18
  import { bridgeToolResultDataImages, } from './host/media-bridge.js';
18
19
  /** Cordis plugin name. */
19
20
  export const name = 'renderer';
@@ -40,7 +41,7 @@ export function apply(ctx, config = {}) {
40
41
  };
41
42
  rawTable.push(row);
42
43
  });
43
- // Register first-class `render_artifact` tool and system-prompt guidance when Host services exist.
44
+ // Register first-class `render_artifact` tool, tool-aware prompt guidance, and bundled skill.
44
45
  if (resolved.enableArtifactTool) {
45
46
  const toolDef = createRenderArtifactToolDefinition({ maxContentBytes: resolved.maxContentBytes });
46
47
  const registerOnTools = (target) => {
@@ -58,20 +59,38 @@ export function apply(ctx, config = {}) {
58
59
  const prompt = target.get?.('systemPrompt');
59
60
  if (prompt === undefined || typeof prompt.section !== 'function')
60
61
  return;
62
+ const section = createArtifactPromptSection(() => target.get?.('tools'));
61
63
  if (typeof target.effect === 'function') {
62
- target.effect(() => prompt.section(ARTIFACT_PROMPT_SECTION), 'dsh-renderer: artifact prompt section');
64
+ target.effect(() => prompt.section(section), 'dsh-renderer: artifact prompt section');
63
65
  }
64
66
  else {
65
- prompt.section(ARTIFACT_PROMPT_SECTION);
67
+ prompt.section(section);
68
+ }
69
+ };
70
+ const registerSkill = (target) => {
71
+ const skills = target.get?.('skills');
72
+ if (skills === undefined || typeof skills.register !== 'function')
73
+ return;
74
+ if (typeof target.effect === 'function') {
75
+ target.effect(() => skills.register(ARTIFACT_SKILL_REGISTRATION), 'dsh-renderer: visual-artifact skill');
76
+ }
77
+ else {
78
+ skills.register(ARTIFACT_SKILL_REGISTRATION);
66
79
  }
67
80
  };
68
81
  if (typeof ext.inject === 'function') {
69
82
  ext.inject(['tools'], registerOnTools);
70
83
  ext.inject(['systemPrompt'], registerPrompt);
84
+ if (resolved.enableArtifactSkill) {
85
+ ext.inject(['skills'], registerSkill);
86
+ }
71
87
  }
72
88
  else {
73
89
  registerOnTools(ext);
74
90
  registerPrompt(ext);
91
+ if (resolved.enableArtifactSkill) {
92
+ registerSkill(ext);
93
+ }
75
94
  }
76
95
  }
77
96
  // Optional tool output image bridge: stays inactive unless explicitly enabled.
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Zero-dependency streaming JSON parser and durable event extractor for
3
+ * `render_artifact` tool calls.
4
+ *
5
+ * Shared by the Conversation node assembler (`artifact-node.ts`) and the
6
+ * `ctx.resources` session-history recovery provider (`artifact-resource.ts`).
7
+ *
8
+ * @module dsh-renderer/shared/artifact-stream
9
+ */
10
+ import { computeArtifactId } from './content-complexity.js';
11
+ import { utf8ByteLength } from './sanitize.js';
12
+ /** Canonical tool name matching Host registration (`src/host/artifact-tool.ts`). */
13
+ export const RENDER_ARTIFACT_TOOL_NAME = 'render_artifact';
14
+ const VALID_ARTIFACT_KINDS = new Set(['html', 'svg', 'code']);
15
+ function isRecord(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
17
+ }
18
+ function normalizeArtifactKind(raw) {
19
+ if (typeof raw !== 'string')
20
+ return undefined;
21
+ const lower = raw.trim().toLowerCase();
22
+ return VALID_ARTIFACT_KINDS.has(lower) ? lower : undefined;
23
+ }
24
+ function normalizeArtifactLang(kind, rawLang) {
25
+ if (kind === 'html')
26
+ return 'html';
27
+ if (kind === 'svg')
28
+ return 'svg';
29
+ if (typeof rawLang === 'string') {
30
+ const trimmed = rawLang.trim().toLowerCase();
31
+ if (trimmed.length > 0)
32
+ return trimmed.slice(0, 32);
33
+ }
34
+ return 'text';
35
+ }
36
+ function countContentLines(content) {
37
+ const trimmed = content.trim();
38
+ return trimmed.length === 0 ? 0 : trimmed.split(/\r?\n/).length;
39
+ }
40
+ function skipWhitespace(source, index) {
41
+ let i = index;
42
+ while (i < source.length) {
43
+ const ch = source.charCodeAt(i);
44
+ if (ch === 32 || ch === 9 || ch === 10 || ch === 13) {
45
+ i += 1;
46
+ }
47
+ else {
48
+ break;
49
+ }
50
+ }
51
+ return i;
52
+ }
53
+ /**
54
+ * Decode a JSON string literal starting at `openQuoteIndex` (`"`), tolerating
55
+ * truncation mid-stream or mid-escape without throwing.
56
+ */
57
+ function readJsonStringPrefix(source, openQuoteIndex) {
58
+ let i = openQuoteIndex + 1;
59
+ let out = '';
60
+ while (i < source.length) {
61
+ const ch = source[i];
62
+ if (ch === '"') {
63
+ return { value: out, nextIndex: i + 1, closed: true };
64
+ }
65
+ if (ch !== '\\') {
66
+ out += ch;
67
+ i += 1;
68
+ continue;
69
+ }
70
+ if (i + 1 >= source.length) {
71
+ return { value: out, nextIndex: source.length, closed: false };
72
+ }
73
+ const esc = source[i + 1];
74
+ switch (esc) {
75
+ case '"':
76
+ case '\\':
77
+ case '/':
78
+ out += esc;
79
+ i += 2;
80
+ break;
81
+ case 'b':
82
+ out += '\b';
83
+ i += 2;
84
+ break;
85
+ case 'f':
86
+ out += '\f';
87
+ i += 2;
88
+ break;
89
+ case 'n':
90
+ out += '\n';
91
+ i += 2;
92
+ break;
93
+ case 'r':
94
+ out += '\r';
95
+ i += 2;
96
+ break;
97
+ case 't':
98
+ out += '\t';
99
+ i += 2;
100
+ break;
101
+ case 'u': {
102
+ if (i + 6 > source.length) {
103
+ return { value: out, nextIndex: source.length, closed: false };
104
+ }
105
+ const hex = source.slice(i + 2, i + 6);
106
+ if (/^[0-9a-fA-F]{4}$/.test(hex)) {
107
+ out += String.fromCharCode(Number.parseInt(hex, 16));
108
+ }
109
+ i += 6;
110
+ break;
111
+ }
112
+ default:
113
+ out += esc;
114
+ i += 2;
115
+ break;
116
+ }
117
+ }
118
+ return { value: out, nextIndex: source.length, closed: false };
119
+ }
120
+ /** Skip any non-string JSON value (object, array, number, boolean, null) safely. */
121
+ function skipJsonValue(source, start) {
122
+ const i = skipWhitespace(source, start);
123
+ if (i >= source.length)
124
+ return source.length;
125
+ const first = source[i];
126
+ if (first === '"') {
127
+ return readJsonStringPrefix(source, i).nextIndex;
128
+ }
129
+ if (first === '{' || first === '[') {
130
+ let depth = 0;
131
+ let cursor = i;
132
+ while (cursor < source.length) {
133
+ const ch = source[cursor];
134
+ if (ch === '"') {
135
+ const str = readJsonStringPrefix(source, cursor);
136
+ cursor = str.nextIndex;
137
+ if (!str.closed)
138
+ return source.length;
139
+ continue;
140
+ }
141
+ if (ch === '{' || ch === '[') {
142
+ depth += 1;
143
+ }
144
+ else if (ch === '}' || ch === ']') {
145
+ depth -= 1;
146
+ if (depth === 0)
147
+ return cursor + 1;
148
+ }
149
+ cursor += 1;
150
+ }
151
+ return source.length;
152
+ }
153
+ let cursor = i;
154
+ while (cursor < source.length) {
155
+ const ch = source[cursor];
156
+ if (ch === ',' || ch === '}' || ch === ']' || ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
157
+ break;
158
+ }
159
+ cursor += 1;
160
+ }
161
+ return cursor;
162
+ }
163
+ /**
164
+ * Incrementally extract top-level `title`, `kind`, `lang`, and streamed `content`
165
+ * size/line estimates from a partial JSON object produced by `tool-call-delta`.
166
+ */
167
+ export function extractStreamingArtifactFields(rawJsonPrefix) {
168
+ let i = skipWhitespace(rawJsonPrefix, 0);
169
+ if (i >= rawJsonPrefix.length || rawJsonPrefix[i] !== '{') {
170
+ return {};
171
+ }
172
+ i += 1;
173
+ let title;
174
+ let kind;
175
+ let lang;
176
+ let contentBytes;
177
+ let contentLines;
178
+ while (i < rawJsonPrefix.length) {
179
+ i = skipWhitespace(rawJsonPrefix, i);
180
+ if (i >= rawJsonPrefix.length || rawJsonPrefix[i] === '}')
181
+ break;
182
+ if (rawJsonPrefix[i] === ',') {
183
+ i += 1;
184
+ continue;
185
+ }
186
+ if (rawJsonPrefix[i] !== '"')
187
+ break;
188
+ const keyToken = readJsonStringPrefix(rawJsonPrefix, i);
189
+ if (!keyToken.closed)
190
+ break;
191
+ const key = keyToken.value;
192
+ i = skipWhitespace(rawJsonPrefix, keyToken.nextIndex);
193
+ if (i >= rawJsonPrefix.length || rawJsonPrefix[i] !== ':')
194
+ break;
195
+ i = skipWhitespace(rawJsonPrefix, i + 1);
196
+ if (i >= rawJsonPrefix.length)
197
+ break;
198
+ if (rawJsonPrefix[i] === '"') {
199
+ const valToken = readJsonStringPrefix(rawJsonPrefix, i);
200
+ i = valToken.nextIndex;
201
+ if (key === 'title') {
202
+ const cleaned = valToken.value.replace(/\s+/g, ' ').trim().slice(0, 120);
203
+ if (cleaned.length > 0)
204
+ title = cleaned;
205
+ }
206
+ else if (key === 'kind') {
207
+ const normalized = normalizeArtifactKind(valToken.value);
208
+ if (normalized !== undefined)
209
+ kind = normalized;
210
+ }
211
+ else if (key === 'lang') {
212
+ const cleaned = valToken.value.trim().toLowerCase().slice(0, 32);
213
+ if (cleaned.length > 0)
214
+ lang = cleaned;
215
+ }
216
+ else if (key === 'content') {
217
+ if (valToken.value.length > 0) {
218
+ contentBytes = utf8ByteLength(valToken.value);
219
+ contentLines = countContentLines(valToken.value);
220
+ }
221
+ }
222
+ if (!valToken.closed)
223
+ break;
224
+ }
225
+ else {
226
+ i = skipJsonValue(rawJsonPrefix, i);
227
+ }
228
+ }
229
+ return { title, kind, lang, contentBytes, contentLines };
230
+ }
231
+ /**
232
+ * Parse and validate complete `render_artifact` arguments (either a JSON string
233
+ * from `tool/call` or a plain object from PTC `tool/ptc-dispatch*`).
234
+ */
235
+ export function parseArtifactToolArguments(raw) {
236
+ let obj = raw;
237
+ if (typeof obj === 'string') {
238
+ if (obj.trim().length === 0)
239
+ return null;
240
+ try {
241
+ obj = JSON.parse(obj);
242
+ }
243
+ catch {
244
+ return null;
245
+ }
246
+ }
247
+ if (!isRecord(obj))
248
+ return null;
249
+ const rawTitle = typeof obj['title'] === 'string' ? obj['title'].replace(/\s+/g, ' ').trim().slice(0, 120) : '';
250
+ const kind = normalizeArtifactKind(obj['kind']);
251
+ const rawContent = obj['content'];
252
+ if (kind === undefined || typeof rawContent !== 'string' || rawContent.trim().length === 0) {
253
+ return null;
254
+ }
255
+ const lang = normalizeArtifactLang(kind, obj['lang']);
256
+ const title = rawTitle.length > 0 ? rawTitle : kind.toUpperCase();
257
+ const bytes = utf8ByteLength(rawContent);
258
+ const lines = countContentLines(rawContent);
259
+ const artifactId = computeArtifactId(kind, rawContent, lang);
260
+ return {
261
+ artifactId,
262
+ title,
263
+ kind,
264
+ lang,
265
+ content: rawContent,
266
+ lines,
267
+ bytes,
268
+ };
269
+ }
270
+ /**
271
+ * Extract a complete logged `render_artifact` invocation from a durable DSH
272
+ * Session event (`tool/call`, `tool/ptc-dispatch-start`, or `tool/ptc-dispatch`).
273
+ */
274
+ export function extractLoggedRenderArtifact(event) {
275
+ if (event.type !== 'tool/call' && event.type !== 'tool/ptc-dispatch-start' && event.type !== 'tool/ptc-dispatch') {
276
+ return undefined;
277
+ }
278
+ if (!isRecord(event.data) || event.data['name'] !== RENDER_ARTIFACT_TOOL_NAME) {
279
+ return undefined;
280
+ }
281
+ const rawCallId = event.type === 'tool/call' ? event.data['callId'] : event.data['subCallId'];
282
+ if (typeof rawCallId !== 'string' || rawCallId.length === 0) {
283
+ return undefined;
284
+ }
285
+ const parsed = parseArtifactToolArguments(event.data['arguments']);
286
+ if (parsed === null) {
287
+ return undefined;
288
+ }
289
+ return {
290
+ callId: rawCallId,
291
+ ...parsed,
292
+ };
293
+ }
@@ -19,7 +19,8 @@ export const DEFAULT_RENDERER_CONFIG = Object.freeze({
19
19
  enableWorkbench: true,
20
20
  complexContentToSidebar: true,
21
21
  enableArtifactTool: true,
22
- autoOpenArtifact: false,
22
+ enableArtifactSkill: true,
23
+ autoOpenArtifact: true,
23
24
  enableTurnMediaFallback: true,
24
25
  bridgeToolDataImages: false,
25
26
  maxContentBytes: 524_288,
@@ -72,6 +73,9 @@ export function normalizeClientConfig(raw) {
72
73
  enableArtifactTool: typeof input['enableArtifactTool'] === 'boolean'
73
74
  ? input['enableArtifactTool']
74
75
  : DEFAULT_RENDERER_CONFIG.enableArtifactTool,
76
+ enableArtifactSkill: typeof input['enableArtifactSkill'] === 'boolean'
77
+ ? input['enableArtifactSkill']
78
+ : DEFAULT_RENDERER_CONFIG.enableArtifactSkill,
75
79
  autoOpenArtifact: typeof input['autoOpenArtifact'] === 'boolean'
76
80
  ? input['autoOpenArtifact']
77
81
  : DEFAULT_RENDERER_CONFIG.autoOpenArtifact,
@@ -44,7 +44,10 @@ const DIFF_FILE_RE = /^(?:diff --git |\+\+\+ )/gm;
44
44
  const DIFF_HUNK_RE = /^@@\s+-\d+/gm;
45
45
  const LANGUAGE_LABELS = {
46
46
  html: 'HTML',
47
+ htm: 'HTML',
48
+ xhtml: 'HTML',
47
49
  svg: 'SVG',
50
+ 'svg+xml': 'SVG',
48
51
  xml: 'XML',
49
52
  css: 'CSS',
50
53
  scss: 'SCSS',
@@ -102,7 +105,10 @@ const LANGUAGE_LABELS = {
102
105
  };
103
106
  const EXTENSION_BY_LANG = {
104
107
  html: 'html',
108
+ htm: 'html',
109
+ xhtml: 'html',
105
110
  svg: 'svg',
111
+ 'svg+xml': 'svg',
106
112
  xml: 'xml',
107
113
  css: 'css',
108
114
  scss: 'scss',
@@ -190,13 +196,69 @@ function measureLines(code) {
190
196
  }
191
197
  return { lines: split.length, maxLineLength };
192
198
  }
193
- /** Classify a lowercased fence language into a coarse content category. */
194
- export function classifyContentCategory(lang) {
199
+ const HTML_FENCE_ALIASES = new Set(['html', 'htm', 'xhtml']);
200
+ const SVG_FENCE_ALIASES = new Set(['svg', 'svg+xml']);
201
+ /**
202
+ * Strip leading UTF-8 BOM, whitespace, XML declarations (`<?xml ...?>`),
203
+ * `<!DOCTYPE ...>` prologs, and `<!-- ... -->` comments to inspect the root tag.
204
+ */
205
+ function stripXmlProlog(source) {
206
+ let cursor = source.startsWith('\uFEFF') ? 1 : 0;
207
+ while (cursor < source.length) {
208
+ // Skip whitespace
209
+ while (cursor < source.length && /\s/.test(source[cursor])) {
210
+ cursor += 1;
211
+ }
212
+ if (source.startsWith('<?', cursor)) {
213
+ const end = source.indexOf('?>', cursor + 2);
214
+ if (end === -1)
215
+ return '';
216
+ cursor = end + 2;
217
+ continue;
218
+ }
219
+ if (source.startsWith('<!--', cursor)) {
220
+ const end = source.indexOf('-->', cursor + 4);
221
+ if (end === -1)
222
+ return '';
223
+ cursor = end + 3;
224
+ continue;
225
+ }
226
+ if (/^<!doctype\b/i.test(source.slice(cursor, cursor + 16))) {
227
+ const end = source.indexOf('>', cursor + 9);
228
+ if (end === -1)
229
+ return '';
230
+ cursor = end + 1;
231
+ continue;
232
+ }
233
+ break;
234
+ }
235
+ return source.slice(cursor);
236
+ }
237
+ /**
238
+ * Resolve whether a Markdown fence language + body should use a visual preview
239
+ * layer (`'html'` or `'svg'`), including `htm`/`xhtml`/`svg+xml` aliases and
240
+ * root-element `<svg>` sniffing inside `xml` fences.
241
+ */
242
+ export function resolveVisualFenceKind(lang, code) {
195
243
  const normalized = lang.trim().toLowerCase();
196
- if (normalized === 'html')
244
+ if (HTML_FENCE_ALIASES.has(normalized))
197
245
  return 'html';
198
- if (normalized === 'svg')
246
+ if (SVG_FENCE_ALIASES.has(normalized))
199
247
  return 'svg';
248
+ if (normalized === 'xml') {
249
+ const root = stripXmlProlog(code);
250
+ if (/^<svg(?=[\s/>]|$)/i.test(root)) {
251
+ return 'svg';
252
+ }
253
+ }
254
+ return null;
255
+ }
256
+ /** Classify a lowercased fence language (and optional body for XML `<svg>` sniffing) into a content category. */
257
+ export function classifyContentCategory(lang, code = '') {
258
+ const visual = resolveVisualFenceKind(lang, code);
259
+ if (visual !== null)
260
+ return visual;
261
+ const normalized = lang.trim().toLowerCase();
200
262
  if (MARKDOWN_LANGS.has(normalized))
201
263
  return 'markdown';
202
264
  if (DATA_LANGS.has(normalized))
@@ -591,12 +653,12 @@ export function analyzeCodeComplexity(lang, code, meta) {
591
653
  }
592
654
  /** Unified complexity analyzer dispatching HTML, SVG, and general code/document fences. */
593
655
  export function analyzeFenceComplexity(lang, code, meta) {
594
- const normalized = lang.trim().toLowerCase();
595
- if (normalized === 'html')
656
+ const visual = resolveVisualFenceKind(lang, code);
657
+ if (visual === 'html')
596
658
  return analyzeHtmlComplexity(code, meta);
597
- if (normalized === 'svg')
659
+ if (visual === 'svg')
598
660
  return analyzeSvgComplexity(code, meta);
599
- return analyzeCodeComplexity(normalized, code, meta);
661
+ return analyzeCodeComplexity(lang.trim().toLowerCase(), code, meta);
600
662
  }
601
663
  /**
602
664
  * Decide whether a still-streaming fence should collapse early into a "Generating…"
@@ -615,14 +677,15 @@ export function shouldCollapseWhileStreaming(lang, code, meta) {
615
677
  const normalized = lang.trim().toLowerCase();
616
678
  if (normalized === 'math')
617
679
  return false;
618
- if (normalized === 'html') {
680
+ const visual = resolveVisualFenceKind(normalized, code);
681
+ if (visual === 'html') {
619
682
  if (FULL_DOC_RE.test(code))
620
683
  return true;
621
684
  if (HTML_TAG_RE.test(code) && /<(?:head|style|body)\b/i.test(code))
622
685
  return true;
623
686
  return analyzeHtmlComplexity(code, meta).isComplex;
624
687
  }
625
- if (normalized === 'svg') {
688
+ if (visual === 'svg') {
626
689
  const vb = SVG_VIEWBOX_RE.exec(code);
627
690
  if (vb !== null) {
628
691
  const w = Number.parseFloat(vb[1] ?? '0') || 0;
@@ -659,13 +722,14 @@ export function deriveFenceDocumentTitle(lang, code, meta, fallback) {
659
722
  return cleaned;
660
723
  }
661
724
  }
662
- if (normalized === 'html' || normalized === 'svg') {
725
+ const visual = resolveVisualFenceKind(normalized, code);
726
+ if (visual === 'html' || visual === 'svg') {
663
727
  const titleTag = /<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(code);
664
728
  const tagTitle = titleTag?.[1] !== undefined ? cleanTitleText(titleTag[1]) : '';
665
729
  if (tagTitle.length > 0 && !GENERIC_TITLES.has(tagTitle.toLowerCase())) {
666
730
  return tagTitle;
667
731
  }
668
- if (normalized === 'html') {
732
+ if (visual === 'html') {
669
733
  const headingTag = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(code);
670
734
  const headingTitle = headingTag?.[1] !== undefined ? cleanTitleText(headingTag[1]) : '';
671
735
  if (headingTitle.length > 0)