Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(mcp-host): write DOCX markdown the way it was written

marcoteb3ed7ca60099c
diff --git a/mcp-host/src/workflow/docxImages.ts b/mcp-host/src/workflow/docxImages.ts
new file mode 100644
index 000000000..2d12c4ee2
--- /dev/null
+++ b/mcp-host/src/workflow/docxImages.ts
@@ -0,0 +1,66 @@
+import { AlignmentType, ImageRun, Paragraph } from 'docx'
+import * as path from 'path'
+import { type ImageSize, fitImageSize, loadEmbeddableImage } from './embeddedImages'
+
+export interface DocxImagePlacement {
+ /** Requested size in pixels; the image keeps its proportions and fits the box. */
+ width?: number
+ height?: number
+ alignment?: unknown
+ altText?: string
+ spacing?: { before?: number; after?: number }
+}
+
+function alignmentOf(value: unknown) {
+ if (value === 'center') return AlignmentType.CENTER
+ if (value === 'right') return AlignmentType.RIGHT
+ return AlignmentType.LEFT
+}
+
+/**
+ * A paragraph holding the image `ref` names, fitted to `box`, or undefined when
+ * it cannot be embedded; the reason is added to `warnings`, prefixed with the
+ * argument `label` so the logo and an image of the same name can be told apart.
+ * A path that leaves the output folder still fails the call, with an error
+ * naming the argument and the fix.
+ */
+export function docxImageParagraph(
+ ref: unknown,
+ outputDir: string,
+ box: ImageSize,
+ placement: DocxImagePlacement,
+ warnings: string[],
+ label: string
+): Paragraph | undefined {
+ const notes: string[] = []
+ let image: ReturnType<typeof loadEmbeddableImage>
+ try {
+ image = loadEmbeddableImage(ref, outputDir, notes, label)
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err)
+ if (!message.startsWith('path traversal blocked')) throw err
+ throw new Error(
+ `${label}: ${message}. Pass the file name in the output folder, such as the ` +
+ "'sales.png' clerum__generate_chart returns, not a path.",
+ { cause: err }
+ )
+ }
+ warnings.push(...notes.map(note => (note.startsWith(label) ? note : `${label}: ${note}`)))
+ if (!image) return undefined
+ const size = fitImageSize(image, box, { width: placement.width, height: placement.height })
+ return new Paragraph({
+ alignment: alignmentOf(placement.alignment),
+ spacing: placement.spacing,
+ children: [
+ new ImageRun({
+ type: image.format === 'png' ? 'png' : 'jpg',
+ data: image.data,
+ transformation: size,
+ altText: {
+ name: path.basename(image.path),
+ ...(placement.altText ? { description: placement.altText } : {}),
+ },
+ }),
+ ],
+ })
+}
diff --git a/mcp-host/src/workflow/docxInline.ts b/mcp-host/src/workflow/docxInline.ts
new file mode 100644
index 000000000..3c8193f3f
--- /dev/null
+++ b/mcp-host/src/workflow/docxInline.ts
@@ -0,0 +1,136 @@
+/**
+ * Inline markdown, and the bits of HTML models mix into it, as Word runs.
+ */
+import { ExternalHyperlink, type IFontAttributesProperties, type IRunOptions, TextRun } from 'docx'
+import {
+ type EastAsianScript,
+ bidiLanguage,
+ eastAsianScript,
+ isRtlText,
+ scriptSegments,
+} from './docxScript'
+import { htmlToMarkdownInline, markdownSpans } from './inlineMarkup'
+
+export type DocxInline = TextRun | ExternalHyperlink
+
+export interface RunStyle {
+ color?: string
+ /** Half-points. */
+ size?: number
+ bold?: boolean
+ italics?: boolean
+}
+
+/** Formatting shared by the runs of one span; the font names faces by slot. */
+type RunOptions = Omit<IRunOptions, 'text' | 'children' | 'break' | 'font'> & {
+ font?: IFontAttributesProperties
+}
+
+/**
+ * Runs for `text`: one per line, each after the first starting on a new line,
+ * and within a line one per stretch of left-to-right or right-to-left text,
+ * the RTL ones marked so Word orders and shapes them as such. `rtlParagraph`
+ * is the direction of the paragraph the runs go into, by default `text`'s own.
+ */
+export function textRuns(
+ text: string,
+ options: RunOptions,
+ eastAsia?: EastAsianScript,
+ rtlParagraph = isRtlText(text)
+): TextRun[] {
+ const font = eastAsia ? { ...options.font, eastAsia: eastAsia.font } : options.font
+ const runs: TextRun[] = []
+ text.split('\n').forEach((line, i) => {
+ scriptSegments(line, rtlParagraph).forEach((segment, k) => {
+ runs.push(
+ new TextRun({
+ ...options,
+ ...(font ? { font } : {}),
+ text: segment.text,
+ ...(segment.rtl ? { rightToLeft: true } : {}),
+ ...(segment.rtl || eastAsia
+ ? {
+ language: {
+ ...(segment.rtl ? { bidirectional: bidiLanguage(segment.text) } : {}),
+ ...(eastAsia ? { eastAsia: eastAsia.lang } : {}),
+ },
+ }
+ : {}),
+ ...(i > 0 && k === 0 ? { break: 1 } : {}),
+ })
+ )
+ })
+ })
+ return runs
+}
+
+interface RunContext {
+ warnings: string[]
+ eastAsia?: EastAsianScript
+ /** The paragraph reads right to left. */
+ rtl: boolean
+ /** Half-points; code is set a point smaller than the text around it. */
+ codeSize: number
+}
+
+function appendRuns(markdown: string, base: RunOptions, ctx: RunContext, out: DocxInline[]): void {
+ for (const span of markdownSpans(markdown)) {
+ const style: RunOptions = {
+ ...base,
+ ...(span.bold ? { bold: true } : {}),
+ ...(span.italics ? { italics: true } : {}),
+ ...(span.strike ? { strike: true } : {}),
+ }
+ if (span.image !== undefined) {
+ ctx.warnings.push(
+ `The image '${span.image}' was inside a line of text and was left out; ` +
+ 'put ![alt](file.png) on a line of its own to embed it.'
+ )
+ if (span.text) out.push(...textRuns(span.text, style, ctx.eastAsia, ctx.rtl))
+ } else if (span.link !== undefined) {
+ out.push(
+ new ExternalHyperlink({
+ link: span.link,
+ children: textRuns(
+ span.text,
+ { ...style, color: '1D4ED8', underline: {} },
+ ctx.eastAsia,
+ ctx.rtl
+ ),
+ })
+ )
+ } else if (span.code) {
+ out.push(
+ ...textRuns(
+ span.text,
+ { ...style, font: { ascii: 'Consolas', hAnsi: 'Consolas' }, size: ctx.codeSize },
+ ctx.eastAsia,
+ ctx.rtl
+ )
+ )
+ } else {
+ out.push(...textRuns(span.text, style, ctx.eastAsia, ctx.rtl))
+ }
+ }
+}
+
+/**
+ * Runs for one block of inline markdown: **bold**, *italic*, ***both***,
+ * ~~strike~~, `code`, [links](https://...) and backslash escapes, after inline
+ * HTML is read. An image written inside a sentence cannot be placed there, so
+ * its alt text stands in for it and a warning says how to embed it.
+ */
+export function inlineRuns(text: string, style: RunStyle, warnings: string[]): DocxInline[] {
+ const size = style.size ?? 22
+ const base: RunOptions = { color: style.color, size, bold: style.bold, italics: style.italics }
+ const source = htmlToMarkdownInline(text)
+ const runs: DocxInline[] = []
+ const ctx = {
+ warnings,
+ eastAsia: eastAsianScript(source),
+ rtl: isRtlText(source),
+ codeSize: size - 2,
+ }
+ appendRuns(source, base, ctx, runs)
+ return runs.length > 0 ? runs : [new TextRun({ text: '', color: style.color })]
+}
diff --git a/mcp-host/src/workflow/docxMarkdown.ts b/mcp-host/src/workflow/docxMarkdown.ts
new file mode 100644
index 000000000..326154b76
--- /dev/null
+++ b/mcp-host/src/workflow/docxMarkdown.ts
@@ -0,0 +1,343 @@
+/**
+ * The markdown body of a generated Word document, as paragraphs and tables.
+ */
+import { BorderStyle, HeadingLevel, Paragraph, ShadingType, type Table, TextRun } from 'docx'
+import { inlineRuns, textRuns } from './docxInline'
+import { docxDirection, isRtlText } from './docxScript'
+import { DOCX_LIST_LEVELS, type DocxListNumbering, type DocxPalette, docxHex } from './docxStyle'
+import { buildDocxTable } from './docxTable'
+import { imageTarget, quoteParagraphs, withoutClosingHashes } from './inlineMarkup'
+
+export interface DocxBodyContext {
+ palette: DocxPalette
+ numbering: DocxListNumbering
+ warnings: string[]
+ /** The paragraph holding an image named in the body, or undefined when it cannot be embedded. */
+ image(file: string, alt: string): Paragraph | undefined
+}
+
+const BULLET_RE = /^[-*+]\s+/
+const ORDERED_RE = /^(\d{1,9})[.)]\s+/
+const HEADING_RE = /^(#{1,6})\s+(.*)$/
+const FENCE_RE = /^(```|~~~)/
+const QUOTE_RE = /^>\s?/
+const IMAGE_LINE_RE = /^!\[([^\]\n]*)\]\(((?:[^()\n]|\([^()\n]*\))*)\)$/
+const SEPARATOR_CELL_RE = /^:?-+:?$/
+
+function indentOf(line: string): number {
+ const m = /^[ \t]*/.exec(line)
+ return m ? m[0].replace(/\t/g, ' ').length : 0
+}
+
+function isListLine(line: string): boolean {
+ const t = line.trimStart()
+ return BULLET_RE.test(t) || ORDERED_RE.test(t)
+}
+
+/** Cells of a pipe-table row. `\|` is a literal pipe inside a cell. */
+function splitTableRow(line: string): string[] {
+ let t = line.trim()
+ if (t.startsWith('|')) t = t.slice(1)
+ if (t.endsWith('|') && !t.endsWith('\\|')) t = t.slice(0, -1)
+ return t.split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'))
+}
+
+/**
+ * A delimiter row such as `|---|:--:|`. Checked cell by cell: the one-regex
+ * form backtracks quadratically over a long run of spaces.
+ */
+function isTableSeparator(line: string): boolean {
+ if (!line.includes('-') || !line.includes('|')) return false
+ const cells = splitTableRow(line)
+ return cells.every(cell => SEPARATOR_CELL_RE.test(cell))
+}
+
+/**
+ * A GFM table starts at a row followed by a separator. Without outer pipes the
+ * header must have as many cells as the separator, which is what tells a table
+ * apart from a sentence that happens to contain a pipe.
+ */
+function startsTable(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
+ )
+}
+
+function blankParagraph(): Paragraph {
+ return new Paragraph({ children: [new TextRun({ text: '' })] })
+}
+
+interface ListFrame {
+ indent: number
+ ordered: boolean
+ reference: string
+ instance: number
+ last?: number
+}
+
+/**
+ * Consume one list, nested items included, starting at `start`. Depth follows
+ * the stack of indents seen so far, as the PDF generator does, so a 4-space
+ * sub-item is one level down rather than two. Blank lines between items keep a
+ * loose list together; a different marker, or a count that starts over at 1,
+ * begins a new list.
+ */
+function parseList(lines: string[], start: number, ctx: DocxBodyContext, out: Paragraph[]): number {
+ const base = indentOf(lines[start])
+ const stack: ListFrame[] = []
+ let i = start
+ while (i < lines.length) {
+ const line = lines[i]
+ if (line.trim() === '') {
+ let next = i
+ while (next < lines.length && lines[next].trim() === '') next++
+ if (next < lines.length && isListLine(lines[next]) && indentOf(lines[next]) >= base) {
+ i = next
+ continue
+ }
+ break
+ }
+ if (!isListLine(line) || indentOf(line) < base) break
+
+ const indent = indentOf(line)
+ const trimmed = line.trimStart()
+ const numbered = ORDERED_RE.exec(trimmed)
+ const ordered = numbered !== null
+ const number = numbered ? Number(numbered[1]) : undefined
+
+ while (stack.length > 0 && stack[stack.length - 1].indent > indent) stack.pop()
+ let frame: ListFrame | undefined = stack[stack.length - 1]
+ if (
+ frame &&
+ frame.indent === indent &&
+ (frame.ordered !== ordered || (number === 1 && (frame.last ?? 0) > 1))
+ ) {
+ stack.pop()
+ frame = undefined
+ }
+ if (!frame || (frame.indent < indent && stack.length < DOCX_LIST_LEVELS)) {
+ frame = { indent, ordered, ...ctx.numbering.begin(ordered, number ?? 1) }
+ stack.push(frame)
+ }
+ frame.last = number
+
+ const item = trimmed.replace(BULLET_RE, '').replace(ORDERED_RE, '')
+ out.push(
+ new Paragraph({
+ ...docxDirection(item),
+ numbering: {
+ reference: frame.reference,
+ instance: frame.instance,
+ level: stack.length - 1,
+ },
+ children: inlineRuns(item, { color: docxHex(ctx.palette.text) }, ctx.warnings),
+ })
+ )
+ i++
+ }
+ return i
+}
+
+/** Whether `line` opens a block other than a table row, which ends a table. */
+function startsOtherBlock(line: string): boolean {
+ const t = line.trim()
+ if (t.startsWith('|')) return false
+ return (
+ HEADING_RE.test(t) ||
+ FENCE_RE.test(t) ||
+ QUOTE_RE.test(t) ||
+ IMAGE_LINE_RE.test(t) ||
+ isListLine(line)
+ )
+}
+
+function headingParagraph(level: number, text: string, ctx: DocxBodyContext): Paragraph {
+ const { palette, warnings } = ctx
+ const content = withoutClosingHashes(text)
+ const style =
+ level === 1
+ ? { heading: HeadingLevel.HEADING_1, before: 360, after: 160, size: 36, bold: true }
+ : level === 2
+ ? { heading: HeadingLevel.HEADING_2, before: 280, after: 120, size: 28, bold: true }
+ : { heading: HeadingLevel.HEADING_3, before: 200, after: 80, size: 22, bold: false }
+ const color = docxHex(level <= 2 ? palette.primary : palette.muted)
+ return new Paragraph({
+ ...docxDirection(content),
+ heading: style.heading,
+ spacing: { before: style.before, after: style.after },
+ // docx's heading styles do not keep with the next paragraph, so a heading
+ // could end a page with its section starting on the next.
+ keepNext: true,
+ keepLines: true,
+ children: inlineRuns(content, { color, size: style.size, bold: style.bold }, warnings),
+ })
+}
+
+/**
+ * Paragraphs and tables for a markdown body: headings, lists, pipe tables,
+ * fenced code, quotes, rules, images on a line of their own, and paragraphs of
+ * inline markdown.
+ */
+export function bodyToDocxChildren(body: string, ctx: DocxBodyContext): (Paragraph | Table)[] {
+ const { palette, warnings } = ctx
+ const out: (Paragraph | Table)[] = []
+ const lines = body.split('\n')
+ let tables = 0
+ let i = 0
+
+ while (i < lines.length) {
+ const line = lines[i]
+ const trimmed = line.trim()
+
+ const fence = FENCE_RE.exec(trimmed)
+ if (fence) {
+ const marker = fence[1]
+ // The language after the opening fence is noted above the block, as in the PDF.
+ const language = trimmed.slice(marker.length).trim()
+ const code: string[] = []
+ i++
+ while (i < lines.length && !lines[i].trimStart().startsWith(marker)) {
+ code.push(lines[i])
+ i++
+ }
+ i++
+ if (language) {
+ out.push(
+ new Paragraph({
+ spacing: { before: 60, after: 0 },
+ children: textRuns(language, { size: 16, color: docxHex(palette.muted) }),
+ })
+ )
+ }
+ for (const codeLine of code) {
+ out.push(
+ new Paragraph({
+ spacing: { before: 0, after: 0 },
+ shading: { type: ShadingType.CLEAR, fill: docxHex(palette.surface) },
+ children: [
+ new TextRun({
+ text: codeLine === '' ? ' ' : codeLine,
+ font: { ascii: 'Courier New', hAnsi: 'Courier New' },
+ size: 18,
+ color: docxHex(palette.text),
+ }),
+ ],
+ })
+ )
+ }
+ out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { after: 80 } }))
+ continue
+ }
+
+ const heading = HEADING_RE.exec(trimmed)
+ if (heading) {
+ out.push(headingParagraph(heading[1].length, heading[2], ctx))
+ i++
+ continue
+ }
+
+ const image = IMAGE_LINE_RE.exec(trimmed)
+ if (image) {
+ const paragraph = ctx.image(imageTarget(image[2]), image[1])
+ if (paragraph) out.push(paragraph)
+ i++
+ continue
+ }
+
+ if (startsTable(lines, i)) {
+ const headers = splitTableRow(line)
+ const rows: string[][] = []
+ i += 2
+ while (
+ i < lines.length &&
+ lines[i].trim() !== '' &&
+ lines[i].includes('|') &&
+ !startsOtherBlock(lines[i])
+ ) {
+ rows.push(splitTableRow(lines[i]))
+ i++
+ }
+ out.push(
+ buildDocxTable(headers, rows, palette, 'striped', warnings, `The body's table ${++tables}`)
+ )
+ out.push(new Paragraph({ children: [new TextRun({ text: '' })], spacing: { before: 60 } }))
+ continue
+ }
+
+ // A rule wins over a list: "- - -" and "* * *" are rules in markdown.
+ if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed.replace(/\s+/g, ''))) {
+ 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
+ }
+
+ if (isListLine(line)) {
+ const items: Paragraph[] = []
+ i = parseList(lines, i, ctx, items)
+ out.push(...items)
+ continue
+ }
+
+ if (QUOTE_RE.test(trimmed)) {
+ const quoted: string[] = []
+ while (i < lines.length && QUOTE_RE.test(lines[i].trimStart())) {
+ quoted.push(lines[i].trimStart().replace(QUOTE_RE, ''))
+ i++
+ }
+ const paragraphs = quoteParagraphs(quoted)
+ const bar = { style: BorderStyle.SINGLE, color: docxHex(palette.primary), size: 12, space: 8 }
+ // In a right-to-left paragraph Word reads the indent from the right but
+ // draws borders where they are named, so the bar moves to the right.
+ paragraphs.forEach((quote, n) =>
+ out.push(
+ new Paragraph({
+ ...docxDirection(quote),
+ spacing: { before: n === 0 ? 120 : 0, after: n === paragraphs.length - 1 ? 120 : 80 },
+ indent: { left: 360 },
+ border: isRtlText(quote) ? { right: bar } : { left: bar },
+ children: inlineRuns(quote, { color: docxHex(palette.muted) }, warnings),
+ })
+ )
+ )
+ continue
+ }
+
+ if (trimmed === '') {
+ out.push(blankParagraph())
+ i++
+ continue
+ }
+
+ out.push(
+ new Paragraph({
+ ...docxDirection(line),
+ spacing: { after: 80 },
+ children: inlineRuns(line, { color: docxHex(palette.text) }, warnings),
+ })
+ )
+ i++
+ }
+
+ return out
+}
+
+/** Whether the body holds anything besides images on lines of their own. */
+export function bodyHasText(body: string): boolean {
+ return body.split('\n').some(line => line.trim() !== '' && !IMAGE_LINE_RE.test(line.trim()))
+}
diff --git a/mcp-host/src/workflow/docxScript.ts b/mcp-host/src/workflow/docxScript.ts
new file mode 100644
index 000000000..edc43c659
--- /dev/null
+++ b/mcp-host/src/workflow/docxScript.ts
@@ -0,0 +1,137 @@
+/**
+ * Direction and script handling for the generated Word documents.
+ *
+ * Word lays out a paragraph right to left only when it carries w:bidi, and
+ * treats neutral characters inside a run as right-to-left only when the run
+ * carries w:rtl. Arabic and Hebrew letters take the complex-script font (w:cs)
+ * and CJK the East Asian one, so both are named explicitly: a document that
+ * names only a Latin face leaves Word to substitute, which draws boxes where
+ * the substitute lacks the glyphs.
+ */
+
+/** Latin face of the body text. */
+export const DOCX_LATIN_FONT = 'Calibri'
+
+/**
+ * Complex-script face for Arabic and Hebrew. Arial carries both in every
+ * weight on Windows and Word for Mac; where its italic lacks Arabic, Word
+ * slants the upright glyphs.
+ */
+export const DOCX_COMPLEX_FONT = 'Arial'
+
+const HEBREW_LETTER = /\p{Script=Hebrew}/u
+const ARABIC_LETTER =
+ /[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Nko}\p{Script=Samaritan}\p{Script=Mandaic}\p{Script=Adlam}\p{Script=Hanifi_Rohingya}]/u
+const RTL_LETTER = new RegExp(`${HEBREW_LETTER.source}|${ARABIC_LETTER.source}`, 'u')
+
+/**
+ * A right-to-left stretch of one script: its letters with the digits, spaces
+ * and punctuation between them and the marks on the last one, but not the
+ * neutrals after it, which take the paragraph's direction. Hebrew and Arabic
+ * stay in separate runs because Word picks the face by the run's language and
+ * draws boxes for Arabic tagged as Hebrew. The marks are matched once, after
+ * the repetition, so no stretch of them can be split two ways.
+ */
+function span(letter: RegExp): string {
+ return `${letter.source}(?:[^\\p{L}]*${letter.source})*\\p{M}*`
+}
+const RTL_SPAN = new RegExp(`${span(HEBREW_LETTER)}|${span(ARABIC_LETTER)}`, 'gu')
+
+/** Whether `text` reads right to left: its first letter, as the bidi algorithm decides, is RTL. */
+export function isRtlText(text: string): boolean {
+ const first = /\p{L}/u.exec(text)?.[0]
+ return first !== undefined && RTL_LETTER.test(first)
+}
+
+/** Paragraph options that set the paragraph's direction from its text. */
+export function docxDirection(text: string): { bidirectional?: true } {
+ return isRtlText(text) ? { bidirectional: true } : {}
+}
+
+export interface ScriptSegment {
+ text: string
+ rtl: boolean
+}
+
+const LETTER = /\p{L}/u
+
+/**
+ * `text` cut into left-to-right and right-to-left stretches, in logical order.
+ * In a right-to-left paragraph, digits and punctuation with no letter of their
+ * own join the right-to-left stretch beside them: in a left-to-right run Word
+ * sets them apart from the words they belong to ("المبيعات2026", "מספר.42").
+ */
+export function scriptSegments(text: string, rtlParagraph = false): ScriptSegment[] {
+ if (!RTL_LETTER.test(text)) return [{ text, rtl: rtlParagraph && !LETTER.test(text) }]
+ const out: ScriptSegment[] = []
+ let at = 0
+ RTL_SPAN.lastIndex = 0
+ for (let m = RTL_SPAN.exec(text); m; m = RTL_SPAN.exec(text)) {
+ if (m.index > at) out.push({ text: text.slice(at, m.index), rtl: false })
+ out.push({ text: m[0], rtl: true })
+ at = m.index + m[0].length
+ }
+ if (at < text.length) out.push({ text: text.slice(at), rtl: false })
+ if (!rtlParagraph) return out
+ const merged: Array<ScriptSegment & { neutral: boolean }> = []
+ for (const segment of out) {
+ const neutral = !segment.rtl && !LETTER.test(segment.text)
+ const rtl = segment.rtl || neutral
+ const last = merged[merged.length - 1]
+ if (last && last.rtl && rtl && (neutral || last.neutral)) {
+ last.text += segment.text
+ last.neutral = last.neutral && neutral
+ } else {
+ merged.push({ text: segment.text, rtl, neutral })
+ }
+ }
+ return merged.map(({ text: t, rtl }) => ({ text: t, rtl }))
+}
+
+/** Language tag for a right-to-left run of one script. */
+export function bidiLanguage(text: string): string {
+ return HEBREW_LETTER.test(text) ? 'he-IL' : 'ar-SA'
+}
+
+export interface EastAsianScript {
+ font: string
+ lang: string
+}
+
+// Each face ships with Windows and with Word for Mac.
+const JAPANESE: EastAsianScript = { font: 'Yu Gothic', lang: 'ja-JP' }
+const KOREAN: EastAsianScript = { font: 'Malgun Gothic', lang: 'ko-KR' }
+const CHINESE: EastAsianScript = { font: 'Microsoft YaHei', lang: 'zh-CN' }
+
+const CJK_CHAR = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/gu
+
+/**
+ * The East Asian face and language a block names for itself, chosen from the
+ * whole block so Han characters in Japanese text get the Japanese face:
+ * Japanese with kana, Korean with Hangul. Han characters alone may be any of
+ * the three, so such a block takes the document's (documentEastAsianScript).
+ */
+export function eastAsianScript(text: string): EastAsianScript | undefined {
+ if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) return JAPANESE
+ if (/\p{Script=Hangul}/u.test(text)) return KOREAN
+ return undefined
+}
+
+/**
+ * The East Asian script of a whole document: that of the lines holding most of
+ * its CJK characters, where a line of Han characters alone counts as Chinese.
+ */
+export function documentEastAsianScript(text: string): EastAsianScript | undefined {
+ const counts = new Map<EastAsianScript, number>()
+ for (const line of text.split('\n')) {
+ const cjk = line.match(CJK_CHAR)?.length ?? 0
+ if (cjk === 0) continue
+ const script = eastAsianScript(line) ?? CHINESE
+ counts.set(script, (counts.get(script) ?? 0) + cjk)
+ }
+ let best: EastAsianScript | undefined
+ for (const script of [JAPANESE, KOREAN, CHINESE]) {
+ if ((counts.get(script) ?? 0) > (best ? (counts.get(best) ?? 0) : 0)) best = script
+ }
+ return best
+}
diff --git a/mcp-host/src/workflow/docxStyle.ts b/mcp-host/src/workflow/docxStyle.ts
new file mode 100644
index 000000000..9d50ed921
--- /dev/null
+++ b/mcp-host/src/workflow/docxStyle.ts
@@ -0,0 +1,115 @@
+/**
+ * Palettes, page geometry and list numbering for the generated Word documents.
+ */
+import { AlignmentType, type ILevelsOptions, LevelFormat } from 'docx'
+
+export interface DocxPalette {
+ // Stored as '#xxxxxx' like the PDF palettes; docxHex() gives the bare form docx expects.
+ primary: string
+ primaryDark: string
+ text: string
+ muted: string
+ border: string
+ zebra: string
+ surface: string
+}
+
+export 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',
+ },
+}
+
+/** '#1e3a8a' as the bare uppercase hex docx expects for colors and fills. */
+export function docxHex(c: string): string {
+ return c.startsWith('#') ? c.slice(1).toUpperCase() : c.toUpperCase()
+}
+
+/** Width between the margins of the default A4 page (11906 twips less two 1440 margins). */
+export const DOCX_CONTENT_WIDTH_TWIPS = 9026
+
+/** Word's list levels are 0-8. */
+export const DOCX_LIST_LEVELS = 9
+
+const BULLET_REFERENCE = 'doc-bullets'
+const ORDERED_REFERENCE = 'doc-ordered'
+const BULLET_GLYPHS = ['\u2022', '\u25E6', '\u25AA']
+const ORDERED_FORMATS = [LevelFormat.DECIMAL, LevelFormat.LOWER_LETTER, LevelFormat.LOWER_ROMAN]
+
+function levels(ordered: boolean, start: number): ILevelsOptions[] {
+ return Array.from({ length: DOCX_LIST_LEVELS }, (_, level) => ({
+ level,
+ format: ordered ? ORDERED_FORMATS[level % 3] : LevelFormat.BULLET,
+ text: ordered ? `%${level + 1}.` : BULLET_GLYPHS[level % 3],
+ start,
+ alignment: AlignmentType.LEFT,
+ style: { paragraph: { indent: { left: 360 * (level + 1), hanging: 240 } } },
+ }))
+}
+
+export interface DocxListRef {
+ reference: string
+ instance: number
+}
+
+/**
+ * Numbering for the lists of one document. Every list gets its own instance,
+ * because paragraphs sharing an instance form one sequence in Word.
+ */
+export class DocxListNumbering {
+ private nextInstance = 0
+ private readonly starts = new Set<number>()
+
+ begin(ordered: boolean, start = 1): DocxListRef {
+ const instance = this.nextInstance++
+ if (!ordered) return { reference: BULLET_REFERENCE, instance }
+ if (start === 1) return { reference: ORDERED_REFERENCE, instance }
+ // docx sets an instance's start from its definition, so each start needs its own.
+ this.starts.add(start)
+ return { reference: `${ORDERED_REFERENCE}-from-${start}`, instance }
+ }
+
+ config(): Array<{ reference: string; levels: ILevelsOptions[] }> {
+ return [
+ { reference: BULLET_REFERENCE, levels: levels(false, 1) },
+ { reference: ORDERED_REFERENCE, levels: levels(true, 1) },
+ ...[...this.starts].map(start => ({
+ reference: `${ORDERED_REFERENCE}-from-${start}`,
+ levels: levels(true, start),
+ })),
+ ]
+ }
+}
diff --git a/mcp-host/src/workflow/docxTable.ts b/mcp-host/src/workflow/docxTable.ts
new file mode 100644
index 000000000..8821bf6f7
--- /dev/null
+++ b/mcp-host/src/workflow/docxTable.ts
@@ -0,0 +1,333 @@
+import { type SKRSContext2D, createCanvas } from '@napi-rs/canvas'
+import {
+ BorderStyle,
+ Paragraph,
+ ShadingType,
+ Table,
+ TableCell,
+ TableLayoutType,
+ TableRow,
+ WidthType,
+} from 'docx'
+import { inlineRuns } from './docxInline'
+import { docxDirection, isRtlText } from './docxScript'
+import { DOCX_CONTENT_WIDTH_TWIPS, type DocxPalette, docxHex } from './docxStyle'
+import { CHART_FONT_FAMILY, ensureFontsReady } from './fonts'
+import { inlineSpans } from './inlineMarkup'
+import { headerText } from './tableRows'
+
+export type DocxTableLayout = 'striped' | 'minimal' | 'grid'
+
+function cellText(cell: unknown): string {
+ if (cell === null || cell === undefined) return ''
+ return typeof cell === 'object' ? JSON.stringify(cell) : String(cell)
+}
+
+/** A4 width between the 1440-twip margins, turned to landscape. */
+const LANDSCAPE_CONTENT_TWIPS = 16838 - 2 * 1440
+
+/** Page and type size tried in turn; the first that holds every word wins. */
+const ATTEMPTS: Array<{ landscape: boolean; size: number }> = [
+ { landscape: false, size: 11 },
+ { landscape: false, size: 10 },
+ { landscape: false, size: 9 },
+ { landscape: false, size: 8 },
+ { landscape: true, size: 11 },
+ { landscape: true, size: 10 },
+ { landscape: true, size: 9 },
+ { landscape: true, size: 8 },
+ { landscape: true, size: 7 },
+]
+
+/** Beyond this many columns Word's autofit lets the table run past the margin. */
+const AUTOFIT_MAX_COLUMNS = 8
+
+/** Twips a word may claim before it is left to break: longer ones are URLs and hashes. */
+const LONG_TOKEN_TWIPS = 2800
+
+/** Added to every column: Word wraps a word that fills its cell exactly. */
+const SLACK_TWIPS = 40
+
+/**
+ * CJK characters, counted one em wide as every CJK face sets them, and the
+ * characters Roboto has no glyph for, counted at a generous 0.6 em, so neither
+ * depends on the faces the runtime image happens to ship.
+ */
+const WIDE_CHAR =
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3000-\u303F\uFF01-\uFF60\uFFE0-\uFFE6]/u
+const MEASURED_CHAR = /[\u0000-\u052F\u1E00-\u206F\u20A0-\u20BF]/u
+
+let context: SKRSContext2D | undefined
+const advances = [new Map<string, number>(), new Map<string, number>()]
+
+/**
+ * Advance of one character at 1pt in ems. The few thousand characters Roboto
+ * covers are measured once each with it; Roboto runs 8-10% wider than Calibri
+ * in both weights, so a sum of advances errs toward fitting.
+ */
+function advanceEm(ch: string, bold: boolean): number {
+ if (!MEASURED_CHAR.test(ch)) return WIDE_CHAR.test(ch) ? 1 : 0.6
+ const cache = advances[bold ? 1 : 0]
+ const known = cache.get(ch)
+ if (known !== undefined) return known
+ if (!context) {
+ ensureFontsReady()
+ context = createCanvas(4, 4).getContext('2d')
+ }
+ context.font = `100px "${bold ? `${CHART_FONT_FAMILY} Bold` : CHART_FONT_FAMILY}"`
+ const em = context.measureText(ch).width / 100
+ cache.set(ch, em)
+ return em
+}
+
+/** The text a cell prints, markdown markers and link targets removed, for measuring. */
+function printedText(markdown: string): string {
+ return inlineSpans(markdown)
+ .map(span => span.text)
+ .join('')
+}
+
+interface ColumnExtent {
+ /** Longest word at 1pt, in twips. */
+ word: number
+ /** Longest line at 1pt, in twips. */
+ line: number
+}
+
+/** Widen `extent` to hold the longest word and line of `cell`, in one pass over it. */
+function takeCell(extent: ColumnExtent, cell: string, bold: boolean): void {
+ let word = 0
+ let line = 0
+ for (const ch of printedText(cell)) {
+ if (ch === '\n') {
+ extent.line = Math.max(extent.line, line * 20)
+ line = 0
+ word = 0
+ continue
+ }
+ const em = advanceEm(ch, bold)
+ line += em
+ word = /\s/.test(ch) ? 0 : word + em
+ extent.word = Math.max(extent.word, word * 20)
+ }
+ extent.line = Math.max(extent.line, line * 20)
+}
+
+function extents(head: string[], body: string[][]): ColumnExtent[] {
+ return head.map((h, col) => {
+ const extent = { word: 0, line: 0 }
+ takeCell(extent, h, true)
+ for (const row of body) takeCell(extent, row[col], false)
+ return extent
+ })
+}
+
+const sum = (xs: number[]): number => xs.reduce((a, b) => a + b, 0)
+
+interface DocxTableFit {
+ widths: number[]
+ /** Points. */
+ size: number
+ /** Left and right cell margin, in twips. */
+ side: number
+ landscape: boolean
+ fixed: boolean
+ /** Columns whose longest word is still wider than the column. */
+ broken: number[]
+}
+
+/**
+ * Column widths in twips, type size and page for one table: the first attempt
+ * whose columns hold their longest words. Each column then gets its full
+ * content when that fits, otherwise its longest word and a share of the rest,
+ * and spare room goes to columns by their content.
+ */
+function fitTable(cols: ColumnExtent[]): DocxTableFit {
+ const n = cols.length
+ const plan = ({ landscape, size }: { landscape: boolean; size: number }) => {
+ const fixed = landscape || size < 11 || n > AUTOFIT_MAX_COLUMNS
+ const side = fixed ? 60 : 120
+ const pad = 2 * side + SLACK_TWIPS
+ const room = landscape ? LANDSCAPE_CONTENT_TWIPS : DOCX_CONTENT_WIDTH_TWIPS
+ const min = cols.map(c => Math.min(c.word * size, LONG_TOKEN_TWIPS) + pad)
+ const max = cols.map((c, i) => Math.max(c.line * size + pad, min[i]))
+ let widths: number[]
+ if (sum(max) <= room) {
+ widths = max.map(m => m + ((room - sum(max)) * m) / sum(max))
+ } else if (sum(min) <= room) {
+ const spread = sum(max) - sum(min)
+ widths = min.map((m, i) => m + ((room - sum(min)) * (max[i] - m)) / spread)
+ } else {
+ widths = min.map(m => (room * m) / sum(min))
+ }
+ const whole = widths.map(Math.floor)
+ const broken = whole.flatMap((w, i) => (w + 1 < min[i] ? [i] : []))
+ return { widths: whole, size, side, landscape, fixed, broken }
+ }
+ for (const attempt of ATTEMPTS) {
+ const fit = plan(attempt)
+ if (fit.broken.length === 0) return fit
+ }
+ return plan(ATTEMPTS[ATTEMPTS.length - 1])
+}
+
+/** Header names for a warning: the first three, then how many more. */
+function columnNames(headers: string[], columns: number[]): string {
+ const names = columns.map(c => `'${headers[c]?.trim() || `column ${c + 1}`}'`)
+ if (names.length === 1) return names[0]
+ if (names.length <= 3) return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
+ return `${names.slice(0, 3).join(', ')} and ${names.length - 3} more column(s)`
+}
+
+const LANDSCAPE_TABLES = new WeakSet<Table>()
+
+/**
+ * The body in sections by page orientation. A table set on a landscape page
+ * takes the paragraph after it, the spacer every table is followed by, into
+ * its section.
+ */
+export function docxSections<T extends object>(
+ children: T[]
+): Array<{ landscape: boolean; children: T[] }> {
+ const out: Array<{ landscape: boolean; children: T[] }> = []
+ for (let i = 0; i < children.length; i++) {
+ const child = children[i]
+ const landscape = child instanceof Table && LANDSCAPE_TABLES.has(child)
+ const run = landscape && i + 1 < children.length ? [child, children[++i]] : [child]
+ const last = out[out.length - 1]
+ if (last && last.landscape === landscape) last.children.push(...run)
+ else out.push({ landscape, children: run })
+ }
+ return out
+}
+
+function padRow(row: string[], width: number): string[] {
+ if (row.length >= width) return row.slice(0, width)
+ return [...row, ...Array<string>(width - row.length).fill('')]
+}
+
+function borders(layout: DocxTableLayout, palette: DocxPalette) {
+ const none = { style: BorderStyle.NONE, color: 'auto', size: 0 }
+ const light = { style: BorderStyle.SINGLE, color: docxHex(palette.border), size: 4 }
+ if (layout === 'minimal') {
+ return {
+ top: light,
+ bottom: light,
+ left: none,
+ right: none,
+ insideHorizontal: none,
+ insideVertical: none,
+ }
+ }
+ if (layout === 'grid') {
+ return {
+ top: light,
+ bottom: light,
+ left: light,
+ right: light,
+ insideHorizontal: light,
+ insideVertical: light,
+ }
+ }
+ const strong = { style: BorderStyle.SINGLE, color: docxHex(palette.primaryDark), size: 6 }
+ return {
+ top: strong,
+ bottom: strong,
+ left: none,
+ right: none,
+ insideHorizontal: { style: BorderStyle.SINGLE, color: docxHex(palette.border), size: 2 },
+ insideVertical: none,
+ }
+}
+
+/**
+ * A table with a header row. Headers may be numbers (a year is a common
+ * heading); cells carry inline markdown, and <br> breaks a line inside one.
+ * Ragged rows are padded or cut to the header count. A table too wide for the
+ * portrait page is set in smaller type or on a landscape page, which
+ * docxSections puts in a section of its own; `label` names it in warnings.
+ */
+export function buildDocxTable(
+ headers: unknown[],
+ rows: unknown[][],
+ palette: DocxPalette,
+ layout: DocxTableLayout,
+ warnings: string[],
+ label: string
+): Table {
+ const head = headers.map(headerText)
+ const long = rows.filter(row => row.length > head.length).length
+ if (long > 0) {
+ warnings.push(
+ `${label} had ${long} row(s) with more cells than its ${head.length} headers; the extra ` +
+ 'cells were left out. Add a header for every column.'
+ )
+ }
+ const body = rows.map(row => padRow(row.map(cellText), head.length))
+ const fit = fitTable(extents(head, body))
+ if (fit.landscape) {
+ warnings.push(
+ `${label} has more columns than a portrait page can show legibly, so it was set on ` +
+ 'a landscape page.'
+ )
+ }
+ if (fit.broken.length > 0) {
+ const many = fit.broken.length > 1
+ warnings.push(
+ `${label}: words in ${columnNames(head, fit.broken)} are wider than ` +
+ `${many ? 'those columns' : 'that column'}, so they break across lines; ` +
+ 'split the table or leave out columns.'
+ )
+ }
+ const size = fit.size * 2
+ const { side, widths } = fit
+
+ const headerRow = new TableRow({
+ tableHeader: true,
+ children: head.map(
+ (h, i) =>
+ new TableCell({
+ width: { size: widths[i], type: WidthType.DXA },
+ shading: { type: ShadingType.CLEAR, fill: docxHex(palette.primary), color: 'auto' },
+ children: [
+ new Paragraph({
+ ...docxDirection(h),
+ children: inlineRuns(h, { color: 'FFFFFF', bold: true, size }, warnings),
+ }),
+ ],
+ margins: { top: 80, bottom: 80, left: side, right: side },
+ })
+ ),
+ })
+
+ const bodyRows = body.map(
+ (row, r) =>
+ new TableRow({
+ children: row.map((cell, i) => {
+ const fill = layout === 'striped' && r % 2 === 1 ? docxHex(palette.zebra) : undefined
+ return new TableCell({
+ width: { size: widths[i], type: WidthType.DXA },
+ ...(fill ? { shading: { type: ShadingType.CLEAR, fill, color: 'auto' } } : {}),
+ children: [
+ new Paragraph({
+ ...docxDirection(cell),
+ children: inlineRuns(cell, { color: docxHex(palette.text), size }, warnings),
+ }),
+ ],
+ margins: { top: 60, bottom: 60, left: side, right: side },
+ })
+ }),
+ })
+ )
+
+ const table = new Table({
+ width: { size: sum(widths), type: WidthType.DXA },
+ columnWidths: widths,
+ ...(fit.fixed ? { layout: TableLayoutType.FIXED } : {}),
+ ...(isRtlText(head.join(' ')) ? { visuallyRightToLeft: true } : {}),
+ rows: [headerRow, ...bodyRows],
+ borders: borders(layout, palette),
+ })
+ if (fit.landscape) LANDSCAPE_TABLES.add(table)
+ return table
+}