@aqian0/dsh-renderer 0.0.0-stage → 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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/cordis.patch.yml +4 -0
  4. package/icon.svg +5 -0
  5. package/lib/client.js +789 -0
  6. package/lib/config.js +96 -0
  7. package/lib/host/artifact-skill.js +55 -0
  8. package/lib/host/artifact-tool.js +177 -0
  9. package/lib/host/media-bridge.js +102 -0
  10. package/lib/index.js +120 -0
  11. package/lib/shared/artifact-stream.js +293 -0
  12. package/lib/shared/config-defaults.js +92 -0
  13. package/lib/shared/content-complexity.js +812 -0
  14. package/lib/shared/media-extractor.js +154 -0
  15. package/lib/shared/sandbox-core.js +286 -0
  16. package/lib/shared/sanitize.js +539 -0
  17. package/lib/types/client/artifact-node.d.ts +62 -0
  18. package/lib/types/client/artifact-resource.d.ts +30 -0
  19. package/lib/types/client/artifact-toolview.d.ts +17 -0
  20. package/lib/types/client/code-view.d.ts +22 -0
  21. package/lib/types/client/document-card.d.ts +33 -0
  22. package/lib/types/client/fence-layer.d.ts +26 -0
  23. package/lib/types/client/highlight.d.ts +24 -0
  24. package/lib/types/client/icons.d.ts +10 -0
  25. package/lib/types/client/locales.d.ts +57 -0
  26. package/lib/types/client/sandbox.d.ts +23 -0
  27. package/lib/types/client/styles.d.ts +20 -0
  28. package/lib/types/client/svg-view.d.ts +19 -0
  29. package/lib/types/client/theme.d.ts +20 -0
  30. package/lib/types/client/turn-media.d.ts +10 -0
  31. package/lib/types/client/types.d.ts +293 -0
  32. package/lib/types/client/workbench.d.ts +24 -0
  33. package/lib/types/client.d.ts +10 -0
  34. package/lib/types/config.d.ts +50 -0
  35. package/lib/types/host/artifact-skill.d.ts +39 -0
  36. package/lib/types/host/artifact-tool.d.ts +82 -0
  37. package/lib/types/host/media-bridge.d.ts +47 -0
  38. package/lib/types/index.d.ts +29 -0
  39. package/lib/types/shared/artifact-stream.d.ts +52 -0
  40. package/lib/types/shared/config-defaults.d.ts +56 -0
  41. package/lib/types/shared/content-complexity.d.ts +94 -0
  42. package/lib/types/shared/media-extractor.d.ts +42 -0
  43. package/lib/types/shared/sandbox-core.d.ts +128 -0
  44. package/lib/types/shared/sanitize.d.ts +97 -0
  45. package/locale/en.json +6 -0
  46. package/locale/zh.json +6 -0
  47. package/package.json +95 -4
