Skip to content

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

TypeScript

fix(mcp-host): keep fontkit from hanging or failing a PDF on text it cannot shape

marcotebd8265f425f90
diff --git a/mcp-host/src/workflow/__tests__/fonts.test.ts b/mcp-host/src/workflow/__tests__/fonts.test.ts
index 4768f1d52..535b0d974 100644
--- a/mcp-host/src/workflow/__tests__/fonts.test.ts
+++ b/mcp-host/src/workflow/__tests__/fonts.test.ts
@@ -144,6 +144,18 @@ describe('per-character fallback for PDFs', () => {
expect(glyphs.familyFor(0xe000, PDF_FONT_FAMILY)).toBeUndefined()
})
+ it('falls back only to faces fontkit shapes without hanging', () => {
+ // Meetei Mayek, Kaithi, Sinhala and Balinese go through fontkit's Universal
+ // Shaping Engine, which loops or throws on some of their sequences; the
+ // images install faces for all of them.
+ for (const cp of [0xabc0, 0xabed, 0x1108d, 0x0dbd, 0x0dda, 0x1b13]) {
+ const family = glyphs.familyFor(cp, PDF_FONT_FAMILY)
+ expect(family === undefined || !/Meetei|Kaithi|Sinhala|Balinese/.test(family), family).toBe(
+ true
+ )
+ }
+ })
+
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] : [])
diff --git a/mcp-host/src/workflow/__tests__/pdfText.test.ts b/mcp-host/src/workflow/__tests__/pdfText.test.ts
index d963d4c2c..3d9aacc00 100644
--- a/mcp-host/src/workflow/__tests__/pdfText.test.ts
+++ b/mcp-host/src/workflow/__tests__/pdfText.test.ts
@@ -31,6 +31,9 @@ const source: PdfGlyphSource = {
Hebrew: { ascent: 1.0, lineHeight: 1.3 },
})[family],
descriptors: () => ({}),
+ isFallback: family => family === 'Arabic' || family === 'Hebrew',
+ // A lone shadda stands for a sequence fontkit fails to shape.
+ shapes: (_family, texts) => !texts.some(t => t.includes('\u0651')),
}
const ctx: TypesetContext = {
@@ -318,3 +321,21 @@ describe('right-to-left lists and tables', () => {
expect(table.widths).toEqual([100, 50])
})
})
+
+describe('runs pdfkit cannot lay out', () => {
+ it('leaves out only the runs that fail, with a note, and keeps the rest', () => {
+ const typesetter = new PdfTypesetter(source)
+ const first = { text: 'Intro \u0645\u0631\u062d\u0628\u0627 end' }
+ const second = { text: 'More \u0651\u0628 text' }
+ typesetter.typeset([first, second], ctx)
+ typesetter.settleShaping()
+ const shown = (node: { text: unknown }) =>
+ (node.text as Array<{ text: string }>).map(r => r.text).join('')
+ expect(shown(first)).toContain('\u0645')
+ expect(shown(second)).not.toContain('\u0651')
+ expect(shown(second)).toContain('More')
+ expect(typesetter.warnings().join(' ')).toMatch(
+ /2 character\(s\) of Arabic text are in a sequence the PDF renderer cannot lay out/
+ )
+ })
+})
diff --git a/mcp-host/src/workflow/fonts.ts b/mcp-host/src/workflow/fonts.ts
index 8d942bb4d..5d7c57f28 100644
--- a/mcp-host/src/workflow/fonts.ts
+++ b/mcp-host/src/workflow/fonts.ts
@@ -521,6 +521,17 @@ function readFaceInfo(face: PdfFace): FaceInfo | undefined {
})
}
+/** The first letter `ranges` cover, to try a face with; "A" when they cover none. */
+function firstLetter(ranges: number[]): string {
+ for (let i = 0; i < ranges.length; i += 2) {
+ for (let cp = ranges[i]; cp <= ranges[i + 1] && cp - ranges[i] < 256; cp++) {
+ const ch = String.fromCodePoint(cp)
+ if (/\p{L}/u.test(ch)) return ch
+ }
+ }
+ return 'A'
+}
+
function coversCodePoint(ranges: number[], cp: number): boolean {
let lo = 0
let hi = ranges.length / 2 - 1
@@ -724,8 +735,30 @@ const FALLBACK_PREFIXES = [
'NotoSansMath',
]
-/** Other regular-weight faces from the families the images install, tried after the list above. */
-const FALLBACK_STEM = /^(noto|dejavu|liberation)[a-z0-9]*(-regular)?$/
+/**
+ * Faces for further scripts, tried last. Only faces that fontkit shaped
+ * thousands of random sequences with, without hanging or running out of memory,
+ * are listed; fontkit loops forever on some Meetei Mayek, Kaithi and Nastaliq
+ * sequences, so no installed face is used unlisted.
+ */
+const MORE_SCRIPT_PREFIXES = [
+ 'NotoSansDevanagari',
+ 'NotoSansBengali',
+ 'NotoSansGurmukhi',
+ 'NotoSansGujarati',
+ 'NotoSansOriya',
+ 'NotoSansTamil',
+ 'NotoSansTelugu',
+ 'NotoSansKannada',
+ 'NotoSansMalayalam',
+ 'NotoSansThai',
+ 'NotoSansLao',
+ 'NotoSansKhmer',
+ 'NotoSansMyanmar',
+ 'NotoSansArmenian',
+ 'NotoSansGeorgian',
+ 'NotoSansEthiopic',
+]
interface FallbackFamily {
family: string
@@ -744,6 +777,10 @@ export interface FaceMetrics {
export interface PdfGlyphSource {
/** Family that can draw `cp` in a run set in `base`, or undefined when no face can. */
familyFor(cp: number, base: string): string | undefined
+ /** Whether `family` is one familyFor falls back to, rather than a body or code face. */
+ isFallback(family: string): boolean
+ /** Whether pdfkit lays out every one of `texts` in `family` without failing. */
+ shapes(family: string, texts: string[]): boolean
/** Whether fontkit puts a right-to-left run set in `family` into display order itself. */
reversesRtl(family: string): boolean
/** Advance width of `text` set in `family` at `size` points. */
@@ -760,15 +797,16 @@ function faceFile(face: PdfFace): string | undefined {
}
/**
- * Whether pdfkit can lay out and embed `ch` in `faces`. Some faces an image
- * ships parse for their cmap yet fail inside pdfkit ("Not a fixed size"), and
- * one such face named by a single run fails the whole document.
+ * Whether pdfkit can lay out and embed each of `texts` in `faces`. Some faces
+ * an image ships parse for their cmap yet fail inside pdfkit ("Not a fixed
+ * size"), and fontkit throws on some sequences it cannot shape; either, in a
+ * single run, fails the whole document.
*/
-function embeds(faces: PdfFaces, ch: string): boolean {
+function embeds(faces: PdfFaces, texts: string | string[]): boolean {
try {
const PdfPrinter = require('pdfmake')
const doc = new PdfPrinter({ Probe: faces }).createPdfKitDocument({
- content: [{ text: ch, font: 'Probe' }],
+ content: (Array.isArray(texts) ? texts : [texts]).map(text => ({ text, font: 'Probe' })),
defaultStyle: { font: 'Probe' },
})
doc.on('data', () => undefined)
@@ -797,11 +835,7 @@ function discoverFallbacks(exclude: Set<string>): FallbackFamily[] {
out.push({ family: 'Fallback-CJK', faces: cjk })
}
FALLBACK_PREFIXES.forEach(add)
- const rest = [...embeddableFaces().keys()]
- .filter(stem => FALLBACK_STEM.test(stem) && !/mono|emoji/.test(stem))
- .sort((a, b) => Number(/serif/.test(a)) - Number(/serif/.test(b)) || a.localeCompare(b))
- for (const stem of rest)
- add(path.basename(embeddableFaces().get(stem)!).replace(/(-Regular)?\.(ttf|otf)$/i, ''))
+ MORE_SCRIPT_PREFIXES.forEach(add)
return out
}
@@ -848,16 +882,29 @@ class GlyphSource implements PdfGlyphSource {
return info !== undefined && coversCodePoint(info.ranges, cp)
}
- /** A fallback face is tried in pdfkit once, with the first character it is chosen for. */
- private usable(fallback: FallbackFamily, cp: number): boolean {
+ /**
+ * A fallback face is tried in pdfkit once, with a letter of its own: a
+ * character a caller sent, such as a lone combining sign, can fail where the
+ * face is sound, and the answer is kept for the whole process.
+ */
+ private usable(fallback: FallbackFamily): boolean {
let ok = this.embeddable.get(fallback.family)
if (ok === undefined) {
- ok = embeds(fallback.faces, String.fromCodePoint(cp))
+ ok = embeds(fallback.faces, firstLetter(this.infoOf(fallback.family)?.ranges ?? []))
this.embeddable.set(fallback.family, ok)
}
return ok
}
+ isFallback(family: string): boolean {
+ return this.fallbackList().some(f => f.family === family)
+ }
+
+ shapes(family: string, texts: string[]): boolean {
+ const faces = this.facesOf(family)
+ return !faces || embeds(faces, texts)
+ }
+
familyFor(cp: number, base: string): string | undefined {
const key = `${base}\u0000${cp}`
if (this.chosen.has(key)) return this.chosen.get(key)
@@ -865,7 +912,7 @@ class GlyphSource implements PdfGlyphSource {
if (this.covers(base, cp)) hit = base
else if (base !== PDF_FONT_FAMILY && this.covers(PDF_FONT_FAMILY, cp)) hit = PDF_FONT_FAMILY
else {
- hit = this.fallbackList().find(f => this.covers(f.family, cp) && this.usable(f, cp))?.family
+ hit = this.fallbackList().find(f => this.covers(f.family, cp) && this.usable(f))?.family
}
this.chosen.set(key, hit)
return hit
diff --git a/mcp-host/src/workflow/internalTools.ts b/mcp-host/src/workflow/internalTools.ts
index 57ff98311..f6f1a1ed6 100644
--- a/mcp-host/src/workflow/internalTools.ts
+++ b/mcp-host/src/workflow/internalTools.ts
@@ -2647,6 +2647,7 @@ const generatePdf: InternalToolDefinition = {
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)
+ typesetter.settleShaping()
const copy = (node: ContentText): ContentText => JSON.parse(JSON.stringify(node))
const docDef: TDocumentDefinitions = {
diff --git a/mcp-host/src/workflow/pdfText.ts b/mcp-host/src/workflow/pdfText.ts
index 4f29a20e3..7160a1e20 100644
--- a/mcp-host/src/workflow/pdfText.ts
+++ b/mcp-host/src/workflow/pdfText.ts
@@ -126,10 +126,28 @@ function startRight(cell: unknown): void {
if (isObject(cell) && cell.alignment === undefined) cell.alignment = 'right'
}
+/** "12 character(s) of Arabic, Hebrew text", counting every character in `chars`. */
+function leftOut(chars: Map<string, number>): string {
+ const total = [...chars.values()].reduce((a, b) => a + b, 0)
+ const scripts = [...new Set([...chars.keys()].map(scriptName).filter(Boolean))]
+ return `${total} character(s)${scripts.length ? ` of ${scripts.join(', ')} text` : ''}`
+}
+
+function samplesOf(chars: Map<string, number>): string {
+ return [...chars.keys()]
+ .slice(0, 5)
+ .map(ch => `'${ch}' (U+${ch.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')})`)
+ .join(', ')
+}
+
export class PdfTypesetter {
/** Every family the typeset content names, for the printer's font table. */
readonly families = new Set<string>()
private readonly missing = new Map<string, number>()
+ /** Characters of runs pdfkit could not lay out in their face, left out by settleShaping. */
+ private readonly unshaped = new Map<string, number>()
+ /** Every run set in a fallback face, by family, for settleShaping to check. */
+ private readonly fallbackRuns = new Map<string, Props[]>()
private readonly advances = new Map<string, number>()
/** Base direction of each typeset text node that has one: 0 left to right, 1 right to left. */
private readonly direction = new WeakMap<object, 0 | 1>()
@@ -146,21 +164,70 @@ export class PdfTypesetter {
this.visit(content as unknown, ctx)
}
- /** Text that was left out, as a note the agent can act on. */
- warnings(): string[] {
- if (this.missing.size === 0) return []
- const total = [...this.missing.values()].reduce((a, b) => a + b, 0)
- const scripts = [...new Set([...this.missing.keys()].map(scriptName).filter(Boolean))]
- const samples = [...this.missing.keys()]
- .slice(0, 5)
- .map(ch => `'${ch}' (U+${ch.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')})`)
+ /**
+ * Check that pdfkit can lay out every run set in a fallback face, and empty
+ * the runs it cannot, so one sequence fontkit fails to shape leaves out those
+ * characters with a note instead of failing the whole document. The runs of a
+ * family are tried together, and split in halves only when that fails.
+ */
+ settleShaping(): void {
+ for (const [family, runs] of this.fallbackRuns) {
+ for (const run of this.unshapeable(family, runs)) {
+ for (const ch of String(run.text)) {
+ if (!/\s/.test(ch)) this.unshaped.set(ch, (this.unshaped.get(ch) ?? 0) + 1)
+ }
+ run.text = ''
+ }
+ }
+ this.fallbackRuns.clear()
+ }
+
+ /** `runs`, the ones set in a fallback face recorded for settleShaping. */
+ private kept(runs: Props[]): Props[] {
+ for (const run of runs) {
+ const family = run.font
+ if (typeof family !== 'string' || !this.glyphs.isFallback(family)) continue
+ const recorded = this.fallbackRuns.get(family)
+ if (recorded) recorded.push(run)
+ else this.fallbackRuns.set(family, [run])
+ }
+ return runs
+ }
+
+ private unshapeable(family: string, runs: Props[]): Props[] {
+ if (
+ this.glyphs.shapes(
+ family,
+ runs.map(r => String(r.text))
+ )
+ )
+ return []
+ if (runs.length === 1) return runs
+ const half = runs.length >> 1
return [
- `${total} character(s)${scripts.length ? ` of ${scripts.join(', ')} text` : ''} have no glyph in ` +
- `the fonts available to the PDF renderer and were left out, for example ${samples.join(', ')}. ` +
- 'clerum__generate_docx keeps such text.',
+ ...this.unshapeable(family, runs.slice(0, half)),
+ ...this.unshapeable(family, runs.slice(half)),
]
}
+ /** Text that was left out, as notes the agent can act on. */
+ warnings(): string[] {
+ const notes: string[] = []
+ if (this.missing.size > 0) {
+ notes.push(
+ `${leftOut(this.missing)} have no glyph in the fonts available to the PDF renderer and ` +
+ `were left out, for example ${samplesOf(this.missing)}. clerum__generate_docx keeps such text.`
+ )
+ }
+ if (this.unshaped.size > 0) {
+ notes.push(
+ `${leftOut(this.unshaped)} are in a sequence the PDF renderer cannot lay out and were left ` +
+ `out, for example ${samplesOf(this.unshaped)}. clerum__generate_docx keeps such text.`
+ )
+ }
+ return notes
+ }
+
private visit(node: unknown, ctx: TypesetContext): unknown {
if (typeof node === 'string') {
const holder: Props = { text: node }
@@ -362,7 +429,7 @@ export class PdfTypesetter {
for (const piece of pieces) this.glyphsOf(piece.text, piece.props, ctx, glyphs)
if (!pieces.some(p => hasRtl(p.text))) {
- const runs = this.runs(this.breakLongWords(glyphs, ctx), ctx)
+ const runs = this.kept(this.runs(this.breakLongWords(glyphs, ctx), ctx))
node.text = runs.length > 0 ? runs : ''
if (pieces.some(p => /\p{L}/u.test(p.text))) this.direction.set(node, 0)
return
@@ -392,7 +459,7 @@ export class PdfTypesetter {
}
runs.push(...lineRuns)
})
- node.text = runs
+ node.text = this.kept(runs)
if (firstBase !== undefined) this.direction.set(node, firstBase)
if (firstBase === 1 && node.alignment === undefined) node.alignment = 'right'
}