@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
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Non-destructive prose media extractor for the `conversation.chat.turnTail` fallback.
3
+ *
4
+ * DSH's built-in `MarkdownText` currently rejects `data:image/*` Markdown image
5
+ * destinations and renders raw HTML (`<img>`, `<svg>`) as literal escaped text.
6
+ * This module scans Assistant prose *outside* code fences and inline code spans
7
+ * to recover those visual items without duplicating fenced `html`/`svg` blocks.
8
+ *
9
+ * @module dsh-renderer/shared/media-extractor
10
+ */
11
+ import { prepareSvgForImage, utf8ByteLength } from './sanitize.js';
12
+ const SAFE_DATA_IMAGE_URI_RE = /^data:image\/(?:png|jpeg|jpg|gif|webp|bmp|x-icon|vnd\.microsoft\.icon|svg\+xml)(?:;[^,\s)]*)?,[^\s)]+$/i;
13
+ const SAFE_HTTP_IMAGE_URI_RE = /^https?:\/\/[^\s"'<>]+$/i;
14
+ /**
15
+ * Blank out fenced code blocks (`` ``` `` or `~~~`) and inline code spans (`` `...` ``)
16
+ * while preserving string length so downstream prose scanning never matches code examples
17
+ * or fences already handled by `conversation.chat.markdown.fence`.
18
+ */
19
+ export function stripMarkdownCode(markdown) {
20
+ const lines = markdown.split('\n');
21
+ const outLines = [];
22
+ let fenceChar = null;
23
+ let fenceLen = 0;
24
+ for (const line of lines) {
25
+ if (fenceChar === null) {
26
+ const open = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
27
+ if (open !== null) {
28
+ fenceChar = open[1][0];
29
+ fenceLen = open[1].length;
30
+ outLines.push('');
31
+ continue;
32
+ }
33
+ // Blank inline code spans on non-fence lines.
34
+ outLines.push(stripInlineCodeSpans(line));
35
+ }
36
+ else {
37
+ const close = /^\s{0,3}(`{3,}|~{3,})\s*$/.exec(line);
38
+ if (close !== null && close[1][0] === fenceChar && close[1].length >= fenceLen) {
39
+ fenceChar = null;
40
+ fenceLen = 0;
41
+ }
42
+ outLines.push('');
43
+ }
44
+ }
45
+ return outLines.join('\n');
46
+ }
47
+ function stripInlineCodeSpans(line) {
48
+ let out = '';
49
+ let i = 0;
50
+ while (i < line.length) {
51
+ if (line[i] !== '`') {
52
+ out += line[i];
53
+ i += 1;
54
+ continue;
55
+ }
56
+ let tickCount = 0;
57
+ while (i + tickCount < line.length && line[i + tickCount] === '`') {
58
+ tickCount += 1;
59
+ }
60
+ const closer = '`'.repeat(tickCount);
61
+ const closeIdx = line.indexOf(closer, i + tickCount);
62
+ if (closeIdx === -1) {
63
+ out += line.slice(i, i + tickCount);
64
+ i += tickCount;
65
+ }
66
+ else {
67
+ out += ' ';
68
+ i = closeIdx + tickCount;
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+ /** Read an HTML attribute value (quoted or unquoted) from a single tag string. */
74
+ function readTagAttr(tagSource, attrName) {
75
+ const re = new RegExp(`\\b${attrName}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\\x60]+))`, 'i');
76
+ const match = re.exec(tagSource);
77
+ if (match === null)
78
+ return undefined;
79
+ return match[1] ?? match[2] ?? match[3];
80
+ }
81
+ /**
82
+ * Extract fallback media items (`data:image/*` Markdown images, raw HTML `<img>` tags,
83
+ * and raw inline `<svg>...</svg>` blocks) from Assistant prose.
84
+ *
85
+ * Returns items in document appearance order, deduplicated and bounded by `maxContentBytes`
86
+ * and `maxItems`.
87
+ */
88
+ export function extractFallbackMedia(markdown, options) {
89
+ const maxItems = options.maxItems ?? 12;
90
+ if (markdown.length === 0 || maxItems <= 0)
91
+ return [];
92
+ const prose = stripMarkdownCode(markdown);
93
+ const candidates = [];
94
+ const seen = new Set();
95
+ const pushUnique = (index, item) => {
96
+ if (seen.has(item.key))
97
+ return;
98
+ if (utf8ByteLength(item.source) > options.maxContentBytes)
99
+ return;
100
+ seen.add(item.key);
101
+ candidates.push({ index, item });
102
+ };
103
+ // 1. Markdown data:image/* images: `![alt](data:image/...)` or `![alt](<data:image/...>)`.
104
+ const mdDataImgRe = /!\[([^\]]*)\]\(\s*<?(data:image\/[^)\s>]+)>?(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/gi;
105
+ for (const match of prose.matchAll(mdDataImgRe)) {
106
+ const rawUrl = (match[2] ?? '').trim();
107
+ if (!SAFE_DATA_IMAGE_URI_RE.test(rawUrl))
108
+ continue;
109
+ const alt = (match[1] ?? '').trim() || 'Image';
110
+ pushUnique(match.index ?? 0, {
111
+ key: `img:${rawUrl}`,
112
+ kind: 'image',
113
+ source: rawUrl,
114
+ alt,
115
+ });
116
+ }
117
+ // 2. Raw HTML `<img ...>` tags (which DSH's MarkdownText renders as literal text).
118
+ const htmlImgRe = /<img\b[^>]*>/gi;
119
+ for (const match of prose.matchAll(htmlImgRe)) {
120
+ const tag = match[0];
121
+ const src = readTagAttr(tag, 'src')?.trim();
122
+ if (src === undefined || src.length === 0)
123
+ continue;
124
+ if (!SAFE_DATA_IMAGE_URI_RE.test(src) && !SAFE_HTTP_IMAGE_URI_RE.test(src))
125
+ continue;
126
+ const alt = readTagAttr(tag, 'alt')?.trim() || readTagAttr(tag, 'title')?.trim() || 'Image';
127
+ pushUnique(match.index ?? 0, {
128
+ key: `img:${src}`,
129
+ kind: 'image',
130
+ source: src,
131
+ alt,
132
+ });
133
+ }
134
+ // 3. Raw inline `<svg ...>...</svg>` blocks outside fences.
135
+ const inlineSvgRe = /<svg\b[\s\S]*?<\/svg>/gi;
136
+ for (const match of prose.matchAll(inlineSvgRe)) {
137
+ const rawSvg = match[0];
138
+ if (utf8ByteLength(rawSvg) > options.maxContentBytes)
139
+ continue;
140
+ const prepared = prepareSvgForImage(rawSvg);
141
+ if (prepared === null)
142
+ continue;
143
+ const titleMatch = /<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(prepared);
144
+ const alt = titleMatch?.[1]?.trim() || 'SVG graphic';
145
+ pushUnique(match.index ?? 0, {
146
+ key: `svg:${prepared}`,
147
+ kind: 'svg',
148
+ source: prepared,
149
+ alt,
150
+ });
151
+ }
152
+ candidates.sort((a, b) => a.index - b.index);
153
+ return candidates.slice(0, maxItems).map((entry) => entry.item);
154
+ }
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Pure runtime state primitives shared by the sandbox iframe host and Artifact workbench:
3
+ * - LRU pool capping concurrently active interactive sandboxes
4
+ * - Strict `postMessage` frame parser with token verification and height clamping
5
+ * - Session-aware in-memory Artifact store with subscription support
6
+ *
7
+ * @module dsh-renderer/shared/sandbox-core
8
+ */
9
+ /**
10
+ * Validate and parse a `MessageEvent.data` payload from a sandboxed iframe.
11
+ *
12
+ * Rejects anything whose `token` does not match the instance's secret token or
13
+ * whose `type` is outside the explicit two-event allowlist (`resize` / `error`).
14
+ */
15
+ export function parseSandboxMessage(data, expectedToken, minHeight, maxHeight) {
16
+ if (data === null || typeof data !== 'object')
17
+ return null;
18
+ const record = data;
19
+ if (record['token'] !== expectedToken)
20
+ return null;
21
+ if (record['type'] === 'dsh-renderer:resize') {
22
+ const rawHeight = record['height'];
23
+ if (typeof rawHeight !== 'number' || !Number.isFinite(rawHeight) || rawHeight <= 0) {
24
+ return null;
25
+ }
26
+ const clamped = Math.min(maxHeight, Math.max(minHeight, Math.ceil(rawHeight)));
27
+ return { type: 'resize', height: clamped };
28
+ }
29
+ if (record['type'] === 'dsh-renderer:error') {
30
+ const rawMessage = record['message'];
31
+ if (typeof rawMessage !== 'string')
32
+ return null;
33
+ const trimmed = rawMessage.trim().slice(0, 500);
34
+ return trimmed.length > 0 ? { type: 'error', message: trimmed } : null;
35
+ }
36
+ return null;
37
+ }
38
+ /**
39
+ * LRU pool that bounds the number of simultaneously live interactive iframe sandboxes.
40
+ *
41
+ * Activating a new sandbox past `capacity` puts the least-recently-used sandbox
42
+ * to sleep via its registered `onSleep` callback so memory and Blob URLs stay bounded
43
+ * across long conversations.
44
+ */
45
+ export class SandboxLruPool {
46
+ capacity;
47
+ active = new Map();
48
+ constructor(capacity) {
49
+ this.capacity = Math.max(1, Math.floor(capacity));
50
+ }
51
+ /** Mark `id` active (or refresh its recency) and evict the oldest entry when full. */
52
+ activate(id, onSleep) {
53
+ if (this.active.has(id)) {
54
+ this.active.delete(id);
55
+ this.active.set(id, onSleep);
56
+ return;
57
+ }
58
+ while (this.active.size >= this.capacity) {
59
+ const oldestKey = this.active.keys().next().value;
60
+ if (oldestKey === undefined)
61
+ break;
62
+ const sleep = this.active.get(oldestKey);
63
+ this.active.delete(oldestKey);
64
+ try {
65
+ sleep?.();
66
+ }
67
+ catch {
68
+ // One misbehaving callback must never stall eviction of other sandboxes.
69
+ }
70
+ }
71
+ this.active.set(id, onSleep);
72
+ }
73
+ /** Refresh recency of an already active sandbox without changing its callback. */
74
+ touch(id) {
75
+ const existing = this.active.get(id);
76
+ if (existing === undefined)
77
+ return;
78
+ this.active.delete(id);
79
+ this.active.set(id, existing);
80
+ }
81
+ /** Remove `id` from the pool without invoking its sleep callback (e.g. normal unmount). */
82
+ release(id) {
83
+ this.active.delete(id);
84
+ }
85
+ /** Put every active sandbox to sleep and clear the pool (e.g. plugin teardown). */
86
+ sleepAll() {
87
+ const callbacks = [...this.active.values()];
88
+ this.active.clear();
89
+ for (const sleep of callbacks) {
90
+ try {
91
+ sleep();
92
+ }
93
+ catch {
94
+ // Keep tearing down remaining sandboxes even if one throws.
95
+ }
96
+ }
97
+ }
98
+ /** Whether `id` is currently active in the pool. */
99
+ isActive(id) {
100
+ return this.active.has(id);
101
+ }
102
+ /** Current number of active sandboxes. */
103
+ size() {
104
+ return this.active.size;
105
+ }
106
+ }
107
+ /** Resource protocol name owned by `@aqian0/dsh-renderer` (`dsh-resource://dsh-renderer/...`). */
108
+ export const ARTIFACT_RESOURCE_PROTOCOL = 'dsh-renderer';
109
+ /** Resource URI prefix used for in-memory / fence-backed right-Sidebar artifact tabs. */
110
+ export const ARTIFACT_RESOURCE_PREFIX = 'dsh-resource://dsh-renderer/artifact/';
111
+ /** Resource URI prefix used for durable Session-backed `render_artifact` tool-call tabs. */
112
+ export const ARTIFACT_CALL_RESOURCE_PREFIX = 'dsh-resource://dsh-renderer/call/';
113
+ /** Build a canonical `dsh-resource://` address for one Artifact id. */
114
+ export function artifactAddressFor(id) {
115
+ return `${ARTIFACT_RESOURCE_PREFIX}${encodeURIComponent(id)}`;
116
+ }
117
+ /** Extract the Artifact id from a `dsh-resource://dsh-renderer/artifact/<id>` address. */
118
+ export function parseArtifactAddress(address) {
119
+ if (!address.startsWith(ARTIFACT_RESOURCE_PREFIX))
120
+ return null;
121
+ const raw = address.slice(ARTIFACT_RESOURCE_PREFIX.length);
122
+ if (raw.length === 0 || raw.includes('/') || raw.includes('?') || raw.includes('#'))
123
+ return null;
124
+ try {
125
+ const decoded = decodeURIComponent(raw);
126
+ return decoded.length > 0 ? decoded : null;
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ }
132
+ /** Build a durable Session-backed `dsh-resource://` address for one `render_artifact` call. */
133
+ export function artifactCallAddressFor(target) {
134
+ const { session, callId } = target;
135
+ const parts = session.kind === 'session'
136
+ ? [session.sessionId, callId]
137
+ : ['subagent', session.parentSessionId, session.childSessionId, session.mode, callId];
138
+ return `${ARTIFACT_CALL_RESOURCE_PREFIX}${parts.map(encodeURIComponent).join('/')}`;
139
+ }
140
+ /** Parse and validate a durable `dsh-resource://dsh-renderer/call/...` address. */
141
+ export function parseArtifactCallAddress(address) {
142
+ if (!address.startsWith(ARTIFACT_CALL_RESOURCE_PREFIX))
143
+ return null;
144
+ const raw = address.slice(ARTIFACT_CALL_RESOURCE_PREFIX.length);
145
+ if (raw.length === 0 || raw.includes('?') || raw.includes('#'))
146
+ return null;
147
+ try {
148
+ const parts = raw.split('/').map((part) => decodeURIComponent(part));
149
+ if (parts.some((part) => part.length === 0))
150
+ return null;
151
+ if (parts.length === 2) {
152
+ return {
153
+ session: { kind: 'session', sessionId: parts[0] },
154
+ callId: parts[1],
155
+ };
156
+ }
157
+ if (parts.length === 5 &&
158
+ parts[0] === 'subagent' &&
159
+ (parts[3] === 'one-shot' || parts[3] === 'continuable' || parts[3] === 'unknown')) {
160
+ return {
161
+ session: {
162
+ kind: 'subagent',
163
+ parentSessionId: parts[1],
164
+ childSessionId: parts[2],
165
+ mode: parts[3],
166
+ },
167
+ callId: parts[4],
168
+ };
169
+ }
170
+ return null;
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ /** Return whether `address` is a well-formed artifact or call resource owned by `@aqian0/dsh-renderer`. */
177
+ export function isArtifactResourceAddress(address) {
178
+ return parseArtifactAddress(address) !== null || parseArtifactCallAddress(address) !== null;
179
+ }
180
+ /**
181
+ * Bounded in-memory store for Artifacts opened in the right Sidebar workbench
182
+ * or fullscreen modal fallback.
183
+ */
184
+ export class ArtifactStore {
185
+ maxEntries;
186
+ records = new Map();
187
+ addressIndex = new Map();
188
+ listeners = new Set();
189
+ modalArtifactId = null;
190
+ seq = 0;
191
+ constructor(maxEntries = 64) {
192
+ this.maxEntries = Math.max(1, Math.floor(maxEntries));
193
+ }
194
+ /** Insert or update an artifact, returning the stored record. */
195
+ put(input) {
196
+ const id = input.id ?? `a-${++this.seq}`;
197
+ const address = input.address ?? artifactAddressFor(id);
198
+ const record = {
199
+ id,
200
+ address,
201
+ kind: input.kind,
202
+ lang: input.lang,
203
+ title: input.title,
204
+ code: input.code,
205
+ sessionId: input.sessionId,
206
+ };
207
+ const previous = this.records.get(id);
208
+ if (previous !== undefined) {
209
+ this.records.delete(id);
210
+ if (this.addressIndex.get(previous.address) === id) {
211
+ this.addressIndex.delete(previous.address);
212
+ }
213
+ }
214
+ else {
215
+ while (this.records.size >= this.maxEntries) {
216
+ const oldest = this.records.keys().next().value;
217
+ if (oldest === undefined)
218
+ break;
219
+ const evicted = this.records.get(oldest);
220
+ this.records.delete(oldest);
221
+ if (evicted !== undefined && this.addressIndex.get(evicted.address) === oldest) {
222
+ this.addressIndex.delete(evicted.address);
223
+ }
224
+ }
225
+ }
226
+ this.records.set(id, record);
227
+ this.addressIndex.set(address, id);
228
+ this.emit();
229
+ return record;
230
+ }
231
+ /** Look up one artifact by id. */
232
+ get(id) {
233
+ return this.records.get(id);
234
+ }
235
+ /** Look up one artifact by its `dsh-resource://` address (`/artifact/...` or `/call/...`). */
236
+ getByAddress(address) {
237
+ const indexedId = this.addressIndex.get(address);
238
+ if (indexedId !== undefined) {
239
+ return this.records.get(indexedId);
240
+ }
241
+ const id = parseArtifactAddress(address);
242
+ return id === null ? undefined : this.records.get(id);
243
+ }
244
+ /** Open an artifact inside the fullscreen modal fallback. */
245
+ openModal(id) {
246
+ if (!this.records.has(id))
247
+ return;
248
+ this.modalArtifactId = id;
249
+ this.emit();
250
+ }
251
+ /** Close the fullscreen modal fallback. */
252
+ closeModal() {
253
+ if (this.modalArtifactId === null)
254
+ return;
255
+ this.modalArtifactId = null;
256
+ this.emit();
257
+ }
258
+ /** Current artifact displayed in the fullscreen modal fallback, if any. */
259
+ getModalArtifact() {
260
+ return this.modalArtifactId === null ? undefined : this.records.get(this.modalArtifactId);
261
+ }
262
+ /** Subscribe to store updates (`useSyncExternalStore` compatible). */
263
+ subscribe(listener) {
264
+ this.listeners.add(listener);
265
+ return () => {
266
+ this.listeners.delete(listener);
267
+ };
268
+ }
269
+ /** Drop all artifacts and listeners on plugin teardown. */
270
+ clear() {
271
+ this.records.clear();
272
+ this.addressIndex.clear();
273
+ this.modalArtifactId = null;
274
+ this.emit();
275
+ }
276
+ emit() {
277
+ for (const listener of this.listeners) {
278
+ try {
279
+ listener();
280
+ }
281
+ catch {
282
+ // Isolate subscriber errors.
283
+ }
284
+ }
285
+ }
286
+ }