Skip to content

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

TypeScript

fix(mcp-host): write generated artifacts whole

marcotebd21c50f4bcd3
diff --git a/mcp-host/src/__tests__/server.artifacts.test.ts b/mcp-host/src/__tests__/server.artifacts.test.ts
index 02b7c1422..a82e97178 100644
--- a/mcp-host/src/__tests__/server.artifacts.test.ts
+++ b/mcp-host/src/__tests__/server.artifacts.test.ts
@@ -88,6 +88,7 @@ describe('RPCServer runtime artifact routes', () => {
outsideFile = path.join(os.tmpdir(), `clerum-outside-${process.pid}-${Date.now()}.txt`)
fs.writeFileSync(path.join(outputDir, 'report.md'), '# ok\n')
fs.writeFileSync(path.join(outputDir, '.clerum-state'), '{}')
+ fs.writeFileSync(path.join(outputDir, '.clerum-partial-in-progress'), 'half a file')
fs.mkdirSync(path.join(outputDir, 'nested'))
fs.writeFileSync(outsideFile, 'secret outside output')
fs.symlinkSync(outsideFile, path.join(outputDir, 'leak.md'))
@@ -106,6 +107,11 @@ describe('RPCServer runtime artifact routes', () => {
sizeBytes: 5,
})
expect(body.artifacts[0].createdAt).toMatch(/\d{4}-\d{2}-\d{2}T/)
+ const partial = await fetch(
+ `${baseUrl}/v1/runtime/artifacts/.clerum-partial-in-progress/download`,
+ { headers: rpcEdgeHeaders }
+ )
+ expect(partial.status).toBe(404)
} finally {
await server.stop()
}
diff --git a/mcp-host/src/workflow/__tests__/artifactOutput.test.ts b/mcp-host/src/workflow/__tests__/artifactOutput.test.ts
index 78d20a333..7e7515047 100644
--- a/mcp-host/src/workflow/__tests__/artifactOutput.test.ts
+++ b/mcp-host/src/workflow/__tests__/artifactOutput.test.ts
@@ -2,7 +2,18 @@ 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 {
+ PARTIAL_PREFIX,
+ artifactResult,
+ capNotes,
+ claimOutputFile,
+ getDirectorySize,
+ outputFilename,
+ replacedBytes,
+ writeArtifact,
+} from '../artifactOutput'
+import { ArtifactPathError, openExistingArtifactFile } from '../artifactPaths'
+import { loadEmbeddableImage } from '../embeddedImages'
import { INTERNAL_TOOLS, enforceQuota } from '../internalTools'
let outputDir: string
@@ -96,6 +107,79 @@ describe('claimOutputFile', () => {
})
})
+describe('writeArtifact', () => {
+ const partials = () => fs.readdirSync(outputDir).filter(name => name.startsWith(PARTIAL_PREFIX))
+
+ it('writes the bytes, replaces an earlier file and leaves no partial file', () => {
+ writeArtifact(claimOutputFile(outputDir, 'r.md'), '# first\n')
+ writeArtifact(claimOutputFile(outputDir, 'r.md'), Buffer.from('# second\n'))
+ expect(fs.readFileSync(path.join(outputDir, 'r.md'), 'utf8')).toBe('# second\n')
+ expect(partials()).toEqual([])
+ })
+
+ it('replaces a link put in the name after the claim, never writing through it', () => {
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-outside-'))
+ try {
+ fs.writeFileSync(path.join(outside, 'victim.txt'), 'original')
+ const target = claimOutputFile(outputDir, 'r.pdf')
+ fs.symlinkSync(path.join(outside, 'victim.txt'), target.filePath)
+ writeArtifact(target, 'new')
+ expect(fs.lstatSync(target.filePath).isSymbolicLink()).toBe(false)
+ expect(fs.readFileSync(target.filePath, 'utf8')).toBe('new')
+ expect(fs.readFileSync(path.join(outside, 'victim.txt'), 'utf8')).toBe('original')
+ } finally {
+ fs.rmSync(outside, { recursive: true, force: true })
+ }
+ })
+
+ it('keeps the earlier file and no partial file when the write fails', () => {
+ writeArtifact(claimOutputFile(outputDir, 'r.md'), 'kept')
+ expect(() => writeArtifact(claimOutputFile(outputDir, 'r.md'), 42 as never)).toThrow()
+ expect(fs.readFileSync(path.join(outputDir, 'r.md'), 'utf8')).toBe('kept')
+ expect(partials()).toEqual([])
+ })
+
+ it('treats a partial file as no artifact: not counted, not opened, not embedded', () => {
+ const name = `${PARTIAL_PREFIX}in-progress`
+ fs.writeFileSync(path.join(outputDir, name), Buffer.alloc(1024))
+ fs.writeFileSync(path.join(outputDir, 'done.md'), 'x')
+ // Witness: the counter does see regular files.
+ expect(getDirectorySize(outputDir)).toBe(1)
+ expect(() => openExistingArtifactFile(outputDir, name)).toThrow(ArtifactPathError)
+ const warnings: string[] = []
+ expect(loadEmbeddableImage(name, outputDir, warnings)).toBeUndefined()
+ expect(warnings.join(' ')).toContain('was not found')
+ })
+
+ it('removes a partial file left by a write that never finished', () => {
+ const stale = path.join(outputDir, `${PARTIAL_PREFIX}stale`)
+ const fresh = path.join(outputDir, `${PARTIAL_PREFIX}fresh`)
+ fs.writeFileSync(stale, 'x')
+ fs.writeFileSync(fresh, 'x')
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000)
+ fs.utimesSync(stale, twoHoursAgo, twoHoursAgo)
+ writeArtifact(claimOutputFile(outputDir, 'r.md'), 'x')
+ expect(fs.existsSync(stale)).toBe(false)
+ // A partial file this recent may belong to a write in progress.
+ expect(fs.existsSync(fresh)).toBe(true)
+ })
+
+ it('does not count the size behind a link planted in the name after the claim', () => {
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-outside-'))
+ try {
+ fs.writeFileSync(path.join(outputDir, 'r.pdf'), 'old')
+ const target = claimOutputFile(outputDir, 'r.pdf')
+ expect(replacedBytes(target)).toBe(3)
+ fs.writeFileSync(path.join(outside, 'big.bin'), Buffer.alloc(4096))
+ fs.rmSync(target.filePath)
+ fs.symlinkSync(path.join(outside, 'big.bin'), target.filePath)
+ expect(replacedBytes(target)).toBe(0)
+ } 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')
diff --git a/mcp-host/src/workflow/artifactOutput.ts b/mcp-host/src/workflow/artifactOutput.ts
index 1ab407e37..30ce31107 100644
--- a/mcp-host/src/workflow/artifactOutput.ts
+++ b/mcp-host/src/workflow/artifactOutput.ts
@@ -1,7 +1,7 @@
/**
* Naming, placing and reporting the files the document generators write.
*/
-import { createHash } from 'crypto'
+import { createHash, randomUUID } from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import type { ArtifactMetadata, InternalToolResult } from './types'
@@ -89,13 +89,92 @@ function lstat(file: string): fs.Stats | undefined {
}
}
-/** Size of the file a write is about to replace, so a quota check does not count it twice. */
+/**
+ * Size of the file a write is about to replace, so a quota check does not count
+ * it twice. Only a regular file counts: a link planted in its place since
+ * claimOutputFile must not lend the size of whatever it points to.
+ */
export function replacedBytes(target: OutputTarget): number {
if (!target.replacesExisting) return 0
+ const entry = lstat(target.filePath)
+ return entry?.isFile() ? entry.size : 0
+}
+
+/** Prefix of a file still being written: never listed, served, embedded or counted. */
+export const PARTIAL_PREFIX = '.clerum-partial-'
+
+export function isPartialArtifactName(name: string): boolean {
+ return path.basename(name).startsWith(PARTIAL_PREFIX)
+}
+
+/** A partial file this old was left by a write that never finished. */
+const ABANDONED_PARTIAL_MS = 60 * 60 * 1000
+
+function removeAbandonedPartials(dir: string): void {
+ let names: string[]
try {
- return fs.statSync(target.filePath).size
+ names = fs.readdirSync(dir)
} catch {
- return 0
+ return
+ }
+ const cutoff = Date.now() - ABANDONED_PARTIAL_MS
+ for (const name of names) {
+ if (!isPartialArtifactName(name)) continue
+ const file = path.join(dir, name)
+ const entry = lstat(file)
+ if (entry?.isFile() && entry.mtimeMs < cutoff) {
+ try {
+ fs.unlinkSync(file)
+ } catch {
+ // Another write removed it, or it cannot be removed; the next write retries.
+ }
+ }
+ }
+}
+
+/**
+ * Writes `data` under `target` whole: into a new file beside it, created
+ * without following links, flushed, then renamed over the name. A reader sees
+ * the previous file or this one, never part of it; a link in the name's place
+ * is replaced, not followed; a write that fails leaves the previous file and
+ * no partial one.
+ */
+export function writeArtifact(target: OutputTarget, data: string | Uint8Array): void {
+ const dir = path.dirname(target.filePath)
+ removeAbandonedPartials(dir)
+ const partial = path.join(dir, `${PARTIAL_PREFIX}${randomUUID()}`)
+ const { O_WRONLY, O_CREAT, O_EXCL, O_NOFOLLOW } = fs.constants
+ const fd = fs.openSync(partial, O_WRONLY | O_CREAT | O_EXCL | (O_NOFOLLOW ?? 0), 0o666)
+ let published = false
+ try {
+ try {
+ fs.writeFileSync(fd, data)
+ fs.fsyncSync(fd)
+ } finally {
+ fs.closeSync(fd)
+ }
+ fs.renameSync(partial, target.filePath)
+ published = true
+ } finally {
+ if (!published) {
+ try {
+ fs.unlinkSync(partial)
+ } catch {
+ // Already gone; the error being thrown is the one that matters.
+ }
+ }
+ }
+ // The file is published; flushing the folder only makes the new name
+ // survive a crash, so a folder that cannot be opened for it is not an error.
+ try {
+ const dirFd = fs.openSync(dir, fs.constants.O_RDONLY)
+ try {
+ fs.fsyncSync(dirFd)
+ } finally {
+ fs.closeSync(dirFd)
+ }
+ } catch {
+ // Some filesystems refuse to fsync a directory.
}
}
@@ -162,9 +241,7 @@ export function artifactResult(
}
export function ensureDir(dir: string): void {
- if (!fs.existsSync(dir)) {
- fs.mkdirSync(dir, { recursive: true })
- }
+ fs.mkdirSync(dir, { recursive: true })
}
// A dashboard with charts inlines the Chart.js UMD bundle (~210 KB) so the
@@ -183,7 +260,7 @@ export function getDirectorySize(dir: string): number {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) {
total += getDirectorySize(full)
- } else if (entry.isFile()) {
+ } else if (entry.isFile() && !isPartialArtifactName(entry.name)) {
try {
total += fs.statSync(full).size
} catch {
diff --git a/mcp-host/src/workflow/artifactPaths.ts b/mcp-host/src/workflow/artifactPaths.ts
index e59d57aa9..a7f286f88 100644
--- a/mcp-host/src/workflow/artifactPaths.ts
+++ b/mcp-host/src/workflow/artifactPaths.ts
@@ -1,5 +1,6 @@
import * as fs from 'fs'
import * as path from 'path'
+import { isPartialArtifactName } from './artifactOutput'
// Keep this aligned with control-api/src/k8s.ts until the artifact policy is
// promoted to a shared runtime dependency consumed by both services.
@@ -49,6 +50,10 @@ function resolveArtifactCandidate(outputDir: string, filename: string): Artifact
if (!isSafeArtifactFilename(filename)) {
throw new ArtifactPathError(400, 'Invalid filename')
}
+ // A file still being written is not an artifact yet.
+ if (isPartialArtifactName(filename)) {
+ throw new ArtifactPathError(404, 'Artifact not found')
+ }
const root = path.resolve(outputDir)
const candidate = path.resolve(root, filename)
diff --git a/mcp-host/src/workflow/chartGenerator.ts b/mcp-host/src/workflow/chartGenerator.ts
index 5e4598d7b..3e8ad58fa 100644
--- a/mcp-host/src/workflow/chartGenerator.ts
+++ b/mcp-host/src/workflow/chartGenerator.ts
@@ -8,7 +8,6 @@ import {
type Scale,
registerables,
} from 'chart.js'
-import * as fs from 'fs'
import {
artifactResult,
claimOutputFile,
@@ -16,6 +15,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import { ChartDataError, type NormalizedPoint, normalizeChartData } from './chartData'
import {
@@ -954,7 +954,7 @@ export async function runGenerateChart(
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, pngBuffer.byteLength, replacedBytes(target))
- fs.writeFileSync(target.filePath, pngBuffer)
+ writeArtifact(target, pngBuffer)
const summary =
`Chart written: ${target.filename} (${canvas.width}x${canvas.height} px, ` +
diff --git a/mcp-host/src/workflow/dashboardRender.ts b/mcp-host/src/workflow/dashboardRender.ts
index 414f7c62f..131b62348 100644
--- a/mcp-host/src/workflow/dashboardRender.ts
+++ b/mcp-host/src/workflow/dashboardRender.ts
@@ -3,7 +3,6 @@
* the tool entry. The stylesheet, the page parts and the templates are in
* dashboardCss, dashboardComponents and dashboardTemplates.
*/
-import * as fs from 'fs'
import {
artifactResult,
claimOutputFile,
@@ -11,6 +10,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import { loadChartJsBundle } from './dashboardChartJs'
import { DashboardCharts } from './dashboardCharts'
@@ -194,7 +194,7 @@ export async function runGenerateDashboard(
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, Buffer.byteLength(html, 'utf-8'), replacedBytes(target))
- fs.writeFileSync(target.filePath, html, 'utf-8')
+ writeArtifact(target, html)
return artifactResult(target, 'html', { warnings })
} catch (err) {
diff --git a/mcp-host/src/workflow/docxGenerator.ts b/mcp-host/src/workflow/docxGenerator.ts
index fef25f316..459cfa44a 100644
--- a/mcp-host/src/workflow/docxGenerator.ts
+++ b/mcp-host/src/workflow/docxGenerator.ts
@@ -13,7 +13,6 @@ import {
TabStopType,
TextRun,
} from 'docx'
-import * as fs from 'fs'
import {
artifactResult,
claimOutputFile,
@@ -21,6 +20,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import { EMPTY_DOCUMENT_NOTE, printedBranding } from './documentChrome'
import { type DocxImagePlacement, docxImageParagraph } from './docxImages'
@@ -307,7 +307,7 @@ export async function runGenerateDocx(
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, buffer.byteLength, replacedBytes(target))
- fs.writeFileSync(target.filePath, buffer)
+ writeArtifact(target, buffer)
return artifactResult(target, 'docx', { warnings: [...new Set(warnings)] })
} catch (err) {
diff --git a/mcp-host/src/workflow/embeddedImages.ts b/mcp-host/src/workflow/embeddedImages.ts
index 5c4e933f1..143fffe19 100644
--- a/mcp-host/src/workflow/embeddedImages.ts
+++ b/mcp-host/src/workflow/embeddedImages.ts
@@ -5,6 +5,7 @@ import { createCanvas, loadImage } from '@napi-rs/canvas'
import { spawn } from 'child_process'
import * as fs from 'fs'
import * as path from 'path'
+import { isPartialArtifactName } from './artifactOutput'
import { imageTarget } from './inlineMarkup'
import { own } from './ownEntry'
@@ -237,7 +238,7 @@ function resolveImagePath(
)
file = sibling
}
- if (!fs.existsSync(file) || !fs.statSync(file).isFile()) {
+ if (isPartialArtifactName(file) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
warnings.push(`Image '${requested}' was not found in the output folder and was left out.`)
return undefined
}
diff --git a/mcp-host/src/workflow/markdownGenerator.ts b/mcp-host/src/workflow/markdownGenerator.ts
index c91c774a8..a9cdd43aa 100644
--- a/mcp-host/src/workflow/markdownGenerator.ts
+++ b/mcp-host/src/workflow/markdownGenerator.ts
@@ -1,5 +1,4 @@
/** clerum__generate_markdown: the text, written as given. */
-import * as fs from 'fs'
import {
artifactResult,
claimOutputFile,
@@ -7,6 +6,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import type { InternalToolResult } from './types'
@@ -41,7 +41,7 @@ export async function runGenerateMarkdown(
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, Buffer.byteLength(content, 'utf-8'), replacedBytes(target))
- fs.writeFileSync(target.filePath, content, 'utf-8')
+ writeArtifact(target, content)
return artifactResult(target, 'md')
} catch (err) {
diff --git a/mcp-host/src/workflow/pdfGenerator.ts b/mcp-host/src/workflow/pdfGenerator.ts
index 1f69c576b..9a3767d97 100644
--- a/mcp-host/src/workflow/pdfGenerator.ts
+++ b/mcp-host/src/workflow/pdfGenerator.ts
@@ -1,5 +1,4 @@
/** The PDF generator (clerum__generate_pdf): markdown body, tables and images typeset with pdfmake. */
-import * as fs from 'fs'
import * as path from 'path'
import { type Content, type ContentText, type TDocumentDefinitions } from 'pdfmake/interfaces'
import {
@@ -9,6 +8,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import {
EMPTY_DOCUMENT_NOTE,
@@ -444,7 +444,7 @@ export async function runGeneratePdf(
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, pdfBuffer.byteLength, replacedBytes(target))
- fs.writeFileSync(target.filePath, pdfBuffer)
+ writeArtifact(target, pdfBuffer)
return artifactResult(target, 'pdf', { warnings: [...warnings, ...typesetter.warnings()] })
} catch (err) {
diff --git a/mcp-host/src/workflow/pptxGenerator.ts b/mcp-host/src/workflow/pptxGenerator.ts
index 6b9581c9e..ac61b146f 100644
--- a/mcp-host/src/workflow/pptxGenerator.ts
+++ b/mcp-host/src/workflow/pptxGenerator.ts
@@ -1,5 +1,4 @@
/** clerum__generate_pptx: builds the deck (pptxDeck, loaded on first use) and writes it. */
-import * as fs from 'fs'
import {
artifactResult,
claimOutputFile,
@@ -7,6 +6,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import type { InternalToolResult } from './types'
@@ -19,11 +19,11 @@ export async function runGeneratePptx(
const warnings: string[] = []
const { buildPptxDeck } = await import('./pptxDeck')
const { buffer, slides } = await buildPptxDeck(args, outputDir, warnings)
- // Buffer first, quota check, then write — atomic, no partial files.
+ // Buffer first, quota check, then an atomic write.
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, buffer.byteLength, replacedBytes(target))
- fs.writeFileSync(target.filePath, buffer)
+ writeArtifact(target, buffer)
return artifactResult(target, 'pptx', {
summary: `File generated: ${target.filename} (pptx), ${slides} slide${slides === 1 ? '' : 's'}.`,
warnings,
diff --git a/mcp-host/src/workflow/xlsxGenerator.ts b/mcp-host/src/workflow/xlsxGenerator.ts
index cde925fc5..f87530938 100644
--- a/mcp-host/src/workflow/xlsxGenerator.ts
+++ b/mcp-host/src/workflow/xlsxGenerator.ts
@@ -1,5 +1,4 @@
/** clerum__generate_xlsx: builds the workbook (xlsxWorkbook, loaded on first use) and writes it. */
-import * as fs from 'fs'
import {
artifactResult,
claimOutputFile,
@@ -7,6 +6,7 @@ import {
ensureDir,
outputFilename,
replacedBytes,
+ writeArtifact,
} from './artifactOutput'
import type { InternalToolResult } from './types'
@@ -33,7 +33,7 @@ export async function runGenerateXlsx(
ensureDir(outputDir)
const target = claimOutputFile(outputDir, filename)
enforceQuota(outputDir, built.buffer.byteLength, replacedBytes(target))
- fs.writeFileSync(target.filePath, built.buffer)
+ writeArtifact(target, built.buffer)
return artifactResult(target, 'xlsx', {
summary: `File generated: ${target.filename} (xlsx): ${built.summary}.`,
warnings,