Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(files): close round-6 review findings on file reference ingress
Alfredo Lopez9cd8f65df9e4
diff --git a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsxindex ad61dd801..cdbe2b15f 100644--- a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx+++ b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/index.tsx@@ -17,8 +17,18 @@ function referenceId(drive: string, resourceId: string): string {return `global-file:${drive}:${resourceId}`}-export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFilesModalProps) {+export function ComposerGlobalFilesModal({+ attachedIds,+ onAdd,+ onClose,+}: ComposerGlobalFilesModalProps) {const ctrl = useGfsBrowserController()+ // The limit is per message, so files attached in an earlier open of this+ // picker use up part of it. Without this each open allowed a fresh+ // FILE_REFERENCE_MAX_COUNT and the send was refused after the fact.+ const attached = useMemo(() => new Set(attachedIds), [attachedIds])+ const alreadyAttached = attached.size+ const capacity = Math.max(0, FILE_REFERENCE_MAX_COUNT - alreadyAttached)const closeButtonRef = useRef<HTMLButtonElement | null>(null)const [selected, setSelected] = useState<ComposerGlobalFileSelection>({})@@ -31,17 +41,21 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFilesreturn () => window.removeEventListener('keydown', handleKeyDown)}, [onClose])- const toggleFile = useCallback((file: ComposerGlobalFileReference) => {- setSelected(previous => {- if (previous[file.id]) {- const next = { ...previous }- delete next[file.id]- return next- }- if (Object.keys(previous).length >= FILE_REFERENCE_MAX_COUNT) return previous- return { ...previous, [file.id]: file }- })- }, [])+ const toggleFile = useCallback(+ (file: ComposerGlobalFileReference) => {+ setSelected(previous => {+ if (attached.has(file.id)) return previous+ if (previous[file.id]) {+ const next = { ...previous }+ delete next[file.id]+ return next+ }+ if (Object.keys(previous).length >= capacity) return previous+ return { ...previous, [file.id]: file }+ })+ },+ [attached, capacity]+ )const selectedFiles = useMemo(() => Object.values(selected), [selected])const entries = ctrl.current ? ctrl.items : ctrl.accessibleResources@@ -221,7 +235,8 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFilesversion: entry.version,bytes: entry.bytes,}- const checked = Boolean(selected[id])+ const isAttached = attached.has(id)+ const checked = isAttached || Boolean(selected[id])return (<labelclassName={`composer-global-files-row composer-global-files-row--file${checked ? ' composer-global-files-row--selected' : ''}`}@@ -231,7 +246,7 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFilesclassName="composer-global-files-checkbox"type="checkbox"checked={checked}- disabled={!checked && selectedFiles.length >= FILE_REFERENCE_MAX_COUNT}+ disabled={isAttached || (!checked && selectedFiles.length >= capacity)}onChange={() => toggleFile(file)}/><span className="composer-global-files-entry-icon" aria-hidden="true">@@ -242,7 +257,7 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFiles<small>{formatSharedFileSize(entry.bytes)}</small></span><span className="composer-global-files-selected-label">- {checked ? 'Selected' : 'Select'}+ {isAttached ? 'Attached' : checked ? 'Selected' : 'Select'}</span></label>)@@ -292,9 +307,10 @@ export function ComposerGlobalFilesModal({ onAdd, onClose }: ComposerGlobalFiles<strong>{selectedFiles.length}</strong><span>{selectedFiles.length === 1 ? 'file selected' : 'files selected'}</span></span>- {selectedFiles.length >= FILE_REFERENCE_MAX_COUNT ? (- <span className="composer-global-files-selection-summary">- Up to {FILE_REFERENCE_MAX_COUNT} files per message.+ {selectedFiles.length >= capacity ? (+ <span className="composer-global-files-selection-summary" role="status">+ Up to {FILE_REFERENCE_MAX_COUNT} files per message+ {alreadyAttached > 0 ? ` (${alreadyAttached} already attached)` : ''}.</span>) : null}<span className="action-row">diff --git a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/types.ts b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/types.tsindex 3cf667d79..b06e36997 100644--- a/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/types.ts+++ b/desktop-app/ui/src/components/agents/ComposerGlobalFilesModal/types.ts@@ -1,6 +1,8 @@import type { ComposerGlobalFileReference } from '@/uiTypes'export type ComposerGlobalFilesModalProps = {+ /** Ids of the global files already in the composer; they count against the per-message limit. */+ attachedIds: readonly string[]onAdd: (attachments: ComposerGlobalFileReference[]) => voidonClose: () => void}diff --git a/desktop-app/ui/src/components/agents/ComposerPanel.tsx b/desktop-app/ui/src/components/agents/ComposerPanel.tsxindex 30351311f..318169a32 100644--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx@@ -1197,6 +1197,9 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr) : null}{globalFilesModalOpen ? (<ComposerGlobalFilesModal+ attachedIds={composerReferenceAttachments+ .filter(attachment => attachment.type === 'global_file')+ .map(attachment => attachment.id)}onAdd={onAddComposerReferenceAttachments}onClose={() => setGlobalFilesModalOpen(false)}/>diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsxindex 6697c5888..54f5d3ee0 100644--- a/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerGlobalFilesModal.test.tsx@@ -43,10 +43,14 @@ function baseController() {}}-function renderModal() {+function attachedElsewhere(count: number): string[] {+ return Array.from({ length: count }, (_, index) => `global-file:main:elsewhere-${index}`)+}++function renderModal(attachedIds: string[] = []) {const onAdd = vi.fn()const onClose = vi.fn()- render(<ComposerGlobalFilesModal onAdd={onAdd} onClose={onClose} />)+ render(<ComposerGlobalFilesModal attachedIds={attachedIds} onAdd={onAdd} onClose={onClose} />)return { onAdd, onClose }}@@ -113,7 +117,7 @@ describe('ComposerGlobalFilesModal', () => {renderModal()- const boxes = screen.getAllByRole('checkbox')+ const boxes = screen.getAllByRole<HTMLInputElement>('checkbox')for (const box of boxes) act(() => fireEvent.click(box))expect(boxes.slice(0, 10).every(box => box.checked)).toBe(true)// The eleventh stayed unselectable and the footer names the limit.@@ -124,6 +128,74 @@ describe('ComposerGlobalFilesModal', () => {expect(screen.getByText('Up to 10 files per message.')).toBeTruthy()})+ it('counts files already in the composer against the ten-file message limit', () => {+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleResources: Array.from({ length: 6 }, (_, index) => ({+ resourceId: `file-${index}`,+ rid: `file-${index}`,+ gfsUri: `gfs://main/file-${index}`,+ drive: 'main',+ parentResourceId: null,+ name: `file-${index}.txt`,+ kind: 'file',+ path: `/file-${index}.txt`,+ version: 1,+ bytes: 12,+ })),+ })++ const { onAdd } = renderModal(attachedElsewhere(7))++ const boxes = screen.getAllByRole<HTMLInputElement>('checkbox')+ for (const box of boxes) act(() => fireEvent.click(box))+ // Liveness witness: the picker did select, so the stop below is the limit+ // and not a modal that ignores clicks.+ expect(boxes.slice(0, 3).every(box => box.checked)).toBe(true)+ expect(boxes.slice(3).every(box => !box.checked && box.disabled)).toBe(true)+ expect(screen.getByText('Up to 10 files per message (7 already attached).')).toBeTruthy()+ fireEvent.click(screen.getByRole('button', { name: 'Attach 3' }))+ expect(onAdd).toHaveBeenCalledTimes(1)+ expect(onAdd.mock.calls[0]![0]).toHaveLength(3)+ // The limit summary is announced when it appears.+ expect(screen.getByRole('status').textContent).toContain('7 already attached')+ })++ it('shows a file already in the composer as attached and does not count it twice', () => {+ hookMock.useGfsBrowserController.mockReturnValue({+ ...baseController(),+ accessibleResources: Array.from({ length: 2 }, (_, index) => ({+ resourceId: `file-${index}`,+ rid: `file-${index}`,+ gfsUri: `gfs://main/file-${index}`,+ drive: 'main',+ parentResourceId: null,+ name: `file-${index}.txt`,+ kind: 'file',+ path: `/file-${index}.txt`,+ version: 1,+ bytes: 12,+ })),+ })++ // Nine attached, one of them file-0: one slot is left for file-1.+ const { onAdd } = renderModal([...attachedElsewhere(8), 'global-file:main:file-0'])++ const [attachedBox, freeBox] = screen.getAllByRole<HTMLInputElement>('checkbox')+ expect(attachedBox!.checked).toBe(true)+ expect(attachedBox!.disabled).toBe(true)+ expect(screen.getByText('Attached')).toBeTruthy()+ // Liveness witness: the free row is selectable, so the disabled state above+ // belongs to the attached row and not to a modal that blocks every click.+ expect(freeBox!.disabled).toBe(false)+ act(() => fireEvent.click(freeBox!))+ expect(freeBox!.checked).toBe(true)+ fireEvent.click(screen.getByRole('button', { name: 'Attach 1' }))+ expect(onAdd.mock.calls[0]![0].map((file: { id: string }) => file.id)).toEqual([+ 'global-file:main:file-1',+ ])+ })+it('answers a rate-limited discovery with a retry, not "No shared files yet"', async () => {vi.useFakeTimers()const retryDiscovery = vi.fn()diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsxindex ab454c74e..2e9b9aaef 100644--- a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx@@ -121,7 +121,23 @@ vi.mock('@hooks/useHostModels', () => ({useHostModels: () => composerModelState,}))vi.mock('../ComposerAgentFilesModal', () => ({ ComposerAgentFilesModal: () => null }))-vi.mock('../ComposerGlobalFilesModal', () => ({ ComposerGlobalFilesModal: () => null }))+const globalFilesMock = vi.hoisted(() => ({+ showComposerItem: false,+ modalProps: undefined as { attachedIds: readonly string[] } | undefined,+}))++vi.mock('@constants/agentFeatures', async importOriginal => ({+ ...(await importOriginal<typeof import('@constants/agentFeatures')>()),+ get SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM() {+ return globalFilesMock.showComposerItem+ },+}))+vi.mock('../ComposerGlobalFilesModal', () => ({+ ComposerGlobalFilesModal: (props: { attachedIds: readonly string[] }) => {+ globalFilesMock.modalProps = props+ return null+ },+}))const annotationCanvasMock = vi.hoisted(() => ({onSave: undefined as ((updated: ComposerImageAttachment) => void) | undefined,}))@@ -151,6 +167,8 @@ beforeEach(() => {afterEach(() => {cleanup()annotationCanvasMock.onSave = undefined+ globalFilesMock.showComposerItem = false+ globalFilesMock.modalProps = undefineddraftState.value = ''draftState.set.mockReset()Object.assign(composerState, {@@ -275,6 +293,43 @@ describe.each([})})+describe('ComposerPanel EvenDrive picker', () => {+ it('hands the picker the ids of the global files already in the composer, and only those', () => {+ globalFilesMock.showComposerItem = true+ Object.assign(composerState, {+ composerReferenceAttachments: [+ {+ id: 'global-file:main:aaaa',+ type: 'global_file',+ resourceId: 'aaaa',+ drive: 'main',+ gfsUri: 'gfs://main/aaaa',+ label: 'a.md',+ version: 1,+ bytes: 1,+ },+ {+ id: 'agent-file:ctx:/b.md',+ type: 'agent_file',+ contextId: 'ctx',+ filesystemName: 'ctx',+ path: '/b.md',+ kind: 'file',+ label: 'b.md',+ },+ ],+ })+ render(<ComposerPanel inline={false} />)+ // Liveness witness: the modal is not mounted until EvenDrive is chosen.+ expect(globalFilesMock.modalProps).toBeUndefined()++ fireEvent.click(screen.getByRole('button', { name: 'Add context' }))+ fireEvent.click(screen.getByRole('menuitem', { name: /EvenDrive/ }))++ expect(globalFilesMock.modalProps?.attachedIds).toEqual(['global-file:main:aaaa'])+ })+})+describe('ComposerPanel reference submenu portaling', () => {it('portals the submenu out of the drawer overflow-clipping ancestors', () => {// Reproduce the narrow-drawer DOM: the composer sits inside ancestors thatdiff --git a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.fileReferences.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.fileReferences.test.tsxindex de2f1de26..dba454a73 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.fileReferences.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.fileReferences.test.tsx@@ -247,6 +247,99 @@ describe('sendAgentMessage — references the Host did not receive (#666 M1)', (})})+describe('sendAgentMessage — file limit (#666 M4)', () => {+ function manyFiles(count: number): ComposerGlobalFileReference[] {+ return Array.from({ length: count }, (_, index) => {+ const rid = index.toString(16).padStart(32, 'a')+ return {+ ...planFile,+ id: `global-file:main:${rid}`,+ resourceId: rid,+ gfsUri: `gfs://main/${rid}`,+ label: `f${index}.md`,+ }+ })+ }++ it('refuses an eleventh file before anything is cleared or sent', async () => {+ clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })+ const { result, spies } = renderController()+ await settleMount()++ // Two picker opens, each within the ten-file limit on its own.+ act(() => {+ result.current.handleAddComposerReferenceAttachments(manyFiles(6))+ })+ act(() => {+ result.current.handleAddComposerReferenceAttachments(manyFiles(11).slice(6))+ })+ // Liveness witness: all eleven are in the composer, so the refusal below+ // comes from the limit and not from an empty selection.+ expect(result.current.composerReferenceAttachments).toHaveLength(11)++ await act(async () => {+ await result.current.handleSendAgentMessage('Summarize the files')+ })++ const limit = 'A message can reference at most 10 files.'+ expect(result.current.agentError).toBe(limit)+ expect(spies.pushToast).toHaveBeenCalledWith(limit, 'error')+ expect(clerum.rpc.invokeHostMessage).not.toHaveBeenCalled()+ // The composer keeps the selection so the user can remove one and resend.+ expect(result.current.composerReferenceAttachments).toHaveLength(11)+ expect(result.current.agentSending).toBe(false)+ })++ it('sends after the user removes the extra file, so the refusal does not lock the composer', async () => {+ clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })+ const { result } = renderController()+ await settleMount()++ const files = manyFiles(11)+ act(() => {+ result.current.handleAddComposerReferenceAttachments(files)+ })+ await act(async () => {+ await result.current.handleSendAgentMessage('Summarize the files')+ })+ // Liveness witness: the first attempt was refused.+ expect(result.current.agentError).toBe('A message can reference at most 10 files.')+ expect(clerum.rpc.invokeHostMessage).not.toHaveBeenCalled()++ act(() => {+ result.current.handleRemoveComposerReferenceAttachment(files[10]!.id)+ })+ // Removing a file answers the refusal, so the error goes away with it.+ expect(result.current.agentError).toBeNull()++ await act(async () => {+ await result.current.handleSendAgentMessage('Summarize the files')+ })+ expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)+ })++ it('refuses a selection whose reference cannot be built, before anything is cleared or sent', async () => {+ clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })+ const { result, spies } = renderController()+ await settleMount()++ act(() => {+ result.current.handleAddComposerReferenceAttachments([+ { ...planFile, label: 'drafts/plan.md' },+ ])+ })+ await act(async () => {+ await result.current.handleSendAgentMessage('Summarize the plan')+ })++ expect(result.current.agentError).toMatch(/^Global file reference is invalid \(/)+ expect(spies.pushToast).toHaveBeenCalledWith(result.current.agentError, 'error')+ expect(clerum.rpc.invokeHostMessage).not.toHaveBeenCalled()+ expect(result.current.composerReferenceAttachments).toHaveLength(1)+ expect(result.current.agentSending).toBe(false)+ })+})+describe('sendAgentMessage — payload too large (#666 L12)', () => {it('names images and attached files in the 413 message', async () => {clerum.rpc.invokeHostMessage.mockRejectedValue(new Error('Request Entity Too Large'))diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex eb484f1d8..d33944b75 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -2545,6 +2545,20 @@ export function useAgentChatController({visualModelForSend = selection.intentModel ?? selection.effectiveModel ?? undefinedvisualModelRevisionForSend = selection.confirmedRevision ?? undefined}+ // #666 — build the structured references before anything is cleared or+ // created. A selection past the shared limit (or an invalid reference)+ // must leave the composer and its draft as the user typed them, with the+ // reason on screen, instead of failing after the send cleared the composer.+ let fileReferencesForSend: ReturnType<typeof buildComposerFileReferences>+ try {+ fileReferencesForSend = buildComposerFileReferences(effectiveReferences)+ } catch (error) {+ const blocker = error instanceof Error ? error.message : String(error)+ setAgentError(blocker)+ pushToast(blocker, 'error')+ agentSendInFlightRef.current = false+ return+ }let sendChatId = activeChatId// Captured for the retention snapshot: the model this attempt actually// asked for (issue #654), readable from the catch below.@@ -2706,7 +2720,7 @@ export function useAgentChatController({if (sendScope !== sendScopeGeneration.current) returnconst pendingModel = pendingModelForSendconst requestModel = requestModelForRetention- const fileReferences = buildComposerFileReferences(effectiveReferences)+ const fileReferences = fileReferencesForSendconst request = {content: effectiveContentForRequest,channelType: 'rpc',diff --git a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts b/desktop-app/ui/src/hooks/domain/useComposerAttachments.tsindex 04c54c222..63a6812c3 100644--- a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts+++ b/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts@@ -174,10 +174,16 @@ export function useComposerAttachments({[clearSendError])- const handleRemoveComposerReferenceAttachment = useCallback((attachmentId: string) => {- composerAttachmentRevisionRef.current += 1- setComposerReferenceAttachments(previous => previous.filter(att => att.id !== attachmentId))- }, [])+ const handleRemoveComposerReferenceAttachment = useCallback(+ (attachmentId: string) => {+ composerAttachmentRevisionRef.current += 1+ setComposerReferenceAttachments(previous => previous.filter(att => att.id !== attachmentId))+ // Removing a file is how the user answers the "at most 10 files" refusal,+ // so the refusal must not stay on screen afterwards.+ clearSendError()+ },+ [clearSendError]+ )return {composerImageAttachments,diff --git a/desktop-app/ui/src/lib/composerReferencesPrompt.ts b/desktop-app/ui/src/lib/composerReferencesPrompt.tsindex 19700de71..83e067cac 100644--- a/desktop-app/ui/src/lib/composerReferencesPrompt.ts+++ b/desktop-app/ui/src/lib/composerReferencesPrompt.ts@@ -6,8 +6,9 @@ function normalizeComposerReferenceName(value: string): string {}/**- * Each value is a JSON string literal with line-breaking and invisible- * characters escaped, so a name cannot add a line or an entry to this section.+ * Each value is a JSON string literal in which control, format, separator and+ * default-ignorable characters are escaped, so a name cannot add a line or an+ * entry to this section.* parseChatMessageDisplay reads the same form back.*/function quotedList(values: string[]): string {diff --git a/mcp-host/README.md b/mcp-host/README.mdindex 7bc8a86e7..d760f90ad 100644--- a/mcp-host/README.md+++ b/mcp-host/README.md@@ -56,7 +56,6 @@ MCP Host is a Kubernetes-native service that reads Host CRD configuration and pr| `CLERUM_ATTACHMENT_MAX_COUNT` | Maximum number of attachments returned per response. | `CLERUM_ATTACHMENT_MAX_COUNT=3` || `CLERUM_ATTACHMENT_MAX_BYTES` | Maximum decoded size per attachment in bytes (oversized payloads are dropped). | `CLERUM_ATTACHMENT_MAX_BYTES=52428800` || `CLERUM_ATTACHMENT_FILE_MAX_BYTES` | Maximum decoded size in bytes of one incoming `kind:'file'` attachment; one larger file rejects the message with `FILE_ATTACHMENT_TOO_LARGE`. File base64 also counts against the 6 MiB non-image body budget, so two files at the 3 MiB default get HTTP 413 before admission. An invalid value stops the Host at startup. | `CLERUM_ATTACHMENT_FILE_MAX_BYTES=3145728` |-| `CLERUM_FILE_REFERENCE_MAX_COUNT` | Maximum number of `fileReferences` (structured Global Files selections, #666) one message may carry; more rejects the message with `FILE_REFERENCE_INVALID`. An invalid value stops the Host at startup. | `CLERUM_FILE_REFERENCE_MAX_COUNT=10` || `CLERUM_ATTACHMENT_TEXT_READ_MAX_BYTES` | Maximum bytes one `clerum__attachment_read` call returns; longer text is returned with `truncated:true` and read on with `offset`. An invalid value stops the Host at startup. | `CLERUM_ATTACHMENT_TEXT_READ_MAX_BYTES=262144` || `CLERUM_MEMORY_ENABLED` | Enables workspace memory persistence features. | `CLERUM_MEMORY_ENABLED=true` || `CLERUM_MEMORY_WORKSPACE_PATH` | Sets workspace directory path used when memory mode is enabled. | `CLERUM_MEMORY_WORKSPACE_PATH=/workspace` |diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex df9dd656d..50564750a 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.467",+ "version": "0.1.468","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.467",+ "version": "0.1.468","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex ba0acd518..2467f53fa 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.467",+ "version": "0.1.468","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/agent/__tests__/incomingAdmission.test.ts b/mcp-host/src/agent/__tests__/incomingAdmission.test.tsindex 325d9d9d3..ab2790689 100644--- a/mcp-host/src/agent/__tests__/incomingAdmission.test.ts+++ b/mcp-host/src/agent/__tests__/incomingAdmission.test.ts@@ -8,6 +8,7 @@*/import { type Mock, describe, expect, it, vi } from 'vitest'import { createHash } from 'node:crypto'+import { FileAttachmentErrorCode } from '../../core/errors'import type { IncomingMessage, MessageResponse, SetModelResult } from '../../server/types'import { type IncomingAdmissionDeps, createIncomingAdmission } from '../incomingAdmission'@@ -432,6 +433,27 @@ describe('#666 file attachments at admission', () => {expect(refusalLogs(spies)).toHaveLength(0)})+ it('logs the code of a file attachment refused before any image gate runs', async () => {+ const { admit, spies } = makeAdmission()+ const tampered = {+ ...fileAttachment(),+ digest: { algorithm: 'sha256' as const, hex: '0'.repeat(64) },+ }++ const response = await admit(message({ attachments: [tampered as never] }))++ // Witness: admission really refused the turn, and did so on the attachment.+ expect(response.success).toBe(false)+ const code = (response as { error?: { code?: string } }).error?.code+ expect(code).toBe(FileAttachmentErrorCode.DigestMismatch)+ expect(spies.dispatch).toHaveBeenCalledTimes(0)+ const logged = spies.info.mock.calls+ .map(call => call[0] as Record<string, unknown>)+ .filter(fields => fields.event === 'message_attachment_refused')+ expect(logged).toEqual([expect.objectContaining({ code })])+ expect(spies.resolveImageInput).not.toHaveBeenCalled()+ })+it('still refuses an image sent with a file on a model that cannot read images', async () => {const { admit, spies } = makeAdmission({resolveImageInput: vi.fn(() => ({ capability: UNSUPPORTED })),diff --git a/mcp-host/src/agent/__tests__/taskExecutor.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.test.tsindex 8ffda2d2e..287517ac2 100644--- a/mcp-host/src/agent/__tests__/taskExecutor.test.ts+++ b/mcp-host/src/agent/__tests__/taskExecutor.test.ts@@ -40,11 +40,14 @@ vi.mock('../../config', () => ({devModelName: 'test-model',devModelProvider: 'openai',contextMaxTokens: 100000,+ toolSpilloverThresholdBytes: 1_048_576,nativeTool: {workspacePath: '/tmp',shellTimeout: 5000,maxOutputLength: 10000,enableShell: false,+ // Registering clerum__attachment_read for a file attachment needs it.+ attachmentTextReadMaxBytes: 262_144,},},}))@@ -2008,6 +2011,70 @@ describe('TaskExecutor effective limits', () => {expect.objectContaining({ code: 'TASK_ITERATION_LIMIT' }))})+ it('persists the sanitized source message on the approval it suspends', async () => {+ const task = createTask('read the notes'),+ deps = createDeps()+ const bytes = Buffer.from('SENTINEL-666-executor-bytes').toString('base64')+ task.sourceMessage!.attachments = [+ {+ id: 'file-1',+ kind: 'file',+ mimeType: 'text/plain',+ encoding: 'base64',+ dataBase64: bytes,+ filename: 'notes.txt',+ sizeBytes: 27,+ },+ ]+ task.sourceMessage!.fileReferenceResolutions = [+ {+ availability: 'available',+ reference: {+ schemaVersion: 1,+ id: 'gfs:main:123@v3',+ source: {+ kind: 'gfs',+ drive: 'main',+ resourceId: '123',+ gfsUri: 'gfs://main/123',+ version: 3,+ },+ name: 'notes.txt',+ declaredMediaType: null,+ detectedMediaType: 'text/plain',+ class: 'text',+ detection: 'text_utf8',+ mismatch: false,+ byteLength: 4,+ textReadable: true,+ reader: 'text',+ modelImageInput: 'unsupported',+ },+ },+ ]+ vi.mocked(runToolUseLoop).mockResolvedValue({+ type: 'need_approval',+ approval: {+ request_id: 'r-source',+ tool_name: 'test',+ tool_call_id: 'tc',+ parameters: {},+ description: 'confirm',+ context_snapshot: [{ role: 'user', content: 'read the notes' }],+ },+ })+ // Liveness witness: the live message does carry the inline bytes, so the+ // absence checked below is the sanitizer's doing and not an empty fixture.+ expect(task.sourceMessage!.attachments![0].dataBase64).toBe(bytes)+ const executor = new TaskExecutor(task, deps)+ await executor.run()+ expect(deps.onFail).not.toHaveBeenCalled()+ const persisted = executor.pendingApproval!.sourceMessage!+ expect(persisted.fileReferenceResolutions).toEqual(task.sourceMessage!.fileReferenceResolutions)+ expect(persisted.attachments).toHaveLength(1)+ expect(persisted.attachments![0]).toMatchObject({ id: 'file-1', filename: 'notes.txt' })+ expect(JSON.stringify(persisted)).not.toContain(bytes)+ })it('renews a legacy approval on the same task before executing anything', async () => {const task = createTask(),deps = createDeps()diff --git a/mcp-host/src/agent/fileReferenceResolver.ts b/mcp-host/src/agent/fileReferenceResolver.tsindex f54477b1f..714e9f71e 100644--- a/mcp-host/src/agent/fileReferenceResolver.ts+++ b/mcp-host/src/agent/fileReferenceResolver.ts@@ -317,7 +317,11 @@ export async function resolveFileReferences(// R4-M3 — undici puts the header value or a credentialed URL in the message// of a causeless TypeError, and the message route answers error.message// verbatim. Wrap the rethrow so only this fixed text can leave the Host;- // the cause keeps the original error for the log.+ // the cause keeps the original error for a caller that inspects it. The+ // route logs `err` through the Host logger, whose serializer keeps only name,+ // code and status of that Error and does not follow `cause`, so the original+ // message stays out of the log too; the cost is that the log line does not+ // name the original error class.throw new Error('file reference resolution failed: unexpected Host error', { cause: error })} finally {clearTimeout(timer)diff --git a/mcp-host/src/agent/incomingAdmission.ts b/mcp-host/src/agent/incomingAdmission.tsindex 6653bd536..ea65eae61 100644--- a/mcp-host/src/agent/incomingAdmission.ts+++ b/mcp-host/src/agent/incomingAdmission.ts@@ -112,7 +112,7 @@ export function createIncomingAdmission(deps: IncomingAdmissionDeps): IncomingAdevent: 'message_attachment_refused',userId: message.sender,chatId: message.threadId ?? null,- code: validated.error.code ?? null,+ code: validated.error.code,},'Host runtime event')diff --git a/mcp-host/src/agent/stateMachine.ts b/mcp-host/src/agent/stateMachine.tsindex 1ddf99329..b3f05a027 100644--- a/mcp-host/src/agent/stateMachine.ts+++ b/mcp-host/src/agent/stateMachine.ts@@ -760,6 +760,9 @@ export class AgentStateMachine extends EventEmitter {const rehydrated = await this.coldStartLoader.loadPendingApprovals(now)for (const entry of rehydrated) {if (!entry.session_key) throw new Error('rehydrated approval is missing its session key')+ // The persisted message has no inline file bytes (ResumeSourceMessage).+ // Task carries the wider incoming type; the readers of file attachments+ // check `dataBase64` at runtime (attachmentRead.ts) instead of assuming it.const sourceMessage = entry.source_message as Task['sourceMessage']const task: Task = {id: entry.task_id,diff --git a/mcp-host/src/config.fileIngress.test.ts b/mcp-host/src/config.fileIngress.test.tsnew file mode 100644index 000000000..66affb0eb--- /dev/null+++ b/mcp-host/src/config.fileIngress.test.ts@@ -0,0 +1,46 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { FILE_REFERENCE_MAX_COUNT } from '@clerum/gfs-interaction-policy'++// #666 file ingress limits. The Host takes its reference-count limit from the+// contract's shared constant, the same one the Desktop composer imports, and+// exposes no override, so the two cannot disagree. An unparseable spillover+// threshold stops the Host at load instead of describing "NaN bytes" to the+// model.+const SPILLOVER = 'CLERUM_TOOL_SPILLOVER_THRESHOLD'++afterEach(() => {+ vi.unstubAllEnvs()+ vi.resetModules()+})++describe('#666 file ingress configuration', () => {+ it('takes the reference-count limit from the shared contract constant', async () => {+ vi.resetModules()+ const { config } = await import('./config')+ expect(FILE_REFERENCE_MAX_COUNT).toBeGreaterThan(0)+ expect(config.fileReferenceMaxCount).toBe(FILE_REFERENCE_MAX_COUNT)+ })++ it('ignores the retired CLERUM_FILE_REFERENCE_MAX_COUNT variable', async () => {+ vi.resetModules()+ vi.stubEnv('CLERUM_FILE_REFERENCE_MAX_COUNT', String(FILE_REFERENCE_MAX_COUNT + 5))+ const { config } = await import('./config')+ expect(config.fileReferenceMaxCount).toBe(FILE_REFERENCE_MAX_COUNT)+ })++ it.each(['abc', '0', '1.5', '10k'])(+ 'rejects a spillover threshold of %j at config load, naming the variable',+ async value => {+ vi.resetModules()+ vi.stubEnv(SPILLOVER, value)+ await expect(import('./config')).rejects.toThrow(SPILLOVER)+ }+ )++ it('loads an explicit spillover threshold', async () => {+ vi.resetModules()+ vi.stubEnv(SPILLOVER, '16384')+ const { config } = await import('./config')+ expect(config.toolSpilloverThresholdBytes).toBe(16_384)+ })+})diff --git a/mcp-host/src/config.ts b/mcp-host/src/config.tsindex 564237560..8a9ffa187 100644--- a/mcp-host/src/config.ts+++ b/mcp-host/src/config.ts@@ -1,6 +1,7 @@/*** Configuration settings loaded from environment variables.*/+import { FILE_REFERENCE_MAX_COUNT } from '@clerum/gfs-interaction-policy'import type { ApprovalConfig } from './core/extensions/approvalTypes'import type { GuardrailsConfig } from './core/guardrails/config'import { NativeToolConfig } from './core/interfaces'@@ -236,7 +237,11 @@ export interface Config {attachmentFileMaxBytes: number/** Bytes one `clerum__attachment_read` call may return (issue #666). */attachmentTextReadMaxBytes: number- /** Structured file references one incoming message may carry (issue #666). */+ /**+ * Structured file references one incoming message may carry (issue #666).+ * The shared contract constant the Desktop composer also enforces; not+ * operator-tunable, because the Desktop cannot observe a Host-only value.+ */fileReferenceMaxCount: numberactivityBufferSize: numberactivityMaxEventBytes: number@@ -974,7 +979,7 @@ export const config: Config = {attachmentMaxBytes: parseInt(getEnv('CLERUM_ATTACHMENT_MAX_BYTES', '52428800')!, 10),attachmentFileMaxBytes: getExecutionLimit('CLERUM_ATTACHMENT_FILE_MAX_BYTES', 3_145_728),attachmentTextReadMaxBytes,- fileReferenceMaxCount: getExecutionLimit('CLERUM_FILE_REFERENCE_MAX_COUNT', 10),+ fileReferenceMaxCount: FILE_REFERENCE_MAX_COUNT,activityBufferSize: parseInt(getEnv('MCP_HOST_ACTIVITY_BUFFER_SIZE', '1000')!, 10),activityMaxEventBytes: parseInt(getEnv('MCP_HOST_ACTIVITY_MAX_EVENT_BYTES', '2048')!, 10),diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sourceMessageResumeRoundTrip.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sourceMessageResumeRoundTrip.test.tsindex a702e744f..424c5c6cc 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sourceMessageResumeRoundTrip.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sourceMessageResumeRoundTrip.test.ts@@ -5,8 +5,11 @@* a hand-written fixture.*/import { afterEach, describe, expect, it } from 'vitest'+import { buildGfsFileReference, classifyBytes } from '@clerum/gfs-interaction-policy'+import { sourceMessageForResume } from '../../../../agent/sourceMessageForResume'import { prepareStatements } from '../../../../db/statements'import type { PendingApprovalRow } from '../../../../db/worker/protocol'+import { referencedFilePins } from '../../../../internalTools/gfs'import type { ResumeSourceMessage } from '../../../types'import { ConversationManager } from '../../conversation'import { reconstructPendingApproval } from '../reconstruct'@@ -14,6 +17,7 @@ import { type StoreHandle, makeSqliteStore } from './testHelpers'const SESSION_KEY = 'user-r4m2:rpc:agent:default'const FILE_BYTES = Buffer.from('SENTINEL-666-resume-bytes')+const RID = '0123456789abcdef0123456789abcdef'let handle: StoreHandle | undefinedafterEach(async () => {@@ -51,12 +55,12 @@ describe('#666 R4-M2 — source message resume round-trip', () => {availability: 'available',reference: {schemaVersion: 1,- id: 'gfs:main:123@v3',+ id: `gfs:main:${RID}@v3`,source: {kind: 'gfs',drive: 'main',- resourceId: '123',- gfsUri: 'gfs://main/123',+ resourceId: RID,+ gfsUri: `gfs://main/${RID}`,version: 3,},name: 'notes.txt',@@ -93,9 +97,125 @@ describe('#666 R4-M2 — source message resume round-trip', () => {const s = prepareStatements(handle.worker.db)const row = s.selectPendingApprovalBySession.get(conv.id) as PendingApprovalRowexpect(row.source_message).not.toBeNull()- expect(row.source_message).not.toContain(FILE_BYTES.toString('base64'))const rehydrated = reconstructPendingApproval(row)expect(rehydrated.sourceMessage).toEqual(sourceMessage)+ // The sanitizer itself is pinned in sourceMessageForResume.test.ts and the+ // executor call site in taskExecutor.test.ts; this fixture is hand-built, so+ // it only proves the column stores what it is given.+ })++ it('rebuilds the file version pins on the cold-start listing without the attachment bytes', async () => {+ const built = buildGfsFileReference({+ drive: 'main',+ resourceId: RID,+ gfsUri: `gfs://main/${RID}`,+ version: 3,+ name: 'notes.txt',+ declaredMediaType: null,+ byteLength: 4,+ classification: classifyBytes({+ bytes: new Uint8Array(0),+ totalByteLength: 4,+ declaredMediaType: null,+ filename: 'notes.txt',+ }),+ })+ if (!built.ok) throw new Error('fixture reference must build')++ handle = makeSqliteStore()+ const manager = new ConversationManager(handle.store)+ const conv = await manager.getOrCreate(SESSION_KEY)+ await manager.startTurn(conv, 'read the notes', 'task-cold')+ const incoming = {+ content: 'read the notes',+ channelType: 'rpc',+ channelId: 'chatllm',+ sender: 'user-1',+ timestamp: '2026-09-29T10:00:00Z',+ messageId: 'message-cold',+ attachments: [+ {+ id: 'file-1',+ kind: 'file',+ mimeType: 'text/plain',+ encoding: 'base64',+ filename: 'notes.txt',+ dataBase64: FILE_BYTES.toString('base64'),+ },+ ],+ fileReferences: [built.value],+ fileReferenceResolutions: [+ { availability: 'stale', reference: built.value, resolvedVersion: 5 },+ ],+ } as unknown as Parameters<typeof sourceMessageForResume>[0]+ await manager.suspendForApproval(conv, {+ request_id: 'req-cold',+ tool_name: 'internal__do',+ parameters: {},+ description: 'Approve internal__do',+ tool_call_id: 'call-cold',+ context_snapshot: [],+ sourceMessage: sourceMessageForResume(incoming),+ task_budget: {+ elapsedActiveMs: 0,+ iterationsUsed: 1,+ durationMs: 86400000,+ maxIterations: 1000,+ },+ })++ // A restarted pod has neither the cached conversation (whose in-memory+ // approval would be returned as is) nor its ordinals.+ handle.store['cache'].delete(SESSION_KEY)+ handle.store['ordinals'].clear()+ handle.store['sessionKeyById'].clear()++ const listings = await handle.store.loadAllPendingApprovals()+ // Liveness witness: the approval came back through the cold path.+ expect(listings).toHaveLength(1)+ const listed = listings[0]?.sourceMessage as ResumeSourceMessage | undefined+ expect(listed?.content).toBe('read the notes')+ expect(JSON.stringify(listed)).not.toContain(FILE_BYTES.toString('base64'))+ expect([...referencedFilePins(listed?.fileReferenceResolutions).values()]).toEqual([+ { version: 3, currentVersion: 5 },+ ])+ })++ it('fails loud on a corrupt source_message column instead of dropping the pins', async () => {+ handle = makeSqliteStore()+ const manager = new ConversationManager(handle.store)+ const conv = await manager.getOrCreate(SESSION_KEY)+ await manager.startTurn(conv, 'read the notes', 'task-corrupt')+ await handle.store.persistSuspend(conv, {+ request_id: 'req-corrupt',+ tool_name: 'internal__do',+ parameters: {},+ description: 'Approve internal__do',+ tool_call_id: 'call-corrupt',+ context_snapshot: [],+ sourceMessage: {+ content: 'read the notes',+ channelType: 'rpc',+ channelId: 'chatllm',+ sender: 'user-1',+ timestamp: '2026-09-28T10:00:00Z',+ messageId: 'message-1',+ hostRef: 'chatllm',+ },+ task_budget: {+ elapsedActiveMs: 0,+ iterationsUsed: 1,+ durationMs: 86400000,+ maxIterations: 1000,+ },+ })++ const s = prepareStatements(handle.worker.db)+ const row = s.selectPendingApprovalBySession.get(conv.id) as PendingApprovalRow+ // Liveness witness: the intact row reconstructs, so the throw below comes+ // from the corrupt column and not from an unrelated field.+ expect(reconstructPendingApproval(row).sourceMessage?.content).toBe('read the notes')+ expect(() => reconstructPendingApproval({ ...row, source_message: '{not json' })).toThrow()})it('reconstructs without a source message for legacy rows', async () => {diff --git a/mcp-host/src/core/conversation/persistence/reconstruct.ts b/mcp-host/src/core/conversation/persistence/reconstruct.tsindex 680d42413..4b8c1095d 100644--- a/mcp-host/src/core/conversation/persistence/reconstruct.ts+++ b/mcp-host/src/core/conversation/persistence/reconstruct.ts@@ -184,11 +184,9 @@ export function reconstructPendingApproval(row: PendingApprovalRow): PendingApprfunction parseSourceMessage(raw: string | null): ResumeSourceMessage | undefined {if (!raw) return undefined- try {- return JSON.parse(raw) as ResumeSourceMessage- } catch {- return undefined- }+ // A corrupt row throws, like context_snapshot, parameters and task_budget:+ // dropping it would silently resume without the file version pins.+ return JSON.parse(raw) as ResumeSourceMessage}function mapState(raw: string): ConversationState {diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex c4d5ebff4..aa4411581 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -556,14 +556,14 @@ export class SqliteConversationStore implements ConversationStore {}const approval =conv.pending_approval ?? reconstructPendingApproval(row.approval as PendingApprovalRow)- const sourceMessage = row.approval.source_message- ? (JSON.parse(row.approval.source_message) as Record<string, unknown>)- : undefinedout.push({sessionKey,approval,taskId: row.approval.task_id,- sourceMessage,+ // One parse of the column, typed, in reconstructPendingApproval. The+ // cold-start loader hands this value to the resumed task, so it is the+ // path the file version pins take after a restart.+ sourceMessage: approval.sourceMessage,// expires_at is REAL (epoch seconds); convert to ms so the// cold-start loader's TTL compare against `Date.now()` is a direct// numeric compare.diff --git a/mcp-host/src/server/__tests__/messageRoute.test.ts b/mcp-host/src/server/__tests__/messageRoute.test.tsindex dd6c968b5..ac5a4f00f 100644--- a/mcp-host/src/server/__tests__/messageRoute.test.ts+++ b/mcp-host/src/server/__tests__/messageRoute.test.ts@@ -1,7 +1,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { Request, Response } from 'express'import { createHash } from 'node:crypto'-import { buildGfsFileReference, classifyBytes } from '@clerum/gfs-interaction-policy'+import {+ FILE_REFERENCE_MAX_COUNT,+ buildGfsFileReference,+ classifyBytes,+} from '@clerum/gfs-interaction-policy'import { type IncomingAdmissionDeps, createIncomingAdmission } from '../../agent/incomingAdmission'import { config } from '../../config'import { ConversationError, ConversationErrorCode } from '../../core/errors'@@ -484,8 +488,8 @@ describe('handleMessageRoute — structured file references (#666)', () => {})})- it('accepts exactly the configured maximum', async () => {- const refs = Array.from({ length: config.fileReferenceMaxCount }, (_, i) => reference(i + 1))+ it('accepts exactly the contract maximum', async () => {+ const refs = Array.from({ length: FILE_REFERENCE_MAX_COUNT }, (_, i) => reference(i + 1))const { dispatch, handlers } = route()const captured = makeRes()await handleMessageRoute(request(refs), captured.res, handlers)@@ -496,7 +500,7 @@ describe('handleMessageRoute — structured file references (#666)', () => {it.each([['more references than the limit',- () => Array.from({ length: config.fileReferenceMaxCount + 1 }, (_, i) => reference(i + 1)),+ () => Array.from({ length: FILE_REFERENCE_MAX_COUNT + 1 }, (_, i) => reference(i + 1)),'FILE_REFERENCE_INVALID',],['a non-list value', () => ({ id: 'x' }), 'FILE_REFERENCE_INVALID'],diff --git a/packages/gfs-interaction-policy/fileReference.cjs b/packages/gfs-interaction-policy/fileReference.cjsindex 15d338e77..5adea4c34 100644--- a/packages/gfs-interaction-policy/fileReference.cjs+++ b/packages/gfs-interaction-policy/fileReference.cjs@@ -39,20 +39,25 @@ const SHA256_HEX = /^[0-9a-f]{64}$/const GFS_RID = /^[0-9a-f]{32}$/const FILE_REFERENCE_MAX_COUNT = 10-// Characters JSON.stringify leaves raw that still break or hide model-visible-// text: DEL, C1 controls, soft hyphen and the Mongolian vowel separator,-// Hangul fillers, zero-width characters, the Unicode line and paragraph-// separators, bidi controls, invisible joiners and math operators, variation-// selectors, the BOM and the Unicode tag block. Angle brackets are escaped too,-// so a quoted value can never contribute a closing turn-context tag.-const UNSAFE_AFTER_JSON =- /[<>\u{7f}\u{80}-\u{9f}\u{ad}\u{61c}\u{115f}\u{1160}\u{180e}\u{200b}-\u{200f}\u{2028}\u{2029}\u{202a}-\u{202e}\u{2060}-\u{2064}\u{2066}-\u{2069}\u{3164}\u{fe00}-\u{fe0f}\u{feff}\u{e0000}-\u{e007f}]/gu+// Code points JSON.stringify leaves raw that still break or hide model-visible+// text, selected by Unicode property so the set follows the engine's Unicode+// version instead of a hand-kept range list: control characters (Cc: DEL and+// C1), format characters (Cf: zero-width, bidi, joiners, tag characters,+// interlinear marks), the line and paragraph separators (Zl, Zp) and every+// Default_Ignorable_Code_Point (variation selectors, Hangul fillers, the+// combining grapheme joiner, the Mongolian free variation selectors, and the+// unassigned code points reserved as ignorable). Angle brackets are escaped too,+// so a quoted value can never contribute a closing turn-context tag. Non-ASCII+// spaces (Zs, such as U+00A0), private-use code points and other unassigned code+// points occupy visible width or a replacement glyph and stay raw.+const UNSAFE_AFTER_JSON = /[<>\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu/*** Quotes a value for text a model reads (a file name, a path, a label). The- * result is a JSON string literal with every line-breaking or invisible- * character escaped and angle brackets neutralized, so the value stays on its- * line and inside its quotes and cannot close the surrounding turn-context tag.+ * result is a JSON string literal in which every control, format, line or+ * paragraph separator and default-ignorable character is escaped, and angle+ * brackets are neutralized, so the value stays on its line and inside its quotes+ * and cannot close the surrounding turn-context tag.*/function quotePromptValue(value) {if (typeof value !== 'string') throw new TypeError('quotePromptValue requires a string.')diff --git a/packages/gfs-interaction-policy/fileReference.d.ts b/packages/gfs-interaction-policy/fileReference.d.tsindex 01f6ef0d2..ebdc830df 100644--- a/packages/gfs-interaction-policy/fileReference.d.ts+++ b/packages/gfs-interaction-policy/fileReference.d.ts@@ -44,16 +44,18 @@ export type FileReferenceParseResult =export declare const FILE_REFERENCE_SCHEMA_VERSION: 1/**- * The maximum number of file references one message may carry. Must match the- * mcp-host default for CLERUM_FILE_REFERENCE_MAX_COUNT.+ * The maximum number of file references one message may carry. mcp-host+ * admission and the Desktop composer both enforce this single export, so the+ * two cannot disagree.*/export declare const FILE_REFERENCE_MAX_COUNT: 10export declare function parseFileReferenceV1(input: unknown): FileReferenceParseResult/**- * A JSON string literal of `value` with every line-breaking or invisible- * character escaped and angle brackets neutralized, for text a model reads.+ * A JSON string literal of `value` in which every control, format, line or+ * paragraph separator and default-ignorable character is escaped and angle+ * brackets are neutralized, for text a model reads.*/export declare function quotePromptValue(value: string): stringdiff --git a/packages/gfs-interaction-policy/fileReference.test.cjs b/packages/gfs-interaction-policy/fileReference.test.cjsindex 61d273a62..35cc7c70f 100644--- a/packages/gfs-interaction-policy/fileReference.test.cjs+++ b/packages/gfs-interaction-policy/fileReference.test.cjs@@ -279,6 +279,53 @@ describe('quotePromptValue', () => {assert.equal(JSON.parse(quoted), name)})+ it('leaves no control, format, separator or default-ignorable code point raw', () => {+ // The specification is the Unicode property set, not a range list: walk+ // every scalar value so a code point the engine's Unicode version adds+ // later is caught too. The matched count is a liveness witness (a scan+ // that matched nothing would pass the negative assertion below vacuously)+ // and is a floor, never an equality, because it grows with Unicode.+ const hidden = /[<>\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u+ let scanned = 0+ let matched = 0+ for (let codePoint = 0; codePoint <= 0x10ffff; codePoint += 1) {+ if (codePoint >= 0xd800 && codePoint <= 0xdfff) continue+ const char = String.fromCodePoint(codePoint)+ const quoted = quotePromptValue(`a${char}b`)+ scanned += 1+ if (hidden.test(char)) {+ matched += 1+ assert.equal(+ hidden.test(quoted.slice(1, -1)),+ false,+ `U+${codePoint.toString(16).toUpperCase()} survived raw`+ )+ }+ assert.equal(JSON.parse(quoted), `a${char}b`)+ }+ assert.equal(scanned, 0x110000 - 0x800)+ assert.ok(matched > 1000, `only ${matched} code points matched the hidden set`)+ // Negative control: text outside the hidden set stays raw. The last space+ // in the sample is U+00A0 (Zs), which the quoting leaves as it is.+ assert.equal(quotePromptValue('a é 日 😀 '), '"a é 日 😀 "')+ })++ it('escapes named format and ignorable code points beyond the ASCII and C1 controls', () => {+ const cases = [+ [0x034f, '\\u034f'],+ [0x206a, '\\u206a'],+ [0x206f, '\\u206f'],+ [0xfff9, '\\ufff9'],+ [0xfffb, '\\ufffb'],+ [0x0600, '\\u0600'],+ [0xe0100, '\\udb40\\udd00'],+ [0xe01ef, '\\udb40\\uddef'],+ ]+ for (const [codePoint, escaped] of cases) {+ assert.equal(quotePromptValue(`a${String.fromCodePoint(codePoint)}b`), `"a${escaped}b"`)+ }+ })+it('bounds the client input a refusal message echoes', () => {const longValue = 'x'.repeat(200)const version = parseFileReferenceV1({ schemaVersion: longValue })