@aqian0/dsh-renderer 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +119 -2
- package/cordis.patch.yml +4 -0
- package/icon.svg +5 -0
- package/lib/client.js +738 -0
- package/lib/config.js +92 -0
- package/lib/host/artifact-tool.js +141 -0
- package/lib/host/media-bridge.js +102 -0
- package/lib/index.js +101 -0
- package/lib/shared/config-defaults.js +88 -0
- package/lib/shared/content-complexity.js +748 -0
- package/lib/shared/media-extractor.js +154 -0
- package/lib/shared/sandbox-core.js +217 -0
- package/lib/shared/sanitize.js +539 -0
- package/lib/types/client/artifact-toolview.d.ts +17 -0
- package/lib/types/client/code-view.d.ts +22 -0
- package/lib/types/client/document-card.d.ts +33 -0
- package/lib/types/client/fence-layer.d.ts +26 -0
- package/lib/types/client/highlight.d.ts +24 -0
- package/lib/types/client/icons.d.ts +10 -0
- package/lib/types/client/locales.d.ts +54 -0
- package/lib/types/client/sandbox.d.ts +23 -0
- package/lib/types/client/styles.d.ts +20 -0
- package/lib/types/client/svg-view.d.ts +19 -0
- package/lib/types/client/theme.d.ts +20 -0
- package/lib/types/client/turn-media.d.ts +10 -0
- package/lib/types/client/types.d.ts +181 -0
- package/lib/types/client/workbench.d.ts +24 -0
- package/lib/types/client.d.ts +10 -0
- package/lib/types/config.d.ts +48 -0
- package/lib/types/host/artifact-tool.d.ts +53 -0
- package/lib/types/host/media-bridge.d.ts +47 -0
- package/lib/types/index.d.ts +29 -0
- package/lib/types/shared/config-defaults.d.ts +54 -0
- package/lib/types/shared/content-complexity.d.ts +88 -0
- package/lib/types/shared/media-extractor.d.ts +42 -0
- package/lib/types/shared/sandbox-core.d.ts +101 -0
- package/lib/types/shared/sanitize.d.ts +97 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +91 -4
package/lib/config.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
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 complex documents directly as cards.'),
|
|
40
|
+
autoOpenArtifact: z
|
|
41
|
+
.boolean()
|
|
42
|
+
.default(DEFAULT_RENDERER_CONFIG.autoOpenArtifact)
|
|
43
|
+
.description('Automatically open settled render_artifact results in the right Sidebar instead of waiting for a click.'),
|
|
44
|
+
enableTurnMediaFallback: z
|
|
45
|
+
.boolean()
|
|
46
|
+
.default(DEFAULT_RENDERER_CONFIG.enableTurnMediaFallback)
|
|
47
|
+
.description('Render inline data:image/* URIs and raw <img>/<svg> prose fragments in the turn footer.'),
|
|
48
|
+
bridgeToolDataImages: z
|
|
49
|
+
.boolean()
|
|
50
|
+
.default(DEFAULT_RENDERER_CONFIG.bridgeToolDataImages)
|
|
51
|
+
.description('Convert data:image/* payloads in Host tool results into durable DSH image attachments.'),
|
|
52
|
+
maxContentBytes: z
|
|
53
|
+
.natural()
|
|
54
|
+
.min(1024)
|
|
55
|
+
.max(16_777_216)
|
|
56
|
+
.default(DEFAULT_RENDERER_CONFIG.maxContentBytes)
|
|
57
|
+
.description('Maximum UTF-8 byte length accepted for one previewed HTML/SVG snippet.'),
|
|
58
|
+
inlineMaxHeight: z
|
|
59
|
+
.natural()
|
|
60
|
+
.min(120)
|
|
61
|
+
.max(2400)
|
|
62
|
+
.default(DEFAULT_RENDERER_CONFIG.inlineMaxHeight)
|
|
63
|
+
.description('Maximum height in CSS pixels for inline Chat previews.'),
|
|
64
|
+
maxActiveSandboxes: z
|
|
65
|
+
.natural()
|
|
66
|
+
.min(1)
|
|
67
|
+
.max(32)
|
|
68
|
+
.default(DEFAULT_RENDERER_CONFIG.maxActiveSandboxes)
|
|
69
|
+
.description('Maximum number of concurrently active HTML iframe sandboxes before LRU sleep.'),
|
|
70
|
+
});
|
|
71
|
+
/**
|
|
72
|
+
* Validate and normalize partial plugin configuration through {@link Config}.
|
|
73
|
+
*
|
|
74
|
+
* Deduplicates `fenceLanguages` while preserving declared order so downstream
|
|
75
|
+
* slot registrations never attempt duplicate keys.
|
|
76
|
+
*
|
|
77
|
+
* @param config - raw configuration object from Cordis.
|
|
78
|
+
*/
|
|
79
|
+
export function resolveConfig(config = {}) {
|
|
80
|
+
const { fenceLanguages: rawLanguages, ...rest } = config;
|
|
81
|
+
const parsed = Config(rawLanguages === undefined ? rest : { ...rest, fenceLanguages: [...rawLanguages] });
|
|
82
|
+
const uniqueLanguages = [];
|
|
83
|
+
for (const lang of parsed.fenceLanguages) {
|
|
84
|
+
if (!uniqueLanguages.includes(lang)) {
|
|
85
|
+
uniqueLanguages.push(lang);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
...parsed,
|
|
90
|
+
fenceLanguages: uniqueLanguages,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
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
|
+
/** Placement order beside built-in tool guidance (`TOOL_REPORT: 2900` .. `MCP_SERVERS: 3100`). */
|
|
20
|
+
const ARTIFACT_PROMPT_ORDER = 2950;
|
|
21
|
+
const VALID_KINDS = new Set(['html', 'svg', 'code']);
|
|
22
|
+
/** Validate and normalize raw `render_artifact` tool arguments. */
|
|
23
|
+
function parseArtifactArgs(raw, maxContentBytes) {
|
|
24
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
25
|
+
throw new Error('render_artifact requires an object argument payload');
|
|
26
|
+
}
|
|
27
|
+
const obj = raw;
|
|
28
|
+
const rawTitle = typeof obj['title'] === 'string' ? obj['title'].trim() : '';
|
|
29
|
+
if (rawTitle.length === 0) {
|
|
30
|
+
throw new Error('render_artifact requires a non-empty string "title"');
|
|
31
|
+
}
|
|
32
|
+
const title = rawTitle.replace(/\s+/g, ' ').slice(0, 120);
|
|
33
|
+
const rawKind = typeof obj['kind'] === 'string' ? obj['kind'].trim().toLowerCase() : '';
|
|
34
|
+
if (!VALID_KINDS.has(rawKind)) {
|
|
35
|
+
throw new Error('render_artifact "kind" must be one of "html", "svg", or "code"');
|
|
36
|
+
}
|
|
37
|
+
const kind = rawKind;
|
|
38
|
+
const rawContent = obj['content'];
|
|
39
|
+
if (typeof rawContent !== 'string' || rawContent.trim().length === 0) {
|
|
40
|
+
throw new Error('render_artifact requires a non-empty string "content"');
|
|
41
|
+
}
|
|
42
|
+
const bytes = utf8ByteLength(rawContent);
|
|
43
|
+
if (bytes > maxContentBytes) {
|
|
44
|
+
throw new Error(`render_artifact content (${formatByteSize(bytes)}) exceeds maxContentBytes (${formatByteSize(maxContentBytes)})`);
|
|
45
|
+
}
|
|
46
|
+
const rawLang = typeof obj['lang'] === 'string' ? obj['lang'].trim().toLowerCase() : '';
|
|
47
|
+
const lang = kind === 'html' ? 'html' : kind === 'svg' ? 'svg' : rawLang.length > 0 ? rawLang.slice(0, 32) : 'text';
|
|
48
|
+
const lines = rawContent.trim().split(/\r?\n/).length;
|
|
49
|
+
return { title, kind, lang, content: rawContent, bytes, lines };
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Create a dependency-free DSH `ToolDefinition` object for `render_artifact`.
|
|
53
|
+
*
|
|
54
|
+
* Uses only the DSH-supported JSON Schema subset (`type`, `properties`, `required`,
|
|
55
|
+
* `additionalProperties`, `enum`, `description`).
|
|
56
|
+
*/
|
|
57
|
+
export function createRenderArtifactToolDefinition(options) {
|
|
58
|
+
return {
|
|
59
|
+
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.',
|
|
61
|
+
parameters: {
|
|
62
|
+
type: 'object',
|
|
63
|
+
additionalProperties: false,
|
|
64
|
+
properties: {
|
|
65
|
+
title: {
|
|
66
|
+
type: 'string',
|
|
67
|
+
description: 'Concise human-readable title shown on the document card and right-Sidebar tab.',
|
|
68
|
+
},
|
|
69
|
+
kind: {
|
|
70
|
+
type: 'string',
|
|
71
|
+
enum: ['html', 'svg', 'code'],
|
|
72
|
+
description: 'Presentation kind: html (interactive sandbox), svg (zoomable vector viewer), or code (syntax-highlighted code, Markdown, or structured data).',
|
|
73
|
+
},
|
|
74
|
+
lang: {
|
|
75
|
+
type: 'string',
|
|
76
|
+
description: 'Language identifier for syntax highlighting and download extension when kind is "code" (e.g. ts, py, json, md, sql, diff).',
|
|
77
|
+
},
|
|
78
|
+
content: {
|
|
79
|
+
type: 'string',
|
|
80
|
+
description: 'Complete source text of the artifact.',
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
required: ['title', 'kind', 'content'],
|
|
84
|
+
},
|
|
85
|
+
output: {
|
|
86
|
+
schema: {
|
|
87
|
+
type: 'object',
|
|
88
|
+
additionalProperties: false,
|
|
89
|
+
properties: {
|
|
90
|
+
artifactId: { type: 'string' },
|
|
91
|
+
title: { type: 'string' },
|
|
92
|
+
kind: { type: 'string', enum: ['html', 'svg', 'code'] },
|
|
93
|
+
lang: { type: 'string' },
|
|
94
|
+
lines: { type: 'integer' },
|
|
95
|
+
bytes: { type: 'integer' },
|
|
96
|
+
},
|
|
97
|
+
required: ['artifactId', 'title', 'kind', 'lang', 'lines', 'bytes'],
|
|
98
|
+
},
|
|
99
|
+
render(_args, value) {
|
|
100
|
+
return [
|
|
101
|
+
{
|
|
102
|
+
type: 'text',
|
|
103
|
+
text: `Rendered artifact "${value.title}" (${value.kind}/${value.lang}, ${value.lines} lines, ${formatByteSize(value.bytes)}).`,
|
|
104
|
+
},
|
|
105
|
+
];
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
isConcurrencySafe: () => true,
|
|
109
|
+
async execute(args, exec) {
|
|
110
|
+
if (exec?.signal?.aborted) {
|
|
111
|
+
throw exec.signal.reason ?? new Error('render_artifact aborted');
|
|
112
|
+
}
|
|
113
|
+
const parsed = parseArtifactArgs(args, options.maxContentBytes);
|
|
114
|
+
const artifactId = computeArtifactId(parsed.kind, parsed.content, parsed.lang);
|
|
115
|
+
return await Promise.resolve({
|
|
116
|
+
artifactId,
|
|
117
|
+
title: parsed.title,
|
|
118
|
+
kind: parsed.kind,
|
|
119
|
+
lang: parsed.lang,
|
|
120
|
+
lines: parsed.lines,
|
|
121
|
+
bytes: parsed.bytes,
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
presentCall(args) {
|
|
125
|
+
if (args === null || typeof args !== 'object' || Array.isArray(args))
|
|
126
|
+
return undefined;
|
|
127
|
+
const title = args['title'];
|
|
128
|
+
return {
|
|
129
|
+
card: 'generic',
|
|
130
|
+
title: typeof title === 'string' && title.trim().length > 0 ? title.trim() : ARTIFACT_TOOL_NAME,
|
|
131
|
+
kind: 'other',
|
|
132
|
+
};
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** Concise system-prompt section steering the model to use `render_artifact` for heavy standalone output. */
|
|
137
|
+
export const ARTIFACT_PROMPT_SECTION = {
|
|
138
|
+
name: ARTIFACT_PROMPT_SECTION_NAME,
|
|
139
|
+
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.',
|
|
141
|
+
};
|
|
@@ -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,101 @@
|
|
|
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_PROMPT_SECTION, createRenderArtifactToolDefinition, } from './host/artifact-tool.js';
|
|
17
|
+
import { bridgeToolResultDataImages, } from './host/media-bridge.js';
|
|
18
|
+
/** Cordis plugin name. */
|
|
19
|
+
export const name = 'renderer';
|
|
20
|
+
/** Host services required before {@link apply} runs (none: optional hooks bind lazily). */
|
|
21
|
+
export const inject = [];
|
|
22
|
+
export { Config, DEFAULT_RENDERER_CONFIG, RENDERER_CONFIG_GLOBAL, SUPPORTED_FENCE_LANGUAGES, normalizeClientConfig, resolveConfig, };
|
|
23
|
+
/**
|
|
24
|
+
* Activate the Host side of `@aqian0/dsh-renderer`.
|
|
25
|
+
*
|
|
26
|
+
* @param ctx - live Cordis context.
|
|
27
|
+
* @param config - partial plugin configuration.
|
|
28
|
+
*/
|
|
29
|
+
export function apply(ctx, config = {}) {
|
|
30
|
+
const resolved = resolveConfig(config);
|
|
31
|
+
const ext = ctx;
|
|
32
|
+
// Publish normalized configuration into every served Web GUI boot HTML.
|
|
33
|
+
ext.on('webserver/index-inject', (rawTable) => {
|
|
34
|
+
if (!Array.isArray(rawTable))
|
|
35
|
+
return;
|
|
36
|
+
const row = {
|
|
37
|
+
kind: 'global',
|
|
38
|
+
name: RENDERER_CONFIG_GLOBAL,
|
|
39
|
+
value: resolved,
|
|
40
|
+
};
|
|
41
|
+
rawTable.push(row);
|
|
42
|
+
});
|
|
43
|
+
// Register first-class `render_artifact` tool and system-prompt guidance when Host services exist.
|
|
44
|
+
if (resolved.enableArtifactTool) {
|
|
45
|
+
const toolDef = createRenderArtifactToolDefinition({ maxContentBytes: resolved.maxContentBytes });
|
|
46
|
+
const registerOnTools = (target) => {
|
|
47
|
+
const tools = target.get?.('tools');
|
|
48
|
+
if (tools === undefined || typeof tools.register !== 'function')
|
|
49
|
+
return;
|
|
50
|
+
if (typeof target.effect === 'function') {
|
|
51
|
+
target.effect(() => tools.register(toolDef), 'dsh-renderer: render_artifact tool');
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
tools.register(toolDef);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
const registerPrompt = (target) => {
|
|
58
|
+
const prompt = target.get?.('systemPrompt');
|
|
59
|
+
if (prompt === undefined || typeof prompt.section !== 'function')
|
|
60
|
+
return;
|
|
61
|
+
if (typeof target.effect === 'function') {
|
|
62
|
+
target.effect(() => prompt.section(ARTIFACT_PROMPT_SECTION), 'dsh-renderer: artifact prompt section');
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
prompt.section(ARTIFACT_PROMPT_SECTION);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
if (typeof ext.inject === 'function') {
|
|
69
|
+
ext.inject(['tools'], registerOnTools);
|
|
70
|
+
ext.inject(['systemPrompt'], registerPrompt);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
registerOnTools(ext);
|
|
74
|
+
registerPrompt(ext);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Optional tool output image bridge: stays inactive unless explicitly enabled.
|
|
78
|
+
if (resolved.bridgeToolDataImages) {
|
|
79
|
+
ext.on('tools/post-execute', async (exec, result, next) => {
|
|
80
|
+
const nextFn = typeof next === 'function' ? next : undefined;
|
|
81
|
+
const attachments = ext.get?.('attachments');
|
|
82
|
+
if (attachments === undefined ||
|
|
83
|
+
typeof attachments.saveImage !== 'function' ||
|
|
84
|
+
result === null ||
|
|
85
|
+
typeof result !== 'object') {
|
|
86
|
+
return nextFn?.();
|
|
87
|
+
}
|
|
88
|
+
const execObj = exec !== null && typeof exec === 'object' ? exec : {};
|
|
89
|
+
const toolName = typeof execObj['name'] === 'string' ? execObj['name'] : 'tool';
|
|
90
|
+
const signal = execObj['signal'] instanceof AbortSignal ? execObj['signal'] : undefined;
|
|
91
|
+
const enriched = await bridgeToolResultDataImages(toolName, result, attachments, {
|
|
92
|
+
maxBytes: resolved.maxContentBytes,
|
|
93
|
+
signal,
|
|
94
|
+
});
|
|
95
|
+
if (enriched === null) {
|
|
96
|
+
return nextFn?.();
|
|
97
|
+
}
|
|
98
|
+
return { kind: 'accept', content: enriched };
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Zero-dependency configuration types, defaults, and browser-safe normalizer.
|
|
3
|
+
*
|
|
4
|
+
* Kept separate from `src/config.ts` (which imports `@deepseek-ai/schemastery`)
|
|
5
|
+
* so the browser Client bundle stays 100% dependency-free.
|
|
6
|
+
*
|
|
7
|
+
* @module dsh-renderer/shared/config-defaults
|
|
8
|
+
*/
|
|
9
|
+
/** Supported Markdown fence languages rendered by Phase 1 of `@aqian0/dsh-renderer`. */
|
|
10
|
+
export const SUPPORTED_FENCE_LANGUAGES = ['html', 'svg'];
|
|
11
|
+
/** Global property name written by the Host `webserver/index-inject` hook and read by the Client. */
|
|
12
|
+
export const RENDERER_CONFIG_GLOBAL = '__DSH_RENDERER_CONFIG__';
|
|
13
|
+
/** Baseline defaults used when configuration fields or Host injections are absent. */
|
|
14
|
+
export const DEFAULT_RENDERER_CONFIG = Object.freeze({
|
|
15
|
+
enableFencePreview: true,
|
|
16
|
+
fenceLanguages: Object.freeze([...SUPPORTED_FENCE_LANGUAGES]),
|
|
17
|
+
defaultView: 'preview',
|
|
18
|
+
allowExternalResources: false,
|
|
19
|
+
enableWorkbench: true,
|
|
20
|
+
complexContentToSidebar: true,
|
|
21
|
+
enableArtifactTool: true,
|
|
22
|
+
autoOpenArtifact: false,
|
|
23
|
+
enableTurnMediaFallback: true,
|
|
24
|
+
bridgeToolDataImages: false,
|
|
25
|
+
maxContentBytes: 524_288,
|
|
26
|
+
inlineMaxHeight: 480,
|
|
27
|
+
maxActiveSandboxes: 6,
|
|
28
|
+
});
|
|
29
|
+
/**
|
|
30
|
+
* Safely coerce an untrusted global config payload (e.g. `globalThis.__DSH_RENDERER_CONFIG__`)
|
|
31
|
+
* into a complete {@link RendererPluginConfig} without requiring Schemastery in the browser bundle.
|
|
32
|
+
*
|
|
33
|
+
* @param raw - untrusted value read from the browser global object.
|
|
34
|
+
*/
|
|
35
|
+
export function normalizeClientConfig(raw) {
|
|
36
|
+
if (raw === null || typeof raw !== 'object') {
|
|
37
|
+
return DEFAULT_RENDERER_CONFIG;
|
|
38
|
+
}
|
|
39
|
+
const input = raw;
|
|
40
|
+
const supported = new Set(SUPPORTED_FENCE_LANGUAGES);
|
|
41
|
+
let fenceLanguages = [...DEFAULT_RENDERER_CONFIG.fenceLanguages];
|
|
42
|
+
if (Array.isArray(input['fenceLanguages'])) {
|
|
43
|
+
const filtered = [];
|
|
44
|
+
for (const item of input['fenceLanguages']) {
|
|
45
|
+
if (typeof item === 'string' && supported.has(item) && !filtered.includes(item)) {
|
|
46
|
+
filtered.push(item);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
fenceLanguages = filtered;
|
|
50
|
+
}
|
|
51
|
+
const defaultView = input['defaultView'] === 'code' ? 'code' : 'preview';
|
|
52
|
+
const clampInt = (value, min, max, fallback) => {
|
|
53
|
+
if (typeof value !== 'number' || !Number.isInteger(value))
|
|
54
|
+
return fallback;
|
|
55
|
+
return Math.min(max, Math.max(min, value));
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
enableFencePreview: typeof input['enableFencePreview'] === 'boolean'
|
|
59
|
+
? input['enableFencePreview']
|
|
60
|
+
: DEFAULT_RENDERER_CONFIG.enableFencePreview,
|
|
61
|
+
fenceLanguages,
|
|
62
|
+
defaultView,
|
|
63
|
+
allowExternalResources: typeof input['allowExternalResources'] === 'boolean'
|
|
64
|
+
? input['allowExternalResources']
|
|
65
|
+
: DEFAULT_RENDERER_CONFIG.allowExternalResources,
|
|
66
|
+
enableWorkbench: typeof input['enableWorkbench'] === 'boolean'
|
|
67
|
+
? input['enableWorkbench']
|
|
68
|
+
: DEFAULT_RENDERER_CONFIG.enableWorkbench,
|
|
69
|
+
complexContentToSidebar: typeof input['complexContentToSidebar'] === 'boolean'
|
|
70
|
+
? input['complexContentToSidebar']
|
|
71
|
+
: DEFAULT_RENDERER_CONFIG.complexContentToSidebar,
|
|
72
|
+
enableArtifactTool: typeof input['enableArtifactTool'] === 'boolean'
|
|
73
|
+
? input['enableArtifactTool']
|
|
74
|
+
: DEFAULT_RENDERER_CONFIG.enableArtifactTool,
|
|
75
|
+
autoOpenArtifact: typeof input['autoOpenArtifact'] === 'boolean'
|
|
76
|
+
? input['autoOpenArtifact']
|
|
77
|
+
: DEFAULT_RENDERER_CONFIG.autoOpenArtifact,
|
|
78
|
+
enableTurnMediaFallback: typeof input['enableTurnMediaFallback'] === 'boolean'
|
|
79
|
+
? input['enableTurnMediaFallback']
|
|
80
|
+
: DEFAULT_RENDERER_CONFIG.enableTurnMediaFallback,
|
|
81
|
+
bridgeToolDataImages: typeof input['bridgeToolDataImages'] === 'boolean'
|
|
82
|
+
? input['bridgeToolDataImages']
|
|
83
|
+
: DEFAULT_RENDERER_CONFIG.bridgeToolDataImages,
|
|
84
|
+
maxContentBytes: clampInt(input['maxContentBytes'], 1024, 16_777_216, DEFAULT_RENDERER_CONFIG.maxContentBytes),
|
|
85
|
+
inlineMaxHeight: clampInt(input['inlineMaxHeight'], 120, 2400, DEFAULT_RENDERER_CONFIG.inlineMaxHeight),
|
|
86
|
+
maxActiveSandboxes: clampInt(input['maxActiveSandboxes'], 1, 32, DEFAULT_RENDERER_CONFIG.maxActiveSandboxes),
|
|
87
|
+
};
|
|
88
|
+
}
|