length-extrapolating-architecture-data / dev /code_Nagi-ovo__dsh-visualize.txt
ag2003's picture
Upload folder using huggingface_hub
5b48487 verified
Raw History Blame Contribute Delete
100 kB
# ===== file: lib/client.js ===== window.__ModuleLoader__.load({ id: "@nagi-ovo/dsh-visualize", factory: (require) => { var module = { exports: {} }; var exports = module.exports; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); let react = require("react"); let react_jsx_runtime = require("react/jsx-runtime"); /** * Narrow one persisted `tool/result` meta value to a {@link VisualizeMeta}. * Wire data cannot be trusted to match the compiled shape (an older or newer * host may have logged it), so a mismatch declines to `undefined` — the caller * falls back to the generic presentation instead of throwing on replay. * @param meta - the raw persisted meta value. * @returns the narrowed descriptor, or `undefined` for the generic path. */ function visualizeMetaFrom(meta) { if (typeof meta !== "object" || meta === null) return void 0; const record = meta; if (record["kind"] !== "visualize") return void 0; const { fragment, title, mode, path } = record; if (typeof fragment !== "string" || typeof title !== "string" || typeof path !== "string") return void 0; if (mode !== "inline" && mode !== "wide") return void 0; return { kind: "visualize", fragment, title, mode, path }; } /** * Rebuild a descriptor from the call's own arguments when persisted meta is * missing. Nested dispatches (`run_code` / PTC) never project presentation * meta, but they do log `arguments`; a create's fragment is in that JSON. * * An `update` without a fragment cannot be rebuilt from the wire (the patched * markup lives in execute's value, which nested logs do not keep) and * declines. Incomplete streaming JSON is not parsed via throw/catch: only a * trailing `}` is treated as complete, otherwise a *closed* `"fragment"` * string is taken through {@link extractStreamingFragment}'s scanner. * @param argsRaw - running `block.argsRaw` or settled `block.call.argsRaw`. * @returns a card descriptor, or `undefined` to keep the quiet fallback. */ function visualizeMetaFromArgs(argsRaw) { if (typeof argsRaw !== "string" || argsRaw.length === 0) return void 0; const complete = parseCompleteArgs(argsRaw); if (complete !== void 0) { if (complete["action"] === "update" && typeof complete["fragment"] !== "string") return void 0; return descriptorFromFields(complete["fragment"], complete["title"], complete["mode"], complete["path"]); } const closed = scanFragment(argsRaw, true); if (closed === void 0) return void 0; return descriptorFromFields(closed, void 0, void 0, void 0); } /** * Accept only a complete JSON object, gated on a trailing `}` so a streaming * prefix never enters `JSON.parse`. * @param raw - accumulated argument text. * @returns the object, or `undefined` when the prefix is incomplete or illegal. */ function parseCompleteArgs(raw) { let end = raw.length; while (end > 0) { const ch = raw[end - 1]; if (ch === " " || ch === "\n" || ch === "\r" || ch === " ") { end -= 1; continue; } break; } if (end === 0 || raw[end - 1] !== "}") return void 0; try { const parsed = JSON.parse(raw.slice(0, end)); if (typeof parsed !== "object" || parsed === null) return void 0; return parsed; } catch { return; } } /** * Narrow wire fields into a descriptor. Empty markup after dropping a * trailing half-script is declined rather than mounting a blank frame. */ function descriptorFromFields(fragment, title, mode, path) { if (typeof fragment !== "string") return void 0; if (mode !== void 0 && mode !== "inline" && mode !== "wide") return void 0; const markup = trimStreamingScripts(fragment); if (markup.trim().length === 0) return void 0; return { kind: "visualize", fragment: markup, title: typeof title === "string" && title.trim().length > 0 ? title.trim() : "Visualization", mode: mode === "wide" ? "wide" : "inline", path: typeof path === "string" ? path : "" }; } /** JSON short escapes, keyed by the character after the backslash. */ const JSON_ESCAPES = { "\"": "\"", "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: " " }; /** * Extract the `fragment` string value from a *possibly incomplete* streaming * tool-call JSON argument prefix. The streaming preview calls this on every * accumulated delta: it scans for the `"fragment":"` opener, then unescapes * characters until the (possibly absent) closing quote, dropping a trailing * half-finished escape sequence rather than misreading it. * @param argsRaw - the accumulated raw argument text, valid JSON or a prefix. * @returns the fragment decoded so far, or `undefined` before the opener streams in. */ function extractStreamingFragment(argsRaw) { return scanFragment(argsRaw, false); } /** * Walk a possibly incomplete `"fragment":"...` value. * @param argsRaw - accumulated argument text. * @param requireClosed - when true, decline until the closing quote arrives * (the settled-card fallback must not mount on a half-streamed string). * @returns the decoded fragment, or `undefined` when the opener is absent * or, if required, the string is still open. */ function scanFragment(argsRaw, requireClosed) { const opener = /"fragment"\s*:\s*"/u.exec(argsRaw); if (!opener) return void 0; let out = ""; for (let i = opener.index + opener[0].length; i < argsRaw.length; i++) { const ch = argsRaw[i]; if (ch === "\"") return out; if (ch !== "\\") { out += ch; continue; } const next = argsRaw[i + 1]; if (next === void 0) return requireClosed ? void 0 : out; if (next === "u") { const hex = argsRaw.slice(i + 2, i + 6); if (hex.length < 4) return requireClosed ? void 0 : out; const code = Number.parseInt(hex, 16); if (Number.isNaN(code)) return requireClosed ? void 0 : out; out += String.fromCharCode(code); i += 5; continue; } const short = JSON_ESCAPES[next]; if (short === void 0) return requireClosed ? void 0 : out; out += short; i += 1; } return requireClosed ? void 0 : out; } /** Matches the last script opener (complete or still missing its `>`). */ const LAST_SCRIPT_OPEN = /<script\b[^>]*>?(?![\s\S]*<script\b)/iu; /** * Prepare a streamed fragment prefix for the live preview: complete * `<script>…<\/script>` blocks are kept — they are finished JavaScript the * preview shell executes on arrival, which is how a script-drawn chart paints * during generation — while a trailing block whose `<\/script>` has not * streamed in yet is dropped whole (a half-streamed body is almost never * valid JavaScript). * @param fragment - the fragment prefix streamed so far. * @returns the preview-safe markup. */ function trimStreamingScripts(fragment) { const opener = LAST_SCRIPT_OPEN.exec(fragment); if (!opener) return fragment; const rest = fragment.slice(opener.index + opener[0].length); return /<\/script\s*>/iu.test(rest) ? fragment : fragment.slice(0, opener.index); } //#endregion //#region src/frame-css.ts /** * The stylesheet injected into every visualization frame: theme tokens with * host-bridged overrides, a minimal reset, and the base-class vocabulary the * bundled skill teaches (`.card`, `.btn`, `.viz-*`, form utilities). Kept as a * TS string so the browser bundle needs no CSS loader and the node-side specs * can assert against it. * * Token contract: every `--<name>` here is declared as * `var(--dsh-viz-<name>, <fallback>)`. The card resolves the host palette * (DSH `--dsw-alias-*` design tokens, whale-blue accent included) and injects * the `--dsh-viz-*` values on the frame's `:root`; outside DSH the fallbacks * keep the frame legible in both appearances via `light-dark()`. * * @module @nagi-ovo/dsh-visualize/frame-css */ /** The frame stylesheet, inlined into the sandboxed srcdoc document. */ const FRAME_CSS = ` :root { color-scheme: light dark; --background: var(--dsh-viz-background, transparent); --foreground: var(--dsh-viz-foreground, light-dark(rgb(26 28 31), rgb(240 242 245))); --card: var(--dsh-viz-card, light-dark(rgb(0 0 0 / 4%), rgb(255 255 255 / 6%))); --card-foreground: var(--dsh-viz-foreground, light-dark(rgb(26 28 31), rgb(240 242 245))); --muted-foreground: var(--dsh-viz-muted-foreground, light-dark(rgb(26 28 31 / 55%), rgb(240 242 245 / 55%))); --border: var(--dsh-viz-border, light-dark(rgb(0 0 0 / 10%), rgb(255 255 255 / 12%))); --primary: var(--dsh-viz-primary, light-dark(rgb(65 118 230), rgb(110 150 240))); --primary-foreground: var(--dsh-viz-primary-foreground, light-dark(rgb(255 255 255), rgb(13 13 13))); --viz-series-1: var(--dsh-viz-primary, light-dark(rgb(65 118 230), rgb(110 150 240))); --viz-series-2: light-dark(rgb(226 116 26), rgb(245 152 66)); --viz-series-3: light-dark(rgb(16 148 82), rgb(72 196 130)); --viz-series-4: light-dark(rgb(146 94 220), rgb(176 132 240)); --viz-series-5: light-dark(rgb(212 66 84), rgb(240 110 126)); --viz-series-6: light-dark(rgb(160 138 22), rgb(206 182 70)); --radius: 8px; --font-size-base: 14px; } * { box-sizing: border-box; } html, body { margin: 0; padding: 0; } body { background: var(--background); color: var(--foreground); font: 400 var(--font-size-base)/1.5 system-ui, -apple-system, 'Segoe UI', sans-serif; } h1, h2, h3 { margin: 0 0 0.5em; font-weight: 500; line-height: 1.3; } h1 { font-size: 1.3em; } h2 { font-size: 1.15em; } h3 { font-size: 1em; } p { margin: 0 0 0.75em; } a { color: var(--primary); } svg text { fill: var(--foreground); font-size: 12px; } .text-small { font-size: 12px; color: var(--muted-foreground); } .card { background: var(--card); color: var(--card-foreground); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px 14px; } .btn { appearance: none; display: inline-flex; align-items: center; gap: 6px; padding: 5px 12px; border: 1px solid var(--border); border-radius: var(--radius); background: transparent; color: var(--foreground); font: inherit; cursor: pointer; } .btn:hover { background: color-mix(in oklab, var(--foreground) 6%, transparent); } .btn-primary, .btn[aria-pressed='true'], .btn[aria-selected='true'], .btn.is-selected { background: var(--primary); border-color: var(--primary); color: var(--primary-foreground); } .btn-ghost { border-color: transparent; } .btn:disabled { opacity: 0.5; cursor: default; } .viz-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; } .viz-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } .viz-controls { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; margin-bottom: 12px; } .viz-stat .viz-stat-label, .viz-stat > :first-child { font-size: 12px; color: var(--muted-foreground); } .viz-stat-value { font-size: 1.4em; font-weight: 500; line-height: 1.2; } .viz-badge { display: inline-block; padding: 1px 8px; border-radius: 999px; background: color-mix(in oklab, var(--primary) 14%, transparent); color: var(--primary); font-size: 12px; } .form-label { display: block; font-size: 12px; color: var(--muted-foreground); margin-bottom: 4px; } .form-control, .form-select { width: 100%; padding: 5px 10px; border: 1px solid var(--border); border-radius: var(--radius); background: transparent; color: var(--foreground); font: inherit; } .form-check { display: flex; align-items: center; gap: 6px; } .form-check input { accent-color: var(--primary); } input[type='range'] { accent-color: var(--primary); } table { border-collapse: collapse; width: 100%; } th, td { text-align: left; padding: 5px 10px; border-bottom: 1px solid var(--border); } th { font-weight: 500; color: var(--muted-foreground); font-size: 12px; } .table-responsive { overflow-x: auto; } `; const RESOURCE_SOURCES = [ "blob:", "data:", ...[ "https://cdnjs.cloudflare.com", "https://cdn.jsdelivr.net", "https://esm.sh", "https://fonts.bunny.net", "https://fonts.googleapis.com", "https://fonts.gstatic.com", "https://unpkg.com" ] ].join(" "); /** The frame document's Content-Security-Policy. */ const FRAME_CSP = [ "default-src 'none'", `script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${RESOURCE_SOURCES}`, `style-src 'unsafe-inline' ${RESOURCE_SOURCES}`, `img-src ${RESOURCE_SOURCES}`, `font-src ${RESOURCE_SOURCES}`, `media-src ${RESOURCE_SOURCES}`, "worker-src blob:", "connect-src blob: data:", "frame-src 'none'", "object-src 'none'", "base-uri 'none'", "form-action 'none'" ].join("; "); /** Wire type of the frame→card height report message. */ const HEIGHT_MESSAGE_TYPE = "dsh-visualize:height"; /** Wire type of the card→frame streaming fragment update message. */ const STREAM_MESSAGE_TYPE = "dsh-visualize:stream"; /** * Assemble the complete srcdoc document for one visualization frame. * @param options - fragment, title, bridged palette, and report token. * @returns the HTML document string for the iframe's `srcDoc`. */ function buildFrameDoc(options) { const rootVars = Object.entries(options.themeVars).map(([name, value]) => [name, sanitizeCssValue(value)]).filter(([, value]) => value.length > 0).map(([name, value]) => `--dsh-viz-${name}: ${value};`).join(" "); return `<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="referrer" content="no-referrer"> <meta http-equiv="Content-Security-Policy" content="${FRAME_CSP}"> <title>${escapeHtml(options.title)}</title> <style>${FRAME_CSS} :root { ${rootVars} color-scheme: ${options.colorScheme}; } body { padding: 4px 2px; }</style> </head> <body> ${options.fragment} <script>${heightReporter(options.reportToken)}<\/script> </body> </html> `; } /** * The frame-side height reporter: posts the document's scroll height to the * parent on load and on every resize, so the card can size the iframe to its * content (a sandboxed frame's document is unreachable from the parent). * @param reportToken - correlation token echoed in each message. * @returns the inline script body. */ function heightReporter(reportToken) { const token = JSON.stringify(reportToken); return ` (function () { var post = function () { parent.postMessage({ type: ${JSON.stringify(HEIGHT_MESSAGE_TYPE)}, token: ${token}, height: document.documentElement.scrollHeight, }, '*'); }; new ResizeObserver(post).observe(document.documentElement); addEventListener('load', post); post(); })(); `; } /** * Assemble the persistent streaming shell: an initially empty document that * receives fragment prefixes over `postMessage` and syncs them into its DOM * incrementally — unchanged elements persist (no reload churn) and newly * arrived elements float in via an enter animation, the Claude-style * component-by-component reveal. Scripts inside synced markup stay inert by * the `innerHTML` parsing rule, which is exactly right for a half-generated * fragment; the settled card runs the finished scripts. * @param options - bridged palette, scheme, and correlation token (fragment is ignored). * @returns the HTML document string for the preview iframe's `srcDoc`. */ function buildStreamShellDoc(options) { return buildFrameDoc({ ...options, title: "Streaming preview", fragment: `<div id="dsh-viz-stream-root"></div> <style> .dsh-viz-enter { animation: dsh-viz-enter 0.4s cubic-bezier(0.2, 0.7, 0.3, 1) both; } @keyframes dsh-viz-enter { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } } </style> <script>${streamSync(options.reportToken)}<\/script>` }); } /** * The frame-side incremental DOM sync: parses each posted fragment prefix * into a detached tree and reconciles it against the live root by child * index — same tag syncs attributes and recurses, a mismatch replaces, a new * node appends with the enter class, extras drop. Index-based reconciliation * is exact for streamed markup, which only ever grows or refines its tail. * @param reportToken - correlation token accepted on incoming messages. * @returns the inline script body. */ function streamSync(reportToken) { return ` (function () { var root = document.getElementById('dsh-viz-stream-root'); var token = ${JSON.stringify(reportToken)}; function syncAttrs(cur, next) { var i, attrs = cur.attributes; for (i = attrs.length - 1; i >= 0; i--) { if (!next.hasAttribute(attrs[i].name)) cur.removeAttribute(attrs[i].name); } attrs = next.attributes; for (i = 0; i < attrs.length; i++) { if (cur.getAttribute(attrs[i].name) !== attrs[i].value) cur.setAttribute(attrs[i].name, attrs[i].value); } } function executable(node) { // Scripts parsed via innerHTML are permanently inert; an executable clone // runs on insertion. Streamed markup only ever appends, so each complete // script block arrives at its index exactly once and runs exactly once. var script = document.createElement('script'); for (var i = 0; i < node.attributes.length; i++) { script.setAttribute(node.attributes[i].name, node.attributes[i].value); } script.textContent = node.textContent; return script; } function sync(cur, next) { var want = next.childNodes, have = cur.childNodes, i; for (i = 0; i < want.length; i++) { var target = want[i], live = have[i]; if (live === undefined) { var added = target.nodeName === 'SCRIPT' ? executable(target) : target.cloneNode(true); if (added.nodeType === 1 && added.nodeName !== 'SCRIPT') added.classList.add('dsh-viz-enter'); cur.appendChild(added); continue; } if (live.nodeType !== target.nodeType || live.nodeName !== target.nodeName) { cur.replaceChild(target.cloneNode(true), live); continue; } if (live.nodeType === 3 || live.nodeType === 8) { if (live.nodeValue !== target.nodeValue) live.nodeValue = target.nodeValue; continue; } if (live.nodeType === 1) { syncAttrs(live, target); sync(live, target); } } while (cur.childNodes.length > want.length) cur.removeChild(cur.lastChild); } addEventListener('message', function (event) { var data = event.data; if (!data || data.type !== ${JSON.stringify(STREAM_MESSAGE_TYPE)} || data.token !== token) return; if (typeof data.fragment !== 'string') return; var next = document.createElement('div'); next.innerHTML = data.fragment; sync(root, next); }); })(); `; } /** * Keep one bridged palette value inert inside a style block: resolved * computed-style colors never contain declaration or block delimiters, so any * occurrence marks a malformed value, dropped rather than repaired. * @param value - the raw computed-style value. * @returns the trimmed value, or empty when it must be dropped. */ function sanitizeCssValue(value) { const trimmed = value.trim(); return /[;{}<>]/u.test(trimmed) ? "" : trimmed; } /** * Minimal HTML text escape for the frame `<title>`. * @param text - raw text. * @returns the escaped text. */ function escapeHtml(text) { return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"); } //#endregion //#region src/client/theme.ts /** * Host-theme resolution shared by the settled card and the streaming preview: * reads the DSH `--dsw-alias-*` design tokens (whale-blue brand accent * included) off `document.body` and derives the host color scheme. The body is * the read point because DSH mounts the token definitions there (dark override * under `body[data-ds-dark-theme]`), and custom properties only cascade * DOWNWARD — a `:root`-mounted theme still reaches the body by inheritance, * the reverse read never works. Missing tokens resolve to empty strings the * shell drops, so the frame stylesheet's `light-dark()` fallbacks apply * outside DSH. */ /** Host design token → frame variable bridge (values resolved per render). */ const TOKEN_BRIDGE = [ ["foreground", "--dsw-alias-label-primary"], ["card", "--dsw-alias-bg-layer-1"], ["muted-foreground", "--dsw-alias-label-caption"], ["border", "--dsw-alias-border-l2"], ["primary", "--dsw-alias-brand-primary-new-colorprimary-new-color"], ["primary-foreground", "--dsw-alias-label-primary-inverted"] ]; /** * Resolve the bridged palette and the host color scheme from computed style. * @returns the palette map and scheme for {@link buildFrameDoc}. */ function resolveTheme() { const computed = getComputedStyle(document.body); const themeVars = {}; for (const [frameName, hostToken] of TOKEN_BRIDGE) themeVars[frameName] = computed.getPropertyValue(hostToken); const scheme = computed.colorScheme; return { themeVars, colorScheme: scheme.includes("dark") && !scheme.includes("light") ? "dark" : scheme.includes("light") && !scheme.includes("dark") ? "light" : document.body.hasAttribute("data-ds-dark-theme") ? "dark" : matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" }; } //#endregion //#region src/client/VisualizeCard.tsx /** * The `visualize` toolview: renders the persisted fragment from the call's * durable meta inside `<iframe sandbox="allow-scripts">` with the frame's own * CSP. Replay-stable by construction — everything drawn derives from the * logged call slice, never from the fragment file. * * Theme bridge: the card resolves the host's `--dsw-alias-*` design tokens * (whale-blue brand accent included) at render time and injects them into the * frame document as `--dsh-viz-*` variables; a mutation of the root element's * attributes or an OS appearance flip re-resolves them, so the frame follows * live theme switches. The frame body stays transparent to blend with the * conversation surface. * * Height: a sandboxed frame's document is unreachable from the parent, so the * frame posts its scroll height (tagged with this call's id) and the card * sizes the iframe, capped per mode with internal scrolling past the cap. */ /** Iframe height bounds; content beyond the cap scrolls inside the frame. */ const MIN_HEIGHT = 48; const HEIGHT_CAP = { inline: 800, wide: 1200 }; const headerStyle = { display: "flex", alignItems: "baseline", gap: 8, fontSize: 12, opacity: .65, margin: "2px 0 6px", overflow: "hidden", whiteSpace: "nowrap" }; const frameStyle$1 = { display: "block", width: "100%", border: 0, background: "transparent", colorScheme: "normal" }; /** First text line of the durable result content, for the error row. */ function firstResultLine(content) { for (const block of content) if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) { const newline = block.text.indexOf("\n"); return newline === -1 ? block.text : block.text.slice(0, newline); } return "visualization failed"; } /** The settled, well-formed card: header line plus the sandboxed frame. */ function Frame({ meta, callId }) { const [themeTick, setThemeTick] = (0, react.useState)(0); const [height, setHeight] = (0, react.useState)(MIN_HEIGHT); (0, react.useEffect)(() => { const bump = () => setThemeTick((tick) => tick + 1); const observer = new MutationObserver(bump); observer.observe(document.documentElement, { attributes: true }); observer.observe(document.body, { attributes: true }); const media = matchMedia("(prefers-color-scheme: dark)"); media.addEventListener("change", bump); return () => { observer.disconnect(); media.removeEventListener("change", bump); }; }, []); (0, react.useEffect)(() => { const onMessage = (event) => { const data = event.data; if (typeof data !== "object" || data === null) return; const report = data; if (report.type !== "dsh-visualize:height" || report.token !== callId) return; if (typeof report.height !== "number" || !Number.isFinite(report.height)) return; setHeight(Math.max(MIN_HEIGHT, Math.min(Math.ceil(report.height), HEIGHT_CAP[meta.mode]))); }; addEventListener("message", onMessage); return () => removeEventListener("message", onMessage); }, [callId, meta.mode]); const doc = (0, react.useMemo)(() => { const { themeVars, colorScheme } = resolveTheme(); return buildFrameDoc({ fragment: meta.fragment, title: meta.title, themeVars, colorScheme, reportToken: callId }); }, [ meta, callId, themeTick ]); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { style: headerStyle, title: meta.path === "" ? meta.title : meta.path, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: { fontWeight: 500 }, children: meta.title }), meta.path !== "" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis" }, children: meta.path })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", { sandbox: "allow-scripts", referrerPolicy: "no-referrer", title: meta.title, srcDoc: doc, style: { ...frameStyle$1, height } })] }); } /** * Keyed toolview for the `visualize` tool. Running calls and malformed or * failed results stay quiet single lines; a well-formed persisted meta — or * the fragment in the call's own arguments for nested dispatches — mounts * the frame. */ function VisualizeCard({ callId, block }) { const argsRaw = "kind" in block ? block.call?.argsRaw : "argsRaw" in block ? block.argsRaw : void 0; if (!("kind" in block)) { const live = visualizeMetaFromArgs(argsRaw); if (live !== void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Frame, { meta: live, callId }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: headerStyle, children: "Visualize · rendering…" }); } if (block.isError) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { style: headerStyle, children: ["Visualize · ", firstResultLine(block.content)] }); const meta = visualizeMetaFrom(block.meta) ?? visualizeMetaFromArgs(argsRaw); if (meta === void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: headerStyle, children: firstResultLine(block.content) }); return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Frame, { meta, callId }); } //#endregion //#region src/client/StreamingPreview.tsx /** * Live streaming preview docked under the composer: while the model is still * generating a `visualize` call, the accumulated argument stream * (`assistant/chunk` tool-call deltas folded into the conversation snapshot's * `partial`) is parsed for the fragment prefix and rendered into the same * sandboxed frame the settled card uses — markup and style only, scripts * neutered until the call settles (a half-streamed script body is almost * never valid JavaScript). Renders nothing when no `visualize` call is * streaming; once the call settles the preview unmounts and the transcript * card takes over. */ /** * Flush interval for posting fragment updates into the persistent shell. * Updates are incremental DOM syncs, not reloads, so this can run near * per-delta speed; 150ms keeps the reveal continuous at negligible cost. */ const FLUSH_MS = 150; /** * Preview height ceiling. The frame tracks the shell's *measured* content * height (its height reports), so invisible early markup — style blocks, * empty containers — keeps the frame collapsed and painted components grow * it; the cap stops a tall fragment from crowding out the composer. Reserving * space no paint has claimed reads as a layout bug, not as anticipation. */ const PREVIEW_MAX_HEIGHT = 300; /** * The input dock spans the conversation view, not the composer column, so the * preview constrains itself to the composer's width family and centers. */ const wrapStyle = { margin: "6px auto 2px", maxWidth: 760, width: "100%" }; const labelStyle = { fontSize: 12, opacity: .65, margin: "0 0 4px" }; const frameStyle = { display: "block", width: "100%", border: 0, background: "transparent", transition: "height 240ms ease" }; /** * Throttle a fast-changing string: re-emits at most every {@link FLUSH_MS}, * with a trailing flush so the final value always lands. A plain trailing * debounce would starve under a continuous token stream — every delta would * reset the timer — so this flushes on the leading edge when the interval has * already elapsed. * @param value - the raw per-render value. * @returns the throttled value. */ function useThrottled(value) { const [shown, setShown] = (0, react.useState)(value); const lastFlush = (0, react.useRef)(0); (0, react.useEffect)(() => { const elapsed = Date.now() - lastFlush.current; if (elapsed >= FLUSH_MS) { lastFlush.current = Date.now(); setShown(value); return; } const timer = setTimeout(() => { lastFlush.current = Date.now(); setShown(value); }, FLUSH_MS - elapsed); return () => clearTimeout(timer); }, [value]); return shown; } /** The mounted preview, split out so hooks only run while a call streams. */ function Preview({ argsRaw }) { const fragment = extractStreamingFragment(useThrottled(argsRaw)); const preview = fragment === void 0 ? "" : trimStreamingScripts(fragment); const hasContent = preview.trim().length > 0; const frameRef = (0, react.useRef)(null); const [loaded, setLoaded] = (0, react.useState)(false); const [contentHeight, setContentHeight] = (0, react.useState)(0); (0, react.useEffect)(() => { const onMessage = (event) => { const report = event.data; if (report?.type !== "dsh-visualize:height" || report.token !== "streaming-preview") return; if (typeof report.height !== "number" || !Number.isFinite(report.height)) return; setContentHeight(Math.max(0, Math.ceil(report.height))); }; addEventListener("message", onMessage); return () => removeEventListener("message", onMessage); }, []); const doc = (0, react.useMemo)(() => buildStreamShellDoc({ ...resolveTheme(), reportToken: "streaming-preview" }), []); (0, react.useEffect)(() => { if (!loaded || !hasContent) return; frameRef.current?.contentWindow?.postMessage({ type: STREAM_MESSAGE_TYPE, token: "streaming-preview", fragment: preview }, "*"); }, [ loaded, hasContent, preview ]); return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { style: wrapStyle, children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: labelStyle, children: hasContent ? "Visualize · streaming preview" : "Visualize · composing…" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("iframe", { ref: frameRef, sandbox: "allow-scripts", referrerPolicy: "no-referrer", title: "Visualization streaming preview", srcDoc: doc, style: { ...frameStyle, height: hasContent ? Math.min(contentHeight, PREVIEW_MAX_HEIGHT) : 0 }, onLoad: () => setLoaded(true) })] }); } /** * Dock entry: mounts the preview exactly while the streaming partial carries * a `visualize` tool-call block. */ function StreamingPreview({ session }) { const blocks = session?.partial?.blocks; if (blocks === void 0) return null; let argsRaw; for (const block of blocks) if (block.kind === "tool-call" && block.name === "visualize") argsRaw = block.argsRaw; if (argsRaw === void 0) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Preview, { argsRaw }); } //#endregion //#region src/client/folding.ts /** Settings namespace owned by the host Chat target. */ const CHAT_NAMESPACE = "ui-chat"; /** * Whether a saved mode folds on a 0.1.7+ host. An unset value is the host's * `standard` default. * @param view - saved `transcriptView`. * @returns true unless the reader chose `verbose`. */ function configFormsFolds(view) { return view !== "verbose"; } /** * Whether a saved mode folds on a 0.1.2–0.1.6 host. An unset value is the * host's `compact` default. * @param view - saved `transcriptView`. * @returns true for `compact` or unset. */ function settingsScopeFolds(view) { return view === void 0 || view === "compact"; } /** * Adapt a settings face into a boolean observable. * @param face - the host namespace binding. * @param folds - the generation's mode rule. * @returns an observable whose snapshot is a primitive, so it is stable. */ function observe(face, folds) { return { getSnapshot: () => folds(face.getSnapshot().value?.transcriptView), subscribe: (listener) => { const dispose = face.subscribe(listener); return typeof dispose === "function" ? dispose : () => void 0; } }; } /** * Narrow an unknown value to an object exposing a method. * @param value - candidate service. * @param method - required method name. * @returns the value when it carries the method. */ function hasMethod(value, method) { return typeof value === "object" && value !== null && typeof value[method] === "function"; } /** * Resolve the folding observable for this host. Call it once the Chat target * is up (its turn-tail declaration is the signal), when both settings * services, where present, are already provided. * @param host - the client context, read through optional `get`. * @returns whether finished turns currently fold, observed live. */ function foldingSource(host) { const forms = host.get("configForms"); if (hasMethod(forms, "get")) return observe(forms.get(CHAT_NAMESPACE), configFormsFolds); const scope = host.get("settingsScope"); if (hasMethod(scope, "bind")) return observe(scope.bind({ namespace: CHAT_NAMESPACE }), settingsScopeFolds); return { getSnapshot: () => false, subscribe: () => () => void 0 }; } //#endregion //#region src/client/TurnCards.tsx /** Definition kind and Turn data key; namespaced by package to stay unique. */ const TURN_CARDS_KEY = "dsh-visualize"; /** * Accept a successful root `visualize` result. The persisted meta names its * own kind, so no call-to-name bookkeeping is needed. * @param data - `tool/result` payload. * @returns the card descriptor, or undefined when unrelated or failed. */ function resultMeta(data) { return data.message.isError === true ? void 0 : visualizeMetaFrom(data.meta); } /** * Fold one result into the turn's cards. A repeated call id (a later surface * replacement of the same result) keeps the first; a later card at an existing * path (an `update` patch) replaces that card in place, so a corrected card is * shown once, in its original position. * @param cards - cards so far. * @param card - the incoming card. * @returns the next card list, or the same list when unchanged. */ function foldCard(cards, card) { if (cards.some((existing) => existing.callId === card.callId)) return cards; const index = cards.findIndex((existing) => existing.meta.path === card.meta.path); if (index === -1) return [...cards, card]; return cards.map((existing, at) => at === index ? card : existing); } /** Turn-local visualize accumulator; it publishes Turn data and no view Node. */ const turnCardsDefinition = { kind: TURN_CARDS_KEY, match: (event) => { if (event.type === "turn/start") return { id: String(event.data.turn), role: "start" }; if (event.type !== "tool/result") return null; const data = event.data; return resultMeta(data) === void 0 ? null : { id: String(data.turn), role: "update" }; }, start: (_context, match) => { if (match.event.type !== "turn/start") throw new Error("dsh-visualize: turn cards start requires turn/start"); return { turn: match.event.data.turn, cards: [] }; }, update: (context, match) => { if (match.event.type !== "tool/result") return context.state; const data = match.event.data; const meta = resultMeta(data); if (meta === void 0) return context.state; const cards = foldCard(context.state.cards, { callId: String(data.message.source.callId), seq: match.event.seq, meta }); return cards === context.state.cards ? context.state : { ...context.state, cards }; }, buildLocationData: (context, scope, previous) => { if (scope !== "turn" || context.state === void 0) return null; const { turn, cards } = context.state; if (previous?.kind === "turn" && previous.turn === turn && previous.key === "dsh-visualize" && previous.value.cards === cards) return previous; return { kind: "turn", turn, key: TURN_CARDS_KEY, value: { cards } }; } }; /** * The cards settled before the turn's closing reply. * @param turn - the closing turn; older hosts may omit its data store. * @param seq - the closing assistant message's sequence number. * @returns the cards to show, possibly empty. */ function cardsBefore(turn, seq) { return (turn?.data?.get("dsh-visualize")?.cards ?? []).filter((card) => card.seq < seq); } /** * Chain selector for dsh 0.1.5 and earlier, whose turn tail elects one entry. * @param owner - the turn-tail owner currency. * @returns the cards as the match, or null to decline this turn. */ function selectTurnCards(owner) { const cards = cardsBefore(owner.turn, owner.seq); return cards.length === 0 ? null : cards; } const listStyle = { display: "grid", gap: 12, margin: "8px 0 4px" }; /** * Turn-tail entry. A list turn tail mounts it on every turn, so it declines * turns without cards itself, and it stays empty whenever the host is not * folding — the toolview card is then already in view. * @param props - turn owner props plus the injected folding selector. * @returns the turn's cards, or null. */ function TurnCards({ turn, seq, useVisualizeFolds }) { const folds = useVisualizeFolds((value) => value); const cards = cardsBefore(turn, seq); if (!folds || cards.length === 0) return null; return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: listStyle, children: cards.map((card) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Frame, { meta: card.meta, callId: `turn-tail:${card.callId}` }, card.callId)) }); } //#endregion //#region src/client/index.tsx const name = "dsh-visualize"; const inject = ["slots"]; /** * Look up the Conversation event registry without declaring the service, so * hosts that predate it still load the plugin. * @param host - client context. * @returns the registry, or undefined on dsh 0.1.1. */ function conversationEvents(host) { const service = host.get("uiConversation"); return typeof service?.events?.register === "function" ? service.events : void 0; } /** * Turn-tail registration valid on both slot shapes the host has shipped: dsh * 0.1.5 and earlier declare a chain (register requires `select`, orders by * `priority`), 0.1.6 onward a list (register requires `id`, orders by * `order`). Each register validates only its own kind's field. The cards sit * after the host's deliverables and before other plugins' low-rank entries. * @param host - client context, for the folding preference. * @returns the register options. */ function turnTailOptions(host) { const folds = foldingSource(host); return { name: "conversation.chat.turnTail", id: "dsh-visualize-cards", order: 100, priority: 100, select: selectTurnCards, inject: () => ({ hooks: { visualizeFolds: folds } }) }; } /** * Register the keyed toolview and the dock preview. Waiting on each hole's * declaration mirrors the official registrants: entry application order is * loader-driven, and a direct register racing the declaration fails boot. * @param ctx - client root context. */ function apply(ctx) { ctx.slots.inject("tool.call.toolview", () => ctx.slots.register({ name: "tool.call.toolview", key: "visualize" }, VisualizeCard)); ctx.slots.inject("conversation.input.dock", () => ctx.slots.register({ name: "conversation.input.dock", id: "visualize-stream", order: 30 }, StreamingPreview)); ctx.slots.inject("conversation.chat.turnTail", () => { const events = conversationEvents(ctx); if (events === void 0) return () => void 0; const disposeDefinition = events.register(turnCardsDefinition); const disposeTail = ctx.slots.register(turnTailOptions(ctx), TurnCards); return () => { disposeTail(); disposeDefinition(); }; }); } //#endregion exports.apply = apply; exports.inject = inject; exports.name = name; return module.exports; } }); # ===== file: lib/index.js ===== import z from "@deepseek-ai/schemastery"; import { defineTool } from "@deepseek-ai/dsh-tools"; import { readFile } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill"; //#region src/skill.ts /** * Bundled `visualize` skill provider: the fragment-authoring contract the * model loads before its first `visualize` call. Mirrors the official * `dsh-skill-badge` provider shape — one bundled candidate whose body ships * in this package's `assets/`. * * @module @nagi-ovo/dsh-visualize/skill */ const PROVIDER_NAME = "dsh-visualize"; const SKILL_BODY_URL = new URL("../assets/visualize-skill.md", import.meta.url); /** Absolute path of the skill body, for agents that cannot load skills. */ const SKILL_BODY_PATH = fileURLToPath(SKILL_BODY_URL); /** Absolute directory the skill body's relative references resolve against. */ const SKILL_RESOURCE_DIR = fileURLToPath(new URL("../assets/", import.meta.url)); const RESOURCE_BASE = { kind: "directory", path: SKILL_RESOURCE_DIR }; const CANDIDATE = { name: "visualize", description: "Authoring contract for the visualize tool, which renders interactive cards in the conversation: simulations, algorithm walkthroughs, charts, comparisons, and product-screen mockups. Load before the first visualize call in a session — it defines the fragment structure, theming variables, size ceiling, and allowed resources the tool validates against.", invocation: { modelInvocable: true, userInvocable: true }, provider: PROVIDER_NAME, source: "bundled", resourceBase: RESOURCE_BASE, rank: BUNDLED_SKILL_RANK, locator: SKILL_BODY_URL }; /** The bundled provider registered on `ctx.skills`. */ const visualizeSkillProvider = { name: PROVIDER_NAME, list: () => Promise.resolve([CANDIDATE]), async get(_candidate) { return { name: CANDIDATE.name, description: CANDIDATE.description, invocation: CANDIDATE.invocation, provider: CANDIDATE.provider, source: CANDIDATE.source, resourceBase: RESOURCE_BASE, content: await readFile(SKILL_BODY_URL, "utf8") }; } }; //#endregion //#region src/fragment.ts /** * Pure fragment contract shared by the tool (validation at execute time), the * browser card (meta narrowing at render time), and the specs. No I/O and no * DOM so both halves and vitest can load it unchanged. * * A *fragment* is the model-authored inline-HTML body of one visualization: * literal markup without a document skeleton. The card owns the skeleton — it * wraps the fragment in a sandboxed iframe document with its own CSP — so a * fragment that ships its own `<!doctype>`/`<html>`/`<head>`/`<body>` would * nest documents and is rejected loudly instead of rendered broken. * * @module @nagi-ovo/dsh-visualize/fragment */ /** * Wire name of the tool, the keyed toolview, and the streaming-preview match. * Lives in this pure module so the browser half can import it without pulling * the node-side tool implementation into the client bundle. */ const VISUALIZE_TOOL_NAME = "visualize"; /** Document-skeleton tags a fragment must not contain (case-insensitive). */ const SKELETON_TAG = /<!doctype\b|<\s*(?:html|head|body)\b/iu; /** * Validate one fragment against the inline contract. * @param fragment - the file content the model wrote. * @param maxBytes - deployment size ceiling for one fragment. * @returns the fragment's UTF-8 size in bytes. * @throws Error naming the violated rule; the tool surfaces it as `isError`. */ function validateFragment(fragment, maxBytes) { if (fragment.trim().length === 0) throw new Error("invalid visualization: the fragment file is empty"); const sizeBytes = byteLength(fragment); if (sizeBytes > maxBytes) throw new Error(`invalid visualization: fragment is ${sizeBytes} bytes, over the ${maxBytes}-byte limit — shrink the inline data first (fewer rows, coarser buckets, fewer decimals)`); const skeleton = SKELETON_TAG.exec(fragment); if (skeleton) throw new Error(`invalid visualization: fragment contains a document-skeleton tag (${JSON.stringify(skeleton[0])}) — write only the inline body; the host supplies <!doctype>, <html>, <head>, and <body>`); return sizeBytes; } /** * Characters of real card content quoted back when a patch fails to apply, so * the model can correct `old_str` from the true bytes without re-reading the * whole card. */ const PATCH_CONTEXT_CHARS = 160; /** * Shortest matching prefix of a failed `old_str` still worth reporting as a * location hint; below this any HTML shares enough characters to point * somewhere misleading. */ const MIN_ANCHOR_CHARS = 12; /** * Replace one exact, unique occurrence of `oldStr` in a rendered card's * fragment. Iterating by patch instead of re-emitting the whole fragment is * what keeps a small correction small: the model re-states only the changed * region, and the card's markup never enters its output twice. * * A patch that does not resolve to exactly one site is refused rather than * guessed at, because both wrong outcomes are silent — a near-miss would edit * markup the model never saw, and an ambiguous match would edit an arbitrary * one of several sites. The thrown message carries the surrounding real * content so the caller can correct `old_str` within the same turn. * * @param base - the current fragment of the card being patched. * @param oldStr - exact text to replace, whitespace included. * @param newStr - replacement text; empty deletes the matched region. * @returns the patched fragment. * @throws Error naming why the patch did not apply; the tool surfaces it as `isError`. */ function applyFragmentPatch(base, oldStr, newStr) { if (oldStr.length === 0) throw new Error("invalid visualization patch: old_str is empty — pass the exact card text to replace"); const first = base.indexOf(oldStr); if (first === -1) throw new Error(`invalid visualization patch: old_str does not appear in the card. ${nearestAnchor(base, oldStr)}`); if (base.indexOf(oldStr, first + oldStr.length) !== -1) throw new Error(`invalid visualization patch: old_str appears ${countOccurrences(base, oldStr)} times in the card — extend it with neighbouring lines until exactly one site matches`); return base.slice(0, first) + newStr + base.slice(first + oldStr.length); } /** * Describe where a failed `old_str` stopped matching: the longest prefix of it * that does occur, and the card's real text at that site. Prefix occurrence is * monotone in length, so the longest one is a binary search. * @param base - the current fragment of the card being patched. * @param oldStr - the `old_str` that failed to match. * @returns a sentence naming the divergence point, or advising a full re-render. */ function nearestAnchor(base, oldStr) { let matched = 0; let beyond = oldStr.length; while (matched < beyond) { const mid = Math.ceil((matched + beyond) / 2); if (base.includes(oldStr.slice(0, mid))) matched = mid; else beyond = mid - 1; } if (matched < MIN_ANCHOR_CHARS) return "None of it matched, so the card is not in the state you assumed — re-render the whole card instead."; const at = base.indexOf(oldStr.slice(0, matched)); return `Its first ${matched} characters do match, at offset ${at}, where the card actually reads ${JSON.stringify(base.slice(at, at + PATCH_CONTEXT_CHARS))} — correct old_str against that and retry.`; } /** * Count non-overlapping occurrences of a needle, matching the replacement * semantics {@link applyFragmentPatch} would apply. * @param base - the text to scan. * @param needle - the non-empty needle to count. * @returns the number of non-overlapping occurrences. */ function countOccurrences(base, needle) { let count = 0; for (let at = base.indexOf(needle); at !== -1; at = base.indexOf(needle, at + needle.length)) count += 1; return count; } /** * Narrow one persisted `tool/result` meta value to a {@link VisualizeMeta}. * Wire data cannot be trusted to match the compiled shape (an older or newer * host may have logged it), so a mismatch declines to `undefined` — the caller * falls back to the generic presentation instead of throwing on replay. * @param meta - the raw persisted meta value. * @returns the narrowed descriptor, or `undefined` for the generic path. */ function visualizeMetaFrom(meta) { if (typeof meta !== "object" || meta === null) return void 0; const record = meta; if (record["kind"] !== "visualize") return void 0; const { fragment, title, mode, path } = record; if (typeof fragment !== "string" || typeof title !== "string" || typeof path !== "string") return void 0; if (mode !== "inline" && mode !== "wide") return void 0; return { kind: "visualize", fragment, title, mode, path }; } /** * UTF-8 byte length without Buffer, so the browser bundle needs no polyfill. * @param text - the string to measure. * @returns its UTF-8 encoding length in bytes. */ function byteLength(text) { return new TextEncoder().encode(text).length; } //#endregion //#region src/tool.ts const DESCRIPTION = `Show the user an interactive HTML visualization, rendered as a live card in the conversation. \`create\` (the default) takes the whole markup in \`fragment\`: literal inline HTML only (no <!doctype>, <html>, <head>, or <body> — the card supplies the document, stylesheet, and theme). To correct a card you already rendered, call \`update\` with its \`path\` and one exact \`old_str\`/\`new_str\` replacement instead of re-sending the whole fragment. The card appears while you generate; a copy of the finished fragment is saved into the session workspace. Load the \`visualize\` skill for the authoring contract before your first call. If this session has no skill tool, read the same contract from ${SKILL_BODY_PATH} (its relative paths resolve against ${SKILL_RESOURCE_DIR}) with a file or shell tool; do not search for it anywhere else.`; /** * Build the `visualize` tool definition over the composed filesystem seam. * @param ctx - registrant context carrying `ctx.fs` for the workspace copy. * @param maxFragmentBytes - deployment size ceiling for one fragment. * @returns the tool definition to register on `ctx.tools`. */ function visualizeTool(ctx, maxFragmentBytes) { return defineTool({ name: VISUALIZE_TOOL_NAME, description: DESCRIPTION, parameters: { action: { type: "string", enum: ["create", "update"], description: "`create` (default) renders a new card from `fragment`. `update` patches the card at `path`, replacing `old_str` with `new_str` — use it for a correction touching fewer than 20 lines in fewer than 5 places, and at most 4 times per reply; re-create the card for anything larger." }, fragment: { type: "string", description: "create only, required: the inline HTML fragment to render (markup, style, and script — no document skeleton)." }, title: { type: "string", description: "Concise card title. Defaults to \"Visualization\" on create; required on update." }, mode: { type: "string", enum: ["inline", "wide"], description: "Card width: `inline` (default) or `wide` for side-by-side panel comparisons." }, path: { type: "string", description: "update only, required: workspace path of the card to patch, as its own call reported it." }, old_str: { type: "string", description: "update only, required: the exact card text to replace, whitespace included. It must appear exactly once — keep it as short as stays unique." }, new_str: { type: "string", description: "update only, required: the replacement text. Empty deletes the matched region." } }, output: { schema: { type: "object", additionalProperties: false, properties: { action: { type: "string", required: true, enum: ["create", "update"] }, path: { type: "string", required: true }, title: { type: "string", required: true }, mode: { type: "string", required: true, enum: ["inline", "wide"] }, sizeBytes: { type: "integer", required: true }, fragment: { type: "string", required: true } } }, render: (_args, value) => [{ type: "text", text: value.action === "update" ? `Patched "${value.title}" in place (${value.sizeBytes} bytes; updated card at ${value.path}). The user sees the corrected visualization in the conversation; patch that path for any further correction.` : `Rendered "${value.title}" inline (${value.sizeBytes} bytes; workspace copy at ${value.path}). The user sees the interactive visualization in the conversation.` }], presentationMeta: (_args, value) => ({ kind: "visualize", fragment: value.fragment, title: value.title, mode: value.mode, path: value.path }) }, isConcurrencySafe: (args) => (args.action ?? "create") === "create", async execute(args, exec) { const action = args.action ?? "create"; const sandboxPolicy = ctx.get("sandboxPolicy")?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} }); const cwd = sandboxPolicy?.workspaceRoot ?? exec.agent?.session.header.cwd; const resolveOpts = { ...cwd !== void 0 ? { cwd } : {}, signal: exec.signal }; let source; let fragment; if (action === "update") { source = await ctx.fs.resolve(required(args.path, "path", action), resolveOpts); fragment = applyFragmentPatch(await ctx.fs.readText(source, exec.signal), required(args.old_str, "old_str", action), present(args.new_str, "new_str", action)); } else fragment = required(args.fragment, "fragment", action); const sizeBytes = validateFragment(fragment, maxFragmentBytes); const title = action === "update" ? required(args.title, "title", action).trim() : args.title?.trim() || "Visualization"; const target = source ?? await ctx.fs.resolve(`viz/${slugOf(title)}-${contentHash(fragment)}.html`, resolveOpts); await ctx.fs.writeText(target, fragment, void 0, exec.signal, sandboxPolicy); return { action, path: target.displayPath, title, mode: args.mode ?? "inline", sizeBytes, fragment }; }, presentCall: () => ({ card: "generic", title: "Visualize", kind: "other" }), presentResult(_args, result) { if (result.isError) return void 0; const meta = visualizeMetaFrom(result.meta); if (meta === void 0) return void 0; return { card: "generic", title: `Visualization · ${meta.title}` }; } }); } /** * Take one argument the chosen action cannot run without. The parameter schema * cannot express "required on update only", so the per-action requirement is * enforced here and fails loud rather than defaulting into a wrong card. * @param value - the raw argument value. * @param name - the parameter name, as the model wrote it. * @param action - the action that requires it, named in the message. * @returns the raw value, whitespace preserved. * @throws Error naming the missing parameter; the tool surfaces it as `isError`. */ function required(value, name, action) { if (value === void 0 || value.trim().length === 0) throw new Error(`invalid visualization: \`${name}\` is required when action is "${action}"`); return value; } /** * Take one argument that must be supplied but may legitimately be empty — an * empty `new_str` is how a patch deletes the region it matched. * @param value - the raw argument value. * @param name - the parameter name, as the model wrote it. * @param action - the action that requires it, named in the message. * @returns the raw value, including the empty string. * @throws Error naming the missing parameter; the tool surfaces it as `isError`. */ function present(value, name, action) { if (value === void 0) throw new Error(`invalid visualization: \`${name}\` is required when action is "${action}"`); return value; } /** * Lowercase, hyphenated, ASCII-safe file slug of a card title. * @param title - the resolved card title. * @returns a non-empty slug. */ function slugOf(title) { const slug = title.toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-").replaceAll(/^-+|-+$/gu, "").slice(0, 48); return slug.length > 0 ? slug : "visualization"; } /** * Stable 8-hex-digit content hash (FNV-1a) naming the workspace copy. * @param text - the fragment content. * @returns the hash as fixed-width hex. */ function contentHash(text) { let hash = 2166136261; for (let i = 0; i < text.length; i++) { hash ^= text.charCodeAt(i); hash = Math.imul(hash, 16777619); } return (hash >>> 0).toString(16).padStart(8, "0"); } //#endregion //#region src/index.ts /** Cordis plugin name. */ const name = "dsh-visualize"; /** Required services: the tool registry, the skill registry, and the fs seam. */ const inject = [ "tools", "skills", "fs" ]; /** Schemastery configuration validated by the Loader. */ const Config = z.object({ maxFragmentBytes: z.natural().default(1e6) }); /** * Register the tool and the bundled skill provider. * @param ctx - registrant context. * @param config - validated deployment configuration. */ function apply(ctx, config) { ctx.tools.register(visualizeTool(ctx, config.maxFragmentBytes)); ctx.skills.registerProvider(() => visualizeSkillProvider); } //#endregion export { Config, VISUALIZE_TOOL_NAME, apply, inject, name, validateFragment, visualizeMetaFrom }; # ===== file: src/client/StreamingPreview.tsx ===== /** * Live streaming preview docked under the composer: while the model is still * generating a `visualize` call, the accumulated argument stream * (`assistant/chunk` tool-call deltas folded into the conversation snapshot's * `partial`) is parsed for the fragment prefix and rendered into the same * sandboxed frame the settled card uses — markup and style only, scripts * neutered until the call settles (a half-streamed script body is almost * never valid JavaScript). Renders nothing when no `visualize` call is * streaming; once the call settles the preview unmounts and the transcript * card takes over. */ import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls the `conversation.input.dock` SlotMap declaration. import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { extractStreamingFragment, trimStreamingScripts, VISUALIZE_TOOL_NAME } from '../fragment.ts' import { buildStreamShellDoc, HEIGHT_MESSAGE_TYPE, STREAM_MESSAGE_TYPE } from '../shell.ts' import { resolveTheme } from './theme.ts' /** Dock entry props: the InputZone owner share (live conversation snapshot). */ type StreamingPreviewProps = PropsRuntime<'conversation.input.dock'> /** * Flush interval for posting fragment updates into the persistent shell. * Updates are incremental DOM syncs, not reloads, so this can run near * per-delta speed; 150ms keeps the reveal continuous at negligible cost. */ const FLUSH_MS = 150 /** * Preview height ceiling. The frame tracks the shell's *measured* content * height (its height reports), so invisible early markup — style blocks, * empty containers — keeps the frame collapsed and painted components grow * it; the cap stops a tall fragment from crowding out the composer. Reserving * space no paint has claimed reads as a layout bug, not as anticipation. */ const PREVIEW_MAX_HEIGHT = 300 /** * The input dock spans the conversation view, not the composer column, so the * preview constrains itself to the composer's width family and centers. */ const wrapStyle: CSSProperties = { margin: '6px auto 2px', maxWidth: 760, width: '100%' } const labelStyle: CSSProperties = { fontSize: 12, opacity: 0.65, margin: '0 0 4px', } const frameStyle: CSSProperties = { display: 'block', width: '100%', border: 0, background: 'transparent', transition: 'height 240ms ease', } /** * Throttle a fast-changing string: re-emits at most every {@link FLUSH_MS}, * with a trailing flush so the final value always lands. A plain trailing * debounce would starve under a continuous token stream — every delta would * reset the timer — so this flushes on the leading edge when the interval has * already elapsed. * @param value - the raw per-render value. * @returns the throttled value. */ function useThrottled(value: string): string { const [shown, setShown] = useState(value) const lastFlush = useRef(0) useEffect(() => { const elapsed = Date.now() - lastFlush.current if (elapsed >= FLUSH_MS) { lastFlush.current = Date.now() setShown(value) return } const timer = setTimeout(() => { lastFlush.current = Date.now() setShown(value) }, FLUSH_MS - elapsed) return () => clearTimeout(timer) }, [value]) return shown } /** The mounted preview, split out so hooks only run while a call streams. */ function Preview({ argsRaw }: { argsRaw: string }) { const throttled = useThrottled(argsRaw) const fragment = extractStreamingFragment(throttled) const preview = fragment === undefined ? '' : trimStreamingScripts(fragment) const hasContent = preview.trim().length > 0 const frameRef = useRef<HTMLIFrameElement | null>(null) const [loaded, setLoaded] = useState(false) const [contentHeight, setContentHeight] = useState(0) // Follow the shell's height reports so the frame hugs what is actually // painted; the CSS transition turns each growth step into a smooth reveal. useEffect(() => { const onMessage = (event: MessageEvent) => { const report = event.data as { type?: unknown; token?: unknown; height?: unknown } | null if (report?.type !== HEIGHT_MESSAGE_TYPE || report.token !== 'streaming-preview') return if (typeof report.height !== 'number' || !Number.isFinite(report.height)) return setContentHeight(Math.max(0, Math.ceil(report.height))) } addEventListener('message', onMessage) return () => removeEventListener('message', onMessage) }, []) // The shell loads ONCE per streaming call; updates flow over postMessage // and sync incrementally, so unchanged components persist and new ones // float in instead of the whole frame reloading per flush. const doc = useMemo(() => buildStreamShellDoc({ ...resolveTheme(), reportToken: 'streaming-preview', }), []) useEffect(() => { if (!loaded || !hasContent) return frameRef.current?.contentWindow?.postMessage({ type: STREAM_MESSAGE_TYPE, token: 'streaming-preview', fragment: preview, }, '*') }, [loaded, hasContent, preview]) return ( <div style={wrapStyle}> <div style={labelStyle}> {hasContent ? 'Visualize · streaming preview' : 'Visualize · composing…'} </div> <iframe ref={frameRef} sandbox="allow-scripts" referrerPolicy="no-referrer" title="Visualization streaming preview" srcDoc={doc} style={{ ...frameStyle, height: hasContent ? Math.min(contentHeight, PREVIEW_MAX_HEIGHT) : 0 }} onLoad={() => setLoaded(true)} /> </div> ) } /** * Dock entry: mounts the preview exactly while the streaming partial carries * a `visualize` tool-call block. */ export function StreamingPreview({ session }: StreamingPreviewProps) { // Defensive guard mirroring the official dock rows: a host passing no // session must degrade to an empty dock instead of crashing. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const blocks = session?.partial?.blocks if (blocks === undefined) return null // Last matching block: a turn can contain several visualize calls; only the // most recent one can still be streaming. let argsRaw: string | undefined for (const block of blocks) { if (block.kind === 'tool-call' && block.name === VISUALIZE_TOOL_NAME) argsRaw = block.argsRaw } if (argsRaw === undefined) return null return <Preview argsRaw={argsRaw} /> } # ===== file: src/client/TurnCards.tsx ===== /** * A turn's settled visualizations, shown again under its final answer. * * From dsh 0.1.2 the Web chat folds a finished turn's process — every tool * row, visualize cards included — behind its duration summary whenever the * reader's work-details mode folds (the default). A visualization is the * turn's output rather than its process, so this re-shows the turn's cards on * the turn tail, the seat the host's own deliverables use for the same * reason. The toolview card stays inside the fold as the call's own record. * * The cards come from a state-only Conversation Definition that collects each * successful `visualize` result's persisted meta per turn; nothing here reads * the session log directly or imports host runtime code. */ import type { CSSProperties } from 'react' import type { ConversationLocationData, ConversationNodeDefinition, TurnLocation, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { HostObservable, InjectFace, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls the `conversation.chat.turnTail` SlotMap declaration. import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import { visualizeMetaFrom, type VisualizeMeta } from '../fragment.ts' import { Frame } from './VisualizeCard.tsx' /** Definition kind and Turn data key; namespaced by package to stay unique. */ export const TURN_CARDS_KEY = 'dsh-visualize' /** One settled card, keyed by the call that produced it. */ export interface TurnCard { readonly callId: string readonly seq: number readonly meta: VisualizeMeta } /** Per-turn value published on the Turn Location. */ export interface VisualizeTurnData { readonly cards: readonly TurnCard[] } declare module '@deepseek-ai/dsh-client-ui-conversation/client' { interface ConversationTurnDataMap { /** Settled visualize cards of this Turn, one per card path. */ 'dsh-visualize': VisualizeTurnData } } interface TurnCardsState extends VisualizeTurnData { readonly turn: number } /** The slice of a `tool/result` event this Definition reads. */ interface ToolResultData { readonly turn: number readonly meta?: unknown readonly message: { readonly isError?: boolean; readonly source: { readonly callId: unknown } } } /** * Accept a successful root `visualize` result. The persisted meta names its * own kind, so no call-to-name bookkeeping is needed. * @param data - `tool/result` payload. * @returns the card descriptor, or undefined when unrelated or failed. */ function resultMeta(data: ToolResultData): VisualizeMeta | undefined { return data.message.isError === true ? undefined : visualizeMetaFrom(data.meta) } /** * Fold one result into the turn's cards. A repeated call id (a later surface * replacement of the same result) keeps the first; a later card at an existing * path (an `update` patch) replaces that card in place, so a corrected card is * shown once, in its original position. * @param cards - cards so far. * @param card - the incoming card. * @returns the next card list, or the same list when unchanged. */ export function foldCard(cards: readonly TurnCard[], card: TurnCard): readonly TurnCard[] { if (cards.some(existing => existing.callId === card.callId)) return cards const index = cards.findIndex(existing => existing.meta.path === card.meta.path) if (index === -1) return [...cards, card] return cards.map((existing, at) => at === index ? card : existing) } /** Turn-local visualize accumulator; it publishes Turn data and no view Node. */ export const turnCardsDefinition: ConversationNodeDefinition<TurnCardsState> = { kind: TURN_CARDS_KEY, match: (event) => { if (event.type === 'turn/start') return { id: String(event.data.turn), role: 'start' } if (event.type !== 'tool/result') return null const data = event.data as ToolResultData return resultMeta(data) === undefined ? null : { id: String(data.turn), role: 'update' } }, start: (_context, match) => { if (match.event.type !== 'turn/start') throw new Error('dsh-visualize: turn cards start requires turn/start') return { turn: match.event.data.turn, cards: [] } }, update: (context, match) => { if (match.event.type !== 'tool/result') return context.state const data = match.event.data as ToolResultData const meta = resultMeta(data) if (meta === undefined) return context.state const cards = foldCard(context.state.cards, { callId: String(data.message.source.callId), seq: match.event.seq, meta }) return cards === context.state.cards ? context.state : { ...context.state, cards } }, buildLocationData: (context, scope, previous) => { if (scope !== 'turn' || context.state === undefined) return null const { turn, cards } = context.state if (previous?.kind === 'turn' && previous.turn === turn && previous.key === TURN_CARDS_KEY && previous.value.cards === cards) return previous return { kind: 'turn', turn, key: TURN_CARDS_KEY, value: { cards } } satisfies ConversationLocationData }, } /** * The cards settled before the turn's closing reply. * @param turn - the closing turn; older hosts may omit its data store. * @param seq - the closing assistant message's sequence number. * @returns the cards to show, possibly empty. */ export function cardsBefore(turn: TurnLocation | undefined, seq: number): readonly TurnCard[] { // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- older hosts lack the data store const cards = turn?.data?.get(TURN_CARDS_KEY)?.cards ?? [] return cards.filter(card => card.seq < seq) } /** * Chain selector for dsh 0.1.5 and earlier, whose turn tail elects one entry. * @param owner - the turn-tail owner currency. * @returns the cards as the match, or null to decline this turn. */ export function selectTurnCards(owner: { turn?: TurnLocation; seq: number }): readonly TurnCard[] | null { const cards = cardsBefore(owner.turn, owner.seq) return cards.length === 0 ? null : cards } /** Folding observable injected by the registration. */ export type TurnCardsInjected = InjectFace<{ readonly hooks: { readonly visualizeFolds: HostObservable<boolean> } }> const listStyle: CSSProperties = { display: 'grid', gap: 12, margin: '8px 0 4px' } /** * Turn-tail entry. A list turn tail mounts it on every turn, so it declines * turns without cards itself, and it stays empty whenever the host is not * folding — the toolview card is then already in view. * @param props - turn owner props plus the injected folding selector. * @returns the turn's cards, or null. */ export function TurnCards({ turn, seq, useVisualizeFolds }: PropsRuntime<'conversation.chat.turnTail'> & TurnCardsInjected) { const folds = useVisualizeFolds(value => value) const cards = cardsBefore(turn, seq) if (!folds || cards.length === 0) return null return ( <div style={listStyle}> {cards.map(card => ( // A distinct height token: the toolview frame for the same call may be // mounted too (an opened fold) and reports under the bare call id. <Frame key={card.callId} meta={card.meta} callId={`turn-tail:${card.callId}`} /> ))} </div> ) } # ===== file: src/client/VisualizeCard.tsx ===== /** * The `visualize` toolview: renders the persisted fragment from the call's * durable meta inside `<iframe sandbox="allow-scripts">` with the frame's own * CSP. Replay-stable by construction — everything drawn derives from the * logged call slice, never from the fragment file. * * Theme bridge: the card resolves the host's `--dsw-alias-*` design tokens * (whale-blue brand accent included) at render time and injects them into the * frame document as `--dsh-viz-*` variables; a mutation of the root element's * attributes or an OS appearance flip re-resolves them, so the frame follows * live theme switches. The frame body stays transparent to blend with the * conversation surface. * * Height: a sandboxed frame's document is unreachable from the parent, so the * frame posts its scroll height (tagged with this call's id) and the card * sizes the iframe, capped per mode with internal scrolling past the cap. */ import { useEffect, useMemo, useState, type CSSProperties } from 'react' import type { ToolCallViewProps } from '@deepseek-ai/dsh-client-ui-tool/client' import { visualizeMetaFrom, visualizeMetaFromArgs, type VisualizeMeta } from '../fragment.ts' import { buildFrameDoc, HEIGHT_MESSAGE_TYPE } from '../shell.ts' import { resolveTheme } from './theme.ts' /** Iframe height bounds; content beyond the cap scrolls inside the frame. */ const MIN_HEIGHT = 48 const HEIGHT_CAP: Record<'inline' | 'wide', number> = { inline: 800, wide: 1200 } const headerStyle: CSSProperties = { display: 'flex', alignItems: 'baseline', gap: 8, fontSize: 12, opacity: 0.65, margin: '2px 0 6px', overflow: 'hidden', whiteSpace: 'nowrap', } const frameStyle: CSSProperties = { display: 'block', width: '100%', border: 0, background: 'transparent', colorScheme: 'normal', } /** First text line of the durable result content, for the error row. */ function firstResultLine(content: readonly { type: string; text?: string }[]): string { for (const block of content) { if (block.type === 'text' && typeof block.text === 'string' && block.text.length > 0) { const newline = block.text.indexOf('\n') return newline === -1 ? block.text : block.text.slice(0, newline) } } return 'visualization failed' } /** The settled, well-formed card: header line plus the sandboxed frame. */ export function Frame({ meta, callId }: { meta: VisualizeMeta; callId: string }) { // Bumped by the observers below; each bump re-resolves the bridged palette. const [themeTick, setThemeTick] = useState(0) const [height, setHeight] = useState(MIN_HEIGHT) useEffect(() => { const bump = () => setThemeTick(tick => tick + 1) const observer = new MutationObserver(bump) // Both mount points: DSH toggles dark via a body attribute, other hosts // conventionally re-theme via root-element attributes. observer.observe(document.documentElement, { attributes: true }) observer.observe(document.body, { attributes: true }) const media = matchMedia('(prefers-color-scheme: dark)') media.addEventListener('change', bump) return () => { observer.disconnect() media.removeEventListener('change', bump) } }, []) useEffect(() => { const onMessage = (event: MessageEvent) => { const data: unknown = event.data if (typeof data !== 'object' || data === null) return const report = data as { type?: unknown; token?: unknown; height?: unknown } if (report.type !== HEIGHT_MESSAGE_TYPE || report.token !== callId) return if (typeof report.height !== 'number' || !Number.isFinite(report.height)) return setHeight(Math.max(MIN_HEIGHT, Math.min(Math.ceil(report.height), HEIGHT_CAP[meta.mode]))) } addEventListener('message', onMessage) return () => removeEventListener('message', onMessage) }, [callId, meta.mode]) const doc = useMemo(() => { const { themeVars, colorScheme } = resolveTheme() return buildFrameDoc({ fragment: meta.fragment, title: meta.title, themeVars, colorScheme, reportToken: callId, }) // themeTick is the deliberate re-resolution trigger for the palette read. }, [meta, callId, themeTick]) return ( <div> <div style={headerStyle} title={meta.path === '' ? meta.title : meta.path}> <span style={{ fontWeight: 500 }}>{meta.title}</span> {meta.path !== '' && ( <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{meta.path}</span> )} </div> <iframe sandbox="allow-scripts" referrerPolicy="no-referrer" title={meta.title} srcDoc={doc} style={{ ...frameStyle, height }} /> </div> ) } /** * Keyed toolview for the `visualize` tool. Running calls and malformed or * failed results stay quiet single lines; a well-formed persisted meta — or * the fragment in the call's own arguments for nested dispatches — mounts * the frame. */ export function VisualizeCard({ callId, block }: ToolCallViewProps) { // dsh 0.1.7 adds a preparing phase whose block carries no arguments yet. const argsRaw = 'kind' in block ? block.call?.argsRaw : 'argsRaw' in block ? block.argsRaw : undefined if (!('kind' in block)) { const live = visualizeMetaFromArgs(argsRaw) if (live !== undefined) return <Frame meta={live} callId={callId} /> return <div style={headerStyle}>Visualize · rendering…</div> } if (block.isError) { return <div style={headerStyle}>Visualize · {firstResultLine(block.content)}</div> } const meta = visualizeMetaFrom(block.meta) ?? visualizeMetaFromArgs(argsRaw) if (meta === undefined) { // A settled call without either the descriptor or a parseable fragment: // show the durable result text instead of guessing at markup. return <div style={headerStyle}>{firstResultLine(block.content)}</div> } return <Frame meta={meta} callId={callId} /> } # ===== file: src/client/folding.ts ===== /** * Whether the host chat currently folds a finished turn's process rows — and * with them every visualize card — out of sight. * * The answer is the Chat target's own "work details" preference, stored under * the `ui-chat` settings namespace as `transcriptView`. Two host generations * expose it through different services with the same snapshot face: * * - dsh 0.1.2–0.1.6: `settingsScope.bind({ namespace })`; modes `normal` and * `compact`, default `compact`, and only `compact` folds. * - dsh 0.1.7+: `configForms.get(namespace)`; modes `compact`, `standard`, * `detailed`, `verbose`, default `standard`, and every mode but `verbose` * folds (the legacy `normal`/`expanded` values map onto folding modes). * * dsh 0.1.1 has neither service and never folds. */ import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' /** Settings namespace owned by the host Chat target. */ const CHAT_NAMESPACE = 'ui-chat' /** The snapshot face both host settings services return for one namespace. */ interface ChatSettingsFace { getSnapshot(): { readonly value?: { readonly transcriptView?: unknown } | undefined } subscribe(listener: () => void): (() => void) | void } /** The context surface this module reads; optional lookup only. */ export interface FoldingHost { get(name: string): unknown } /** * Whether a saved mode folds on a 0.1.7+ host. An unset value is the host's * `standard` default. * @param view - saved `transcriptView`. * @returns true unless the reader chose `verbose`. */ export function configFormsFolds(view: unknown): boolean { return view !== 'verbose' } /** * Whether a saved mode folds on a 0.1.2–0.1.6 host. An unset value is the * host's `compact` default. * @param view - saved `transcriptView`. * @returns true for `compact` or unset. */ export function settingsScopeFolds(view: unknown): boolean { return view === undefined || view === 'compact' } /** * Adapt a settings face into a boolean observable. * @param face - the host namespace binding. * @param folds - the generation's mode rule. * @returns an observable whose snapshot is a primitive, so it is stable. */ function observe(face: ChatSettingsFace, folds: (view: unknown) => boolean): HostObservable<boolean> { return { getSnapshot: () => folds(face.getSnapshot().value?.transcriptView), subscribe: (listener) => { const dispose = face.subscribe(listener) return typeof dispose === 'function' ? dispose : () => undefined }, } } /** * Narrow an unknown value to an object exposing a method. * @param value - candidate service. * @param method - required method name. * @returns the value when it carries the method. */ function hasMethod<M extends string>(value: unknown, method: M): value is Record<M, (...args: never[]) => unknown> { return typeof value === 'object' && value !== null && typeof (value as Record<string, unknown>)[method] === 'function' } /** * Resolve the folding observable for this host. Call it once the Chat target * is up (its turn-tail declaration is the signal), when both settings * services, where present, are already provided. * @param host - the client context, read through optional `get`. * @returns whether finished turns currently fold, observed live. */ export function foldingSource(host: FoldingHost): HostObservable<boolean> { const forms = host.get('configForms') if (hasMethod(forms, 'get')) { return observe((forms.get as (namespace: string) => ChatSettingsFace)(CHAT_NAMESPACE), configFormsFolds) } const scope = host.get('settingsScope') if (hasMethod(scope, 'bind')) { return observe((scope.bind as (options: { namespace: string }) => ChatSettingsFace)({ namespace: CHAT_NAMESPACE }), settingsScopeFolds) } return { getSnapshot: () => false, subscribe: () => () => undefined } } # ===== file: src/client/index.tsx ===== /** * dsh-visualize, browser half: the settled visualization card under the * `visualize` key of the atomic toolview hole, the streaming preview in the * composer's input dock, and — on hosts that fold finished turns — the turn's * cards again under its final answer. Clients without this half degrade to * the tool's generic result text by the documented toolview fallback. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' // Type-only: pulls the `ctx.slots` Context merge. import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' // Type-only: pulls the `tool.call.toolview` SlotMap declaration. import type {} from '@deepseek-ai/dsh-client-ui-tool/client' // Type-only: pulls the `conversation.input.dock` SlotMap declaration. import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import type { ConversationNodeDefinition } from '@deepseek-ai/dsh-client-ui-conversation/client' import { VisualizeCard } from './VisualizeCard.tsx' import { StreamingPreview } from './StreamingPreview.tsx' import { foldingSource, type FoldingHost } from './folding.ts' import { selectTurnCards, turnCardsDefinition, TurnCards } from './TurnCards.tsx' export const name = 'dsh-visualize' export const inject = ['slots'] /** The Conversation event registry, where the host has one (dsh 0.1.2+). */ interface ConversationEvents { register(definition: ConversationNodeDefinition): () => void } /** * Look up the Conversation event registry without declaring the service, so * hosts that predate it still load the plugin. * @param host - client context. * @returns the registry, or undefined on dsh 0.1.1. */ function conversationEvents(host: FoldingHost): ConversationEvents | undefined { const service = host.get('uiConversation') as { events?: Partial<ConversationEvents> } | undefined return typeof service?.events?.register === 'function' ? service.events as ConversationEvents : undefined } /** * Turn-tail registration valid on both slot shapes the host has shipped: dsh * 0.1.5 and earlier declare a chain (register requires `select`, orders by * `priority`), 0.1.6 onward a list (register requires `id`, orders by * `order`). Each register validates only its own kind's field. The cards sit * after the host's deliverables and before other plugins' low-rank entries. * @param host - client context, for the folding preference. * @returns the register options. */ function turnTailOptions(host: FoldingHost) { const folds = foldingSource(host) return { name: 'conversation.chat.turnTail', id: 'dsh-visualize-cards', order: 100, priority: 100, select: selectTurnCards, inject: () => ({ hooks: { visualizeFolds: folds } }), } as const } /** * Register the keyed toolview and the dock preview. Waiting on each hole's * declaration mirrors the official registrants: entry application order is * loader-driven, and a direct register racing the declaration fails boot. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.slots.inject('tool.call.toolview', () => ctx.slots.register( { name: 'tool.call.toolview', key: 'visualize' }, VisualizeCard, )) ctx.slots.inject('conversation.input.dock', () => ctx.slots.register( { name: 'conversation.input.dock', id: 'visualize-stream', order: 30 }, StreamingPreview, )) // The Chat target declares the turn tail after its own settings and the // Conversation registry are up, so both are resolvable here. ctx.slots.inject('conversation.chat.turnTail', () => { const events = conversationEvents(ctx) if (events === undefined) return () => undefined const disposeDefinition = events.register(turnCardsDefinition as ConversationNodeDefinition) const disposeTail = ctx.slots.register(turnTailOptions(ctx), TurnCards) return () => { disposeTail() disposeDefinition() } }) } # ===== file: src/client/theme.ts ===== /** * Host-theme resolution shared by the settled card and the streaming preview: * reads the DSH `--dsw-alias-*` design tokens (whale-blue brand accent * included) off `document.body` and derives the host color scheme. The body is * the read point because DSH mounts the token definitions there (dark override * under `body[data-ds-dark-theme]`), and custom properties only cascade * DOWNWARD — a `:root`-mounted theme still reaches the body by inheritance, * the reverse read never works. Missing tokens resolve to empty strings the * shell drops, so the frame stylesheet's `light-dark()` fallbacks apply * outside DSH. */ /** Host design token → frame variable bridge (values resolved per render). */ const TOKEN_BRIDGE: readonly (readonly [string, string])[] = [ ['foreground', '--dsw-alias-label-primary'], ['card', '--dsw-alias-bg-layer-1'], ['muted-foreground', '--dsw-alias-label-caption'], ['border', '--dsw-alias-border-l2'], ['primary', '--dsw-alias-brand-primary-new-colorprimary-new-color'], ['primary-foreground', '--dsw-alias-label-primary-inverted'], ] /** The bridged palette and scheme for one frame document build. */ export interface ResolvedTheme { themeVars: Record<string, string> colorScheme: 'light' | 'dark' } /** * Resolve the bridged palette and the host color scheme from computed style. * @returns the palette map and scheme for {@link buildFrameDoc}. */ export function resolveTheme(): ResolvedTheme { const computed = getComputedStyle(document.body) const themeVars: Record<string, string> = {} for (const [frameName, hostToken] of TOKEN_BRIDGE) { themeVars[frameName] = computed.getPropertyValue(hostToken) } const scheme = computed.colorScheme const colorScheme = scheme.includes('dark') && !scheme.includes('light') ? 'dark' : scheme.includes('light') && !scheme.includes('dark') ? 'light' : document.body.hasAttribute('data-ds-dark-theme') ? 'dark' : matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' return { themeVars, colorScheme } } # ===== file: src/fragment.ts ===== /** * Pure fragment contract shared by the tool (validation at execute time), the * browser card (meta narrowing at render time), and the specs. No I/O and no * DOM so both halves and vitest can load it unchanged. * * A *fragment* is the model-authored inline-HTML body of one visualization: * literal markup without a document skeleton. The card owns the skeleton — it * wraps the fragment in a sandboxed iframe document with its own CSP — so a * fragment that ships its own `<!doctype>`/`<html>`/`<head>`/`<body>` would * nest documents and is rejected loudly instead of rendered broken. * * @module @nagi-ovo/dsh-visualize/fragment */ /** * Wire name of the tool, the keyed toolview, and the streaming-preview match. * Lives in this pure module so the browser half can import it without pulling * the node-side tool implementation into the client bundle. */ export const VISUALIZE_TOOL_NAME = 'visualize' /** Width intent of one visualization card. */ export type VisualizeMode = 'inline' | 'wide' /** * What one `visualize` call does: render a card from whole markup, or patch * the markup of a card an earlier call already rendered. */ export type VisualizeAction = 'create' | 'update' /** The `tool/result` meta descriptor persisted for replay-stable rendering. */ export interface VisualizeMeta { /** Discriminant for consumers sharing the meta channel. */ kind: 'visualize' /** The validated fragment body, inlined so replay never re-reads the file. */ fragment: string /** Concise human title shown in the card header. */ title: string /** Width intent; `wide` asks the card for the expanded inline surface. */ mode: VisualizeMode /** Session-relative or absolute source path, kept for provenance display. */ path: string } /** Document-skeleton tags a fragment must not contain (case-insensitive). */ const SKELETON_TAG = /<!doctype\b|<\s*(?:html|head|body)\b/iu /** * Validate one fragment against the inline contract. * @param fragment - the file content the model wrote. * @param maxBytes - deployment size ceiling for one fragment. * @returns the fragment's UTF-8 size in bytes. * @throws Error naming the violated rule; the tool surfaces it as `isError`. */ export function validateFragment(fragment: string, maxBytes: number): number { if (fragment.trim().length === 0) { throw new Error('invalid visualization: the fragment file is empty') } const sizeBytes = byteLength(fragment) if (sizeBytes > maxBytes) { throw new Error( `invalid visualization: fragment is ${sizeBytes} bytes, over the ${maxBytes}-byte limit — ` + 'shrink the inline data first (fewer rows, coarser buckets, fewer decimals)', ) } const skeleton = SKELETON_TAG.exec(fragment) if (skeleton) { throw new Error( `invalid visualization: fragment contains a document-skeleton tag (${JSON.stringify(skeleton[0])}) — ` + 'write only the inline body; the host supplies <!doctype>, <html>, <head>, and <body>', ) } return sizeBytes } /** * Characters of real card content quoted back when a patch fails to apply, so * the model can correct `old_str` from the true bytes without re-reading the * whole card. */ const PATCH_CONTEXT_CHARS = 160 /** * Shortest matching prefix of a failed `old_str` still worth reporting as a * location hint; below this any HTML shares enough characters to point * somewhere misleading. */ const MIN_ANCHOR_CHARS = 12 /** * Replace one exact, unique occurrence of `oldStr` in a rendered card's * fragment. Iterating by patch instead of re-emitting the whole fragment is * what keeps a small correction small: the model re-states only the changed * region, and the card's markup never enters its output twice. * * A patch that does not resolve to exactly one site is refused rather than * guessed at, because both wrong outcomes are silent — a near-miss would edit * markup the model never saw, and an ambiguous match would edit an arbitrary * one of several sites. The thrown message carries the surrounding real * content so the caller can correct `old_str` within the same turn. * * @param base - the current fragment of the card being patched. * @param oldStr - exact text to replace, whitespace included. * @param newStr - replacement text; empty deletes the matched region. * @returns the patched fragment. * @throws Error naming why the patch did not apply; the tool surfaces it as `isError`. */ export function applyFragmentPatch(base: string, oldStr: string, newStr: string): string { if (oldStr.length === 0) { throw new Error('invalid visualization patch: old_str is empty — pass the exact card text to replace') } const first = base.indexOf(oldStr) if (first === -1) { throw new Error(`invalid visualization patch: old_str does not appear in the card. ${nearestAnchor(base, oldStr)}`) } if (base.indexOf(oldStr, first + oldStr.length) !== -1) { throw new Error( `invalid visualization patch: old_str appears ${countOccurrences(base, oldStr)} times in the card — ` + 'extend it with neighbouring lines until exactly one site matches', ) } return base.slice(0, first) + newStr + base.slice(first + oldStr.length) } /** * Describe where a failed `old_str` stopped matching: the longest prefix of it * that does occur, and the card's real text at that site. Prefix occurrence is * monotone in length, so the longest one is a binary search. * @param base - the current fragment of the card being patched. * @param oldStr - the `old_str` that failed to match. * @returns a sentence naming the divergence point, or advising a full re-render. */ function nearestAnchor(base: string, oldStr: string): string { let matched = 0 let beyond = oldStr.length while (matched < beyond) { const mid = Math.ceil((matched + beyond) / 2) if (base.includes(oldStr.slice(0, mid))) matched = mid else beyond = mid - 1 } if (matched < MIN_ANCHOR_CHARS) { return 'None of it matched, so the card is not in the state you assumed — re-render the whole card instead.' } const at = base.indexOf(oldStr.slice(0, matched)) return `Its first ${matched} characters do match, at offset ${at}, where the card actually reads ` + `${JSON.stringify(base.slice(at, at + PATCH_CONTEXT_CHARS))} — correct old_str against that and retry.` } /** * Count non-overlapping occurrences of a needle, matching the replacement * semantics {@link applyFragmentPatch} would apply. * @param base - the text to scan. * @param needle - the non-empty needle to count. * @returns the number of non-overlapping occurrences. */ function countOccurrences(base: string, needle: string): number { let count = 0 for (let at = base.indexOf(needle); at !== -1; at = base.indexOf(needle, at + needle.length)) count += 1 return count } /** * Narrow one persisted `tool/result` meta value to a {@link VisualizeMeta}. * Wire data cannot be trusted to match the compiled shape (an older or newer * host may have logged it), so a mismatch declines to `undefined` — the caller * falls back to the generic presentation instead of throwing on replay. * @param meta - the raw persisted meta value. * @returns the narrowed descriptor, or `undefined` for the generic path. */ export function visualizeMetaFrom(meta: unknown): VisualizeMeta | undefined { if (typeof meta !== 'object' || meta === null) return undefined const record = meta as Record<string, unknown> if (record['kind'] !== 'visualize') return undefined const { fragment, title, mode, path } = record if (typeof fragment !== 'string' || typeof title !== 'string' || typeof path !== 'string') return undefined if (mode !== 'inline' && mode !== 'wide') return undefined return { kind: 'visualize', fragment, title, mode, path } } /** * Rebuild a descriptor from the call's own arguments when persisted meta is * missing. Nested dispatches (`run_code` / PTC) never project presentation * meta, but they do log `arguments`; a create's fragment is in that JSON. * * An `update` without a fragment cannot be rebuilt from the wire (the patched * markup lives in execute's value, which nested logs do not keep) and * declines. Incomplete streaming JSON is not parsed via throw/catch: only a * trailing `}` is treated as complete, otherwise a *closed* `"fragment"` * string is taken through {@link extractStreamingFragment}'s scanner. * @param argsRaw - running `block.argsRaw` or settled `block.call.argsRaw`. * @returns a card descriptor, or `undefined` to keep the quiet fallback. */ export function visualizeMetaFromArgs(argsRaw: unknown): VisualizeMeta | undefined { if (typeof argsRaw !== 'string' || argsRaw.length === 0) return undefined const complete = parseCompleteArgs(argsRaw) if (complete !== undefined) { // Default action is create. Update's full markup is not in the arguments. if (complete['action'] === 'update' && typeof complete['fragment'] !== 'string') return undefined return descriptorFromFields(complete['fragment'], complete['title'], complete['mode'], complete['path']) } const closed = scanFragment(argsRaw, true) if (closed === undefined) return undefined return descriptorFromFields(closed, undefined, undefined, undefined) } /** * Accept only a complete JSON object, gated on a trailing `}` so a streaming * prefix never enters `JSON.parse`. * @param raw - accumulated argument text. * @returns the object, or `undefined` when the prefix is incomplete or illegal. */ function parseCompleteArgs(raw: string): Record<string, unknown> | undefined { let end = raw.length while (end > 0) { const ch = raw[end - 1]! if (ch === ' ' || ch === '\n' || ch === '\r' || ch === '\t') { end -= 1 continue } break } if (end === 0 || raw[end - 1] !== '}') return undefined try { const parsed: unknown = JSON.parse(raw.slice(0, end)) if (typeof parsed !== 'object' || parsed === null) return undefined return parsed as Record<string, unknown> } catch { return undefined } } /** * Narrow wire fields into a descriptor. Empty markup after dropping a * trailing half-script is declined rather than mounting a blank frame. */ function descriptorFromFields( fragment: unknown, title: unknown, mode: unknown, path: unknown, ): VisualizeMeta | undefined { if (typeof fragment !== 'string') return undefined if (mode !== undefined && mode !== 'inline' && mode !== 'wide') return undefined const markup = trimStreamingScripts(fragment) if (markup.trim().length === 0) return undefined return { kind: 'visualize', fragment: markup, title: typeof title === 'string' && title.trim().length > 0 ? title.trim() : 'Visualization', mode: mode === 'wide' ? 'wide' : 'inline', path: typeof path === 'string' ? path : '', } } /** * UTF-8 byte length without Buffer, so the browser bundle needs no polyfill. * @param text - the string to measure. * @returns its UTF-8 encoding length in bytes. */ function byteLength(text: string): number { return new TextEncoder().encode(text).length } /** JSON short escapes, keyed by the character after the backslash. */ const JSON_ESCAPES: Record<string, string> = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r
# ===== file: lib/client.js =====
window.__ModuleLoader__.load({
id: "@nagi-ovo/dsh-visualize",
factory: (require) => {
var module = { exports: {} };
var exports = module.exports;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
let react = require("react");
let react_jsx_runtime = require("react/jsx-runtime");
/**
* Narrow one persisted `tool/result` meta value to a {@link VisualizeMeta}.
* Wire data cannot be trusted to match the compiled shape (an older or newer
* host may have logged it), so a mismatch declines to `undefined` — the caller
* falls back to the generic presentation instead of throwing on replay.
* @param meta - the raw persisted meta value.
* @returns the narrowed descriptor, or `undefined` for the generic path.
*/
function visualizeMetaFrom(meta) {
if (typeof meta !== "object" || meta === null) return void 0;
const record = meta;
if (record["kind"] !== "visualize") return void 0;
const { fragment, title, mode, path } = record;
if (typeof fragment !== "string" || typeof title !== "string" || typeof path !== "string") return void 0;
if (mode !== "inline" && mode !== "wide") return void 0;
return {
kind: "visualize",
fragment,
title,
mode,
path
};
}
/**
* Rebuild a descriptor from the call's own arguments when persisted meta is
* missing. Nested dispatches (`run_code` / PTC) never project presentation
* meta, but they do log `arguments`; a create's fragment is in that JSON.
*
* An `update` without a fragment cannot be rebuilt from the wire (the patched
* markup lives in execute's value, which nested logs do not keep) and
* declines. Incomplete streaming JSON is not parsed via throw/catch: only a
* trailing `}` is treated as complete, otherwise a *closed* `"fragment"`
* string is taken through {@link extractStreamingFragment}'s scanner.
* @param argsRaw - running `block.argsRaw` or settled `block.call.argsRaw`.
* @returns a card descriptor, or `undefined` to keep the quiet fallback.
*/
function visualizeMetaFromArgs(argsRaw) {
if (typeof argsRaw !== "string" || argsRaw.length === 0) return void 0;
const complete = parseCompleteArgs(argsRaw);
if (complete !== void 0) {
if (complete["action"] === "update" && typeof complete["fragment"] !== "string") return void 0;
return descriptorFromFields(complete["fragment"], complete["title"], complete["mode"], complete["path"]);
}
const closed = scanFragment(argsRaw, true);
if (closed === void 0) return void 0;
return descriptorFromFields(closed, void 0, void 0, void 0);
}
/**
* Accept only a complete JSON object, gated on a trailing `}` so a streaming
* prefix never enters `JSON.parse`.
* @param raw - accumulated argument text.
* @returns the object, or `undefined` when the prefix is incomplete or illegal.
*/
function parseCompleteArgs(raw) {
let end = raw.length;
while (end > 0) {
const ch = raw[end - 1];
if (ch === " " || ch === "\n" || ch === "\r" || ch === " ") {
end -= 1;
continue;
}
break;
}
if (end === 0 || raw[end - 1] !== "}") return void 0;
try {
const parsed = JSON.parse(raw.slice(0, end));
if (typeof parsed !== "object" || parsed === null) return void 0;
return parsed;
} catch {
return;
}
}
/**
* Narrow wire fields into a descriptor. Empty markup after dropping a
* trailing half-script is declined rather than mounting a blank frame.
*/
function descriptorFromFields(fragment, title, mode, path) {
if (typeof fragment !== "string") return void 0;
if (mode !== void 0 && mode !== "inline" && mode !== "wide") return void 0;
const markup = trimStreamingScripts(fragment);
if (markup.trim().length === 0) return void 0;
return {
kind: "visualize",
fragment: markup,
title: typeof title === "string" && title.trim().length > 0 ? title.trim() : "Visualization",
mode: mode === "wide" ? "wide" : "inline",
path: typeof path === "string" ? path : ""
};
}
/** JSON short escapes, keyed by the character after the backslash. */
const JSON_ESCAPES = {