Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(codex): refuse missing catalog rows and order-independent hop totals
Alfredo Lopez22b72ada2ae0
diff --git a/codex-llm-proxy/src/server.ts b/codex-llm-proxy/src/server.tsindex 6626ca831..8fbad8376 100644--- a/codex-llm-proxy/src/server.ts+++ b/codex-llm-proxy/src/server.ts@@ -24,7 +24,7 @@ import {import {LIMITS,SCHEMA_VERSION_V2,- measureNonImageAuthorizeBytes,+ measureNonImageCompletionBytes,requestBodyLimitBytes,} from '@clerum/llm-provider-attempt-contract'import { RequestLimitError, streamGate, visualStreamGate } from './requestLimits.js'@@ -223,7 +223,7 @@ export function createProxyApps(// fields stay on the contract's 1 MiB non-image ceiling.if (wholeBodyBytes > Math.min(configuredLimit, requestBodyLimitBytes(request)) ||- measureNonImageAuthorizeBytes(req.body) > LIMITS.maxRequestBodyBytes+ measureNonImageCompletionBytes(req.body) > LIMITS.maxRequestBodyBytes) {releaseAdmission()reject(res, 413, 'payload_too_large')diff --git a/desktop-app/ui/src/components/agents/ComposerPanel.tsx b/desktop-app/ui/src/components/agents/ComposerPanel.tsxindex 56a8d6df5..c6e3ad1eb 100644--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx@@ -632,9 +632,18 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPrupdated.dataBase64,imageBudget.maxDimension)+ const otherBase64Bytes = composerImageAttachments.reduce(+ (total, attachment) =>+ attachment.id === updated.id ? total : total + attachment.dataBase64.length,+ 0+ )+ const combinedOverflow =+ imageBudget.maxTotalBase64Bytes != null &&+ otherBase64Bytes + updated.dataBase64.length > imageBudget.maxTotalBase64Bytesif (!composerImageExceedsPerImageBudget(updated.sizeBytes, imageBudget.maxImageBytes) &&- !dimensionError+ !dimensionError &&+ !combinedOverflow) {onUpdateComposerImageAttachment(updated)return@@ -646,11 +655,18 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr)} ${imageBudget.sizeUnit} per image.`)}+ if (dimensionError) {+ throw new Error(+ `${updated.name || 'Image'} was kept unchanged. Max resolution is ${imageBudget.maxDimension} px.`+ )+ }throw new Error(- `${updated.name || 'Image'} was kept unchanged. Max resolution is ${imageBudget.maxDimension} px.`+ `${updated.name || 'Image'} was kept unchanged. The images in one message are limited to ${formatComposerMebibytes(+ imageBudget.maxTotalBase64Bytes ?? 0+ )} ${imageBudget.sizeUnit} in total.`)},- [imageBudget, onUpdateComposerImageAttachment]+ [composerImageAttachments, imageBudget, onUpdateComposerImageAttachment])const handleComposerPaste = useCallback(diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsxindex fd167c219..1909dd7ee 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,16 @@ vi.mock('@hooks/useHostModels', () => ({}))vi.mock('../ComposerAgentFilesModal', () => ({ ComposerAgentFilesModal: () => null }))vi.mock('../ComposerGlobalFilesModal', () => ({ ComposerGlobalFilesModal: () => null }))-vi.mock('../AnnotationCanvas', () => ({ AnnotationCanvas: () => null }))+const annotationCanvasMock = vi.hoisted(() => ({+ onSave: undefined as ((updated: ComposerImageAttachment) => void) | undefined,+}))++vi.mock('../AnnotationCanvas', () => ({+ AnnotationCanvas: (props: { onSave: (updated: ComposerImageAttachment) => void }) => {+ annotationCanvasMock.onSave = props.onSave+ return null+ },+}))function setScrollHeight(textarea: HTMLTextAreaElement, value: number) {Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value })@@ -136,6 +145,7 @@ beforeEach(() => {afterEach(() => {cleanup()+ annotationCanvasMock.onSave = undefineddraftState.value = ''draftState.set.mockReset()Object.assign(composerState, {@@ -590,6 +600,37 @@ describe('ComposerPanel with an image-capable model', () => {)})+ it('refuses an annotation save that would exceed the combined image budget', () => {+ const already: ComposerImageAttachment = {+ id: 'already-attached',+ name: 'already.png',+ mimeType: 'image/png',+ dataBase64: 'A'.repeat(COMPOSER_MAX_TOTAL_IMAGE_BASE64_BYTES - 32),+ sizeBytes: 1,+ previewDataUrl: 'data:image/png;base64,AAAA',+ }+ const editing: ComposerImageAttachment = {+ id: 'editing',+ name: 'edit.png',+ mimeType: 'image/png',+ dataBase64: 'B'.repeat(16),+ sizeBytes: 1,+ previewDataUrl: 'data:image/png;base64,BBBB',+ }+ composerState.composerImageAttachments = [already, editing]+ render(<ComposerPanel inline />)+ fireEvent.click(screen.getByText('edit.png'))+ expect(annotationCanvasMock.onSave).toEqual(expect.any(Function))++ expect(() =>+ annotationCanvasMock.onSave?.({+ ...editing,+ dataBase64: 'B'.repeat(64),+ })+ ).toThrow(/edit\.png was kept unchanged.*8 MB in total/)+ expect(actionsMock.handleUpdateComposerImageAttachment).not.toHaveBeenCalled()+ })+it('counts images already in the composer toward the combined budget', async () => {composerState.composerImageAttachments = [{diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.tsindex 80e1287f3..f70725a95 100644--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@ -9,7 +9,7 @@ export type ReleaseManifest = {export const releaseManifest: ReleaseManifest = {releaseId: 'v0.9.0',externalRestApiVersion: '0.1.84',- rpcProxyVersion: '0.1.88',+ rpcProxyVersion: '0.1.89',desktopVersion: '0.9.0',minimumDesktopVersion: '0.1.252',}diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex fb023890b..8ee570bfc 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.363",+ "version": "0.1.364","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.363",+ "version": "0.1.364","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 2fc9ce550..81e89ac35 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.363",+ "version": "0.1.364","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/bodylimits.test.ts b/mcp-host/src/__tests__/bodylimits.test.tsindex 094588db7..51a2ace6b 100644--- a/mcp-host/src/__tests__/bodylimits.test.ts+++ b/mcp-host/src/__tests__/bodylimits.test.ts@@ -258,6 +258,18 @@ describe('mcp-host runtime message body budget', () => {expect(captured).toHaveLength(0)})+ it.each([+ { label: '15MiB then 2MiB', sizes: [15 * MIB, 2 * MIB] as const },+ { label: '2MiB then 15MiB', sizes: [2 * MIB, 15 * MIB] as const },+ ])('rejects $label on the 16MiB decoded total regardless of order', async ({ sizes }) => {+ captured = []+ const response = await postMessage(+ messagePayload([imageAttachment('a1', sizes[0]), imageAttachment('a2', sizes[1])])+ )+ expect(response.status).toBe(413)+ expect(captured).toHaveLength(0)+ })+it('still rejects text-only content over the 6MiB non-image budget', async () => {captured = []const response = await postMessage({diff --git a/mcp-host/src/agent/__tests__/incomingAdmission.test.ts b/mcp-host/src/agent/__tests__/incomingAdmission.test.tsindex f8805b30e..8ac5e6bad 100644--- a/mcp-host/src/agent/__tests__/incomingAdmission.test.ts+++ b/mcp-host/src/agent/__tests__/incomingAdmission.test.ts@@ -151,6 +151,35 @@ describe('#654 incoming admission gate', () => {])})+ it('refuses a Codex image when the catalog has no row for the model', async () => {+ const { admit, spies } = makeAdmission({+ hostProvider: () => 'codex-subscription',+ resolveTaskModel: vi.fn(() => ({+ provider: { getProviderType: () => 'codex-subscription' },+ model: 'gpt-5.6-luna',+ })),+ resolveImageInput: vi.fn(() => undefined),+ })++ const response = await admit(imageMessage())++ expect(response).toMatchObject({+ success: false,+ error: { code: 'LLM_IMAGE_INPUT_UNKNOWN', retryable: false, provider: 'codex-subscription' },+ })+ expect(spies.resolveImageInput).toHaveBeenCalledWith('codex-subscription', 'gpt-5.6-luna')+ expect(spies.dispatch).toHaveBeenCalledTimes(0)+ expect(refusalLogs(spies)).toEqual([+ expect.objectContaining({+ event: 'message_image_refused',+ reason: 'model_unknown',+ provider: 'codex-subscription',+ model: 'gpt-5.6-luna',+ code: 'LLM_IMAGE_INPUT_UNKNOWN',+ }),+ ])+ })+it('admits a Codex image when the live catalog has no imageInput field', async () => {const { admit, spies } = makeAdmission({hostProvider: () => 'codex-subscription',diff --git a/mcp-host/src/agent/incomingAdmission.ts b/mcp-host/src/agent/incomingAdmission.tsindex 522d98a93..bb1e9be09 100644--- a/mcp-host/src/agent/incomingAdmission.ts+++ b/mcp-host/src/agent/incomingAdmission.ts@@ -201,9 +201,14 @@ export function createIncomingAdmission(deps: IncomingAdmissionDeps): IncomingAd}const pair = { provider: resolved.provider.getProviderType(), model: resolved.model }const facts = deps.resolveImageInput(pair.provider, pair.model)- const decision = resolveHostImageInput(pair.provider, facts?.capability, {- transportSupported: chatTransportSupportsImageInput(pair.provider),- })+ // A missing catalog row is not an omitted `imageInput` field. Optional+ // chaining would collapse both to `undefined` and the Codex upgrade+ // would advertise support the adapter later rejects.+ const decision = facts+ ? resolveHostImageInput(pair.provider, facts.capability, {+ transportSupported: chatTransportSupportsImageInput(pair.provider),+ })+ : { state: 'unknown' as const, reason: 'model_unknown' as const }if (decision.state !== 'supported') {const code =decision.state === 'unknown'diff --git a/mcp-host/src/config/__tests__/modelResolution.test.ts b/mcp-host/src/config/__tests__/modelResolution.test.tsindex 7f3461147..d74ab32a0 100644--- a/mcp-host/src/config/__tests__/modelResolution.test.ts+++ b/mcp-host/src/config/__tests__/modelResolution.test.ts@@ -151,6 +151,12 @@ describe('projectModels', () => {],})})++ it('degraded: does not advertise Codex image support without a catalog row', () => {+ expect(+ projectModels(view(false), 'codex-subscription', 'gpt-5.6-luna').models[0].imageInput+ ).toEqual({ state: 'unknown', reason: 'model_unknown' })+ })})describe('contextWindowForModel', () => {diff --git a/mcp-host/src/config/modelResolution.ts b/mcp-host/src/config/modelResolution.tsindex 7a381143a..faad4ee3d 100644--- a/mcp-host/src/config/modelResolution.ts+++ b/mcp-host/src/config/modelResolution.ts@@ -123,7 +123,12 @@ export function projectModels(hostDefault: string): { degraded: boolean; models: ModelWireEntry[] } {if (!view.allowlistAvailable()) {- return { degraded: true, models: [entryToWire({ model: hostDefault }, provider)] }+ // Degraded projection is not a catalog row. Do not run the omitted-field+ // Codex upgrade — that path is only for a live allowlist entry.+ return {+ degraded: true,+ models: [{ name: hostDefault, imageInput: { state: 'unknown', reason: 'model_unknown' } }],+ }}const entries = view.allowedModels().get(provider) ?? []return { degraded: false, models: entries.map(entry => entryToWire(entry, provider)) }diff --git a/mcp-host/src/llm/imageInput.ts b/mcp-host/src/llm/imageInput.tsindex fb5cd9fa4..1020902b7 100644--- a/mcp-host/src/llm/imageInput.ts+++ b/mcp-host/src/llm/imageInput.ts@@ -242,10 +242,12 @@ export interface ImageInputRequestFacts {* Subscription has no per-model vision split and no models.dev row: a live* ChatGPT catalog entry has no `imageInput` field. When the V2 transport can* carry the image, that absence is `supported` so Luna and every other Codex- * model match the pre-#669 path. Only a missing allowlist field is upgraded:- * a present value that failed to parse is stored as `{ state: 'unknown' }` and- * stays denied. Curated `unsupported` / dated evidence still wins. Never- * invent models.dev rows.+ * model match the pre-#669 path. Only a missing allowlist field on a present+ * row is upgraded: a present value that failed to parse is stored as+ * `{ state: 'unknown' }` and stays denied. A resolver miss is not a field+ * omission — callers must not pass `capability === undefined` unless they have+ * a row. Curated `unsupported` / dated evidence still wins. Never invent+ * models.dev rows.*/export function resolveHostImageInput(providerType: string,diff --git a/mcp-host/src/server.ts b/mcp-host/src/server.tsindex 0bdf63193..854de7be3 100644--- a/mcp-host/src/server.ts+++ b/mcp-host/src/server.ts@@ -192,19 +192,20 @@ function decodedBase64Bytes(dataBase64: string): number | null {* `kind: 'image'`, `encoding: 'base64'`, a PNG/JPEG MIME type, canonical* base64 whose leading bytes are that image's signature, and at most 16MiB* decoded each within a 20-image / 16MiB total budget. A 21st qualifying- * image is fail-loud rather than charged as text. Anything else is charged- * to the non-image budget, so a claim cannot be smuggled through by mislabelling- * a payload.+ * image, and a qualifying image that would push the decoded total over 16MiB,+ * are fail-loud rather than charged as text. Anything else is charged to the+ * non-image budget, so a claim cannot be smuggled through by mislabelling a+ * payload.*/function inspectChatImageBudget(body: unknown): {creditedBase64: number- tooManyImages: boolean+ rejectImages: boolean} {if (!body || typeof body !== 'object' || Array.isArray(body)) {- return { creditedBase64: 0, tooManyImages: false }+ return { creditedBase64: 0, rejectImages: false }}const attachments = (body as { attachments?: unknown }).attachments- if (!Array.isArray(attachments)) return { creditedBase64: 0, tooManyImages: false }+ if (!Array.isArray(attachments)) return { creditedBase64: 0, rejectImages: false }let credited = 0let decodedTotal = 0@@ -223,26 +224,25 @@ function inspectChatImageBudget(body: unknown): {const dataBase64 = typeof candidate.dataBase64 === 'string' ? candidate.dataBase64 : ''const decoded = decodedBase64Bytes(dataBase64)if (decoded === null || decoded <= 0 || decoded > MAX_IMAGE_DECODED_BYTES) continue- if (decodedTotal + decoded > MAX_IMAGE_DECODED_BYTES_TOTAL) continueconst signature = Buffer.from(dataBase64.slice(0, 16), 'base64')const matchesSignature =mimeType === 'image/png'? signature.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE): signature.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)if (!matchesSignature) continue- if (counted >= MAX_CHAT_IMAGES) {- return { creditedBase64: credited, tooManyImages: true }+ if (counted >= MAX_CHAT_IMAGES || decodedTotal + decoded > MAX_IMAGE_DECODED_BYTES_TOTAL) {+ return { creditedBase64: credited, rejectImages: true }}credited += dataBase64.lengthdecodedTotal += decodedcounted += 1}- return { creditedBase64: credited, tooManyImages: false }+ return { creditedBase64: credited, rejectImages: false }}function chatBodyExceedsNonImageBudget(rawBodyBytes: number, body: unknown): boolean {const budget = inspectChatImageBudget(body)- if (budget.tooManyImages) return true+ if (budget.rejectImages) return truereturn rawBodyBytes - budget.creditedBase64 > MAX_NON_IMAGE_BODY_BYTES}@@ -308,8 +308,8 @@ export class RPCServer {})// Image attachments are sent as base64 in /v1/runtime/messages.- // That route alone gets the larger ceiling described above; every other- // route keeps the 6mb default.+ // That route alone gets the 24 MiB ceiling. Every other route uses this+ // PR's 6mb non-image default (not the historical 10mb parser).const jsonParser = express.json({ limit: '6mb' })const chatJsonParser = express.json({limit: MAX_CHAT_BODY_BYTES,diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjsindex 6cb63f6b8..97faf4814 100644--- a/packages/llm-provider-attempt-contract/index.cjs+++ b/packages/llm-provider-attempt-contract/index.cjs@@ -260,6 +260,19 @@ function measureNonImageAuthorizeBytes(body) {)}+/**+ * Proxy completion JSON includes `executionTicket`, which authorize never+ * measured. Blank images and drop the ticket so a body that sat under the+ * 1 MiB authorize budget is not 413'd on redeem by ~1 KB of JWT.+ */+function measureNonImageCompletionBytes(body) {+ if (!isPlainObject(body)) {+ return measureNonImageAuthorizeBytes(body)+ }+ const { executionTicket: _executionTicket, ...rest } = body+ return measureNonImageAuthorizeBytes(rest)+}+function isBoundedId(value) {return typeof value === 'string' && ID_PATTERN.test(value)}@@ -978,6 +991,7 @@ module.exports = {VISUAL_LIMITS,requestBodyLimitBytes,measureNonImageAuthorizeBytes,+ measureNonImageCompletionBytes,isBoundedId,stableStringify,parseCodexCompletionRequestV1,diff --git a/packages/llm-provider-attempt-contract/index.d.ts b/packages/llm-provider-attempt-contract/index.d.tsindex 635198355..17ed6820b 100644--- a/packages/llm-provider-attempt-contract/index.d.ts+++ b/packages/llm-provider-attempt-contract/index.d.ts@@ -249,6 +249,13 @@ export declare function requestBodyLimitBytes(request: unknown): number* budget even when the nested request declares V2.*/export declare function measureNonImageAuthorizeBytes(body: unknown): number+/**+ * Byte length of a proxy completion document after image payloads inside+ * `body.request` are blanked and `executionTicket` is omitted. The ticket is+ * issued after authorize, so it must not consume the 1 MiB non-image budget+ * that authorize already applied to the pre-ticket wrapper.+ */+export declare function measureNonImageCompletionBytes(body: unknown): number/** Closed identifier used by request ids, ticket claims, and authorize ids. */export declare function isBoundedId(value: unknown): value is stringexport declare function parseCodexCompletionRequestV1(diff --git a/packages/llm-provider-attempt-contract/index.test.cjs b/packages/llm-provider-attempt-contract/index.test.cjsindex de359d7d0..933067387 100644--- a/packages/llm-provider-attempt-contract/index.test.cjs+++ b/packages/llm-provider-attempt-contract/index.test.cjs@@ -1365,6 +1365,50 @@ test('measureNonImageAuthorizeBytes keeps wrapper fields on the 1 MiB budget', (assert.equal(contract.requestBodyLimitBytes(stuffed.request), 25165824)})+test('measureNonImageCompletionBytes omits the execution ticket', () => {+ const request = {+ ...BASE,+ schemaVersion: contract.SCHEMA_VERSION_V2,+ messages: [+ {+ role: 'user',+ content: 'look',+ contentParts: [{ type: 'text', text: 'look' }, imagePart(IMAGE_DATA.png)],+ },+ ],+ }+ const authorize = {+ request,+ invocationId: 'invocation-1',+ attemptGeneration: 1,+ targetRef: 'codex-primary',+ }+ const room = 500+ const pad =+ contract.LIMITS.maxRequestBodyBytes - contract.measureNonImageAuthorizeBytes(authorize) - room+ assert.ok(pad > 64)+ const tightAuthorize = {+ ...authorize,+ invocationId: `${authorize.invocationId}${'x'.repeat(pad)}`,+ }+ assert.ok(contract.measureNonImageAuthorizeBytes(tightAuthorize) < contract.LIMITS.maxRequestBodyBytes)++ const completion = {+ ...tightAuthorize,+ requestHash: 'a'.repeat(64),+ executionTicket: `header.${'a'.repeat(2048)}.sig`,+ }+ assert.ok(contract.measureNonImageAuthorizeBytes(completion) > contract.LIMITS.maxRequestBodyBytes)+ assert.ok(contract.measureNonImageCompletionBytes(completion) <= contract.LIMITS.maxRequestBodyBytes)+ assert.equal(+ contract.measureNonImageCompletionBytes(completion),+ contract.measureNonImageAuthorizeBytes({+ ...tightAuthorize,+ requestHash: completion.requestHash,+ })+ )+})+// ---------------------------------------------------------------------------// Canonical hashing shared by mcp-host (client) and control-api/codex-llm-proxy// (server), plus the structural depth cap.diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex cb55f1410..2c1a7913d 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.88",+ "version": "0.1.89","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.88",+ "version": "0.1.89","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex 72501d0a6..c07c44edd 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.88",+ "version": "0.1.89","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/bodylimits.test.ts b/rpc-proxy/src/__tests__/bodylimits.test.tsindex 14f6d22c3..2b1263ad2 100644--- a/rpc-proxy/src/__tests__/bodylimits.test.ts+++ b/rpc-proxy/src/__tests__/bodylimits.test.ts@@ -288,6 +288,19 @@ describe('rpc-proxy chat message body budget', () => {expect(response.status).toBe(413)})+ it.each([+ { label: '15MiB then 2MiB', sizes: [15 * MIB, 2 * MIB] as const },+ { label: '2MiB then 15MiB', sizes: [2 * MIB, 15 * MIB] as const },+ ])('rejects $label on the 16MiB decoded total regardless of order', async ({ sizes }) => {+ const body = JSON.stringify({+ content: 'look',+ attachments: [imageAttachment('a1', sizes[0]), imageAttachment('a2', sizes[1])],+ })+ expect(Buffer.byteLength(body)).toBeLessThan(24 * MIB)+ const response = await post(MESSAGE_PATH, body)+ expect(response.status).toBe(413)+ })+it('still rejects text-only content over the 6MiB non-image budget', async () => {const response = await postMessage({ content: 'x'.repeat(7 * MIB), attachments: [] })expect(response.status).toBe(413)diff --git a/rpc-proxy/src/middleware/chatJsonBody.ts b/rpc-proxy/src/middleware/chatJsonBody.tsindex d4ff1ce91..4feffd74c 100644--- a/rpc-proxy/src/middleware/chatJsonBody.ts+++ b/rpc-proxy/src/middleware/chatJsonBody.ts@@ -71,19 +71,20 @@ function decodedBase64Bytes(dataBase64: string): number | null {* `kind: 'image'`, `encoding: 'base64'`, a PNG/JPEG MIME type, canonical* base64 whose leading bytes are that image's signature, and at most 16MiB* decoded each within a 20-image / 16MiB total budget. A 21st qualifying- * image is fail-loud rather than charged as text. Anything else is charged- * to the non-image budget, so a claim cannot be smuggled through by mislabelling- * a payload.+ * image, and a qualifying image that would push the decoded total over 16MiB,+ * are fail-loud rather than charged as text. Anything else is charged to the+ * non-image budget, so a claim cannot be smuggled through by mislabelling a+ * payload.*/function inspectChatImageBudget(body: unknown): {creditedBase64: number- tooManyImages: boolean+ rejectImages: boolean} {if (!body || typeof body !== 'object' || Array.isArray(body)) {- return { creditedBase64: 0, tooManyImages: false }+ return { creditedBase64: 0, rejectImages: false }}const attachments = (body as { attachments?: unknown }).attachments- if (!Array.isArray(attachments)) return { creditedBase64: 0, tooManyImages: false }+ if (!Array.isArray(attachments)) return { creditedBase64: 0, rejectImages: false }let credited = 0let decodedTotal = 0@@ -102,26 +103,25 @@ function inspectChatImageBudget(body: unknown): {const dataBase64 = typeof candidate.dataBase64 === 'string' ? candidate.dataBase64 : ''const decoded = decodedBase64Bytes(dataBase64)if (decoded === null || decoded <= 0 || decoded > MAX_IMAGE_DECODED_BYTES) continue- if (decodedTotal + decoded > MAX_IMAGE_DECODED_BYTES_TOTAL) continueconst signature = Buffer.from(dataBase64.slice(0, 16), 'base64')const matchesSignature =mimeType === 'image/png'? signature.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE): signature.subarray(0, JPEG_SIGNATURE.length).equals(JPEG_SIGNATURE)if (!matchesSignature) continue- if (counted >= MAX_CHAT_IMAGES) {- return { creditedBase64: credited, tooManyImages: true }+ if (counted >= MAX_CHAT_IMAGES || decodedTotal + decoded > MAX_IMAGE_DECODED_BYTES_TOTAL) {+ return { creditedBase64: credited, rejectImages: true }}credited += dataBase64.lengthdecodedTotal += decodedcounted += 1}- return { creditedBase64: credited, tooManyImages: false }+ return { creditedBase64: credited, rejectImages: false }}function chatBodyExceedsNonImageBudget(rawBodyBytes: number, body: unknown): boolean {const budget = inspectChatImageBudget(body)- if (budget.tooManyImages) return true+ if (budget.rejectImages) return truereturn rawBodyBytes - budget.creditedBase64 > MAX_NON_IMAGE_BODY_BYTES}