package/lib/config.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Plugin configuration schema and normalization helpers.
3
+ *
4
+ * @module dsh-renderer/config
5
+ */
6
+ import z from '@deepseek-ai/schemastery';
7
+ import { DEFAULT_RENDERER_CONFIG, RENDERER_CONFIG_GLOBAL, SUPPORTED_FENCE_LANGUAGES, normalizeClientConfig, } from './shared/config-defaults.js';
8
+ export { DEFAULT_RENDERER_CONFIG, RENDERER_CONFIG_GLOBAL, SUPPORTED_FENCE_LANGUAGES, normalizeClientConfig };
9
+ const FenceLanguageSchema = z.union([z.const('html'), z.const('svg')]);
10
+ /** Configuration schema of the `renderer` bundle entry. */
11
+ export const Config = z.object({
12
+ enableFencePreview: z
13
+ .boolean()
14
+ .default(DEFAULT_RENDERER_CONFIG.enableFencePreview)
15
+ .description('Enable visual preview layers for supported Markdown code fences.'),
16
+ fenceLanguages: z
17
+ .array(FenceLanguageSchema)
18
+ .default([...DEFAULT_RENDERER_CONFIG.fenceLanguages])
19
+ .description('Markdown fence languages enhanced with inline visual previews.'),
20
+ defaultView: z
21
+ .union([z.const('preview'), z.const('code')])
22
+ .default(DEFAULT_RENDERER_CONFIG.defaultView)
23
+ .description('Initial view shown once a visual code fence finishes streaming.'),
24
+ allowExternalResources: z
25
+ .boolean()
26
+ .default(DEFAULT_RENDERER_CONFIG.allowExternalResources)
27
+ .description('Allow HTML previews to load external HTTPS scripts, styles, fonts, and images.'),
28
+ enableWorkbench: z
29
+ .boolean()
30
+ .default(DEFAULT_RENDERER_CONFIG.enableWorkbench)
31
+ .description('Allow opening previews in the right Sidebar workbench (or fullscreen modal fallback).'),
32
+ complexContentToSidebar: z
33
+ .boolean()
34
+ .default(DEFAULT_RENDERER_CONFIG.complexContentToSidebar)
35
+ .description('Collapse overly complex HTML, SVG, or code/document fences into a Document Expand Card in Chat that opens in the right Sidebar.'),
36
+ enableArtifactTool: z
37
+ .boolean()
38
+ .default(DEFAULT_RENDERER_CONFIG.enableArtifactTool)
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.'),
44
+ autoOpenArtifact: z
45
+ .boolean()
46
+ .default(DEFAULT_RENDERER_CONFIG.autoOpenArtifact)
47
+ .description('Automatically open newly completed live render_artifact results in the right Sidebar (historical replays remain click-to-open).'),
48
+ enableTurnMediaFallback: z
49
+ .boolean()
50
+ .default(DEFAULT_RENDERER_CONFIG.enableTurnMediaFallback)
51
+ .description('Render inline data:image/* URIs and raw <img>/<svg> prose fragments in the turn footer.'),
52
+ bridgeToolDataImages: z
53
+ .boolean()
54
+ .default(DEFAULT_RENDERER_CONFIG.bridgeToolDataImages)
55
+ .description('Convert data:image/* payloads in Host tool results into durable DSH image attachments.'),
56
+ maxContentBytes: z
57
+ .natural()
58
+ .min(1024)
59
+ .max(16_777_216)
60
+ .default(DEFAULT_RENDERER_CONFIG.maxContentBytes)
61
+ .description('Maximum UTF-8 byte length accepted for one previewed HTML/SVG snippet.'),
62
+ inlineMaxHeight: z
63
+ .natural()
64
+ .min(120)
65
+ .max(2400)
66
+ .default(DEFAULT_RENDERER_CONFIG.inlineMaxHeight)
67
+ .description('Maximum height in CSS pixels for inline Chat previews.'),
68
+ maxActiveSandboxes: z
69
+ .natural()
70
+ .min(1)
71
+ .max(32)
72
+ .default(DEFAULT_RENDERER_CONFIG.maxActiveSandboxes)
73
+ .description('Maximum number of concurrently active HTML iframe sandboxes before LRU sleep.'),
74
+ });
75
+ /**
76
+ * Validate and normalize partial plugin configuration through {@link Config}.
77
+ *
78
+ * Deduplicates `fenceLanguages` while preserving declared order so downstream
79
+ * slot registrations never attempt duplicate keys.
80
+ *
81
+ * @param config - raw configuration object from Cordis.
82
+ */
83
+ export function resolveConfig(config = {}) {
84
+ const { fenceLanguages: rawLanguages, ...rest } = config;
85
+ const parsed = Config(rawLanguages === undefined ? rest : { ...rest, fenceLanguages: [...rawLanguages] });
86
+ const uniqueLanguages = [];
87
+ for (const lang of parsed.fenceLanguages) {
88
+ if (!uniqueLanguages.includes(lang)) {
89
+ uniqueLanguages.push(lang);
90
+ }
91
+ }
92
+ return {
93
+ ...parsed,
94
+ fenceLanguages: uniqueLanguages,
95
+ };
96
+ }
@@ -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
+ };
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Host-side `render_artifact` tool definition and system-prompt guidance.
3
+ *
4
+ * Allows the model to emit standalone interactive HTML pages, dense SVG
5
+ * diagrams, and long self-contained code/Markdown documents directly as
6
+ * streaming DSH Document Cards (rendered by `tool.call.toolview`) instead of
7
+ * flooding chat prose with hundreds of lines of raw code. Because tool calls
8
+ * are persisted in the DSH Session log, artifacts remain inspectable across
9
+ * reloads, forks, and replays.
10
+ *
11
+ * @module dsh-renderer/host/artifact-tool
12
+ */
13
+ import { computeArtifactId, formatByteSize } from '../shared/content-complexity.js';
14
+ import { utf8ByteLength } from '../shared/sanitize.js';
15
+ /** Wire tool name shared by the Host tool registration and Client `tool.call.toolview`. */
16
+ export const ARTIFACT_TOOL_NAME = 'render_artifact';
17
+ /** System-prompt section name registered on `ctx.systemPrompt`. */
18
+ export const ARTIFACT_PROMPT_SECTION_NAME = 'dsh-renderer:artifact';
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;
26
+ const VALID_KINDS = new Set(['html', 'svg', 'code']);
27
+ /** Validate and normalize raw `render_artifact` tool arguments. */
28
+ function parseArtifactArgs(raw, maxContentBytes) {
29
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
30
+ throw new Error('render_artifact requires an object argument payload');
31
+ }
32
+ const obj = raw;
33
+ const rawTitle = typeof obj['title'] === 'string' ? obj['title'].trim() : '';
34
+ if (rawTitle.length === 0) {
35
+ throw new Error('render_artifact requires a non-empty string "title"');
36
+ }
37
+ const title = rawTitle.replace(/\s+/g, ' ').slice(0, 120);
38
+ const rawKind = typeof obj['kind'] === 'string' ? obj['kind'].trim().toLowerCase() : '';
39
+ if (!VALID_KINDS.has(rawKind)) {
40
+ throw new Error('render_artifact "kind" must be one of "html", "svg", or "code"');
41
+ }
42
+ const kind = rawKind;
43
+ const rawContent = obj['content'];
44
+ if (typeof rawContent !== 'string' || rawContent.trim().length === 0) {
45
+ throw new Error('render_artifact requires a non-empty string "content"');
46
+ }
47
+ const bytes = utf8ByteLength(rawContent);
48
+ if (bytes > maxContentBytes) {
49
+ throw new Error(`render_artifact content (${formatByteSize(bytes)}) exceeds maxContentBytes (${formatByteSize(maxContentBytes)})`);
50
+ }
51
+ const rawLang = typeof obj['lang'] === 'string' ? obj['lang'].trim().toLowerCase() : '';
52
+ const lang = kind === 'html' ? 'html' : kind === 'svg' ? 'svg' : rawLang.length > 0 ? rawLang.slice(0, 32) : 'text';
53
+ const lines = rawContent.trim().split(/\r?\n/).length;
54
+ return { title, kind, lang, content: rawContent, bytes, lines };
55
+ }
56
+ /**
57
+ * Create a dependency-free DSH `ToolDefinition` object for `render_artifact`.
58
+ *
59
+ * Uses only the DSH-supported JSON Schema subset (`type`, `properties`, `required`,
60
+ * `additionalProperties`, `enum`, `description`).
61
+ */
62
+ export function createRenderArtifactToolDefinition(options) {
63
+ return {
64
+ name: ARTIFACT_TOOL_NAME,
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.',
66
+ parameters: {
67
+ type: 'object',
68
+ additionalProperties: false,
69
+ properties: {
70
+ title: {
71
+ type: 'string',
72
+ description: 'Concise human-readable title shown on the document card and right-Sidebar tab.',
73
+ },
74
+ kind: {
75
+ type: 'string',
76
+ enum: ['html', 'svg', 'code'],
77
+ description: 'Presentation kind: html (interactive sandbox), svg (zoomable vector viewer), or code (syntax-highlighted code, Markdown, or structured data).',
78
+ },
79
+ lang: {
80
+ type: 'string',
81
+ description: 'Language identifier for syntax highlighting and download extension when kind is "code" (e.g. ts, py, json, md, sql, diff).',
82
+ },
83
+ content: {
84
+ type: 'string',
85
+ description: 'Complete source text of the artifact.',
86
+ },
87
+ },
88
+ required: ['title', 'kind', 'content'],
89
+ },
90
+ output: {
91
+ schema: {
92
+ type: 'object',
93
+ additionalProperties: false,
94
+ properties: {
95
+ artifactId: { type: 'string' },
96
+ title: { type: 'string' },
97
+ kind: { type: 'string', enum: ['html', 'svg', 'code'] },
98
+ lang: { type: 'string' },
99
+ lines: { type: 'integer' },
100
+ bytes: { type: 'integer' },
101
+ },
102
+ required: ['artifactId', 'title', 'kind', 'lang', 'lines', 'bytes'],
103
+ },
104
+ render(_args, value) {
105
+ return [
106
+ {
107
+ type: 'text',
108
+ text: `Rendered artifact "${value.title}" (${value.kind}/${value.lang}, ${value.lines} lines, ${formatByteSize(value.bytes)}).`,
109
+ },
110
+ ];
111
+ },
112
+ },
113
+ isConcurrencySafe: () => true,
114
+ async execute(args, exec) {
115
+ if (exec?.signal?.aborted) {
116
+ throw exec.signal.reason ?? new Error('render_artifact aborted');
117
+ }
118
+ const parsed = parseArtifactArgs(args, options.maxContentBytes);
119
+ const artifactId = computeArtifactId(parsed.kind, parsed.content, parsed.lang);
120
+ return await Promise.resolve({
121
+ artifactId,
122
+ title: parsed.title,
123
+ kind: parsed.kind,
124
+ lang: parsed.lang,
125
+ lines: parsed.lines,
126
+ bytes: parsed.bytes,
127
+ });
128
+ },
129
+ presentCall(args) {
130
+ if (args === null || typeof args !== 'object' || Array.isArray(args))
131
+ return undefined;
132
+ const title = args['title'];
133
+ return {
134
+ card: 'generic',
135
+ title: typeof title === 'string' && title.trim().length > 0 ? title.trim() : ARTIFACT_TOOL_NAME,
136
+ kind: 'other',
137
+ };
138
+ },
139
+ };
140
+ }
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. */
150
+ export const ARTIFACT_PROMPT_SECTION = {
151
+ name: ARTIFACT_PROMPT_SECTION_NAME,
152
+ order: ARTIFACT_PROMPT_ORDER,
153
+ text: ARTIFACT_PROMPT_TEXT,
154
+ interpolate: false,
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
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Optional Host bridge converting `data:image/*` base64 payloads returned by
3
+ * third-party tools into durable DSH `ImageBlock` attachments via `ctx.attachments`.
4
+ *
5
+ * @module dsh-renderer/host/media-bridge
6
+ */
7
+ const DATA_IMAGE_BASE64_RE = /data:(image\/(?:png|jpeg|jpg|webp|gif));base64,([A-Za-z0-9+/=\r\n]+)/gi;
8
+ /** Normalize `image/jpg` alias to canonical `image/jpeg`. */
9
+ function normalizeMediaType(raw) {
10
+ const lower = raw.toLowerCase();
11
+ if (lower === 'image/jpg')
12
+ return 'image/jpeg';
13
+ if (lower === 'image/png' || lower === 'image/jpeg' || lower === 'image/webp' || lower === 'image/gif') {
14
+ return lower;
15
+ }
16
+ return null;
17
+ }
18
+ /** Map canonical MIME type to a file extension for display names. */
19
+ function extensionFor(mediaType) {
20
+ switch (mediaType) {
21
+ case 'image/png':
22
+ return 'png';
23
+ case 'image/jpeg':
24
+ return 'jpg';
25
+ case 'image/webp':
26
+ return 'webp';
27
+ case 'image/gif':
28
+ return 'gif';
29
+ }
30
+ }
31
+ /** Decode base64 bytes safely, returning `null` if invalid or empty. */
32
+ function decodeBase64Bytes(raw, maxBytes) {
33
+ const compact = raw.replace(/\s+/g, '');
34
+ if (compact.length === 0 || compact.length % 4 === 1)
35
+ return null;
36
+ // Fast upper-bound byte estimate before allocating decoded bytes.
37
+ const estimated = Math.floor((compact.length * 3) / 4);
38
+ if (estimated <= 0 || estimated > maxBytes)
39
+ return null;
40
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact))
41
+ return null;
42
+ const buf = Buffer.from(compact, 'base64');
43
+ if (buf.byteLength === 0 || buf.byteLength > maxBytes)
44
+ return null;
45
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
46
+ }
47
+ /**
48
+ * Scan a tool result's text blocks for base64 `data:image/*` payloads, persist them
49
+ * through `attachments.saveImage`, and append durable `{ type: 'image', attachment }`
50
+ * blocks so DSH's native `tool.call.images` gallery renders them.
51
+ *
52
+ * Returns `null` when no convertible image was found or saved.
53
+ */
54
+ export async function bridgeToolResultDataImages(toolName, result, attachments, options) {
55
+ if (result.isError || result.content.length === 0)
56
+ return null;
57
+ if (options.signal?.aborted)
58
+ return null;
59
+ const limitBytes = Math.min(options.maxBytes, attachments.imageLimits?.maxImageBytes ?? options.maxBytes);
60
+ const maxImages = options.maxImages ?? 4;
61
+ const appended = [];
62
+ const seenPayloads = new Set();
63
+ let counter = 0;
64
+ for (const block of result.content) {
65
+ if (appended.length >= maxImages)
66
+ break;
67
+ if (block.type !== 'text' || typeof block.text !== 'string')
68
+ continue;
69
+ for (const match of block.text.matchAll(DATA_IMAGE_BASE64_RE)) {
70
+ if (appended.length >= maxImages)
71
+ break;
72
+ if (options.signal?.aborted)
73
+ return null;
74
+ const mediaType = normalizeMediaType(match[1] ?? '');
75
+ const base64 = match[2] ?? '';
76
+ if (mediaType === null)
77
+ continue;
78
+ const dedupeKey = `${mediaType}:${base64.length}:${base64.slice(0, 64)}`;
79
+ if (seenPayloads.has(dedupeKey))
80
+ continue;
81
+ const bytes = decodeBase64Bytes(base64, limitBytes);
82
+ if (bytes === null)
83
+ continue;
84
+ seenPayloads.add(dedupeKey);
85
+ counter += 1;
86
+ try {
87
+ const ref = await attachments.saveImage({
88
+ data: bytes,
89
+ mediaType,
90
+ name: `${toolName}-image-${counter}.${extensionFor(mediaType)}`,
91
+ });
92
+ appended.push({ type: 'image', attachment: ref });
93
+ }
94
+ catch {
95
+ // Invalid/corrupted raster payload: skip without failing the tool call.
96
+ }
97
+ }
98
+ }
99
+ if (appended.length === 0 || options.signal?.aborted)
100
+ return null;
101
+ return [...result.content, ...appended];
102
+ }
package/lib/index.js ADDED
@@ -0,0 +1,120 @@
1
+ /**
2
+ * dsh-renderer Host entry (`renderer` bundle row).
3
+ *
4
+ * Responsibilities on the Host:
5
+ * 1. Validate and normalize plugin configuration through Schemastery.
6
+ * 2. Publish normalized configuration to the Web GUI via `webserver/index-inject`
7
+ * (`globalThis.__DSH_RENDERER_CONFIG__`) so the browser half stays in sync
8
+ * without duplicating configuration storage.
9
+ * 3. Optionally bridge base64 `data:image/*` payloads returned by third-party
10
+ * tools into durable DSH `ImageBlock` attachments when `bridgeToolDataImages`
11
+ * is enabled and `ctx.attachments` is mounted.
12
+ *
13
+ * @module dsh-renderer
14
+ */
15
+ import { Config, DEFAULT_RENDERER_CONFIG, RENDERER_CONFIG_GLOBAL, SUPPORTED_FENCE_LANGUAGES, normalizeClientConfig, resolveConfig, } from './config.js';
16
+ import { ARTIFACT_SKILL_REGISTRATION } from './host/artifact-skill.js';
17
+ import { createArtifactPromptSection, createRenderArtifactToolDefinition, } from './host/artifact-tool.js';
18
+ import { bridgeToolResultDataImages, } from './host/media-bridge.js';
19
+ /** Cordis plugin name. */
20
+ export const name = 'renderer';
21
+ /** Host services required before {@link apply} runs (none: optional hooks bind lazily). */
22
+ export const inject = [];
23
+ export { Config, DEFAULT_RENDERER_CONFIG, RENDERER_CONFIG_GLOBAL, SUPPORTED_FENCE_LANGUAGES, normalizeClientConfig, resolveConfig, };
24
+ /**
25
+ * Activate the Host side of `@aqian0/dsh-renderer`.
26
+ *
27
+ * @param ctx - live Cordis context.
28
+ * @param config - partial plugin configuration.
29
+ */
30
+ export function apply(ctx, config = {}) {
31
+ const resolved = resolveConfig(config);
32
+ const ext = ctx;
33
+ // Publish normalized configuration into every served Web GUI boot HTML.
34
+ ext.on('webserver/index-inject', (rawTable) => {
35
+ if (!Array.isArray(rawTable))
36
+ return;
37
+ const row = {
38
+ kind: 'global',
39
+ name: RENDERER_CONFIG_GLOBAL,
40
+ value: resolved,
41
+ };
42
+ rawTable.push(row);
43
+ });
44
+ // Register first-class `render_artifact` tool, tool-aware prompt guidance, and bundled skill.
45
+ if (resolved.enableArtifactTool) {
46
+ const toolDef = createRenderArtifactToolDefinition({ maxContentBytes: resolved.maxContentBytes });
47
+ const registerOnTools = (target) => {
48
+ const tools = target.get?.('tools');
49
+ if (tools === undefined || typeof tools.register !== 'function')
50
+ return;
51
+ if (typeof target.effect === 'function') {
52
+ target.effect(() => tools.register(toolDef), 'dsh-renderer: render_artifact tool');
53
+ }
54
+ else {
55
+ tools.register(toolDef);
56
+ }
57
+ };
58
+ const registerPrompt = (target) => {
59
+ const prompt = target.get?.('systemPrompt');
60
+ if (prompt === undefined || typeof prompt.section !== 'function')
61
+ return;
62
+ const section = createArtifactPromptSection(() => target.get?.('tools'));
63
+ if (typeof target.effect === 'function') {
64
+ target.effect(() => prompt.section(section), 'dsh-renderer: artifact prompt section');
65
+ }
66
+ else {
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);
79
+ }
80
+ };
81
+ if (typeof ext.inject === 'function') {
82
+ ext.inject(['tools'], registerOnTools);
83
+ ext.inject(['systemPrompt'], registerPrompt);
84
+ if (resolved.enableArtifactSkill) {
85
+ ext.inject(['skills'], registerSkill);
86
+ }
87
+ }
88
+ else {
89
+ registerOnTools(ext);
90
+ registerPrompt(ext);
91
+ if (resolved.enableArtifactSkill) {
92
+ registerSkill(ext);
93
+ }
94
+ }
95
+ }
96
+ // Optional tool output image bridge: stays inactive unless explicitly enabled.
97
+ if (resolved.bridgeToolDataImages) {
98
+ ext.on('tools/post-execute', async (exec, result, next) => {
99
+ const nextFn = typeof next === 'function' ? next : undefined;
100
+ const attachments = ext.get?.('attachments');
101
+ if (attachments === undefined ||
102
+ typeof attachments.saveImage !== 'function' ||
103
+ result === null ||
104
+ typeof result !== 'object') {
105
+ return nextFn?.();
106
+ }
107
+ const execObj = exec !== null && typeof exec === 'object' ? exec : {};
108
+ const toolName = typeof execObj['name'] === 'string' ? execObj['name'] : 'tool';
109
+ const signal = execObj['signal'] instanceof AbortSignal ? execObj['signal'] : undefined;
110
+ const enriched = await bridgeToolResultDataImages(toolName, result, attachments, {
111
+ maxBytes: resolved.maxContentBytes,
112
+ signal,
113
+ });
114
+ if (enriched === null) {
115
+ return nextFn?.();
116
+ }
117
+ return { kind: 'accept', content: enriched };
118
+ });
119
+ }
120
+ }