Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
chore: merge origin/dev and close surviving Jozer review items
Alfredo Lopez42969aea424f
diff --cc codex-llm-proxy/src/codexTransport.tsindex 7afd9b771,8364d87ea..df6a7d7c5--- a/codex-llm-proxy/src/codexTransport.ts+++ b/codex-llm-proxy/src/codexTransport.ts@@@ -86,18 -87,12 +87,21 @@@ export type StreamCodexCompletionResulexport async function streamCodexCompletion(input: StreamCodexCompletionInput): Promise<StreamCodexCompletionResult> {- const parsed = parseCodexCompletionRequestV1(input.request)+ const parsed = parseCodexCompletionRequest(input.request)if (!parsed.ok) {-- throw new CodexTransportError('invalid_request', parsed.message)++ throw new CodexTransportError(++ parsed.kind === 'size' ? 'payload_too_large' : 'invalid_request',++ parsed.message++ )}const request = parsed.value- const digest = hashCodexCompletionRequestV1(request)+ if (request.schemaVersion === 'codex-completion-request.v2' && input.deadlineMs !== undefined) {+ throw new CodexTransportError(+ 'invalid_request',+ 'Visual request deadlines must be inside the authorized request'+ )+ }+ const digest = hashCodexCompletionRequest(request)if (digest !== input.requestHash || input.ticket.requestHash !== input.requestHash) {throw new CodexTransportError('request_hash_mismatch', 'request hash does not match the ticket')}diff --cc codex-llm-proxy/src/server.tsindex 6a5141549,7e048f1f0..6626ca831--- a/codex-llm-proxy/src/server.ts+++ b/codex-llm-proxy/src/server.ts@@@ -270,21 -161,19 +270,33 @@@ export function createProxyApps// to req 'close' aborts the ChatGPT hop on every call (3–12ms canceled).// Abort only when the client drops the response before we finish writing.abortWhenClientDisconnects(req, res, abort)+ const visualRequest =+ (parsed.data.request as { schemaVersion?: unknown }).schemaVersion === SCHEMA_VERSION_V2+ // One `codex_proxy_attempt_finished` line per attempt. Identifiers and+ // counts only: never the body, ticket, frames, tool names or arguments.+ const attempt = {+ providerAttemptId: ticket.providerAttemptId,+ hostRef: ticket.hostRef,+ model: ticket.model,+ requestHash: ticket.requestHash,+ }+ const attemptStarted = Date.now()+ let toolCalls = 0+ let textChunks = 0try {- release = await streamGate.acquire(abort.signal)+ // A visual slot exists only when Content-Length exceeded the ordinary- // cap. V2 keeps it until the stream ends because the image bytes stay- // resident. Every other request releases it and takes the 8-wide gate.- if (visualRequest) {++ // cap. Keep it for the ChatGPT stream only when the parsed V2 body still++ // exceeds that cap (image bytes stay resident). Padding, V1, and small++ // V2 release it and take the 8-wide gate.++ if (visualRequest && wholeBodyBytes > config.maxBodyBytes) {+ release = gated.codexStreamRelease+ gated.codexStreamRelease = undefined+ } else {+ releaseAdmission()+ }+ if (!release) {+ release = await streamGate.acquire(abort.signal)+ }res.status(200)res.setHeader('content-type', 'text/event-stream')res.setHeader('cache-control', 'no-cache')@@@ -439,6 -362,34 +492,35 @@@ export function startProxy(config: Codereturn servers}+ // Every code the proxy or control-api is known to send. The failure metric+ // uses this as its label allowlist because a control-api error body is not+ // bounded by the proxy.+ const ATTEMPT_ERROR_STATUS: Record<string, number> = {+ invalid_request: 400,++ payload_too_large: 413,+ Unauthorized: 401,+ origin_denied: 403,+ request_hash_mismatch: 403,+ ticket_invalid: 403,+ ticket_expired: 403,+ no_grant: 403,+ host_binding_mismatch: 403,+ model_not_allowed: 403,+ insufficient_scope: 403,+ disabled: 404,+ ticket_replayed: 409,+ tool_call_limit_exceeded: 422,+ connection_unavailable: 503,+ provider_unavailable: 503,+ sse_buffer_exceeded: 503,+ invalid_receipt: 503,+ conflict: 503,+ }++ function failureLabel(code: string): string {+ return Object.hasOwn(ATTEMPT_ERROR_STATUS, code) ? code : 'other'+ }+function mapError(err: unknown): { status: number; code: string } {if (err instanceof OriginDeniedError) return { status: 403, code: 'origin_denied' }if (err instanceof RequestLimitError) return { status: 503, code: 'provider_unavailable' }diff --cc codex-llm-proxy/test/codexTransport.conformance.test.tsindex 2af62e41d,d8e8dc04a..b557f0f34--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts@@@ -1,9 -1,6 +1,10 @@@+import { readFileSync } from 'node:fs'++import { createRequire } from 'node:module'import { describe, expect, it, vi } from 'vitest'import {+ hashCodexCompletionRequest,hashCodexCompletionRequestV1,+ parseCodexCompletionRequest,parseCodexCompletionRequestV1,} from '@clerum/llm-provider-attempt-contract'import {@@@ -16,6 -13,6 +17,10 @@@ import { CODEX_COMPLETIONS_ORIGIN } froimport { ToolNameMap } from '../src/toolNameMap.js'import { eventaskUpdateTool, optionalMcpTools, webSearchTool } from './fixtures/optionalMcpTools.js'++const { declaredHeaderPng } = createRequire(import.meta.url)(++ '../../packages/llm-provider-attempt-contract/testImageFixtures.cjs'++) as { declaredHeaderPng: (width: number, height: number) => Buffer }++const REQUEST = {schemaVersion: 'codex-completion-request.v1' as const,requestId: 'req-001',@@@ -72,85 -69,6 +77,132 @@@ function sseResponse}describe('streamCodexCompletion', () => {++ it('maps an over-dimension image to payload_too_large before redeem', async () => {++ const request = {++ schemaVersion: 'codex-completion-request.v2' as const,++ requestId: 'req-over-dimension',++ idempotencyKey: 'idem-over-dimension',++ provider: 'codex-subscription' as const,++ model: 'gpt-5.1',++ messages: [++ {++ role: 'user' as const,++ content: 'look',++ contentParts: [++ { type: 'text' as const, text: 'look' },++ {++ type: 'image' as const,++ mimeType: 'image/png' as const,++ data: declaredHeaderPng(3000, 3000).toString('base64'),++ source: { kind: 'attachment' as const, attachmentId: 'att-1', messageId: 'msg-1' },++ },++ ],++ },++ ],++ }++ const redeem = vi.fn()++ await expect(++ streamCodexCompletion({++ executionTicket: 'visual-ticket',++ requestHash: 'a'.repeat(64),++ request,++ ticket: {++ jti: 'visual-ticket',++ hostRef: 'research-host',++ model: request.model,++ requestHash: 'a'.repeat(64),++ providerAttemptId: 'visual-attempt',++ },++ redeem,++ finalize: vi.fn(),++ fetchFn: vi.fn(),++ })++ ).rejects.toMatchObject({++ code: 'payload_too_large',++ message: expect.stringMatching(/image dimension exceeds 2048/),++ })++ expect(redeem).not.toHaveBeenCalled()++ })+++ it.each(['png', 'jpeg'] as const)(+ 'projects authorized %s parts without leaking provenance upstream',+ async format => {+ const fixtures = JSON.parse(+ readFileSync(+ new URL(+ '../../packages/llm-provider-attempt-contract/fixtures/visual-requests.json',+ import.meta.url+ ),+ 'utf8'+ )+ ) as Record<+ string,+ {+ messages: Array<{+ contentParts: Array<{+ type: string+ text?: string+ mimeType?: string+ data?: string+ }>+ }>+ }+ >+ const parsed = parseCodexCompletionRequest({ ...fixtures[format], model: REQUEST.model })+ expect(parsed.ok).toBe(true)+ if (!parsed.ok) throw new Error(parsed.message)+ const request = parsed.value+ const requestHash = hashCodexCompletionRequest(request)+ const fetchFn = vi.fn<typeof fetch>(async () =>+ sseResponse(['data: {"type":"response.completed"}\n\n'])+ )+ const redeem = vi.fn(async () => redeemSuccess())+ const finalize = vi.fn(async () => ({+ providerAttemptId: 'visual-attempt',+ outcome: 'success' as const,+ duplicate: false,+ }))+ const input: StreamCodexCompletionInput = {+ executionTicket: 'visual-ticket',+ requestHash,+ request,+ ticket: {+ jti: 'visual-ticket',+ hostRef: 'research-host',+ model: request.model,+ requestHash,+ providerAttemptId: 'visual-attempt',+ },+ redeem,+ finalize,+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ }+ await expect(streamCodexCompletion({ ...input, deadlineMs: 1000 })).rejects.toMatchObject({+ code: 'invalid_request',+ })+ expect(redeem).not.toHaveBeenCalled()+ expect(fetchFn).not.toHaveBeenCalled()+ await streamCodexCompletion(input)+ const body = JSON.parse(String(fetchFn.mock.calls[0]?.[1]?.body))+ const sourceParts = fixtures[format].messages[0].contentParts+ expect(body.input[0].content).toEqual(+ sourceParts.map(+ (part: { type: string; text?: string; mimeType?: string; data?: string }) =>+ part.type === 'text'+ ? { type: 'input_text', text: part.text }+ : {+ type: 'input_image',+ image_url: `data:${part.mimeType};base64,${part.data}`,+ detail: 'high',+ }+ )+ )+ expect(JSON.stringify(body)).not.toContain('attachmentId')+ expect(finalize).toHaveBeenCalledOnce()+ }+ )+it('does not read further upstream bytes while the frame consumer is back-pressured', async () => {const encoder = new TextEncoder()const events = [diff --cc codex-llm-proxy/test/server.security.test.tsindex b39509ca1,359d44535..83bcece53--- a/codex-llm-proxy/test/server.security.test.ts+++ b/codex-llm-proxy/test/server.security.test.ts@@@ -1,15 -1,22 +1,22 @@@import { generateKeyPairSync } from 'node:crypto'import jwt from 'jsonwebtoken'import request from 'supertest'- import { describe, expect, it } from 'vitest'++import { describe, expect, it, vi } from 'vitest'import {hashCodexCompletionRequestV1,parseCodexCompletionRequestV1,} from '@clerum/llm-provider-attempt-contract'-import { describe, expect, it, vi } from 'vitest'import { verifyAdminPermit } from '../src/auth/adminPermitVerifier.js'import { verifyExecutionTicket } from '../src/auth/executionTicketVerifier.js'- import { type CodexLlmProxyConfig, loadConfig } from '../src/config.js'- import { ControlApiClient, ControlApiClientError } from '../src/controlApiClient.js'+ import { loadConfig, type CodexLlmProxyConfig } from '../src/config.js'+ import {+ ControlApiClient,+ ControlApiClientError,+ type FinalizeAttemptSuccess,+ type RedeemAttemptSuccess,+ } from '../src/controlApiClient.js'+ import { logger } from '../src/logger.js'+ import { CODEX_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'import { createProxyApps } from '../src/server.js'const { privateKey, publicKey } = generateKeyPairSync('rsa', {diff --cc codex-llm-proxy/test/streamGate.handoff.test.tsindex fd272703f,000000000..9abda5974mode 100644,000000..100644--- a/codex-llm-proxy/test/streamGate.handoff.test.ts+++ b/codex-llm-proxy/test/streamGate.handoff.test.ts@@@ -1,310 -1,0 +1,373 @@@+import { generateKeyPairSync } from 'node:crypto'+import { createServer } from 'node:http'+import { connect as connectTcp } from 'node:net'+import jwt from 'jsonwebtoken'+import { afterEach, describe, expect, it } from 'vitest'+import {+ hashCodexCompletionRequest,+ parseCodexCompletionRequest,+} from '@clerum/llm-provider-attempt-contract'+import { type CodexLlmProxyConfig } from '../src/config.js'+import { createProxyApps } from '../src/server.js'+import {+ STREAM_LIMITS,+ VISUAL_STREAM_LIMITS,+ streamGate,+ visualStreamGate,+} from '../src/requestLimits.js'++const { privateKey, publicKey } = generateKeyPairSync('rsa', {+ modulusLength: 2048,+ publicKeyEncoding: { type: 'spki', format: 'pem' },+ privateKeyEncoding: { type: 'pkcs8', format: 'pem' },+})++function config(overrides: Partial<CodexLlmProxyConfig> = {}): CodexLlmProxyConfig {+ return {+ runtimePort: 8080,+ adminPort: 8081,+ probePort: 9090,+ maxBodyBytes: 1_048_576,+ maxVisualBodyBytes: 24 * 1024 * 1024,+ maxStreamDurationMs: 300_000,+ maxDeadlineMs: 300_000,+ jwtIssuer: 'control-api',+ jwtPublicKey: publicKey,+ executionEnabled: true,+ controlApiBaseUrl: '',+ controlApiServiceName: 'codex-llm-proxy',+ controlApiServiceToken: '',+ ...overrides,+ }+}++function sign(payload: Record<string, unknown>, audience: string): string {+ return jwt.sign(payload, privateKey, {+ algorithm: 'RS256',+ issuer: 'control-api',+ audience,+ expiresIn: 60,+ })+}++function platformToken(): string {+ return sign(+ {+ sub: 'default/research-host',+ hostRefs: ['research-host'],+ workflowControlScopes: ['llm:codex:execute'],+ scope: 'workflow:approval:request',+ },+ 'workflow-approvals'+ )+}++let ticketSeq = 1++function ticket(requestHash: string): string {+ ticketSeq += 1+ return sign(+ {+ jti: `11111111-1111-4111-8111-${String(ticketSeq).padStart(12, '0')}`,+ typ: 'codex-execution-ticket',+ hostRef: 'research-host',+ model: 'gpt-5.1',+ requestHash,+ providerAttemptId: `att-${ticketSeq}`,+ },+ 'codex-llm-proxy'+ )+}++function completionRequest(+ schemaVersion: 'codex-completion-request.v1' | 'codex-completion-request.v2',+ content = 'hi'+) {+ ticketSeq += 1+ return {+ schemaVersion,+ requestId: `req-gate-${ticketSeq}`,+ idempotencyKey: `idem-gate-${ticketSeq}`,+ provider: 'codex-subscription',+ model: 'gpt-5.1',+ messages: [{ role: 'user', content }],+ }+}++function hangStream() {+ let releaseHeld!: () => void+ const held = new Promise<void>(resolve => {+ releaseHeld = resolve+ })+ return {+ release: () => releaseHeld(),+ impl: async () => {+ await held+ return { outcome: 'canceled' as const }+ },+ }+}++async function waitFor(predicate: () => boolean, label: string): Promise<void> {+ const started = Date.now()+ while (!predicate()) {+ if (Date.now() - started > 5_000) throw new Error(label)+ await new Promise(resolve => setTimeout(resolve, 10))+ }+}++function completionPayload(+ schemaVersion: 'codex-completion-request.v1' | 'codex-completion-request.v2',+ content = 'hi'+): { token: string; body: string } {+ const raw = completionRequest(schemaVersion, content)+ const parsed = parseCodexCompletionRequest(raw)+ if (!parsed.ok) throw new Error(parsed.message)+ const requestHash = hashCodexCompletionRequest(parsed.value)+ return {+ token: platformToken(),+ body: JSON.stringify({+ executionTicket: ticket(requestHash),+ requestHash,+ request: raw,+ }),+ }+}++async function postCompletion(+ port: number,+ schemaVersion: 'codex-completion-request.v1' | 'codex-completion-request.v2',+ content = 'hi'+): Promise<Response> {+ const { token, body } = completionPayload(schemaVersion, content)+ return fetch(`http://127.0.0.1:${port}/internal/runtime/v1/codex/completions`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ },+ body,+ })+}++function postChunked(port: number, token: string): Promise<number> {+ return new Promise((resolve, reject) => {+ const socket = connectTcp(port, '127.0.0.1', () => {+ const chunk = Buffer.from('{}')+ socket.write(+ `POST /internal/runtime/v1/codex/completions HTTP/1.1\r\n` ++ `Host: 127.0.0.1:${port}\r\n` ++ `Authorization: Bearer ${token}\r\n` ++ `Content-Type: application/json\r\n` ++ `Connection: close\r\n` ++ `Transfer-Encoding: chunked\r\n` ++ `\r\n` ++ `${chunk.length.toString(16)}\r\n`+ )+ socket.write(chunk)+ socket.write('\r\n0\r\n\r\n')+ })+ const chunks: Buffer[] = []+ const finish = () => {+ const raw = Buffer.concat(chunks).toString('utf8')+ const match = /^HTTP\/1\.1 (\d+)/.exec(raw)+ if (!match) {+ reject(new Error(`no status in ${raw.slice(0, 180)}`))+ return+ }+ resolve(Number(match[1]))+ }+ socket.setTimeout(2_000, () => {+ socket.destroy()+ finish()+ })+ socket.on('data', data => {+ chunks.push(data)+ if (Buffer.concat(chunks).toString('utf8').includes('\r\n\r\n')) {+ socket.destroy()+ finish()+ }+ })+ socket.on('error', err => {+ if ((err as NodeJS.ErrnoException).code !== 'ECONNRESET') reject(err)+ })+ socket.on('close', finish)+ })+}++describe('visual stream-gate handoff', () => {+ const hangs: Array<{ release: () => void }> = []+ const serversToClose: Array<{ close: () => Promise<void> }> = []+ const listeners: Array<ReturnType<typeof createServer>> = []++ afterEach(async () => {+ for (const hang of hangs.splice(0)) hang.release()+ for (const server of serversToClose.splice(0)) await server.close()+ await Promise.all(+ listeners.splice(0).map(+ listener =>+ new Promise<void>((resolve, reject) =>+ listener.close(err => (err ? reject(err) : resolve()))+ )+ )+ )+ await waitFor(+ () =>+ visualStreamGate.snapshot().running === 0 &&+ visualStreamGate.snapshot().queued === 0 &&+ streamGate.snapshot().running === 0 &&+ streamGate.snapshot().queued === 0,+ 'gates did not drain after release'+ )+ })++ it('keeps small V1 text off the visual gate while large V2 streams hold it', async () => {+ expect(VISUAL_STREAM_LIMITS.maxConcurrentStreams).toBe(2)+ expect(STREAM_LIMITS.maxConcurrentStreams).toBe(8)++ const small = completionPayload('codex-completion-request.v1')+ const maxBodyBytes = Buffer.byteLength(small.body) + 512+ const largeContent = 'x'.repeat(maxBodyBytes)+ const large = completionPayload('codex-completion-request.v2', largeContent)+ expect(Buffer.byteLength(large.body)).toBeGreaterThan(maxBodyBytes)++ const hang = hangStream()+ hangs.push(hang)+ const servers = createProxyApps(config({ maxBodyBytes, maxVisualBodyBytes: 1024 * 1024 }), {+ streamCompletion: hang.impl,+ })+ serversToClose.push(servers)+ const listener = createServer(servers.runtimeApp).listen(0)+ listeners.push(listener)+ const address = listener.address()+ if (!address || typeof address === 'string') throw new Error('listener has no port')+ const port = address.port++ const firstVisual = postCompletion(port, 'codex-completion-request.v2', largeContent)+ const secondVisual = postCompletion(port, 'codex-completion-request.v2', largeContent)+ await waitFor(+ () => visualStreamGate.snapshot().running === 2 && streamGate.snapshot().running === 0,+ 'large V2 did not hold the visual gate'+ )++ const v1 = postCompletion(port, 'codex-completion-request.v1')+ await waitFor(+ () => streamGate.snapshot().running === 1 && visualStreamGate.snapshot().running === 2,+ 'small V1 waited on the visual gate instead of the ordinary stream gate'+ )++ const queued = Array.from({ length: VISUAL_STREAM_LIMITS.maxQueuedRequests }, () =>+ postCompletion(port, 'codex-completion-request.v2', largeContent)+ )+ await waitFor(+ () => visualStreamGate.snapshot().queued === VISUAL_STREAM_LIMITS.maxQueuedRequests,+ 'visual queue did not fill to 8'+ )+ const overflow = await postCompletion(port, 'codex-completion-request.v2', largeContent)+ expect(overflow.status).toBe(503)+ expect(await overflow.json()).toEqual({ error: 'provider_unavailable' })++ const textWhileSaturated = postCompletion(port, 'codex-completion-request.v1')+ await waitFor(+ () => streamGate.snapshot().running === 2 && visualStreamGate.snapshot().running === 2,+ 'a small V1 was rejected or queued behind saturated image streams'+ )++ hang.release()+ await Promise.all([v1, textWhileSaturated, firstVisual, secondVisual, ...queued])+ })++ it('does not queue a chunked platform body behind saturated image streams', async () => {+ const small = completionPayload('codex-completion-request.v1')+ const maxBodyBytes = Buffer.byteLength(small.body) + 512+ const largeContent = 'x'.repeat(maxBodyBytes)+ const hang = hangStream()+ hangs.push(hang)+ const servers = createProxyApps(config({ maxBodyBytes, maxVisualBodyBytes: 1024 * 1024 }), {+ streamCompletion: hang.impl,+ })+ serversToClose.push(servers)+ const listener = createServer(servers.runtimeApp).listen(0)+ listeners.push(listener)+ const address = listener.address()+ if (!address || typeof address === 'string') throw new Error('listener has no port')+ const port = address.port++ const firstVisual = postCompletion(port, 'codex-completion-request.v2', largeContent)+ const secondVisual = postCompletion(port, 'codex-completion-request.v2', largeContent)+ await waitFor(+ () => visualStreamGate.snapshot().running === 2 && visualStreamGate.snapshot().queued === 0,+ 'large V2 did not fill the visual gate'+ )++ const status = await postChunked(port, platformToken())+ expect(status).toBe(400)+ expect(visualStreamGate.snapshot()).toEqual({ running: 2, queued: 0 })++ hang.release()+ await Promise.all([firstVisual, secondVisual])+ })++++ it('rejects a between-cap V1 with 413 and leaves the visual gate empty', async () => {++ const small = completionPayload('codex-completion-request.v1')++ const maxBodyBytes = Buffer.byteLength(small.body) + 512++ const largeContent = 'x'.repeat(maxBodyBytes)++ const large = completionPayload('codex-completion-request.v1', largeContent)++ expect(Buffer.byteLength(large.body)).toBeGreaterThan(maxBodyBytes)++++ const servers = createProxyApps(config({ maxBodyBytes, maxVisualBodyBytes: 1024 * 1024 }))++ serversToClose.push(servers)++ const listener = createServer(servers.runtimeApp).listen(0)++ listeners.push(listener)++ const address = listener.address()++ if (!address || typeof address === 'string') throw new Error('listener has no port')++ const port = address.port++++ const response = await fetch(`http://127.0.0.1:${port}/internal/runtime/v1/codex/completions`, {++ method: 'POST',++ headers: {++ Authorization: `Bearer ${large.token}`,++ 'content-type': 'application/json',++ },++ body: large.body,++ })++ expect(response.status).toBe(413)++ expect(await response.json()).toEqual({ error: 'payload_too_large' })++ expect(visualStreamGate.snapshot()).toEqual({ running: 0, queued: 0 })++ expect(streamGate.snapshot()).toEqual({ running: 0, queued: 0 })++ })++++ it('releases the visual slot for a whitespace-padded small V2', async () => {++ const small = completionPayload('codex-completion-request.v2')++ const maxBodyBytes = Buffer.byteLength(small.body) + 64++ const padded = `${small.body}${' '.repeat(maxBodyBytes - Buffer.byteLength(small.body) + 1)}`++ expect(Buffer.byteLength(padded)).toBeGreaterThan(maxBodyBytes)++++ const hang = hangStream()++ hangs.push(hang)++ const servers = createProxyApps(config({ maxBodyBytes, maxVisualBodyBytes: 1024 * 1024 }), {++ streamCompletion: hang.impl,++ })++ serversToClose.push(servers)++ const listener = createServer(servers.runtimeApp).listen(0)++ listeners.push(listener)++ const address = listener.address()++ if (!address || typeof address === 'string') throw new Error('listener has no port')++ const port = address.port++++ const response = fetch(`http://127.0.0.1:${port}/internal/runtime/v1/codex/completions`, {++ method: 'POST',++ headers: {++ Authorization: `Bearer ${small.token}`,++ 'content-type': 'application/json',++ },++ body: padded,++ })++ await waitFor(++ () => streamGate.snapshot().running === 1 && visualStreamGate.snapshot().running === 0,++ 'padded small V2 kept the visual slot instead of the ordinary stream gate'++ )++ hang.release()++ await response++ })+})diff --cc control-api/test/services.llmProviderAttemptAuthorizer.test.tsindex 49a5b9ccc,bf5a2f531..a0a84d9ca--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts@@@ -598,153 -225,6 +598,153 @@@ describe('authorizeLlmProviderAttempt').rejects.toMatchObject({ code: 'unknown_field' })})+ it('rejects a V2 authorize wrapper whose invocationId is not a bounded id', async () => {+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: { ...REQUEST, schemaVersion: 'codex-completion-request.v2' },+ invocationId: 'x'.repeat(200),+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'invalid_request' })+ expect(current.insertAttempt).not.toHaveBeenCalled()+ })++ it('maps a contract size limit to payload_too_large', async () => {+ const oversizeBase64 = 'A'.repeat(4 * Math.ceil(VISUAL_LIMITS.maxImageBytes / 3) + 4)+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: {+ ...REQUEST,+ schemaVersion: 'codex-completion-request.v2',+ messages: [+ {+ role: 'user' as const,+ content: 'look',+ contentParts: [+ { type: 'text' as const, text: 'look' },+ {+ type: 'image' as const,+ mimeType: 'image/png',+ data: oversizeBase64,+ source: {+ kind: 'attachment' as const,+ attachmentId: 'att_1',+ messageId: 'msg-1',+ },+ },+ ],+ },+ ],+ },+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'payload_too_large' })+ expect(current.insertAttempt).not.toHaveBeenCalled()+ }, 30_000)++ it('maps a contract count limit to invalid_request, not payload_too_large', async () => {+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: {+ ...REQUEST,+ schemaVersion: 'codex-completion-request.v2',- messages: Array.from({ length: 129 }, () => ({ role: 'user' as const, content: 'x' })),++ messages: Array.from({ length: 1025 }, () => ({ role: 'user' as const, content: 'x' })),+ },+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'invalid_request' })+ expect(current.insertAttempt).not.toHaveBeenCalled()+ })++ it('maps a contract range limit to invalid_request, not payload_too_large', async () => {+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: {+ ...REQUEST,+ schemaVersion: 'codex-completion-request.v2',+ generation: { maxOutputTokens: 99_999 },+ },+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'invalid_request' })+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: {+ ...REQUEST,+ schemaVersion: 'codex-completion-request.v2',+ deadlineMs: LIMITS.maxDeadlineMs + 1,+ },+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'invalid_request' })+ expect(current.insertAttempt).not.toHaveBeenCalled()+ })++ it('keeps the authorize wrapper on the 1 MiB non-image budget when the nested request is V2', async () => {+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: { ...REQUEST, schemaVersion: 'codex-completion-request.v2' },+ targetRef: 't'.repeat(2 * MIB),+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'payload_too_large' })+ expect(current.insertAttempt).not.toHaveBeenCalled()+ })++ it('maps an over-dimension image to payload_too_large', async () => {+ const current = deps()+ await expect(+ authorizeLlmProviderAttempt(+ claims(),+ body({+ request: {+ ...REQUEST,+ schemaVersion: 'codex-completion-request.v2',+ messages: [+ {+ role: 'user' as const,+ content: 'look',+ contentParts: [+ { type: 'text' as const, text: 'look' },+ {+ type: 'image' as const,+ mimeType: 'image/png',+ data: declaredHeaderPng(3000, 3000).toString('base64'),+ source: {+ kind: 'attachment' as const,+ attachmentId: 'att_1',+ messageId: 'msg-1',+ },+ },+ ],+ },+ ],+ },+ }),+ current+ )+ ).rejects.toMatchObject({ code: 'payload_too_large' })+ expect(current.insertAttempt).not.toHaveBeenCalled()+ })+it('rejects a non-UUID Plugin Workload SDK attempt id', async () => {await expect(authorizeLlmProviderAttempt(diff --cc control-api/vitest.config.tsindex 7252a8c6b,3db0f4243..eb9bc2a77--- a/control-api/vitest.config.ts+++ b/control-api/vitest.config.ts@@@ -1,24 -1,12 +1,27 @@@import { defineConfig } from 'vitest/config'+import { createRequire } from 'node:module'++const require = createRequire(import.meta.url)export default defineConfig({+ resolve: {+ // The image authorization integration imports the real Host and proxy+ // sources. CI installs this package alone; resolve their shared runtime+ // imports from Control API's declared dependencies, without requiring+ // unrelated sibling node_modules or replacing the implementation.+ alias: Object.fromEntries(+ ['@clerum/llm-provider-attempt-contract', '@clerum/llm-providers', 'pino'].map(name => [+ name,+ require.resolve(name),+ ])+ ),+ },test: {environment: 'node',- setupFiles: ['test/realPostgres.requirement.ts'],+ setupFiles: [+ '../scripts/testing/bind-loopback-in-tests.mjs',+ 'test/realPostgres.requirement.ts',+ ],// Control API route suites mock shared modules, env-backed config, and// Supertest apps. Running files in parallel can leak those process-level// fixtures across workers and produce nondeterministic HTTP parse failures.diff --cc external-rest-api/src/releaseManifest.tsindex 98d96df23,f32097a49..80e1287f3--- a/external-rest-api/src/releaseManifest.ts+++ b/external-rest-api/src/releaseManifest.ts@@@ -8,8 -8,8 +8,8 @@@ export type ReleaseManifest =export const releaseManifest: ReleaseManifest = {releaseId: 'v0.9.0',- externalRestApiVersion: '0.1.82',- rpcProxyVersion: '0.1.87',+ externalRestApiVersion: '0.1.84',- rpcProxyVersion: '0.1.84',++ rpcProxyVersion: '0.1.88',desktopVersion: '0.9.0',minimumDesktopVersion: '0.1.252',}diff --cc mcp-host/src/config/__tests__/modelResolution.test.tsindex 799952c56,e1e60d925..7f3461147--- a/mcp-host/src/config/__tests__/modelResolution.test.ts+++ b/mcp-host/src/config/__tests__/modelResolution.test.ts@@@ -97,24 -97,7 +97,36 @@@ describe('projectModels', () =>])expect(projectModels(catalog, 'codex-subscription', 'visual-model').models[0].imageInput- ).toEqual({ state: 'unsupported', reason: 'transport_unsupported', evidence })+ ).toEqual({ state: 'supported', reason: 'supported', evidence })+ })++ it('projects a live ChatGPT Codex row with no imageInput as supported', () => {+ expect(+ projectModels(+ view(true, { 'codex-subscription': [{ model: 'gpt-5.6-luna' }] }),+ 'codex-subscription',+ 'gpt-5.6-luna'+ ).models[0].imageInput+ ).toEqual({ state: 'supported', reason: 'supported' })+ })+++ it('does not upgrade a Codex row whose imageInput failed to parse', () => {++ expect(++ projectModels(++ view(true, {++ 'codex-subscription': [{ model: 'gpt-5.3-codex', imageInput: { state: 'unknown' } }],++ }),++ 'codex-subscription',++ 'gpt-5.3-codex'++ ).models[0].imageInput++ ).toEqual({ state: 'unknown', reason: 'model_unknown' })++ })+++ it('keeps a live OpenAI row with no imageInput unknown', () => {+ expect(+ projectModels(view(true, { openai: [{ model: 'gpt-6' }] }), 'openai', 'gpt-6').models[0]+ .imageInput+ ).toEqual({ state: 'unknown', reason: 'model_unknown' })})it('projects enabled entries with optional metadata', () => {expect(projectModels(view(true, CLAUDE_ALLOWLIST), 'claude', 'claude-opus-4-8')).toEqual({diff --cc mcp-host/src/config/configStore.test.tsindex bd5f3fd8b,bd5f3fd8b..79393e0df--- a/mcp-host/src/config/configStore.test.ts+++ b/mcp-host/src/config/configStore.test.ts@@@ -611,16 -611,16 +611,13 @@@ describe('ConfigStore — allowlist tieexpect(store.allowlistAvailable()).toBe(true)expect(store.allowedModels().get('openai')).toEqual([{-- imageInput: { state: 'unknown' },model: 'gpt-5.4',displayName: 'GPT 5.4',contextWindowTokens: 400000,vendor: 'OpenAI',},])-- expect(store.allowedModels().get('claude')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'claude-opus-4-8' },-- ])++ expect(store.allowedModels().get('claude')).toEqual([{ model: 'claude-opus-4-8' }])expect(store.codexPolicyBinding()).toBeNull()})@@@ -685,9 -685,9 +682,7 @@@store.onChange(handler)await store.start()-- expect(store.allowedModels().get('openai')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'gpt-5.4' },-- ])++ expect(store.allowedModels().get('openai')).toEqual([{ model: 'gpt-5.4' }])const handle = built.watch.active.get(ALLOWLIST_WATCH_KEY)expect(handle).toBeDefined()@@@ -696,10 -696,10 +691,7 @@@data: { openai: JSON.stringify([{ model: 'gpt-5.4' }, { model: 'gpt-6' }]) },})-- expect(store.allowedModels().get('openai')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'gpt-5.4' },-- { imageInput: { state: 'unknown' }, model: 'gpt-6' },-- ])++ expect(store.allowedModels().get('openai')).toEqual([{ model: 'gpt-5.4' }, { model: 'gpt-6' }])expect(handler).toHaveBeenCalledWith({llmKeyChanged: false,envChanged: false,@@@ -804,9 -804,9 +796,7 @@@// The CM is delivered (available), but the bad key is dropped.expect(store.allowlistAvailable()).toBe(true)expect(store.allowedModels().has('openai')).toBe(false)-- expect(store.allowedModels().get('claude')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'claude-opus-4-8' },-- ])++ expect(store.allowedModels().get('claude')).toEqual([{ model: 'claude-opus-4-8' }])// The corrupt-key event logs the key at ERROR but never the raw value.const logged = JSON.stringify(errorSpy.mock.calls)@@@ -833,9 -833,9 +823,7 @@@store = built.storeawait store.start()-- expect(store.allowedModels().get('openai')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'gpt-5.4' },-- ])++ expect(store.allowedModels().get('openai')).toEqual([{ model: 'gpt-5.4' }])// Non-array value for a key is skipped entirely.expect(store.allowedModels().has('zai')).toBe(false)})@@@ -901,9 -901,9 +889,7 @@@})store = built.storeawait store.start()-- expect(store.allowedModels().get('codex-subscription')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'gpt-5.1' },-- ])++ expect(store.allowedModels().get('codex-subscription')).toEqual([{ model: 'gpt-5.1' }])expect(store.codexPolicyBinding()?.connectionKey).toBe('personal-pro')expect(store.codexPolicyBinding()?.models).toEqual(['gpt-5.1'])})@@@ -952,9 -952,9 +938,7 @@@// fail-closed `unknown` decision on it like every other entry (#654). The point// of this assertion is the intersection with the connection's `models`, which// drops `grok-4.5`.-- expect(store.allowedModels().get('grok-subscription')).toEqual([-- { model: 'grok-4.6', imageInput: { state: 'unknown' } },-- ])++ expect(store.allowedModels().get('grok-subscription')).toEqual([{ model: 'grok-4.6' }])expect(store.codexPolicyBinding()?.catalogRevision).toBe(99)})@@@ -1042,8 -1042,8 +1026,8 @@@expect(store.codexPolicyBinding()?.connectionKey).toBe('deployment-default')expect(store.codexPolicyBinding()?.models).toBeUndefined()expect(store.allowedModels().get('codex-subscription')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'gpt-5.3-codex' },-- { imageInput: { state: 'unknown' }, model: 'gpt-5.1' },++ { model: 'gpt-5.3-codex' },++ { model: 'gpt-5.1' },])})@@@ -1070,8 -1070,8 +1054,8 @@@expect(store.codexPolicyBinding()?.connectionKey).toBe('personal-pro')expect(store.codexPolicyBinding()?.models).toBeUndefined()expect(store.allowedModels().get('codex-subscription')).toEqual([-- { imageInput: { state: 'unknown' }, model: 'gpt-5.3-codex' },-- { imageInput: { state: 'unknown' }, model: 'gpt-5.1' },++ { model: 'gpt-5.3-codex' },++ { model: 'gpt-5.1' },])})diff --cc mcp-host/src/config/configStore.tsindex 3c859caa5,3c859caa5..7f18dc5e9--- a/mcp-host/src/config/configStore.ts+++ b/mcp-host/src/config/configStore.ts@@@ -639,20 -639,20 +639,22 @@@ export class ConfigStorecontinue}const entry: AllowedModelEntry = { model: rec.model }-- // An absent imageInput is a row nobody curated; a present one that does-- // not parse is corrupt data. Both fail closed to `unknown`, but only the-- // second is logged — without the value, which is ConfigMap content.-- const parsedImageInput =-- rec.imageInput === undefined-- ? { state: 'unknown' as const }-- : parseImageInputCapability(rec.imageInput)-- if (parsedImageInput === null) {-- logger.error(-- { provider, model: rec.model },-- 'Allowlist entry has malformed imageInput; treating it as unknown'-- )++ // An absent imageInput is a live uncurated row — leave the field unset++ // so Codex can project supported. A present value that does not parse++ // is corrupt: store unknown (and log, without the value) so the Codex++ // override cannot treat it as an omitted catalog row.++ if (rec.imageInput !== undefined) {++ const parsedImageInput = parseImageInputCapability(rec.imageInput)++ if (parsedImageInput === null) {++ logger.error(++ { provider, model: rec.model },++ 'Allowlist entry has malformed imageInput; treating it as unknown'++ )++ entry.imageInput = { state: 'unknown' }++ } else {++ entry.imageInput = parsedImageInput++ }}-- entry.imageInput = parsedImageInput ?? { state: 'unknown' }if (typeof rec.displayName === 'string') entry.displayName = rec.displayName// Optional, operator-declared: accept only a positive integer; drop// NaN/Infinity/negatives silently (it is metadata, not part of thediff --cc mcp-host/src/llm/__tests__/codexLlmProxyClient.test.tsindex d97ac8f0c,f292d3b8a..9fa3a9b52--- a/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts+++ b/mcp-host/src/llm/__tests__/codexLlmProxyClient.test.ts@@@ -1,10 -1,12 +1,17 @@@import { describe, expect, it, vi } from 'vitest'+import {+ buildCodexProxyEnvelope,+ hashCodexCompletionRequest,+ parseCodexCompletionRequest,+} from '@clerum/llm-provider-attempt-contract'- import { CodexLlmProxyClient, resolveCodexProxyRuntimeUrl } from '../codexLlmProxyClient'+ import { LlmErrorCode } from '../../core/errors'+ import {+ CodexLlmProxyClient,+ CodexProxyError,+ resolveCodexProxyRuntimeUrl,+ } from '../codexLlmProxyClient'+ import { CodexSubscriptionProvider } from '../codexSubscription'+ import { classifyFailoverClass } from '../failover/classify'function sse(frames: unknown[]): ReadableStream<Uint8Array> {const encoder = new TextEncoder()diff --cc mcp-host/src/llm/__tests__/codexSubscription.test.tsindex 045bbaf18,c12a9b97f..f96cc29a1--- a/mcp-host/src/llm/__tests__/codexSubscription.test.ts+++ b/mcp-host/src/llm/__tests__/codexSubscription.test.ts@@@ -1,9 -1,4 +1,10 @@@import { describe, expect, it, vi } from 'vitest'++import { createRequire } from 'node:module'+import {+ VISUAL_LIMITS,+ hashCodexCompletionRequest,+ parseCodexCompletionRequest,+} from '@clerum/llm-provider-attempt-contract'import {buildToolDescribeResponse,buildToolSearchResponse,@@@ -11,17 -6,16 +12,22 @@@createToolDescribeTool,createToolSearchTool,} from '../../capabilities/toolCatalogTools'- import { LlmErrorCode } from '../../core/errors'+ import { LlmPortAdapter } from '../../core/adapters/llmPortAdapter'+ import { LlmError, LlmErrorCode } from '../../core/errors'import { DeferrableToolController } from '../../core/orchestration/deferrableToolController'import { DefaultLoopController } from '../../core/orchestration/loopConfig'+import type { ChatMessage } from '../../core/types'import { CodexProxyError } from '../codexLlmProxyClient'import { CodexSubscriptionProvider } from '../codexSubscription'import { classifyFailoverClass } from '../failover/classify'import { CodexAuthorizeError } from '../providerAttemptAuthorizer'import { makeProvider } from '../registry'+import { JPEG_2X2_BASE64, PNG_2X2_BASE64 } from './codexImageFixtures'+++const { declaredHeaderPng } = createRequire(import.meta.url)(++ '../../../../packages/llm-provider-attempt-contract/testImageFixtures.cjs'++) as { declaredHeaderPng: (width: number, height: number) => Buffer }+const requestHash = 'a'.repeat(64)function deps(overrides?: {@@@ -471,223 -567,4 +579,237 @@@ describe('CodexSubscriptionProvider', (await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])expect(wired.authorize).toHaveBeenNthCalledWith(2, expect.any(Object), {})})++ // ─── #650: image input projection ─────────────────────────────────────────++ const METHODS = ['completeSingleTurn', 'completeSingleTurnWithTools'] as const+ type Method = (typeof METHODS)[number]++ function invoke(+ provider: CodexSubscriptionProvider,+ method: Method,+ messages: ChatMessage[]+ ): Promise<unknown> {+ const tools = [{ name: 'echo', description: 'echo', parameters: { type: 'object' } }]+ return method === 'completeSingleTurn'+ ? provider.completeSingleTurn(messages)+ : provider.completeSingleTurnWithTools(messages, tools)+ }++ function userWithImage(+ data = PNG_2X2_BASE64,+ mimeType: 'image/png' | 'image/jpeg' = 'image/png'+ ): ChatMessage[] {+ return [+ {+ role: 'user',+ content: 'what is on screen?',+ contentParts: [+ { type: 'text', text: 'what is on screen?' },+ {+ type: 'image',+ mimeType,+ data,+ source: { kind: 'attachment', attachmentId: 'att-1', messageId: 'msg-1' },+ },+ ],+ },+ ]+ }++ it.each(METHODS)('sends a real PNG as a V2 part through %s', async method => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await invoke(provider, method, userWithImage())++ const authorized = wired.authorize.mock.calls[0][0]+ expect(authorized.request.schemaVersion).toBe('codex-completion-request.v2')+ expect(authorized.request.messages[0]).toEqual({+ role: 'user',+ content: 'what is on screen?',+ contentParts: [+ { type: 'text', text: 'what is on screen?' },+ {+ type: 'image',+ mimeType: 'image/png',+ data: PNG_2X2_BASE64,+ source: { kind: 'attachment', attachmentId: 'att-1', messageId: 'msg-1' },+ },+ ],+ })+ // The authorized hash and the dispatched request are the same canonical+ // projection the proxy and control-api re-derive from these bytes.+ const parsed = parseCodexCompletionRequest(authorized.request)+ expect(parsed.ok).toBe(true)+ if (parsed.ok) {+ expect(authorized.requestHash).toBe(hashCodexCompletionRequest(parsed.value))+ }+ expect(wired.stream.mock.calls[0][0].request).toEqual(authorized.request)+ })++ it('accepts a JPEG part on the default Codex visual path', async () => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await provider.completeSingleTurn(userWithImage(JPEG_2X2_BASE64, 'image/jpeg'))++ const parts = wired.authorize.mock.calls[0][0].request.messages[0].contentParts+ expect(parts[1]).toEqual(+ expect.objectContaining({ mimeType: 'image/jpeg', data: JPEG_2X2_BASE64 })+ )+ })++ it.each(METHODS)('authorizes an image through %s without a capability gate', async method => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await invoke(provider, method, userWithImage())+ expect(wired.authorize).toHaveBeenCalledOnce()+ expect(wired.stream).toHaveBeenCalledOnce()+ })++ it('classifies a missing image source as terminal with no fallback', () => {+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', deps() as never)+ const classified = provider.classifyError(+ new CodexAuthorizeError('image_source_invalid', 'image part has no usable provenance source')+ )+ expect(classified.code).toBe(LlmErrorCode.ApiCallFailed)+ expect(classified.retryable).toBe(false)+ expect(classified.providerDispatched).toBe(false)+ expect(classifyFailoverClass(classified.code, classified.retryable)).toBeNull()+ })++ it.each(METHODS)('rejects an image part without provenance through %s', async method => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)+ const messages = userWithImage()+ messages[0].contentParts = [+ { type: 'text', text: 'what is on screen?' },+ { type: 'image', mimeType: 'image/png', data: PNG_2X2_BASE64 },+ ]++ await expect(invoke(provider, method, messages)).rejects.toMatchObject({+ name: 'CodexAuthorizeError',+ code: 'image_source_invalid',+ })+ expect(wired.authorize).not.toHaveBeenCalled()+ expect(wired.stream).not.toHaveBeenCalled()+ })++ it('rejects parts on a non-user message instead of dropping them', async () => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await expect(+ provider.completeSingleTurn([+ { role: 'user', content: 'hi' },+ {+ role: 'assistant',+ content: 'look',+ contentParts: [{ type: 'text', text: 'look' }],+ },+ ])+ ).rejects.toMatchObject({ name: 'CodexAuthorizeError', code: 'invalid_request' })+ expect(wired.authorize).not.toHaveBeenCalled()+ })++ it('keeps a redacted text-only message on V2 without requiring image input', async () => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)+ const messages = userWithImage()+ // What pre-prune leaves behind: the image became a text part and `content`+ // is restated from the parts.+ messages[0].contentParts = [+ { type: 'text', text: 'what is on screen?' },+ { type: 'text', text: '[image redacted — see turn 1]' },+ ]+ messages[0].content = 'what is on screen?\n[image redacted — see turn 1]'++ await provider.completeSingleTurn(messages)++ const authorized = wired.authorize.mock.calls[0][0]+ expect(authorized.request.schemaVersion).toBe('codex-completion-request.v2')+ expect(authorized.request.messages[0].content).toBe(messages[0].content)+ expect(parseCodexCompletionRequest(authorized.request).ok).toBe(true)+ })++ it('restates content from the parts when the caller left them out of sync', async () => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)+ const messages = userWithImage()+ // A stale `content` must never reach the wire as a contradiction of its own+ // parts: V2 rejects the request outright, so the projection rebuilds it.+ messages[0].content = 'stale text that no part carries'++ await provider.completeSingleTurn(messages)++ expect(wired.authorize.mock.calls[0][0].request.messages[0].content).toBe('what is on screen?')+ })++ it.each(METHODS)(+ 'rejects a signature-only image stub through %s before authorize',+ async method => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await expect(+ invoke(provider, method, userWithImage('iVBORw0KGgo=', 'image/png'))+ ).rejects.toMatchObject({ name: 'CodexAuthorizeError', code: 'invalid_request' })+ expect(wired.authorize).not.toHaveBeenCalled()+ expect(wired.stream).not.toHaveBeenCalled()+ }+ )+++ it('maps an over-dimension image to payload_too_large before authorize', async () => {++ const wired = deps()++ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await expect(++ provider.completeSingleTurn(userWithImage(declaredHeaderPng(3000, 3000).toString('base64')))++ ).rejects.toMatchObject({++ name: 'CodexAuthorizeError',++ code: 'payload_too_large',++ message: expect.stringMatching(/image dimension exceeds 2048/),++ })++ expect(wired.authorize).not.toHaveBeenCalled()++ expect(wired.stream).not.toHaveBeenCalled()++ })+++ it('rejects an over-limit image batch through the shared contract, not a local copy', async () => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)+ const messages = userWithImage()+ messages[0].contentParts = [+ { type: 'text', text: 'what is on screen?' },+ ...Array.from({ length: VISUAL_LIMITS.maxImages + 1 }, (_, index) => ({+ type: 'image' as const,+ mimeType: 'image/png' as const,+ data: PNG_2X2_BASE64,+ source: {+ kind: 'attachment' as const,+ attachmentId: `att-${index}`,+ messageId: 'msg-1',+ },+ })),+ ]++ await expect(provider.completeSingleTurn(messages)).rejects.toMatchObject({+ name: 'CodexAuthorizeError',+ code: 'invalid_request',+ message: expect.stringMatching(new RegExp(`${VISUAL_LIMITS.maxImages} images`)),+ })+ expect(wired.authorize).not.toHaveBeenCalled()+ })++ it('keeps a text-only turn on the unchanged V1 request', async () => {+ const wired = deps()+ const provider = new CodexSubscriptionProvider('gpt-5.6-luna', wired as never)++ await provider.completeSingleTurn([{ role: 'user', content: 'hi' }])++ const request = wired.authorize.mock.calls[0][0].request+ expect(request.schemaVersion).toBe('codex-completion-request.v1')+ expect(request.messages).toEqual([{ role: 'user', content: 'hi' }])+ expect(JSON.stringify(request)).not.toContain('contentParts')+ })})diff --cc mcp-host/src/llm/__tests__/imageInput.test.tsindex b1d33aeb5,e914e9b33..dab4ba3a4--- a/mcp-host/src/llm/__tests__/imageInput.test.ts+++ b/mcp-host/src/llm/__tests__/imageInput.test.ts@@@ -259,64 -251,6 +259,83 @@@ describe('#654 decideImageInput interse).toEqual({ state: 'supported', reason: 'supported', evidence: supported.evidence })})+ it('treats a live Codex catalog row with no imageInput as supported', () => {+ expect(+ decideImageInput({+ providerType: 'codex-subscription',+ method: 'completeWithTools',+ roles: ['user'],+ capability: undefined,+ })+ ).toEqual({ state: 'supported', reason: 'supported' })+ })+++ it('does not upgrade a stored unknown or unparseable Codex imageInput', () => {++ expect(++ decideImageInput({++ providerType: 'codex-subscription',++ method: 'completeWithTools',++ roles: ['user'],++ capability: { state: 'unknown' },++ })++ ).toEqual({ state: 'unknown', reason: 'model_unknown' })++ expect(++ decideImageInput({++ providerType: 'codex-subscription',++ method: 'completeWithTools',++ roles: ['user'],++ capability: { state: 'unsupported' },++ })++ ).toEqual({ state: 'unknown', reason: 'model_unknown' })++ })+++ it('does not upgrade curated-unsupported or expired Codex evidence', () => {+ const unsupported = {+ state: 'unsupported' as const,+ evidence: {+ source: 'curated' as const,+ reference: 'evidence:codex-text-only',+ checkedAt: '2026-09-16T00:00:00Z',+ },+ }+ expect(+ decideImageInput({+ providerType: 'codex-subscription',+ method: 'completeWithTools',+ roles: ['user'],+ capability: unsupported,+ })+ ).toEqual({+ state: 'unsupported',+ reason: 'model_unsupported',+ evidence: unsupported.evidence,+ })++ const expired = {+ state: 'supported' as const,+ evidence: {+ source: 'curated' as const,+ reference: 'evidence:codex',+ checkedAt: '2026-09-01T00:00:00Z',+ validUntil: '2026-10-01T00:00:00.000Z',+ },+ }+ expect(+ decideImageInput({+ providerType: 'codex-subscription',+ method: 'completeWithTools',+ roles: ['user'],+ capability: expired,+ now: Date.parse('2026-10-02T00:00:00Z'),+ })+ ).toEqual({+ state: 'unknown',+ reason: 'evidence_expired',+ validUntil: '2026-10-01T00:00:00.000Z',+ evidence: expired.evidence,+ })+ })+it('treats absent or malformed evidence as unknown, never as support', () => {for (const capability of [undefined, null, {}, { state: 'maybe' }, { state: 'supported' }]) {expect(diff --cc mcp-host/src/llm/codexSubscription.tsindex db2352d64,77438a20f..59c604efe--- a/mcp-host/src/llm/codexSubscription.ts+++ b/mcp-host/src/llm/codexSubscription.ts@@@ -324,13 -294,9 +358,13 @@@ export class CodexSubscriptionProvider// requestHash mismatch. An invalid request never leaves the process.const canonical = hashCanonicalCodexRequest(this.buildRequest(messages, tools, options))if (!canonical.ok) {- throw new CodexAuthorizeError('invalid_request', canonical.message)+ throw new CodexAuthorizeError(- CODEX_REQUEST_INVALID,++ canonical.kind === 'size' ? 'payload_too_large' : CODEX_REQUEST_INVALID,+ `codex completion request rejected: ${canonical.message}`+ )}- const { request, requestHash } = canonical.value+ const wireRequest = canonical.value.request+ const requestHash = canonical.value.requestHashconst context = this.deps.attemptContext({ model: this.model })if (!Number.isInteger(context.policyRevision) ||diff --cc mcp-host/src/llm/imageInput.tsindex 007ab0103,a648c04d9..fb5cd9fa4--- a/mcp-host/src/llm/imageInput.ts+++ b/mcp-host/src/llm/imageInput.ts@@@ -235,34 -233,6 +235,37 @@@ export interface ImageInputRequestFact* implementation ∩ message role. Delegates the evidence half to the shared* resolver so both sides cannot drift.*/+/**+ * Host intersection for one (provider, capability) pair.+ *+ * #669 keeps absence → `unknown` for every non-Codex provider. Codex+ * 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. Curated `unsupported` / dated evidence still- * wins. Never invent models.dev rows.++ * 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.+ */+export function resolveHostImageInput(+ providerType: string,+ capability: unknown,+ options: { transportSupported: boolean; now?: number }+): ImageInputDecision {+ const decision = resolveImageInputCapability(capability, options)+ if (+ imageWireFamilyFor(providerType) === 'codex' &&+ options.transportSupported === true &&++ capability === undefined &&+ decision.state === 'unknown' &&+ decision.reason === 'model_unknown' &&+ decision.evidence === undefined+ ) {+ return { state: 'supported', reason: 'supported' }+ }+ return decision+}+export function decideImageInput(facts: ImageInputRequestFacts): ImageInputDecision {const transportSupported =facts.roles.length > 0 &&diff --cc packages/llm-provider-attempt-contract/index.cjsindex 356a814fa,99ece4f0c..6cb63f6b8--- a/packages/llm-provider-attempt-contract/index.cjs+++ b/packages/llm-provider-attempt-contract/index.cjs@@@ -16,24 -13,12 +16,26 @@@ const PROVIDER_ID = 'codex-subscriptionconst TICKET_TYP = 'codex-execution-ticket'const LIMITS = Object.freeze({+ // V1 ceiling, and the V2 ceiling for everything that is not image data. The+ // measurement that enforces the second half lives in+ // `measureNonImageRequestBytes` below.maxRequestBodyBytes: 1048576,+ /**+ * V2 request/envelope ceiling. It is deliberately larger than+ * `maxRequestBodyBytes` because a V2 body carries base64 image payloads, and+ * it is deliberately larger than one hard-ceiling image (16 MiB decoded ≈+ * 21.3 MiB encoded) plus the 1 MiB non-image share. Typical 5 / 9 requests+ * fit in 14 MiB (`VISUAL_LIMITS.typicalEnvelopeBytes`); this 24 MiB number is+ * the HTTP/nginx hard envelope, not the usual product target. It is not a+ * text/tool allowance: `measureNonImageRequestBytes` keeps that share on the+ * V1 ceiling.+ */+ maxVisualRequestBodyBytes: 25165824,- maxMessages: 128,+ maxMessages: 1024,// Bound calls in each assistant message independently of advertised definitions.- maxToolCalls: 32,+ // A turn of N calls adds N+1 messages, so N stays <= maxMessages/4. At this+ // bound maxOutputTokens leaves 64 output tokens per call in one response.+ maxToolCalls: 256,maxOutputTokens: 16384,maxDeadlineMs: 300000,maxIdLength: 128,diff --cc packages/llm-provider-attempt-contract/index.d.tsindex f1c4edc80,4e9958325..635198355--- a/packages/llm-provider-attempt-contract/index.d.ts+++ b/packages/llm-provider-attempt-contract/index.d.ts@@@ -27,12 -14,9 +27,12 @@@ export declare const PROVIDER_ID: 'codeexport declare const TICKET_TYP: 'codex-execution-ticket'export declare const LIMITS: {+ /** V1 ceiling, and the V2 ceiling for everything that is not image data. */readonly maxRequestBodyBytes: 1048576+ /** V2 request/envelope ceiling; covers image payloads plus the V1 share. */+ readonly maxVisualRequestBodyBytes: 25165824- readonly maxMessages: 128- readonly maxToolCalls: 32+ readonly maxMessages: 1024+ readonly maxToolCalls: 256readonly maxOutputTokens: 16384readonly maxDeadlineMs: 300000readonly maxIdLength: 128diff --cc packages/llm-provider-attempt-contract/index.test.cjsindex 4f3887dbb,0ee11559b..de359d7d0--- a/packages/llm-provider-attempt-contract/index.test.cjs+++ b/packages/llm-provider-attempt-contract/index.test.cjs@@@ -319,20 -281,24 +319,32 @@@ test('tool definition count never widenconst parsed = contract.parseCodexCompletionRequestV1({...BASE,tools: catalog(250),- messages: [{ role: 'assistant', content: '', toolCalls: Array.from({ length: count }, (_, index) => ({- id: `call-${index}`, name: `eventasks__read_${index}`, arguments: {},- })) }],+ messages: [+ {+ role: 'assistant',+ content: '',+ toolCalls: Array.from({ length: count }, (_, index) => ({+ id: `call-${index}`,+ name: `eventasks__read_${index}`,+ arguments: {},+ })),+ },+ ],})- assert.equal(parsed.ok, count === 32)- if (!parsed.ok) assert.equal(parsed.message, 'messages[0].toolCalls exceed 32')+ assert.equal(parsed.ok, count === 256)+ if (!parsed.ok) assert.equal(parsed.message, 'messages[0].toolCalls exceed 256')+ }+ })++ test('message count is bounded at maxMessages', () => {+ assert.equal(contract.LIMITS.maxMessages, 1024)+ for (const count of [1024, 1025]) {+ const parsed = contract.parseCodexCompletionRequestV1({+ ...BASE,+ messages: Array.from({ length: count }, (_, index) => ({ role: 'user', content: `m${index}` })),+ })+ assert.equal(parsed.ok, count === 1024)+ if (!parsed.ok) assert.equal(parsed.message, 'messages exceed 1024')}})diff --cc rpc-proxy/package-lock.jsonindex 72e061899,b9042e3d9..cb55f1410--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-rpc-proxy",- "version": "0.1.87",- "version": "0.1.84",++ "version": "0.1.88","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.87",- "version": "0.1.84",++ "version": "0.1.88","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --cc rpc-proxy/package.jsonindex 9cf066f20,dd8684b18..72501d0a6--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-rpc-proxy",- "version": "0.1.87",- "version": "0.1.84",++ "version": "0.1.88","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --cc tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.jsonindex 1b82ea96d,2a0339ba4..03c3997e4--- a/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json+++ b/tests/e2e/fixtures/codex-subscription/sanitized-upstream-contract.json@@@ -41,9 -41,8 +41,9 @@@"oauthScopes": ["openid", "profile", "email", "offline_access"],"limits": {"maxRequestBodyBytes": 1048576,+ "maxVisualRequestBodyBytes": 25165824,- "maxMessages": 128,- "maxToolCalls": 32,+ "maxMessages": 1024,+ "maxToolCalls": 256,"maxOutputTokens": 16384,"maxStreamDurationMs": 300000,"maxDeadlineMs": 300000,@@@ -62,8 -61,7 +62,9 @@@"ticket_invalid","ticket_replayed","request_hash_mismatch",+ "image_source_invalid",- "payload_too_large"++ "payload_too_large",+ "tool_call_limit_exceeded"],"termsAndTestAccount": {"automationAuthorized": true,diff --cc tests/e2e/fixtures/package-lock.jsonindex 27ae31092,17b402c80..0710b38c1--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.87",- "version": "1.0.86",++ "version": "1.0.88","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.87",- "version": "1.0.86",++ "version": "1.0.88","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --cc tests/e2e/fixtures/package.jsonindex 1835ae0ad,a38efcff1..1e7319e6d--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.87",- "version": "1.0.86",++ "version": "1.0.88","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",diff --cc tests/e2e/integration/codex-subscription-contract-freeze.test.tsindex 51df77e87,a73e8e208..c975fb76b--- a/tests/e2e/integration/codex-subscription-contract-freeze.test.ts+++ b/tests/e2e/integration/codex-subscription-contract-freeze.test.ts@@@ -207,9 -154,9 +207,10 @@@ describe('codex-subscription contract f}expect(limits).not.toHaveProperty('maxTools')- expect(limits?.maxToolCalls).toBe(32)+ expect(limits?.maxToolCalls).toBe(256)+ expect(limits?.maxMessages).toBe(1024)expect(limits?.maxRequestBodyBytes).toBe(1048576)+ expect(limits?.maxVisualRequestBodyBytes).toBe(25165824)const errors = contract.errorTaxonomyexpect(Array.isArray(errors) && (errors as unknown[]).length > 0).toBe(true)diff --cc tests/e2e/package-lock.jsonindex c815b82c1,ea0cfa63e..36c4b726b--- a/tests/e2e/package-lock.json+++ b/tests/e2e/package-lock.json@@@ -1,12 -1,12 +1,12 @@@{"name": "clerum-e2e-tests",- "version": "0.1.89",- "version": "0.1.85",++ "version": "0.1.90","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-e2e-tests",- "version": "0.1.89",- "version": "0.1.85",++ "version": "0.1.90","devDependencies": {"@types/jsonwebtoken": "^9.0.10","@types/node": "^22.0.0",diff --cc tests/e2e/package.jsonindex 2133e3f63,81bd1e857..561f40264--- a/tests/e2e/package.json+++ b/tests/e2e/package.json@@@ -1,6 -1,6 +1,6 @@@{"name": "clerum-e2e-tests",- "version": "0.1.89",- "version": "0.1.85",++ "version": "0.1.90","private": true,"type": "module","scripts": {