Download backend/src/agent/embed-skill.generated.ts from HuggingFaceSwarms/scaling-swarms: direct link, hf CLI and curl.
- Browser
- Download file 21.7 kB
-
https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/backend/src/agent/embed-skill.generated.ts
- Command line
-
hf download hf://spaces/HuggingFaceSwarms/scaling-swarms/backend/src/agent/embed-skill.generated.ts
-
curl -L -o embed-skill.generated.ts https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/backend/src/agent/embed-skill.generated.ts
21.7 kB
| // GENERATED FILE - do not edit by hand. | |
| // Source: backend/embed-kit/{contract,banners,dataviz}.md | |
| // Regenerate with `npm run gen:embed-kit` in backend/. | |
| export const EMBED_CONTRACT_MD = "# Embed runtime and contract\n\nEvery embed is rendered in its own iframe, built from the embed HTML by\n`buildEmbedSrcdoc`: in the editor, in the Embed Studio preview, in the\npublished article and in the PDF. Before the embed, that document already\nprovides `window.Embed` (the shared runtime), D3 (loaded by the runtime),\nthe theme CSS variables for light and dark, and `window.ColorPalettes`.\nAn embed only describes its chart; the runtime owns the plumbing.\n\n## Shape of an embed\n\n```html\n<div class=\"d3-my-chart\"></div>\n<style>\n .d3-my-chart { position: relative; color: var(--text-color); font-size: 12px; }\n .d3-my-chart svg { display: block; width: 100%; overflow: visible; }\n .d3-my-chart .axis path, .d3-my-chart .axis line { stroke: var(--axis-color); }\n .d3-my-chart .axis text { fill: var(--tick-color); }\n .d3-my-chart .grid line { stroke: var(--grid-color); }\n</style>\n<script>\n Embed.mount('d3-my-chart', (ctx) => {\n // 1. Setup, runs once: data, scales, persistent DOM.\n const rows = [\n { model: 'A', score: 71.2 },\n { model: 'B', score: 64.8 },\n ];\n const svg = d3.select(ctx.root).append('svg');\n ctx.describe(`Bar chart of benchmark scores for ${rows.length} models; A is highest.`);\n\n // 2. Render, runs on first paint, width change, theme or palette change.\n return ({ width, height, theme, isDark }) => {\n const h = Math.max(240, Math.round(width * 0.5));\n svg.attr('viewBox', `0 0 ${width} ${h}`).attr('height', h);\n // ... data joins ...\n };\n });\n</script>\n```\n\nRules for the fragment itself:\n\n- The root `<div>` is the first element of the fragment, with a unique,\n descriptive class (`d3-` prefix). No `id` on the root.\n- Every CSS rule is prefixed with the root class. Never style `body`,\n `html`, `svg` or `text` unprefixed.\n- The script is a classic inline script calling `Embed.mount` at top\n level. Do not wrap the call in `DOMContentLoaded`, `setTimeout` or an\n async function: the runtime finds the container from\n `document.currentScript`, which only exists while the script is parsed.\n- No globals. Keep state in the setup closure.\n- Query only inside `ctx.root` (`ctx.root.querySelector`, `d3.select(ctx.root)`).\n- Never hand-roll D3 loading, mount guards, `ResizeObserver` or theme\n observers: the runtime does all of it.\n\n## `Embed.mount(rootClass, setup, options)`\n\n| Option | Default | Meaning |\n|---|---|---|\n| `deps` | `['d3']` | Libraries to load before `setup`. Use `[]` for vanilla JS / canvas embeds. |\n| `resize` | `'width'` | Re-render on width changes only. `'size'` also re-renders on height changes (banners, fill-the-box layouts). |\n| `lazy` | `true` | Mount when the embed nears the viewport. Headless browsers and print always mount eagerly. |\n\n`setup(ctx)` may be async. It may return a render function, or nothing\nfor static or self-driven embeds (then the embed is ready when setup\nresolves).\n\nThe render function receives `{ width, height, theme, isDark }`, where\n`width` / `height` are the root's client size. The first render runs\nsynchronously after setup; later renders are coalesced to one per frame.\nMake render idempotent: use data joins (`selection.join()`), never append\nunconditionally inside it.\n\n## `ctx`\n\n| Member | Purpose |\n|---|---|\n| `root` | The embed's root element. |\n| `colors(kind, n)` | `kind`: `'categorical'`, `'sequential'` or `'diverging'`. Returns `n` colors from the article palette. |\n| `labelColor(color, t = 0.4)` | A palette color mixed toward the text color, so text in a series color stays readable on both themes. |\n| `textOn(background)` | `'#111111'` or `'#ffffff'`, whichever contrasts more with a filled mark (heatmap cell, bar, node). |\n| `describe(text)` | Accessible description: sets `role=\"img\"` and `aria-label` on the top-level svg/canvas and `data-description` on the root. |\n| `rerender()` | Ask for a render (after a control changes, for example). |\n| `animate(tick)` | `tick(time, dt)` on every frame. Paused off-screen and in background tabs; with reduced motion it runs exactly once. |\n| `reducedMotion` | `true` when the visitor prefers reduced motion. |\n| `theme()` | `'light'` or `'dark'`, read at call time. |\n| `signal` | `AbortSignal` aborted when the embed is removed. Pass it to `addEventListener(..., { signal })`. |\n| `onCleanup(fn)` | Run `fn` on removal (timers, workers, WebGL contexts). |\n| `fail(error)` | Show an error inside the embed and mark it failed. Thrown errors in setup or render do this automatically. |\n| `config` | Values of the tweakable settings declared in the fragment (see below), `{ key: value }`. Read them inside render. |\n\nLifecycle signals: the root gets `data-embed-status=\"ready\"` or `\"error\"`\nand dispatches a bubbling `embed:ready` / `embed:error` event after the\nfirst successful render (or failure). `Embed.whenReady()` resolves when\nevery mounted embed has settled.\n\n## Tweakable settings (`config`)\n\nDeclare the few settings an author is likely to adjust in a JSON block\nright after the root. The editor turns it into a Tweak panel (sliders,\ncolor pickers, selects, toggles, text fields) that updates the chart\ninstantly, without asking the model, and saves the new values back into\nthis block:\n\n```html\n<div class=\"d3-my-chart\"></div>\n<script type=\"application/json\" data-embed-config>\n{\n \"title\": { \"type\": \"text\", \"label\": \"Title\", \"value\": \"Accuracy over training\" },\n \"highlight\": { \"type\": \"color\", \"label\": \"Highlight\", \"value\": \"\" },\n \"barGap\": { \"type\": \"range\", \"label\": \"Bar gap\", \"min\": 0, \"max\": 0.6, \"step\": 0.05, \"value\": 0.2 },\n \"scale\": { \"type\": \"select\", \"label\": \"Y scale\", \"options\": [\"linear\", \"log\"], \"value\": \"linear\" },\n \"showLegend\": { \"type\": \"toggle\", \"label\": \"Legend\", \"value\": true }\n}\n</script>\n```\n\n- Types: `range` (`min`, `max`, `step`), `color`, `select` (`options`),\n `toggle`, `text`. Every field has a `label` and a `value`.\n- `ctx.config.barGap` is the current value. Read config inside render\n (not in setup), so a tweak re-renders with the new value.\n- 2 to 6 fields: the settings that change the reading (highlighted\n series, scale, sort, gap, label text), not every margin.\n- Visible text written by the chart (title, axis titles, annotations) comes\n from `text` fields, so authors can fix a label by clicking it.\n- `color` fields default to `\"\"`: use a palette color when empty, so the\n chart keeps following the theme until someone picks a color.\n- The block must be valid JSON (no comments, no trailing commas).\n\n## Data\n\nThe iframe cannot fetch files. Data lives in the script as a JS literal:\n\n- Attached files (CSV, JSON, ...) are read by the author or the agent and\n inlined as a parsed array of objects. Aggregate or downsample large\n files first: above about 5k marks prefer canvas, above about 50k\n pre-aggregate.\n- Never fabricate columns or values for real data. Synthetic data is fine\n for demos and banners; seed it (`d3.randomLcg(42)`) so it is identical\n on every load and in the PDF.\n- Validate what you rely on and fail with a useful message:\n `if (!rows.length) throw new Error('No rows to plot.');`\n\n## Theming\n\nTheme with CSS variables first. They switch instantly with the theme and\nneed no JavaScript:\n\n| Variable | Use |\n|---|---|\n| `--text-color` | Primary text, direct labels, emphasized values. |\n| `--muted-color` | Secondary text, axis titles, annotations. |\n| `--axis-color`, `--tick-color`, `--grid-color` | Axis lines, tick labels, gridlines. |\n| `--border-color` | Separators, swatch outlines, control borders. |\n| `--surface-bg` | Tooltips, popovers, controls. |\n| `--page-bg` | The page color, for knock-out strokes around marks. |\n| `--primary-color` | The one accent: highlight, selection, focus. |\n\nPalette colors come from `ctx.colors()` and must be read inside render,\nbecause they change with the theme and the primary color. Theme flips\nreach the iframe as a `palettes:updated` event and the runtime\nre-renders, so no `MutationObserver` on `data-theme` is needed.\n\nGotchas:\n\n- **Palette colors as text.** Palette colors are tuned for marks and are\n often too light for text. Use `ctx.labelColor(color)` for text in a\n series color, or `--text-color` next to a swatch.\n- **Text on filled marks.** For labels over heatmap cells, bars or nodes,\n color them with `ctx.textOn(fill)`, never with the theme text color and\n never with a hand-written lightness threshold.\n- **Coloring SVG text.** Prefer `.style('fill', ...)` or a scoped CSS rule\n over `.attr('fill', ...)`, so a later CSS rule cannot silently win.\n- **Background.** The root and its children are transparent unless the\n user asks for a surface; the article provides the page. Use\n `--surface-bg` if you need one, never a hardcoded color.\n- **Hardcoded colors** (`#000`, `white`, `steelblue`) break one of the two\n themes. Every color is a variable, a palette color, or `textOn()`.\n- **`--primary-color` is `oklch()`** in articles, and `d3.color` and the\n `d3.interpolate*` helpers cannot parse it (they return null or black).\n Use it as is in CSS, pass it to `ctx.labelColor()` / `ctx.textOn()`, or\n take a palette color from `ctx.colors()` when you need to compute with it.\n\n## Layout and responsiveness\n\n- Width comes from the render argument. Derive height from width with a\n floor and a ceiling (`Math.max(240, Math.min(420, width * 0.5))`), and\n set it on the svg with a matching `viewBox`. The iframe grows to the\n content height on its own.\n- Check at 360px. Below about 520px, drop what does not fit: fewer ticks\n (`Math.floor(innerW / 80)`), direct labels replaced by a legend,\n controls stacked.\n- Nothing may overflow the root horizontally.\n- Labels must not collide: shorten, rotate, thin out, or nudge them.\n\n## UI: controls, legends, tooltips\n\n- Controls, legends and tooltips are HTML inside the root, never SVG.\n- Controls are labeled `<label>` + `<select>` / `<input>`, styled with the\n theme variables, with a visible focus style. Changing a control updates\n state and calls `ctx.rerender()`.\n- Prefer direct labels on the marks over a legend. When a legend is\n needed (many series, narrow screens), make it compact HTML: swatch plus\n name.\n- One tooltip element per embed, absolutely positioned inside the root\n (`position: relative` on the root), clamped so it stays inside the\n root, hidden on pointer leave. Escape any data value you inject as HTML.\n- Use pointer events (`pointermove`, `pointerleave`) so touch works.\n\n## Accessibility\n\n- Call `ctx.describe()` with the chart type, what is plotted, and the\n main takeaway in one or two sentences. Compute it from the data.\n- Never encode meaning by color alone: pair color with labels, position,\n or shape.\n- Interactive elements are focusable, labeled (`aria-label` for icon\n buttons), and have `:focus-visible` styles.\n\n## Motion\n\n- Use `ctx.animate(tick)` for loops; it handles visibility and reduced\n motion.\n- Keep transitions short (under 300ms) and skip them when\n `ctx.reducedMotion` is true.\n- Animation is never the only way to see the data: the final state must\n be readable as a still (the PDF shows a single frame).\n\n## Other libraries\n\nD3 is loaded by the runtime. For anything else (Three.js, Plotly), pass\n`deps: []` and load it inside setup with a single script tag (check the\nglobal first), pin the version, and release GPU resources in\n`ctx.onCleanup`."; | |
| export const EMBED_BANNERS_MD = "# Banners (article hero)\n\nA banner is the decorative embed at the top of the article, above the\ntitle. It follows the embed contract with these differences.\n\n| Constraint | Value |\n|---|---|\n| Box | 5:2, max-width 980px, so 980x392 at full width. The iframe runs in full-bleed mode: no body padding, and the root is forced to fill it. |\n| Root CSS | `width: 100%; aspect-ratio: 5 / 2; overflow: hidden; position: relative;` (keeps the 5:2 box wherever the banner is rendered). |\n| Mount | `Embed.mount('<root-class>', setup, { resize: 'size' })` and draw from both `width` and `height`. |\n| SVG / canvas | Fills the root edge to edge (`width: 100%; height: 100%; display: block`), no margins. |\n| Background | Transparent, like every embed. Weight comes from shapes, lines, motion and color, never from a filled rectangle. |\n| UI | No legend, no controls, no tooltip unless explicitly asked. |\n| Colors | `ctx.colors('sequential' | 'categorical', n)` and `--primary-color`, read inside render so the banner follows the theme and accent color. |\n| Motion | Optional, subtle (drift, slow rotation) through `ctx.animate`. |\n\n## Style direction\n\nBanners set the mood of the article. Prefer abstract or generative\nvisuals tied to the topic: particle fields, flow fields, constellations,\nwave forms, topographic lines, isotype grids, network meshes. Data can be\nsynthetic; seed randomness (`d3.randomLcg(42)`) so the banner looks the\nsame on every load and in the PDF.\n\n## Checks\n\n- Looks good at 980x392 and at 360px wide, in light and dark.\n- The lightest palette stops vanish on a light page: skip them or raise\n their opacity.\n- With reduced motion, the single drawn frame is a complete composition.\n- Thousands of SVG nodes animated per frame are slow: above about 1,500\n moving elements, use canvas."; | |
| export const DATAVIZ_DESIGN_MD = "# Design data visualizations\n\nThis guide is about what makes a figure clear and honest. How to build it\nas an embed (runtime, theming, sizing) lives in the embed contract. Use\nboth when creating a chart.\n\n## 1. Start from the claim\n\n- Write down the one sentence the figure must prove (\"Longer context\n lowers loss after 20B tokens\"). If you cannot, ask the user. Every\n design decision below serves that sentence.\n- The embed `title` states the finding or the question, not the chart\n type (\"Longer context wins after 20B tokens\", not \"Loss chart\").\n `desc` says how to read it: units, what bands mean, how many seeds.\n- One figure, one message. Split a figure that argues two things.\n- The default view, without any interaction, must already show the claim.\n\n## 2. Choose the chart\n\n| Question | Default chart | Avoid |\n|---|---|---|\n| How does a metric evolve (steps, tokens, time)? | Line chart, x = progress | Bars per step |\n| Compare one value across categories | Horizontal bars, sorted by value | Pie with more than 3 slices, 3D |\n| Compare a few values across 2 groupings | Grouped bars or dot plot | Stacked bars when parts must be compared |\n| Part of a whole | Stacked bar (one per group) or a single 100% bar | Donut for precise reading |\n| Relationship between two measures | Scatter, optionally with a fit | Two lines on dual axes |\n| Distribution | Histogram, box, or strip/beeswarm for small n | Mean bar without spread |\n| Ranking across many models and benchmarks | Heatmap or table with inline bars | Radar chart |\n| Before / after, two conditions | Slope chart or dumbbell | Two separate bar charts |\n| Flows between stages | Sankey | Chord for few categories |\n| Many series that tangle | Small multiples with shared axes | One chart with 12 colored lines |\n\nWhen precise values matter more than shape, a well-formatted table with\ninline bars often beats any chart.\n\n## 3. Encode in order of accuracy\n\nPeople read position best, then length, then angle and area, then color\nintensity. Put the comparison that carries the claim on a shared position\naxis.\n\n- Bars and areas start at zero. If zero hides the effect, use a dot plot\n or a line instead of truncating bars.\n- Line charts can start elsewhere, but show the axis values clearly.\n- Use a log scale when values span more than two orders of magnitude or\n when ratios matter (scaling laws, compute, parameters). Label it as log.\n- No dual y-axes. Use two aligned panels, or normalize.\n- Shared scales across small multiples, unless the point is shape and\n you say so.\n- Sort categories by value unless they have a natural order (sizes,\n dates, stages).\n\n## 4. Axes and numbers\n\n- 4 to 6 ticks per axis is plenty; scale tick count with the width.\n- Format numbers for humans: `d3.format('.2s')` for 1.2B tokens,\n `'.1%'` for rates, a fixed precision that matches the measurement\n (`'.3f'` for loss, not 7 decimals).\n- Units go in the axis title once (\"Throughput (tokens/s)\"), not on every\n tick.\n- Axis titles in sentence case, spelled out, no internal variable names\n (`val_loss_ema` becomes \"Validation loss (EMA)\").\n- Light gridlines along the value axis only, no chart borders, no tick\n marks on categorical axes.\n\n## 5. Label directly, annotate the story\n\n- Label lines at their end and bars at their tip, in the series color\n (darkened for contrast). A legend makes readers bounce between key and\n marks; keep it for narrow screens or many series.\n- Highlight the subject, mute the context: the model the article is\n about gets the accent color and full opacity, baselines get a neutral\n gray or lower opacity.\n- Annotate what the text talks about: the step where a run diverged, the\n crossover point, the best score. A short label with a thin leader line\n is enough.\n- Reference lines (human baseline, random chance, previous SOTA) are\n dashed, muted and labeled.\n- Labels must never overlap each other or the marks. Nudge them apart,\n or drop the least important.\n\n## 6. Color\n\n- Color is for identity or magnitude, not decoration. If one color\n works, use one color.\n- Categorical: at most 6 to 8 distinct hues. Beyond that, group into\n \"Other\", facet, or highlight a few and gray the rest.\n- Sequential (one hue, light to dark) for ordered magnitude. Diverging\n only when the midpoint means something (zero, a baseline, 50%).\n- Keep color meaning consistent across the article: the same model has\n the same color in every figure (pass a mapping through `config`).\n- Colorblind safety: never rely on red vs green alone; add labels,\n shapes, or position. Check that the categorical colors differ in\n lightness as well as hue.\n- Gray means \"context\" and the accent means \"look here\". Do not spend the\n accent color on everything.\n\n## 7. Uncertainty\n\n- Show the variability the claim depends on: bands for min/max or\n standard deviation across seeds, error bars or intervals for estimates,\n raw points when n is small.\n- Say what the band or bar represents in `desc` (std over 3 seeds, 95%\n bootstrap CI).\n- When differences are within noise, the figure must make that visible,\n not hide it.\n- Smoothing (EMA) is fine for noisy training curves; show the raw curve\n faintly behind it, and say so.\n\n## 8. Density and overplotting\n\n- Fewer than about 5,000 marks: SVG. More: canvas. More than about\n 50,000: aggregate first (binning, hexbin, downsampling with min/max per\n pixel for curves).\n- Overplotting: lower opacity, smaller marks, jitter for discrete values,\n or switch to a density view.\n- Long series: decimate to about 2 points per pixel; it looks identical\n and renders fast.\n\n## 9. Interaction\n\n- Interaction reveals detail; it never hides the main message. The\n default state is the one that makes the point.\n- Tooltips give exact values and context (series, step, unit), formatted\n like the axes.\n- Controls only for genuine alternative views (metric, model size, log\n vs linear). Defaults come from `config` so the author picks the view\n the text refers to.\n- Hover highlights: emphasize the hovered series, mute the others.\n- Everything must still read in print and PDF, where nothing is\n hovered.\n\n## 10. Text and density of ink\n\n- Sentence case everywhere, no all caps except short acronyms.\n- Remove what does not carry information: chart borders, background\n fills, redundant legends, repeated units, 3D, shadows, gradients on\n data marks.\n- Font sizes: 12px for labels and ticks, 11px minimum for secondary\n text. Never scale text down with the chart width.\n\n## 11. Anti-patterns to refuse or flag\n\n- Truncated bar axes, dual y-axes, 3D charts, pies with many slices,\n radar charts for model comparison, rainbow color scales for ordered\n data, red/green-only encodings, legends with 12 entries, smoothed\n curves without the raw signal, averages without spread, cherry-picked\n axis ranges, animation required to understand the figure.\n\nIf the user explicitly asks for one of these, build it, and mention the\ntradeoff in one sentence.\n\n## 12. Review checklist\n\nBefore replying, picture the figure in light, in dark and at 360px wide,\nand check:\n\n- [ ] The title states the claim and the default view proves it.\n- [ ] A reader can tell what every mark and color means without the\n article text.\n- [ ] Axes have readable titles with units and formatted ticks.\n- [ ] Series are labeled directly, or a compact legend is present.\n- [ ] The subject is highlighted and the context is muted.\n- [ ] Uncertainty is shown and explained when the claim depends on it.\n- [ ] No overlapping labels, no clipped text, nothing unreadable in dark\n mode.\n- [ ] At 360px wide the figure still makes its point.\n- [ ] Color is not the only carrier of meaning.\n- [ ] `ctx.describe()` states the takeaway in words."; | |