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 each chat caller's generated files private

marcoteb15c14db6cb78
diff --git a/mcp-host/src/__tests__/server.artifacts.test.ts b/mcp-host/src/__tests__/server.artifacts.test.ts
index a82e97178..48cfc8666 100644
--- a/mcp-host/src/__tests__/server.artifacts.test.ts
+++ b/mcp-host/src/__tests__/server.artifacts.test.ts
@@ -5,38 +5,67 @@ import * as os from 'os'
import * as path from 'path'
import type { RPCServer } from '../server'
import { MAX_ARTIFACT_BYTES } from '../workflow/artifactPaths'
+import { CALLER_OUTPUTS_DIR, resolveRpcCallerOutputDir } from '../workspace/callerOutputs'
+import { deriveUserKeyFromSource } from '../workspace/userKey'
const ORIGINAL_ENABLE_AUTH = process.env.CLERUM_ENABLE_AUTH
const ORIGINAL_OUTPUT_DIR = process.env.CLERUM_OUTPUT_DIR
const ORIGINAL_WORKFLOW_ENABLED = process.env.CLERUM_WORKFLOW_ENABLED
+/** The Host root the current test's callers live under. */
+let hostRoot = ''
+
async function startServer(
- outputDir: string,
+ _outputDir: string,
secretEntries: Array<{ name: string; value: string }> = [],
- options: { workflowEnabled?: boolean } = {}
+ options: { workflowEnabled?: boolean; resolver?: boolean; sharedOutputDir?: string } = {}
): Promise<{ server: RPCServer; baseUrl: string }> {
process.env.CLERUM_ENABLE_AUTH = 'false'
process.env.CLERUM_HOST_NAME = 'chatllm'
- process.env.CLERUM_OUTPUT_DIR = outputDir
+ // The chat routes never read it; a test can point it at a populated folder.
+ if (options.sharedOutputDir) process.env.CLERUM_OUTPUT_DIR = options.sharedOutputDir
+ else delete process.env.CLERUM_OUTPUT_DIR
if (options.workflowEnabled) process.env.CLERUM_WORKFLOW_ENABLED = 'true'
else delete process.env.CLERUM_WORKFLOW_ENABLED
vi.resetModules()
const { RPCServer } = await import('../server')
const server = new RPCServer(0)
server.setArtifactSecretEntriesProvider(() => secretEntries)
+ // Wired as main.ts wires it.
+ const root = hostRoot
+ if (options.resolver !== false) {
+ server.setChatArtifactDirResolver(userId => resolveRpcCallerOutputDir(root, userId))
+ }
await server.start()
const address = (server as unknown as { server: { address: () => AddressInfo } }).server.address()
return { server, baseUrl: `http://127.0.0.1:${address.port}` }
}
-const rpcEdgeHeaders = {
- 'x-clerum-edge-caller': 'rpc-proxy',
- 'x-clerum-edge-host-ref': 'chatllm',
- 'x-clerum-edge-user-id': 'user-1',
+function edgeHeaders(userId: string): Record<string, string> {
+ return {
+ 'x-clerum-edge-caller': 'rpc-proxy',
+ 'x-clerum-edge-host-ref': 'chatllm',
+ 'x-clerum-edge-user-id': userId,
+ }
+}
+
+const rpcEdgeHeaders = edgeHeaders('user-1')
+
+/** The caller root of a Desktop user, keyed as their chat messages are. */
+function callerRootOf(userId: string): string {
+ return path.join(
+ hostRoot,
+ 'users',
+ deriveUserKeyFromSource({ sender: userId, channelType: 'rpc' })
+ )
}
-function makeOutputDir(): string {
- return fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-runtime-artifact-test-'))
+/** A user's folder of generated files, created on a fresh Host root for user-1. */
+function makeOutputDir(userId = 'user-1'): string {
+ if (!hostRoot) hostRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-runtime-artifact-test-'))
+ const dir = path.join(callerRootOf(userId), CALLER_OUTPUTS_DIR)
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
+ return dir
}
function restoreEnv(): void {
@@ -53,9 +82,10 @@ describe('RPCServer runtime artifact routes', () => {
let outsideFile = ''
afterEach(() => {
- if (outputDir) {
- fs.rmSync(outputDir, { recursive: true, force: true })
- outputDir = ''
+ outputDir = ''
+ if (hostRoot) {
+ fs.rmSync(hostRoot, { recursive: true, force: true })
+ hostRoot = ''
}
if (outsideFile) {
fs.rmSync(outsideFile, { force: true })
@@ -64,7 +94,7 @@ describe('RPCServer runtime artifact routes', () => {
restoreEnv()
})
- it('downloads regular artifacts from the configured output directory', async () => {
+ it("downloads regular artifacts from the caller's own folder", async () => {
outputDir = makeOutputDir()
fs.writeFileSync(path.join(outputDir, 'report.md'), '# ok\n')
const { server, baseUrl } = await startServer(outputDir)
@@ -83,7 +113,7 @@ describe('RPCServer runtime artifact routes', () => {
}
})
- it('lists only regular downloadable artifacts from the configured output directory', async () => {
+ it("lists only regular downloadable artifacts from the caller's own folder", async () => {
outputDir = makeOutputDir()
outsideFile = path.join(os.tmpdir(), `clerum-outside-${process.pid}-${Date.now()}.txt`)
fs.writeFileSync(path.join(outputDir, 'report.md'), '# ok\n')
@@ -117,7 +147,7 @@ describe('RPCServer runtime artifact routes', () => {
}
})
- it('does not download symlink artifacts from the output directory', async () => {
+ it("does not download symlink artifacts from the caller's folder", async () => {
outputDir = makeOutputDir()
outsideFile = path.join(os.tmpdir(), `clerum-outside-${process.pid}-${Date.now()}.txt`)
fs.writeFileSync(outsideFile, 'secret outside output')
@@ -263,4 +293,115 @@ describe('RPCServer runtime artifact routes', () => {
await server.stop()
}
})
+
+ it("lists and downloads only the requesting user's own files, whatever the name", async () => {
+ outputDir = makeOutputDir('user-1')
+ fs.writeFileSync(path.join(outputDir, 'mine.md'), '# one\n')
+ fs.writeFileSync(path.join(makeOutputDir('user-2'), 'theirs.md'), '# two\n')
+ const { server, baseUrl } = await startServer(outputDir)
+
+ try {
+ const names = async (userId: string) => {
+ const res = await fetch(`${baseUrl}/v1/runtime/artifacts`, { headers: edgeHeaders(userId) })
+ expect(res.status).toBe(200)
+ const body = (await res.json()) as { artifacts: Array<{ name: string }> }
+ return body.artifacts.map(a => a.name)
+ }
+ expect(await names('user-1')).toEqual(['mine.md'])
+ expect(await names('user-2')).toEqual(['theirs.md'])
+
+ const guessed = await fetch(`${baseUrl}/v1/runtime/artifacts/theirs.md/download`, {
+ headers: edgeHeaders('user-1'),
+ })
+ expect(guessed.status).toBe(404)
+ const own = await fetch(`${baseUrl}/v1/runtime/artifacts/theirs.md/download`, {
+ headers: edgeHeaders('user-2'),
+ })
+ expect(own.status).toBe(200)
+ expect(await own.text()).toBe('# two\n')
+ } finally {
+ await server.stop()
+ }
+ })
+
+ it('lists nothing and creates no folder for a user who has generated nothing', async () => {
+ outputDir = makeOutputDir('user-1')
+ const { server, baseUrl } = await startServer(outputDir)
+
+ try {
+ const res = await fetch(`${baseUrl}/v1/runtime/artifacts`, { headers: edgeHeaders('user-3') })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ artifacts: [] })
+ const download = await fetch(`${baseUrl}/v1/runtime/artifacts/mine.md/download`, {
+ headers: edgeHeaders('user-3'),
+ })
+ expect(download.status).toBe(404)
+ expect(fs.existsSync(callerRootOf('user-3'))).toBe(false)
+ } finally {
+ await server.stop()
+ }
+ })
+
+ it('answers 503, not another folder, when the caller folder is a link', async () => {
+ outputDir = makeOutputDir('user-1')
+ const elsewhere = path.join(hostRoot, 'elsewhere')
+ fs.mkdirSync(elsewhere)
+ fs.writeFileSync(path.join(elsewhere, 'report.md'), '# not yours\n')
+ fs.rmSync(outputDir, { recursive: true })
+ fs.symlinkSync(elsewhere, outputDir)
+ const { server, baseUrl } = await startServer(outputDir)
+
+ try {
+ const list = await fetch(`${baseUrl}/v1/runtime/artifacts`, { headers: rpcEdgeHeaders })
+ expect(list.status).toBe(503)
+ expect(await list.json()).toMatchObject({ code: 'artifact_store_unavailable' })
+ const download = await fetch(`${baseUrl}/v1/runtime/artifacts/report.md/download`, {
+ headers: rpcEdgeHeaders,
+ })
+ expect(download.status).toBe(503)
+ } finally {
+ await server.stop()
+ }
+ })
+
+ it('answers 503 and never serves the shared folder when no resolver is wired', async () => {
+ outputDir = makeOutputDir('user-1')
+ const shared = path.join(hostRoot, 'outputs')
+ fs.mkdirSync(shared)
+ fs.writeFileSync(path.join(shared, 'report.md'), '# shared\n')
+ const { server, baseUrl } = await startServer(outputDir, [], {
+ resolver: false,
+ sharedOutputDir: shared,
+ })
+
+ try {
+ const list = await fetch(`${baseUrl}/v1/runtime/artifacts`, { headers: rpcEdgeHeaders })
+ expect(list.status).toBe(503)
+ const download = await fetch(`${baseUrl}/v1/runtime/artifacts/report.md/download`, {
+ headers: rpcEdgeHeaders,
+ })
+ expect(download.status).toBe(503)
+ } finally {
+ await server.stop()
+ }
+ })
+
+ it('does not serve CLERUM_OUTPUT_DIR in chat when a resolver is wired', async () => {
+ outputDir = makeOutputDir('user-1')
+ const shared = path.join(hostRoot, 'outputs')
+ fs.mkdirSync(shared)
+ fs.writeFileSync(path.join(shared, 'report.md'), '# shared\n')
+ const { server, baseUrl } = await startServer(outputDir, [], { sharedOutputDir: shared })
+
+ try {
+ const list = await fetch(`${baseUrl}/v1/runtime/artifacts`, { headers: rpcEdgeHeaders })
+ expect(await list.json()).toEqual({ artifacts: [] })
+ const download = await fetch(`${baseUrl}/v1/runtime/artifacts/report.md/download`, {
+ headers: rpcEdgeHeaders,
+ })
+ expect(download.status).toBe(404)
+ } finally {
+ await server.stop()
+ }
+ })
})
diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.ts
index 2282efd8e..e782e92cd 100644
--- a/mcp-host/src/agent/taskExecutor.ts
+++ b/mcp-host/src/agent/taskExecutor.ts
@@ -189,6 +189,20 @@ export function executionModeForSource(source: TaskSource): 'interactive' | 'una
return source === 'channel' ? 'interactive' : 'unattended'
}
+/**
+ * The caller root generated files go under. A message with no sender would
+ * share one folder with every other sender-less message on its channel, so it
+ * gets none and the generators refuse to write. A task with no message at all
+ * (cron, system) keeps the reserved system folder.
+ */
+export function generatedOutputsRoot(
+ sourceMessage: Task['sourceMessage'],
+ callerRoot: string | undefined
+): string | undefined {
+ if (sourceMessage && !(sourceMessage.sender ?? '').trim()) return undefined
+ return callerRoot
+}
+
export interface TaskExecutorDeps {
conversationManager: ConversationManager
llmProvider: SingleTurnProvider
@@ -2285,7 +2299,8 @@ export class TaskExecutor {
// §13 (stateless agents): the active provider's credential slot is the
// only one that survives into shell_exec's child env.
this.deps.llmProvider.getProviderType(),
- gfsWorkspace ? { ...gfsWorkspace, deliveryAvailable: gfsDeliveryEligible } : undefined
+ gfsWorkspace ? { ...gfsWorkspace, deliveryAvailable: gfsDeliveryEligible } : undefined,
+ generatedOutputsRoot(this.task.sourceMessage, this.deps.gfsCallerWorkspacePath)
)
await registerDesktopTools(nativeRegistry)
// Eagerly open this caller's remote OAuth partitions before the catalog is
diff --git a/mcp-host/src/core/orchestration/__tests__/nativeToolPresentation.integration.test.ts b/mcp-host/src/core/orchestration/__tests__/nativeToolPresentation.integration.test.ts
index 046b8eadd..fcbd33cc0 100644
--- a/mcp-host/src/core/orchestration/__tests__/nativeToolPresentation.integration.test.ts
+++ b/mcp-host/src/core/orchestration/__tests__/nativeToolPresentation.integration.test.ts
@@ -21,6 +21,7 @@ import type { SingleTurnProvider } from '../../../llm/types'
import { logger } from '../../../logger'
import { McpManager } from '../../../mcp/manager'
import type { Task, TaskResponsePayload } from '../../../queue/types'
+import { CALLER_OUTPUTS_DIR } from '../../../workspace/callerOutputs'
import { ConversationManager } from '../../conversation/conversation'
import {
CAPABILITY_CONTRACT_TEXT,
@@ -39,6 +40,19 @@ import { NATIVE_DIRECT_DEV_BASELINE } from './nativeDirectDevBaseline'
type RemoteTool = { name: string; description: string; inputSchema: Record<string, unknown> }
const remote = vi.hoisted(() => ({ catalogs: new Map<string, RemoteTool[]>(), calls: vi.fn() }))
+// statfs reports the volume sized to its free space, so the disk's occupancy
+// never meets the free-space floor of the caller's folder.
+vi.mock('fs', async original => {
+ const actual = await original<typeof import('fs')>()
+ return {
+ ...actual,
+ statfsSync: (target: string, options: { bigint: true }) => {
+ const reading = actual.statfsSync(target, options)
+ return { ...reading, blocks: reading.bavail, bfree: reading.bavail }
+ },
+ }
+})
+
vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
Client: class {
server = ''
@@ -144,6 +158,7 @@ const toolResult = (messages: ChatMessage[], id: string) => {
}
let outputDir: string
+let callerRoot: string
let logEvents: Array<Record<string, unknown>>
const savedConfig = {
enableApproval: appConfig.enableApproval,
@@ -158,7 +173,10 @@ const savedOutputDir = process.env.CLERUM_OUTPUT_DIR
beforeEach(() => {
outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'native-presentation-'))
- process.env.CLERUM_OUTPUT_DIR = outputDir
+ // The task's managed caller root; its generated decks go to its own folder.
+ callerRoot = path.join(outputDir, 'users', 'authenticated-user')
+ fs.mkdirSync(callerRoot, { recursive: true })
+ delete process.env.CLERUM_OUTPUT_DIR
logEvents = []
vi.spyOn(logger, 'info').mockImplementation(((entry: unknown) => {
if (entry && typeof entry === 'object' && 'component' in entry)
@@ -178,7 +196,12 @@ afterEach(async () => {
})
const events = (component: string) => logEvents.filter(event => event.component === component)
-const pptxFiles = () => fs.readdirSync(outputDir).filter(file => file.endsWith('.pptx'))
+const pptxFiles = () => {
+ const generated = path.join(callerRoot, CALLER_OUTPUTS_DIR)
+ return fs.existsSync(generated)
+ ? fs.readdirSync(generated).filter(file => file.endsWith('.pptx'))
+ : []
+}
async function runScenario(scenario: Scenario, turns: Turn[]) {
Object.assign(appConfig, {
@@ -294,6 +317,7 @@ async function runScenario(scenario: Scenario, turns: Turn[]) {
onComplete: vi.fn(),
onFail: vi.fn(),
dynamicEnvProvider: () => ({}),
+ gfsCallerWorkspacePath: callerRoot,
}
const executor = new TaskExecutor(task, deps)
// `tool:called` is emitted once per execution, after admission. The call ids
diff --git a/mcp-host/src/core/tools/__tests__/generatedArtifactAttachments.test.ts b/mcp-host/src/core/tools/__tests__/generatedArtifactAttachments.test.ts
index 0a2ecc328..1b9327518 100644
--- a/mcp-host/src/core/tools/__tests__/generatedArtifactAttachments.test.ts
+++ b/mcp-host/src/core/tools/__tests__/generatedArtifactAttachments.test.ts
@@ -1,10 +1,11 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as fs from 'fs'
import JSZip from 'jszip'
import * as os from 'os'
import * as path from 'path'
import { zipEntries } from '../../../workflow/__tests__/support/zipEntries'
import type { ArtifactMetadata } from '../../../workflow/types'
+import { CALLER_OUTPUTS_DIR } from '../../../workspace/callerOutputs'
import type { NativeToolConfig } from '../../interfaces'
import type { Attachment } from '../../types'
import {
@@ -52,15 +53,38 @@ function officePackage(text: string): Promise<Buffer> {
.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' })
}
+// statfs reports the volume sized to its free space, so the disk's occupancy
+// never meets the free-space floor of the caller's folder.
+vi.mock('fs', async original => {
+ const actual = await original<typeof import('fs')>()
+ return {
+ ...actual,
+ statfsSync: (target: string, options: { bigint: true }) => {
+ const reading = actual.statfsSync(target, options)
+ return { ...reading, blocks: reading.bavail, bfree: reading.bavail }
+ },
+ }
+})
+
describe('generated internal artifact attachments', () => {
let outputDir: string
+ // The chat caller the registries below generate for: a managed caller root
+ // (`<host>/users/<key>`), whose own folder receives their files.
+ let callerRoot: string
let originalOutputDir: string | undefined
beforeEach(() => {
originalOutputDir = process.env.CLERUM_OUTPUT_DIR
outputDir = fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-generated-attachments-'))
+ callerRoot = path.join(outputDir, 'host', 'users', 'caller-a')
+ fs.mkdirSync(callerRoot, { recursive: true })
})
+ /** A file the chat generators wrote for the test caller. */
+ function generated(name: string): string {
+ return path.join(callerRoot, CALLER_OUTPUTS_DIR, name)
+ }
+
afterEach(() => {
if (originalOutputDir === undefined) delete process.env.CLERUM_OUTPUT_DIR
else process.env.CLERUM_OUTPUT_DIR = originalOutputDir
@@ -323,7 +347,6 @@ describe('generated internal artifact attachments', () => {
['a markdown link holding a reference', 'probe-[red&#97;ction](https://a.example)-value'],
['an image', 'probe-![redaction](missing.png)-value'],
])('does not attach a PDF that prints a secret split by %s', async (_label, body) => {
- process.env.CLERUM_OUTPUT_DIR = outputDir
const registry = new NativeToolRegistry(
{
workspacePath: outputDir,
@@ -343,7 +366,14 @@ describe('generated internal artifact attachments', () => {
{
maxBytes: 52_428_800,
secretEntriesProvider: () => [{ name: 'PROBE_VALUE', value: 'probe-redaction-value' }],
- }
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
const pdf = registry.get('clerum__generate_pdf')!
const leaked = await pdf.execute({ filename: 'split.pdf', body })
@@ -354,7 +384,6 @@ describe('generated internal artifact attachments', () => {
})
it('does not attach a document whose arguments hold a secret with a quote or a backslash', async () => {
- process.env.CLERUM_OUTPUT_DIR = outputDir
const secret = 'probe"redac\\tion-value'
const registry = new NativeToolRegistry(
{
@@ -375,7 +404,14 @@ describe('generated internal artifact attachments', () => {
{
maxBytes: 52_428_800,
secretEntriesProvider: () => [{ name: 'PROBE_VALUE', value: secret }],
- }
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
const pdf = registry.get('clerum__generate_pdf')!
const leaked = await pdf.execute({ filename: 'quoted.pdf', body: `value: ${secret}` })
@@ -384,7 +420,6 @@ describe('generated internal artifact attachments', () => {
})
it('does not attach a DOCX whose table cell prints a secret a link splits', async () => {
- process.env.CLERUM_OUTPUT_DIR = outputDir
const registry = new NativeToolRegistry(
{
workspacePath: outputDir,
@@ -404,7 +439,14 @@ describe('generated internal artifact attachments', () => {
{
maxBytes: 52_428_800,
secretEntriesProvider: () => [{ name: 'PROBE_VALUE', value: 'probe-redaction-value' }],
- }
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
const docx = registry.get('clerum__generate_docx')!
const cell = 'probe-[redaction](https://a.example)-value'
@@ -421,7 +463,6 @@ describe('generated internal artifact attachments', () => {
const protectedValue = 'probe-redaction-value'
function xlsxTool() {
- process.env.CLERUM_OUTPUT_DIR = outputDir
const registry = new NativeToolRegistry(
{
workspacePath: outputDir,
@@ -441,7 +482,14 @@ describe('generated internal artifact attachments', () => {
{
maxBytes: 52_428_800,
secretEntriesProvider: () => [{ name: 'PROBE_VALUE', value: protectedValue }],
- }
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
return registry.get('clerum__generate_xlsx')!
}
@@ -476,7 +524,7 @@ describe('generated internal artifact attachments', () => {
sheets: [{ name: 'S', rows: [{ [key]: 'ordinary' }] }],
})
expect(result.is_error).toBe(false)
- expect(sheetXml(path.join(outputDir, 'keyed.xlsx'))).toContain(protectedValue)
+ expect(sheetXml(generated('keyed.xlsx'))).toContain(protectedValue)
expect(result.attachments ?? []).toHaveLength(0)
})
})
@@ -485,7 +533,6 @@ describe('generated internal artifact attachments', () => {
const protectedValue = '3141592653'
function tool(name: string) {
- process.env.CLERUM_OUTPUT_DIR = outputDir
const registry = new NativeToolRegistry(
{
workspacePath: outputDir,
@@ -505,7 +552,14 @@ describe('generated internal artifact attachments', () => {
{
maxBytes: 52_428_800,
secretEntriesProvider: () => [{ name: 'PROBE_VALUE', value: protectedValue }],
- }
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
return registry.get(name)!
}
@@ -535,9 +589,7 @@ describe('generated internal artifact attachments', () => {
})
expect(result.is_error).toBe(false)
// Witness: the sheet holds, as a number, digits the arguments never spelled.
- expect(packageXml(path.join(outputDir, 'stored.xlsx'))).toContain(
- `<v>${protectedValue}</v>`
- )
+ expect(packageXml(generated('stored.xlsx'))).toContain(`<v>${protectedValue}</v>`)
expect(result.attachments ?? []).toHaveLength(0)
}
)
@@ -548,7 +600,7 @@ describe('generated internal artifact attachments', () => {
sheets: [{ name: 'S', rows: [['Amount'], ['1,234']], columnFormats: { Amount: '0' } }],
})
expect(result.is_error).toBe(false)
- expect(packageXml(path.join(outputDir, 'ordinary.xlsx'))).toContain('<v>1234</v>')
+ expect(packageXml(generated('ordinary.xlsx'))).toContain('<v>1234</v>')
expect(result.attachments ?? []).toHaveLength(1)
})
@@ -565,7 +617,7 @@ describe('generated internal artifact attachments', () => {
})
const leaked = await tool('clerum__generate_pptx').execute(deck(['3,141,592,653']))
expect(leaked.is_error).toBe(false)
- expect(packageXml(path.join(outputDir, 'chart.pptx'))).toContain(protectedValue)
+ expect(packageXml(generated('chart.pptx'))).toContain(protectedValue)
expect(leaked.attachments ?? []).toHaveLength(0)
const ordinary = await tool('clerum__generate_pptx').execute(deck(['1,234']))
@@ -576,7 +628,6 @@ describe('generated internal artifact attachments', () => {
describe('what a delivered file shows that its arguments never spelled', () => {
function toolWith(name: string, secrets: string[]) {
- process.env.CLERUM_OUTPUT_DIR = outputDir
const registry = new NativeToolRegistry(
{
workspacePath: outputDir,
@@ -596,7 +647,14 @@ describe('generated internal artifact attachments', () => {
{
maxBytes: 52_428_800,
secretEntriesProvider: () => secrets.map((value, i) => ({ name: `PROBE_${i}`, value })),
- }
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
return registry.get(name)!
}
@@ -642,7 +700,7 @@ describe('generated internal artifact attachments', () => {
expect(result.is_error).toBe(false)
// Witness: neither the arguments nor the package spell the value.
expect(JSON.stringify(sheet(cell, format))).not.toContain(secret)
- expect(packageXml(path.join(outputDir, 'shown.xlsx'))).not.toContain(secret)
+ expect(packageXml(generated('shown.xlsx'))).not.toContain(secret)
expect(result.attachments ?? []).toHaveLength(0)
})
@@ -666,7 +724,7 @@ describe('generated internal artifact attachments', () => {
}
const leaked = await toolWith('clerum__generate_pptx', ['3,141,592,653']).execute(deck)
expect(leaked.is_error).toBe(false)
- expect(packageXml(path.join(outputDir, 'labels.pptx'))).not.toContain('3,141,592,653')
+ expect(packageXml(generated('labels.pptx'))).not.toContain('3,141,592,653')
expect(leaked.attachments ?? []).toHaveLength(0)
const ordinary = await toolWith('clerum__generate_pptx', ['9,999,999,999']).execute(deck)
expect(ordinary.attachments ?? []).toHaveLength(1)
@@ -745,7 +803,6 @@ describe('generated internal artifact attachments', () => {
envAllowlist: ['PATH'],
memoryMaxSize: 1048576,
}
- process.env.CLERUM_OUTPUT_DIR = outputDir
const registry = new NativeToolRegistry(
config,
'conv-1',
@@ -754,7 +811,14 @@ describe('generated internal artifact attachments', () => {
undefined,
undefined,
null,
- { maxBytes: 52_428_800 }
+ { maxBytes: 52_428_800 },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
)
const result = await registry.get('clerum__generate_markdown')!.execute({
diff --git a/mcp-host/src/core/tools/__tests__/generatedOutputsPrivacy.test.ts b/mcp-host/src/core/tools/__tests__/generatedOutputsPrivacy.test.ts
new file mode 100644
index 000000000..64657dbe7
--- /dev/null
+++ b/mcp-host/src/core/tools/__tests__/generatedOutputsPrivacy.test.ts
@@ -0,0 +1,287 @@
+// Chat documents go to each caller's own folder: a caller never writes to,
+// lists, downloads or embeds another caller's files, and a folder that cannot
+// be verified is never replaced by a shared one.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { generatedOutputsRoot } from '../../../agent/taskExecutor'
+import { logger } from '../../../logger'
+import { zipEntries } from '../../../workflow/__tests__/support/zipEntries'
+import { enforceQuota } from '../../../workflow/artifactOutput'
+import { INTERNAL_TOOLS } from '../../../workflow/internalTools'
+import { CALLER_OUTPUTS_DIR, resolveRpcCallerOutputDir } from '../../../workspace/callerOutputs'
+import { resolveCallerRootBinding } from '../../../workspace/callerRootBinding'
+import { ScopedWorkspaceProvider } from '../../../workspace/scopedWorkspace'
+import { deriveUserKeyFromSource } from '../../../workspace/userKey'
+import { FileWriteTool } from '../fileWrite'
+import { NativeToolRegistry } from '../nativeToolRegistry'
+
+const volume = vi.hoisted(() => ({ mode: 'roomy' as 'roomy' | 'full' | 'unmeasurable' }))
+
+// A roomy volume is sized to its free space, so the disk's occupancy never
+// meets the floor; a full one leaves less than the floor; an unmeasurable one
+// cannot be read.
+vi.mock('fs', async original => {
+ const actual = await original<typeof import('fs')>()
+ return {
+ ...actual,
+ statfsSync: (target: string, options: { bigint: true }) => {
+ if (volume.mode === 'unmeasurable') {
+ throw Object.assign(new Error('statfs unavailable'), { code: 'ENOSYS' })
+ }
+ const reading = actual.statfsSync(target, options)
+ return volume.mode === 'full'
+ ? { ...reading, bsize: 4096n, blocks: 1000n, bfree: 100n, bavail: 100n }
+ : { ...reading, blocks: reading.bavail, bfree: reading.bavail }
+ },
+ }
+})
+
+const UNAVAILABLE = /could not verify your private output folder/
+
+describe('generated documents are private to their caller', () => {
+ let hostBase: string
+ let shared: string
+ let provider: ScopedWorkspaceProvider
+ const originalOutputDir = process.env.CLERUM_OUTPUT_DIR
+
+ beforeEach(() => {
+ volume.mode = 'roomy'
+ hostBase = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'clerum-private-outputs-')))
+ provider = new ScopedWorkspaceProvider(hostBase)
+ // The folder chat files went to before; chat must neither write nor read it.
+ shared = path.join(hostBase, 'outputs')
+ fs.mkdirSync(shared)
+ process.env.CLERUM_OUTPUT_DIR = shared
+ })
+
+ afterEach(() => {
+ if (originalOutputDir === undefined) delete process.env.CLERUM_OUTPUT_DIR
+ else process.env.CLERUM_OUTPUT_DIR = originalOutputDir
+ fs.rmSync(hostBase, { recursive: true, force: true })
+ vi.restoreAllMocks()
+ })
+
+ /** The caller root a Desktop user's chat task gets. */
+ function rootOf(userId: string): string {
+ const binding = resolveCallerRootBinding(provider, { sender: userId, channelType: 'rpc' })
+ if (!binding.root) throw new Error(`no caller root: ${binding.failureCode}`)
+ return binding.root
+ }
+
+ function registryFor(callerRoot: string | undefined): NativeToolRegistry {
+ return new NativeToolRegistry(
+ {
+ workspacePath: hostBase,
+ shellTimeout: 5000,
+ toolTimeout: 60000,
+ toolProgressInterval: 30000,
+ httpAllowlist: [],
+ envAllowlist: ['PATH'],
+ memoryMaxSize: 1048576,
+ },
+ 'conv-1',
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ null,
+ { maxBytes: 52_428_800 },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ callerRoot
+ )
+ }
+
+ function markdown(callerRoot: string | undefined, filename: string, content: string) {
+ return registryFor(callerRoot).get('clerum__generate_markdown')!.execute({ filename, content })
+ }
+
+ function outputsOf(callerRoot: string): string {
+ return path.join(callerRoot, CALLER_OUTPUTS_DIR)
+ }
+
+ it("keeps each caller's file in their own folder, even under the same name", async () => {
+ const a = rootOf('user-a')
+ const b = rootOf('user-b')
+ expect((await markdown(a, 'report.md', '# A\n')).is_error).toBe(false)
+ expect((await markdown(b, 'report.md', '# B\n')).is_error).toBe(false)
+
+ expect(fs.readFileSync(path.join(outputsOf(a), 'report.md'), 'utf8')).toBe('# A\n')
+ expect(fs.readFileSync(path.join(outputsOf(b), 'report.md'), 'utf8')).toBe('# B\n')
+ expect(fs.statSync(outputsOf(a)).mode & 0o777).toBe(0o700)
+ expect(fs.readdirSync(shared)).toEqual([])
+ })
+
+ it('is found again by the download routes, keyed as the chat message was', async () => {
+ const a = rootOf('user-a')
+ await markdown(a, 'report.md', '# A\n')
+ // A new registry, as after a restart, writes to the same folder.
+ await markdown(rootOf('user-a'), 'later.md', '# later\n')
+
+ const lookup = resolveRpcCallerOutputDir(hostBase, 'user-a')
+ expect(lookup).toEqual({ dir: outputsOf(a) })
+ expect(fs.readdirSync(outputsOf(a)).sort()).toEqual(['later.md', 'report.md'])
+ expect(path.basename(a)).toBe(deriveUserKeyFromSource({ sender: 'user-a', channelType: 'rpc' }))
+ })
+
+ it('writes nothing when the task has no caller folder', async () => {
+ const result = await markdown(undefined, 'report.md', '# lost\n')
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(UNAVAILABLE)
+ expect(result.content).not.toContain(hostBase)
+ expect(fs.readdirSync(shared)).toEqual([])
+ expect(fs.existsSync(path.join(hostBase, 'users'))).toBe(false)
+ })
+
+ it('writes nothing through an outputs folder that is a link', async () => {
+ const a = rootOf('user-a')
+ const elsewhere = path.join(hostBase, 'elsewhere')
+ fs.mkdirSync(elsewhere)
+ fs.symlinkSync(elsewhere, outputsOf(a))
+
+ const result = await markdown(a, 'report.md', '# redirected\n')
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(UNAVAILABLE)
+ expect(fs.readdirSync(elsewhere)).toEqual([])
+ expect(fs.readdirSync(shared)).toEqual([])
+ })
+
+ it('refuses a root that is not a managed caller root', async () => {
+ const stray = path.join(hostBase, 'stray', 'caller')
+ fs.mkdirSync(stray, { recursive: true })
+ const result = await markdown(stray, 'report.md', '# stray\n')
+ expect(result.is_error).toBe(true)
+ expect(fs.existsSync(outputsOf(stray))).toBe(false)
+ })
+
+ it("does not let one caller embed another caller's image", async () => {
+ const a = rootOf('user-a')
+ const b = rootOf('user-b')
+ const chart = await registryFor(a)
+ .get('clerum__generate_chart')!
+ .execute({
+ filename: 'a.png',
+ type: 'bar',
+ data: { labels: ['x'], datasets: [{ label: 's', data: [1] }] },
+ })
+ expect(chart.is_error).toBe(false)
+
+ const docx = (root: string, image: string) =>
+ registryFor(root)
+ .get('clerum__generate_docx')!
+ .execute({ filename: 'd.docx', body: 'Report', images: [image] })
+ const media = (root: string) =>
+ [...zipEntries(path.join(outputsOf(root), 'd.docx')).keys()].filter(
+ name => name.startsWith('word/media/') && !name.endsWith('/')
+ )
+
+ // Control: the owner embeds it.
+ expect((await docx(a, 'a.png')).is_error).toBe(false)
+ expect(media(a)).toHaveLength(1)
+
+ // By name, B's folder has no such file.
+ const byName = await docx(b, 'a.png')
+ expect(byName.is_error).toBe(false)
+ expect(byName.content).toContain("Image 'a.png' was not found in the output folder")
+ expect(media(b)).toEqual([])
+
+ // By path, out of B's folder, it is refused.
+ const keyA = path.basename(a)
+ for (const image of [
+ `../../${keyA}/${CALLER_OUTPUTS_DIR}/a.png`,
+ path.join(outputsOf(a), 'a.png'),
+ ]) {
+ const result = await docx(b, image)
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(/path traversal blocked/)
+ }
+ expect(media(b)).toEqual([])
+ })
+
+ it('does not deliver a file that did not land in the caller folder', async () => {
+ const a = rootOf('user-a')
+ fs.mkdirSync(outputsOf(a))
+ const elsewhere = path.join(hostBase, 'elsewhere')
+ fs.mkdirSync(elsewhere)
+ fs.writeFileSync(path.join(elsewhere, 'report.md'), '# moved\n')
+ fs.symlinkSync(path.join(elsewhere, 'report.md'), path.join(outputsOf(a), 'linked.md'))
+ const tool = INTERNAL_TOOLS.find(t => t.name === 'clerum__generate_markdown')!
+
+ for (const file of [path.join(elsewhere, 'report.md'), path.join(outputsOf(a), 'linked.md')]) {
+ vi.spyOn(tool, 'execute').mockResolvedValueOnce({
+ success: true,
+ artifact: { name: path.basename(file), path: file, format: 'md', sizeBytes: 8 },
+ } as never)
+ const result = await markdown(a, 'report.md', '# moved\n')
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(UNAVAILABLE)
+ expect(result.attachments ?? []).toEqual([])
+ }
+ })
+
+ it('keeps the free space of the Host volume, and removes nothing to make room', async () => {
+ const a = rootOf('user-a')
+ await markdown(a, 'kept.md', '# kept\n')
+ volume.mode = 'full'
+
+ const result = await markdown(a, 'report.md', '# too much\n')
+ expect(result.is_error).toBe(true)
+ expect(result.content).toMatch(/Not enough free space/)
+ expect(fs.readdirSync(outputsOf(a))).toEqual(['kept.md'])
+ })
+
+ it('writes when the volume cannot be measured, and says so once', async () => {
+ const warn = vi.spyOn(logger, 'warn')
+ const a = rootOf('user-a')
+ volume.mode = 'unmeasurable'
+
+ expect((await markdown(a, 'one.md', '# one\n')).is_error).toBe(false)
+ expect((await markdown(a, 'two.md', '# two\n')).is_error).toBe(false)
+ const reports = warn.mock.calls.filter(([, message]) =>
+ String(message).includes('Could not measure the Host volume')
+ )
+ expect(reports).toHaveLength(1)
+ })
+
+ it("leaves a workflow run's output folder without the floor", () => {
+ volume.mode = 'full'
+ const runOutput = path.join(hostBase, 'output')
+ fs.mkdirSync(runOutput)
+ const callerOutputs = outputsOf(rootOf('user-a'))
+ fs.mkdirSync(callerOutputs)
+ expect(() => enforceQuota(runOutput, 10)).not.toThrow()
+ expect(() => enforceQuota(callerOutputs, 10)).toThrow(/Not enough free space/)
+ })
+
+ it('keeps file_write out of the folder, directly or through a link', async () => {
+ const a = rootOf('user-a')
+ await markdown(a, 'report.md', '# A\n')
+ fs.symlinkSync(outputsOf(a), path.join(a, 'alias'))
+ const write = new FileWriteTool(a)
+
+ for (const target of [`${CALLER_OUTPUTS_DIR}/report.md`, 'alias/report.md']) {
+ const result = await write.execute({ path: target, content: 'overwritten' })
+ expect(result.is_error).toBe(true)
+ }
+ expect(fs.readFileSync(path.join(outputsOf(a), 'report.md'), 'utf8')).toBe('# A\n')
+ })
+})
+
+describe('generatedOutputsRoot', () => {
+ it('gives a message with no sender no folder, so its files are not shared', () => {
+ expect(
+ generatedOutputsRoot({ sender: ' ', channelType: 'slack' } as never, '/h/users/k')
+ ).toBe(undefined)
+ expect(generatedOutputsRoot({ sender: 'u1', channelType: 'rpc' } as never, '/h/users/k')).toBe(
+ '/h/users/k'
+ )
+ // Cron and system tasks keep the reserved system folder.
+ expect(generatedOutputsRoot(undefined, '/h/users/_system')).toBe('/h/users/_system')
+ })
+})
diff --git a/mcp-host/src/core/tools/nativeToolRegistry.ts b/mcp-host/src/core/tools/nativeToolRegistry.ts
index d21042c4d..bda9727ab 100644
--- a/mcp-host/src/core/tools/nativeToolRegistry.ts
+++ b/mcp-host/src/core/tools/nativeToolRegistry.ts
@@ -1,3 +1,5 @@
+import * as fs from 'fs'
+import * as path from 'path'
import type { CronScheduler } from '../../agent/cronScheduler'
import { createGetCapabilitiesTool } from '../../capabilities/getCapabilitiesTool'
import {
@@ -18,10 +20,15 @@ import type { LlmProvider } from '../../llm/registryCore'
import type { McpManager } from '../../mcp/manager'
import type { IncomingMessage } from '../../server'
import type { McpTool } from '../../types'
-import { getOutputDir, resolveInternalTools } from '../../workflow/internalTools'
+import { resolveInternalTools } from '../../workflow/internalTools'
import { boilerplateTexts } from '../../workflow/officeBoilerplate'
import { printedForms } from '../../workflow/toolText'
import type { InternalToolDefinition } from '../../workflow/types'
+import {
+ type CallerOutputLookup,
+ callerOutputUnavailableMessage,
+ resolveCallerOutputDir,
+} from '../../workspace/callerOutputs'
import { ScopedWorkspace } from '../../workspace/scopedWorkspace'
import type { Workspace } from '../../workspace/service'
import type { AttachmentReadLedger } from '../attachments/attachmentReadBudget'
@@ -56,6 +63,18 @@ const CHAT_HIDDEN_INTERNAL_TOOL_NAMES = new Set([
'clerum__trigger_workflow',
])
+/** Tools that write a document into the caller's outputs directory. */
+const GENERATOR_PREFIX = 'clerum__generate_'
+
+/** Whether `file`, links resolved, sits directly in `dir`. */
+function directlyInside(file: string, dir: string): boolean {
+ try {
+ return fs.realpathSync(path.dirname(file)) === dir && !fs.lstatSync(file).isSymbolicLink()
+ } catch {
+ return false
+ }
+}
+
/** Adapter: wraps an InternalToolDefinition as a native Tool for use in chat mode. */
class InternalToolAdapter implements Tool {
constructor(
@@ -64,7 +83,13 @@ class InternalToolAdapter implements Tool {
private readonly attachmentOptions: {
maxBytes: number
secretEntriesProvider?: () => Array<{ name: string; value: string }>
- }
+ },
+ /**
+ * For a generator: the caller's own outputs directory, verified on each
+ * call (callerOutputs.ts). It replaces `outputDir`; when it cannot be
+ * verified the call writes nothing.
+ */
+ private readonly callerOutputs?: () => CallerOutputLookup
) {}
name(): string {
return this.def.name
@@ -90,8 +115,21 @@ class InternalToolAdapter implements Tool {
}
async execute(params: Record<string, unknown>, context?: ExecutionContext): Promise<ToolOutput> {
const start = Date.now()
+ let outputDir = this.outputDir
+ if (this.callerOutputs) {
+ const resolved = this.callerOutputs()
+ if (!('dir' in resolved)) {
+ const code = 'failureCode' in resolved ? resolved.failureCode : 'ENOENT'
+ return {
+ content: `Error: ${callerOutputUnavailableMessage(code)}`,
+ duration_ms: Date.now() - start,
+ is_error: true,
+ }
+ }
+ outputDir = resolved.dir
+ }
try {
- const result = await this.def.execute(params, this.outputDir, {
+ const result = await this.def.execute(params, outputDir, {
signal: context?.signal,
timeoutMs: context?.timeoutMs,
visualInput: context?.visualInput,
@@ -105,6 +143,20 @@ class InternalToolAdapter implements Tool {
result.artifact?.format ?? 'unknown'
})`)
: `Error: ${result.error ?? 'Unknown error'}`
+ // The file must be where the caller's folder is now; a folder swapped
+ // during the call must not route the file to anyone else.
+ if (
+ this.callerOutputs &&
+ result.success &&
+ result.artifact &&
+ !directlyInside(result.artifact.path, outputDir)
+ ) {
+ return {
+ content: `Error: ${callerOutputUnavailableMessage('EEXIST')}`,
+ duration_ms: Date.now() - start,
+ is_error: true,
+ }
+ }
const format = result.success ? result.artifact?.format : undefined
// Office packages carry the generator's own text; a protected value
// found only there is left to the payload check (officeBoilerplate).
@@ -118,7 +170,7 @@ class InternalToolAdapter implements Tool {
? buildGeneratedArtifactAttachment({
sourceTool: this.def.name,
artifact: result.artifact,
- outputDir: this.outputDir,
+ outputDir,
maxBytes: this.attachmentOptions.maxBytes,
// The file shows the arguments as the generator prints them, so a
// secret split by a tag or an escape is checked whole too, and
@@ -226,7 +278,12 @@ export class NativeToolRegistry implements ToolRegistry {
callerIdentity: string
callerWorkspacePath?: string
retentionOwnerId?: string
- }
+ },
+ // The caller's verified root (`<host>/users/<key>`). The document
+ // generators write under its reserved outputs directory; without it they
+ // refuse to write, never falling back to a folder shared by the Host.
+ // Trailing optional; only taskExecutor passes it.
+ callerOutputRoot?: string
) {
// A Host-owned GFS store establishes a trusted caller binding even when
// memory is disabled. In that mode file tools never fall back to the shared
@@ -301,7 +358,8 @@ export class NativeToolRegistry implements ToolRegistry {
: []),
]
for (const tool of gfsTools) {
- this.register(new InternalToolAdapter(tool, getOutputDir(), { maxBytes: 52_428_800 }))
+ // GFS tools write no artifact, so they get no output directory.
+ this.register(new InternalToolAdapter(tool, '', { maxBytes: 52_428_800 }))
}
}
@@ -405,7 +463,13 @@ export class NativeToolRegistry implements ToolRegistry {
// Register internal file-generation/context tools. Workflow recipe control is exposed
// through workflow_* tools in chat mode so Desktop-owned user/team context can stay hidden.
- const outputDir = getOutputDir()
+ // Only the generators write files, each into the caller's own folder;
+ // the other internal tools take no output directory.
+ const outputDir = ''
+ const callerOutputs = (): CallerOutputLookup =>
+ callerOutputRoot
+ ? resolveCallerOutputDir(callerOutputRoot, { create: true })
+ : { failureCode: 'ENOENT' }
const resolvedAttachmentOptions = {
maxBytes: attachmentOptions?.maxBytes ?? 52_428_800,
secretEntriesProvider: attachmentOptions?.secretEntriesProvider,
@@ -415,7 +479,14 @@ export class NativeToolRegistry implements ToolRegistry {
// runtime that can't mount SFS at all) so the agent never sees dead tools.
for (const tool of resolveInternalTools()) {
if (CHAT_HIDDEN_INTERNAL_TOOL_NAMES.has(tool.name)) continue
- this.register(new InternalToolAdapter(tool, outputDir, resolvedAttachmentOptions))
+ this.register(
+ new InternalToolAdapter(
+ tool,
+ outputDir,
+ resolvedAttachmentOptions,
+ tool.name.startsWith(GENERATOR_PREFIX) ? callerOutputs : undefined
+ )
+ )
}
// clerum__get_capabilities is a query-style internal tool that exposes
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index e47331bd2..cf9be3611 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -169,7 +169,7 @@ import {
createGovernedRunReporter,
} from './usage/usageReporter'
import { VISUAL_INPUT_LIMITS } from './visualInput/policy'
-import { setOutputDirHostAccessor } from './workflow/internalTools'
+import { getOutputDir, setOutputDirHostAccessor } from './workflow/internalTools'
import { loadPersistedWorkflowControlToken } from './workflow/mcpHostJwtState'
import { submitProviderWorkflowApprovalDecision } from './workflow/providerWorkflowApprovalDecisionClient'
import { confirmProviderWorkflowApprovalMediumEnrollment } from './workflow/providerWorkflowApprovalMediumEnrollmentClient'
@@ -190,6 +190,7 @@ import {
stopRuntimeAuthProactiveRefresh,
} from './workflow/runtimeAuthRefreshScheduler'
import { type McpHostRuntimeAuth, refreshWithRecovery } from './workflow/userApprovalRequester'
+import { countSharedOutputs, resolveRpcCallerOutputDir } from './workspace/callerOutputs'
import { resolveCallerRootBinding } from './workspace/callerRootBinding'
import { ScopedWorkspaceProvider } from './workspace/scopedWorkspace'
@@ -2634,6 +2635,28 @@ function subscribeActivity(onEvent: (event: HostActivityEvent) => void): {
/**
* Start the RPC server.
*/
+/**
+ * Chat files generated before they became per user stay where they were,
+ * unserved and untouched; one line says how many there are.
+ */
+function logSharedOutputs(): void {
+ countSharedOutputs(getOutputDir()).then(
+ found => {
+ if (found?.files) {
+ logger.info(
+ { component: 'GeneratedOutputs', files: found.files, bytes: found.bytes },
+ 'Files from the former shared output folder are no longer listed or served'
+ )
+ }
+ },
+ (err: unknown) =>
+ logger.warn(
+ { component: 'GeneratedOutputs', code: (err as NodeJS.ErrnoException)?.code },
+ 'Could not count the former shared output folder'
+ )
+ )
+}
+
async function startRPCServer(): Promise<void> {
const port = config.serverPort
rpcServer = new RPCServer(port)
@@ -2762,6 +2785,14 @@ async function startRPCServer(): Promise<void> {
rpcServer.onMessage(handleIncomingMessage)
rpcServer.setArtifactSecretEntriesProvider(() => configStore?.listSecretEntries() ?? [])
+ // Generated files are per user: each Desktop user lists and downloads only
+ // their own folder under the Host's caller roots.
+ rpcServer.setChatArtifactDirResolver(userId =>
+ gfsWorkspaceProvider
+ ? resolveRpcCallerOutputDir(gfsWorkspaceProvider.baseRootPath, userId)
+ : { failureCode: 'ENOENT' }
+ )
+ if (process.env.CLERUM_WORKFLOW_ENABLED !== 'true') logSharedOutputs()
rpcServer.onStatus(getStatus)
rpcServer.onActivitySnapshot(getActivitySnapshot)
rpcServer.onActivityStream(subscribeActivity)
diff --git a/mcp-host/src/server.ts b/mcp-host/src/server.ts
index 3f1259554..b85fe77d3 100644
--- a/mcp-host/src/server.ts
+++ b/mcp-host/src/server.ts
@@ -81,11 +81,11 @@ import {
openExistingArtifactFile,
resolveExistingArtifactFile,
} from './workflow/artifactPaths'
-import { getOutputDir } from './workflow/internalTools'
import { isInternalWorkflowArtifactName } from './workflow/mcpHostJwtState'
import { runtimeAuthHealthSnapshot } from './workflow/runtimeAuthHealth'
import { createWorkflowRouter } from './workflow/workflowRouter'
import { WorkflowService } from './workflow/workflowService'
+import type { CallerOutputLookup } from './workspace/callerOutputs'
export type {
HostActivityEvent,
@@ -131,6 +131,12 @@ export type {
SetTitleResult,
} from './server/types'
+/** A caller's generated files cannot be reached safely; no other folder is used instead. */
+const ARTIFACT_STORE_UNAVAILABLE = {
+ error: 'Generated files are unavailable right now',
+ code: 'artifact_store_unavailable',
+} as const
+
/**
* Body budgets for chat payloads carrying base64 attachments.
*
@@ -359,6 +365,7 @@ export class RPCServer {
private setTitleHandler: SetTitleHandler | null = null
private workflowRouter: ReturnType<typeof createWorkflowRouter> | null = null
private artifactSecretEntriesProvider: (() => ArtifactSecretEntry[]) | null = null
+ private chatArtifactDirResolver: ((userId: string) => CallerOutputLookup) | null = null
private lifecycleGate: RuntimeLifecycleGate | null = null
constructor(port: number = 8080) {
@@ -708,16 +715,20 @@ export class RPCServer {
'/v1/runtime/artifacts',
rejectWorkflowRuntimeArtifacts,
runtimeEdgeGuard(['rpc-proxy']),
- (_req, res) => {
+ (req, res) => {
try {
- // Re-resolved per request: getOutputDir() depends on the Host CRD, which
- // hydrates async after boot — a captured value would freeze the path
- // (and point at the old /tmp emptyDir). D.2b.
- const artifactDir = getOutputDir()
- if (!fs.existsSync(artifactDir)) {
+ // Only the caller's own folder, re-verified per request; none yet
+ // means nothing generated.
+ const lookup = this.callerArtifactDir(req)
+ if ('missing' in lookup) {
json(res, 200, { artifacts: [] })
return
}
+ if (!('dir' in lookup)) {
+ json(res, 503, ARTIFACT_STORE_UNAVAILABLE)
+ return
+ }
+ const artifactDir = lookup.dir
const files = []
for (const entry of fs.readdirSync(artifactDir, { withFileTypes: true })) {
if (!entry.isFile() || isInternalWorkflowArtifactName(entry.name)) continue
@@ -752,7 +763,17 @@ export class RPCServer {
json(res, 404, { error: 'Artifact not found' })
return
}
- const artifactDir = getOutputDir()
+ // Another user's file is not found here, whatever its name.
+ const lookup = this.callerArtifactDir(req)
+ if ('missing' in lookup) {
+ json(res, 404, { error: 'Artifact not found' })
+ return
+ }
+ if (!('dir' in lookup)) {
+ json(res, 503, ARTIFACT_STORE_UNAVAILABLE)
+ return
+ }
+ const artifactDir = lookup.dir
let artifact: OpenedArtifactFile
try {
artifact = openExistingArtifactFile(artifactDir, filename)
@@ -940,6 +961,18 @@ export class RPCServer {
this.artifactSecretEntriesProvider = provider
}
+ /** Where a Desktop user's generated files are (callerOutputs.ts). */
+ setChatArtifactDirResolver(resolver: (userId: string) => CallerOutputLookup): void {
+ this.chatArtifactDirResolver = resolver
+ }
+
+ /** The requesting user's folder; unwired or without a user, unavailable, never a shared one. */
+ private callerArtifactDir(req: Request): CallerOutputLookup {
+ const userId = getRuntimeCallerContext(req)?.userId
+ if (!this.chatArtifactDirResolver || !userId) return { failureCode: 'ENOENT' }
+ return this.chatArtifactDirResolver(userId)
+ }
+
/** Stage 3 (stateless-agents) — wire the DRAINING fence + activity tracker
* consulted by the POST /v1/runtime/messages route. */
setLifecycleGate(gate: RuntimeLifecycleGate): void {
diff --git a/mcp-host/src/workflow/artifactOutput.ts b/mcp-host/src/workflow/artifactOutput.ts
index 30ce31107..25edcb798 100644
--- a/mcp-host/src/workflow/artifactOutput.ts
+++ b/mcp-host/src/workflow/artifactOutput.ts
@@ -4,6 +4,9 @@
import { createHash, randomUUID } from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
+import { freeSpaceFloor } from '../internalTools/gfsDownloadStore'
+import { logger } from '../logger'
+import { CALLER_OUTPUTS_DIR } from '../workspace/callerOutputs'
import type { ArtifactMetadata, InternalToolResult } from './types'
const MAX_STEM_LENGTH = 120
@@ -272,7 +275,9 @@ export function getDirectorySize(dir: string): number {
}
/**
- * Enforce the per-recipe output quota before a file is written.
+ * Enforce the output quota of one folder before a file is written: a workflow
+ * run's output, or one chat caller's folder, so in chat each user has their
+ * own. A caller's folder must also leave the Host volume its free-space floor.
*
* Reads the ceiling from `CLERUM_WORKFLOW_OUTPUT_QUOTA_MB` (default: 50 MB).
* Throws if the current directory usage + `incomingBytes` would exceed the cap.
@@ -303,6 +308,45 @@ export function enforceQuota(outputDir: string, incomingBytes: number, replacing
'CLERUM_WORKFLOW_OUTPUT_QUOTA_MB.'
)
}
+ if (path.basename(outputDir) === CALLER_OUTPUTS_DIR)
+ enforceFreeSpaceFloor(outputDir, incomingBytes)
+}
+
+let unmeasurableVolumeReported = false
+
+/**
+ * Every caller's folder shares the Host volume, so their quotas together do
+ * not bound it: a write must leave the free space GFS keeps (freeSpaceFloor).
+ * Nothing is removed to make room. A volume that cannot be measured does not
+ * refuse the write; that is logged once.
+ */
+function enforceFreeSpaceFloor(outputDir: string, incomingBytes: number): void {
+ let space: fs.BigIntStatsFs | undefined
+ try {
+ space = fs.statfsSync(outputDir, { bigint: true })
+ } catch {
+ space = undefined
+ }
+ if (!space || space.bsize <= 0n || space.blocks <= 0n || space.bavail < 0n) {
+ if (!unmeasurableVolumeReported) {
+ unmeasurableVolumeReported = true
+ logger.warn(
+ { component: 'ArtifactOutput' },
+ 'Could not measure the Host volume; generated files are written without the free-space floor'
+ )
+ }
+ return
+ }
+ const blocks = (BigInt(incomingBytes) + space.bsize - 1n) / space.bsize
+ const floor = freeSpaceFloor(space)
+ if (blocks * space.bsize + floor > space.bavail * space.bsize) {
+ const mb = (bytes: bigint) => (Number(bytes) / (1024 * 1024)).toFixed(1)
+ throw new Error(
+ `Not enough free space: the Host keeps ${mb(floor)} MB free and this file needs ` +
+ `${mb(BigInt(incomingBytes))} MB. Make the file smaller, or ask the user to remove ` +
+ 'earlier generated files or an operator to free space on the Host.'
+ )
+ }
}
// ─── generate_chart ──────────────────────────────────────────────────
diff --git a/mcp-host/src/workflow/internalTools.ts b/mcp-host/src/workflow/internalTools.ts
index c1f377cc2..8f88736c8 100644
--- a/mcp-host/src/workflow/internalTools.ts
+++ b/mcp-host/src/workflow/internalTools.ts
@@ -3,7 +3,8 @@
*
* Available to all workflows — no MCP server required. Each tool produces
* a document artifact (markdown, PDF, DOCX, XLSX, PPTX, PNG chart, HTML
- * dashboard) and writes it to the output directory (getOutputDir).
+ * dashboard) and writes it to the output directory: the caller's own folder in
+ * chat (workspace/callerOutputs.ts), getOutputDir in a workflow.
*
* This file lists them. Each schema is in toolSchemas/, and each generator is
* its own module, loaded with its library on first use: pdfmake (PDF), docx
diff --git a/mcp-host/src/workflow/outputDirectory.ts b/mcp-host/src/workflow/outputDirectory.ts
index 6b7aa7e0b..ebe208f54 100644
--- a/mcp-host/src/workflow/outputDirectory.ts
+++ b/mcp-host/src/workflow/outputDirectory.ts
@@ -1,4 +1,4 @@
-/** Where generated artifacts are written: the run's /output in a workflow, the Host workspace in chat. */
+/** Where a workflow run writes its artifacts (/output); in chat, the former shared folder. */
import * as path from 'path'
import { config } from '../config'
@@ -46,6 +46,9 @@ export function validateOutputPath(p: string, outputDir: string): string {
/**
* Resolve the directory for generated artifacts. Re-evaluated on every call.
+ * Chat generation does not use it: each caller's files go to their own folder
+ * (workspace/callerOutputs.ts), and in chat this only names the former shared
+ * folder, counted once at startup.
*
* Resolution order:
* 1. `CLERUM_OUTPUT_DIR` — explicit override (dev / tests / ad-hoc).
diff --git a/mcp-host/src/workspace/callerOutputs.ts b/mcp-host/src/workspace/callerOutputs.ts
new file mode 100644
index 000000000..5ef4b0557
--- /dev/null
+++ b/mcp-host/src/workspace/callerOutputs.ts
@@ -0,0 +1,121 @@
+/**
+ * Where a chat caller's generated files live: a reserved directory inside the
+ * caller's own verified root (`<host>/users/<key>/.clerum-outputs`), the root
+ * file_read and file_write use, but out of reach of those tools. Generation,
+ * attachment, listing and download all resolve it, so one user never reaches
+ * another's files, not even by guessing a name. A directory that cannot be
+ * verified is never replaced by a shared one.
+ */
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+import { verifyManagedCallerRootPath } from './callerRootBinding'
+import { deriveUserKeyFromSource } from './userKey'
+
+export const CALLER_OUTPUTS_DIR = '.clerum-outputs'
+
+export type CallerOutputDir = { dir: string } | { failureCode: string }
+export type CallerOutputLookup = CallerOutputDir | { missing: true }
+
+const KNOWN_CODES = new Set([
+ 'EACCES',
+ 'EEXIST',
+ 'EIO',
+ 'ENOENT',
+ 'ENOSPC',
+ 'ENOTDIR',
+ 'EPERM',
+ 'EROFS',
+])
+
+function failureCode(err: unknown): string {
+ const code = (err as NodeJS.ErrnoException)?.code
+ return typeof code === 'string' && KNOWN_CODES.has(code) ? code : 'EIO'
+}
+
+/**
+ * The outputs directory under `callerRoot`, re-verified on every call: the
+ * caller root must still be the managed `<host>/users/<key>`, and the
+ * directory a real one, not a link. With `create`, a missing directory is made
+ * (owner only); without it, a missing one is reported as such.
+ */
+export function resolveCallerOutputDir(
+ callerRoot: string,
+ opts: { create: boolean }
+): CallerOutputLookup {
+ try {
+ const root = verifyManagedCallerRootPath(callerRoot)
+ if (!root) return { failureCode: 'EEXIST' }
+ const dir = path.join(root, CALLER_OUTPUTS_DIR)
+ let info: fs.Stats
+ try {
+ info = fs.lstatSync(dir)
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
+ if (!opts.create) return { missing: true }
+ fs.mkdirSync(dir, { mode: 0o700 })
+ info = fs.lstatSync(dir)
+ }
+ if (!info.isDirectory() || info.isSymbolicLink() || fs.realpathSync(dir) !== dir) {
+ return { failureCode: 'EEXIST' }
+ }
+ return { dir }
+ } catch (err) {
+ return { failureCode: failureCode(err) }
+ }
+}
+
+/**
+ * The outputs directory of the Desktop user `userId` on the Host based at
+ * `hostBase`, for the artifact routes: the caller key is the one a chat
+ * message from that user gets (channel `rpc`, sender = user id). Read only:
+ * a user with no folder yet has nothing, and none is created.
+ */
+export function resolveRpcCallerOutputDir(hostBase: string, userId: string): CallerOutputLookup {
+ const key = deriveUserKeyFromSource({ sender: userId, channelType: 'rpc' })
+ const root = path.join(path.resolve(hostBase), 'users', key)
+ try {
+ fs.lstatSync(root)
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === 'ENOENT'
+ ? { missing: true }
+ : { failureCode: failureCode(err) }
+ }
+ return resolveCallerOutputDir(root, { create: false })
+}
+
+/** The message a generator returns when the caller's folder cannot be used; it names no path. */
+export function callerOutputUnavailableMessage(code: string): string {
+ return (
+ `Generated files are unavailable: this Host could not verify your private output folder ` +
+ `(${code}). Nothing was saved.`
+ )
+}
+
+/**
+ * Files and bytes left in the folder chat files went to before they became
+ * per user. Nothing reads, serves or removes them now; the count is logged so
+ * an operator knows they are there. Undefined when the folder is absent.
+ */
+export async function countSharedOutputs(
+ dir: string
+): Promise<{ files: number; bytes: number } | undefined> {
+ let entries: fs.Dirent[]
+ try {
+ entries = await fs.promises.readdir(dir, { withFileTypes: true })
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined
+ throw err
+ }
+ let files = 0
+ let bytes = 0
+ for (const entry of entries) {
+ if (!entry.isFile()) continue
+ try {
+ bytes += (await fs.promises.lstat(path.join(dir, entry.name))).size
+ files++
+ } catch {
+ // Removed meanwhile.
+ }
+ }
+ return { files, bytes }
+}
diff --git a/mcp-host/src/workspace/protectedPaths.ts b/mcp-host/src/workspace/protectedPaths.ts
index fd310d2e7..8b01b310a 100644
--- a/mcp-host/src/workspace/protectedPaths.ts
+++ b/mcp-host/src/workspace/protectedPaths.ts
@@ -4,6 +4,9 @@ export const PROTECTED_WORKSPACE_DIRS: ReadonlySet<string> = new Set([
'.clerum-state',
'.gfs-download-store',
'.gfs-downloads',
+ // Each caller's generated files (callerOutputs.ts): written only by the
+ // document generators and read through the artifact routes.
+ '.clerum-outputs',
])
/**
@@ -111,8 +114,26 @@ export class GfsDownloadPathError extends ProtectedWorkspacePathError {
}
}
+export function isGeneratedOutputsPath(relativePath: string): boolean {
+ if (typeof relativePath !== 'string' || relativePath.length === 0) return false
+ return normalizeWorkspacePath(relativePath)
+ .split('/')
+ .some(segment => segment === '.clerum-outputs')
+}
+
+export class GeneratedOutputsPathError extends ProtectedWorkspacePathError {
+ constructor(filename: string) {
+ super(
+ `${filename} is in the folder of generated documents, which only the clerum__generate_* tools write; ` +
+ 'pass a generated file by name to the generator that embeds it instead.'
+ )
+ this.name = 'GeneratedOutputsPathError'
+ }
+}
+
export function protectedWorkspacePathError(relativePath: string): ProtectedWorkspacePathError {
if (isGfsDownloadPath(relativePath)) return new GfsDownloadPathError(relativePath)
+ if (isGeneratedOutputsPath(relativePath)) return new GeneratedOutputsPathError(relativePath)
return new StateDbPathError(relativePath)
}