scaling-swarms / frontend /src /editor /embeds /embed-tool-exec.ts
tfrere's picture
tfrere HF Staff
Cursor
feat(mcp): chart and publish tools, structured errors, JSON 404s
2525af6
Raw History Blame Contribute Delete
6.52 kB
import type { EmbedDataStore } from "./embed-data-store";
import type { EmbedStore } from "./embed-store";
import { MAX_EMBED_SIZE, ensureUniqueFilename, slugify } from "#shared/embed-contract";
import type { EmbedVersionStore } from "./embed-versions";
/**
* Where the studio reads and writes chart HTML. The default writes straight
* into the shared embed store; drafts plug in here without touching the
* tool logic.
*/
export interface EmbedWorkspace {
read(src: string): string;
write(src: string, html: string): void;
has(src: string): boolean;
/** Move the content to `newSrc` (the old key disappears). */
rename(oldSrc: string, newSrc: string): void;
}
export function embedStoreWorkspace(store: EmbedStore): EmbedWorkspace {
return {
read: (src) => store.get(src),
write: (src, html) => store.set(src, html),
has: (src) => store.has(src),
rename: (oldSrc, newSrc) => store.rename(oldSrc, newSrc),
};
}
export interface EmbedMeta {
title?: string;
source?: string;
}
export interface EmbedToolDeps {
workspace: EmbedWorkspace;
dataStore?: EmbedDataStore | null;
versions?: EmbedVersionStore | null;
/** Chart the tool acts on. */
src: string;
author?: string;
/** Id of the user message that started this agent turn. */
turnId?: string;
/** createEmbed({ filename }) renames the chart only when allowed (default true). */
allowRename?: boolean;
onMeta?: (src: string, meta: EmbedMeta) => void;
onWrite?: (src: string) => void;
}
export interface EmbedToolResult {
output: string;
/** Set when createEmbed moved the chart to a new file name. */
renamedTo?: string;
}
/**
* Hard cap on the number of characters we inline when the agent reads
* a data file. Above this, the tool returns a truncated preview with
* a warning so the model doesn't blow past its context window on a
* single tool call.
*/
export const MAX_DATA_INLINE = 120_000;
export { MAX_EMBED_SIZE, slugify, ensureUniqueFilename };
/** Run one Embed Studio tool call against the workspace. */
export function runEmbedTool(toolName: string, args: unknown, deps: EmbedToolDeps): EmbedToolResult {
const { workspace: ws, dataStore, versions, src: currentSrc } = deps;
if (!currentSrc) return { output: "No embed src specified" };
const recordVersion = (target: string, html: string) => {
versions?.record(target, html, { kind: "agent", author: deps.author, turnId: deps.turnId });
};
switch (toolName) {
case "createEmbed": {
const { html, title, source, filename } = (args ?? {}) as {
html?: string;
title?: string;
source?: string;
filename?: string;
};
if (!html?.trim()) return { output: "ERROR: html cannot be empty" };
const stripped = html.trim();
if (stripped.length > MAX_EMBED_SIZE) {
return {
output: `ERROR: chart too large (${stripped.length} bytes, max ${MAX_EMBED_SIZE}). Simplify the code.`,
};
}
// Resolve the target src: if the agent proposed a filename slug,
// slugify + ensure uniqueness. Never rename the banner (its name is
// load-bearing for the article layout).
let targetSrc = currentSrc;
if (filename && currentSrc !== "banner.html" && deps.allowRename !== false) {
targetSrc = ensureUniqueFilename(slugify(filename), (n) => ws.has(n), currentSrc);
}
if (targetSrc !== currentSrc) {
if (ws.has(currentSrc)) ws.rename(currentSrc, targetSrc);
versions?.rename(currentSrc, targetSrc);
}
ws.write(targetSrc, stripped);
recordVersion(targetSrc, stripped);
if (title || source) deps.onMeta?.(targetSrc, { title, source });
deps.onWrite?.(targetSrc);
const lines = stripped.split("\n").length;
const renamed = targetSrc !== currentSrc ? ` [renamed to ${targetSrc}]` : "";
return {
output: `chart created (${lines} lines, ${stripped.length} chars)${title ? ` - "${title}"` : ""}${renamed}`,
...(targetSrc !== currentSrc ? { renamedTo: targetSrc } : {}),
};
}
case "patchEmbed": {
const { search, replace } = (args ?? {}) as { search?: string; replace?: string };
const current = ws.read(currentSrc);
if (!current) return { output: "ERROR: no chart exists yet. Use createEmbed first." };
if (!search) return { output: "ERROR: search block cannot be empty" };
if (!current.includes(search)) {
return {
output:
"ERROR: search block not found in current chart. " +
"Call readEmbed to see the exact current content, then retry.",
};
}
const patched = current.replace(search, replace ?? "");
if (patched.length > MAX_EMBED_SIZE) {
return {
output: `ERROR: patch would exceed size limit (${patched.length} bytes, max ${MAX_EMBED_SIZE}).`,
};
}
ws.write(currentSrc, patched);
recordVersion(currentSrc, patched);
deps.onWrite?.(currentSrc);
return { output: "patch applied successfully" };
}
case "readEmbed": {
const current = ws.read(currentSrc);
return { output: current || "(no chart yet)" };
}
case "listDataFiles": {
if (!dataStore) return { output: "(no data files - data store unavailable)" };
const files = dataStore.list();
if (files.length === 0) return { output: "(no data files attached)" };
return {
output: files
.map((f) => {
const cols = f.columns && f.columns.length > 0 ? ` columns=[${f.columns.join(", ")}]` : "";
const rows = f.rowCount !== undefined ? ` rows=${f.rowCount}` : "";
return `- ${f.name} (${f.ext}, ${f.size} bytes)${rows}${cols}`;
})
.join("\n"),
};
}
case "readDataFile": {
if (!dataStore) return { output: "ERROR: data store unavailable" };
const { name } = (args ?? {}) as { name?: string };
if (!name) return { output: "ERROR: missing file name" };
const file = dataStore.get(name);
if (!file) return { output: `ERROR: data file "${name}" not found` };
const content = file.content;
if (content.length <= MAX_DATA_INLINE) return { output: content };
return {
output:
content.slice(0, MAX_DATA_INLINE) +
`\n\n[TRUNCATED - full file is ${content.length} chars, showing first ${MAX_DATA_INLINE}]`,
};
}
default:
return { output: `Unknown tool: ${toolName}` };
}
}