Skip to content

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

TypeScript

chore: merge origin/dev into Codex large-file branch

Alfredo Lopez720e428f6ba9
diff --cc codex-llm-proxy/src/codexTransport.ts
index f79680048,5fca274bb..c36fa2e8b
--- a/codex-llm-proxy/src/codexTransport.ts
+++ b/codex-llm-proxy/src/codexTransport.ts
@@@ -99,16 -98,11 +106,21 @@@ export async function streamCodexComple
if (request.model !== input.ticket.model) {
throw new CodexTransportError('model_not_allowed', 'request model does not match the ticket')
}
+ if (
+ request.schemaVersion === 'codex-completion-request.v2' &&
+ request.messages.some(message => message.contentParts?.some(part => part.type === 'image')) &&
+ input.imageInputEnabled !== true
+ ) {
+ throw new CodexTransportError(
+ 'image_input_unsupported',
+ 'Image input is not enabled for this Codex model'
+ )
+ }
+ // A client that disconnected before dispatch must not consume the ticket:
+ // nothing was redeemed, so there is no attempt receipt to finalize.
+ if (input.signal?.aborted) {
+ return { outcome: 'canceled' }
+ }
const redeemed = await input.redeem({
executionTicket: input.executionTicket,
requestHash: input.requestHash,
diff --cc codex-llm-proxy/src/config.ts
index 9f96bca4d,2baa3094d..e8b8c3365
--- a/codex-llm-proxy/src/config.ts
+++ b/codex-llm-proxy/src/config.ts
@@@ -36,42 -32,39 +36,65 @@@ function requiredPem(name: string, raw
return value
}
+ // Fail at startup instead of at the first redeem. Messages name the variable
+ // only; the raw value (URL or service token) is never echoed.
+ function requiredHttpUrl(name: string, raw: string | undefined): string {
+ const value = raw?.trim() ?? ''
+ if (!value) throw new Error(`${name} must be set`)
+ let parsed: URL
+ try {
+ parsed = new URL(value)
+ } catch {
+ throw new Error(`${name} must be an absolute http(s) URL`)
+ }
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
+ throw new Error(`${name} must be an absolute http(s) URL`)
+ }
+ return value
+ }
+
+ function requiredNonEmpty(name: string, raw: string | undefined): string {
+ const value = raw?.trim() ?? ''
+ if (!value) throw new Error(`${name} must be set`)
+ return value
+ }
+
export function loadConfig(env: NodeJS.ProcessEnv = process.env): CodexLlmProxyConfig {
+ const imageInputModels = (env.CODEX_IMAGE_INPUT_MODELS ?? '')
+ .split(',')
+ .map(model => model.trim())
+ .filter(Boolean)
+ const maxBodyBytes = requiredPositiveInt(
+ 'CODEX_LLM_PROXY_MAX_BODY_BYTES',
+ env.CODEX_LLM_PROXY_MAX_BODY_BYTES,
+ LIMITS.maxRequestBodyBytes
+ )
+ const maxVisualBodyBytes = requiredPositiveInt(
+ 'CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES',
+ env.CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES,
+ LIMITS.maxVisualRequestBodyBytes
+ )
+ if (imageInputModels.length > 0 && maxVisualBodyBytes < LIMITS.maxVisualRequestBodyBytes) {
+ throw new Error('Visual Codex requests require the full shared envelope byte budget')
+ }
return {
- runtimePort: requiredPositiveInt('CODEX_LLM_PROXY_RUNTIME_PORT', env.CODEX_LLM_PROXY_RUNTIME_PORT, 8080),
- adminPort: requiredPositiveInt('CODEX_LLM_PROXY_ADMIN_PORT', env.CODEX_LLM_PROXY_ADMIN_PORT, 8081),
- probePort: requiredPositiveInt('CODEX_LLM_PROXY_PROBE_PORT', env.CODEX_LLM_PROXY_PROBE_PORT, 9090),
- maxBodyBytes: requiredPositiveInt(
- 'CODEX_LLM_PROXY_MAX_BODY_BYTES',
- env.CODEX_LLM_PROXY_MAX_BODY_BYTES,
- 1_048_576
+ runtimePort: requiredPositiveInt(
+ 'CODEX_LLM_PROXY_RUNTIME_PORT',
+ env.CODEX_LLM_PROXY_RUNTIME_PORT,
+ 8080
+ ),
+ adminPort: requiredPositiveInt(
+ 'CODEX_LLM_PROXY_ADMIN_PORT',
+ env.CODEX_LLM_PROXY_ADMIN_PORT,
+ 8081
),
+ probePort: requiredPositiveInt(
+ 'CODEX_LLM_PROXY_PROBE_PORT',
+ env.CODEX_LLM_PROXY_PROBE_PORT,
+ 9090
+ ),
+ maxBodyBytes,
+ maxVisualBodyBytes,
maxStreamDurationMs: requiredPositiveInt(
'CODEX_LLM_PROXY_MAX_STREAM_DURATION_MS',
env.CODEX_LLM_PROXY_MAX_STREAM_DURATION_MS,
@@@ -85,9 -78,8 +108,12 @@@
jwtIssuer: env.CODEX_LLM_PROXY_JWT_ISSUER?.trim() || 'control-api',
jwtPublicKey: requiredPem('CODEX_LLM_PROXY_JWT_PUBLIC_KEY', env.CODEX_LLM_PROXY_JWT_PUBLIC_KEY),
executionEnabled: env.CODEX_LLM_PROXY_EXECUTION_ENABLED === 'true',
- controlApiBaseUrl: requiredHttpUrl('CODEX_LLM_PROXY_CONTROL_API_URL', env.CODEX_LLM_PROXY_CONTROL_API_URL),
+ imageInputModels,
- controlApiBaseUrl: env.CODEX_LLM_PROXY_CONTROL_API_URL?.trim() || '',
++ controlApiBaseUrl: requiredHttpUrl(
++ 'CODEX_LLM_PROXY_CONTROL_API_URL',
++ env.CODEX_LLM_PROXY_CONTROL_API_URL
++ ),
controlApiServiceName: env.CODEX_LLM_PROXY_CONTROL_API_SERVICE?.trim() || 'codex-llm-proxy',
- controlApiServiceToken: env.CODEX_LLM_PROXY_CONTROL_API_TOKEN?.trim() || '',
+ controlApiServiceToken: requiredNonEmpty('CODEX_LLM_PROXY_CONTROL_API_TOKEN', env.CODEX_LLM_PROXY_CONTROL_API_TOKEN),
}
}
diff --cc codex-llm-proxy/src/server.ts
index 7e7cd21cd,6d6448cfe..ae0d14566
--- a/codex-llm-proxy/src/server.ts
+++ b/codex-llm-proxy/src/server.ts
@@@ -231,11 -162,7 +231,11 @@@ export function createProxyApps
// Abort only when the client drops the response before we finish writing.
abortWhenClientDisconnects(req, res, abort)
try {
- release = await streamGate.acquire(abort.signal)
+ release = gated.codexStreamRelease
+ gated.codexStreamRelease = undefined
+ if (!release) {
- release = await streamGate.acquire()
++ release = await streamGate.acquire(abort.signal)
+ }
res.status(200)
res.setHeader('content-type', 'text/event-stream')
res.setHeader('cache-control', 'no-cache')
diff --cc codex-llm-proxy/test/codexTransport.conformance.test.ts
index be637dd02,7a02f7ca4..277bd1c91
--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts
+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts
@@@ -62,75 -69,105 +62,174 @@@ function sseResponse
}
describe('streamCodexCompletion', () => {
+ it.each(['png', 'jpeg'])(
+ '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'
+ )
+ )
+ 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(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 = {
+ 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)).rejects.toMatchObject({
+ code: 'image_input_unsupported',
+ })
+ expect(redeem).not.toHaveBeenCalled()
+ expect(fetchFn).not.toHaveBeenCalled()
+ await expect(
+ streamCodexCompletion({ ...input, imageInputEnabled: true, deadlineMs: 1000 })
+ ).rejects.toMatchObject({ code: 'invalid_request' })
+ expect(redeem).not.toHaveBeenCalled()
+ await streamCodexCompletion({ ...input, imageInputEnabled: true })
+ 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 = [
+ 'data: {"type":"response.output_text.delta","delta":"one"}\n\n',
+ 'data: {"type":"response.output_text.delta","delta":"two"}\n\n',
+ 'data: {"type":"response.completed","response":{"usage":{}}}\n\n',
+ ]
+ let pulls = 0
+ const fetchFn = vi.fn(async () => {
+ const body = new ReadableStream<Uint8Array>(
+ {
+ pull(controller) {
+ const next = events[pulls]
+ pulls += 1
+ if (next === undefined) controller.close()
+ else controller.enqueue(encoder.encode(next))
+ },
+ },
+ { highWaterMark: 0 }
+ )
+ return new Response(body, { status: 200, headers: { 'content-type': 'text/event-stream' } })
+ })
+ let releaseDrain: (() => void) | undefined
+ const drained = new Promise<void>(resolve => {
+ releaseDrain = resolve
+ })
+ const frames: unknown[] = []
+ const pending = streamCodexCompletion({
+ executionTicket: 'ticket-drain',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-drain',
+ hostRef: 'research-host',
+ model: REQUEST.model,
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-drain',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize: vi.fn(async () => ({
+ providerAttemptId: 'att-drain',
+ outcome: 'success' as const,
+ duplicate: false,
+ })),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ onFrame: frame => {
+ frames.push(frame)
+ // First frame fills the client buffer; later frames are accepted.
+ return frames.length === 1 ? drained : undefined
+ },
+ })
+ await new Promise(resolve => setTimeout(resolve, 50))
+ expect(frames).toEqual([{ type: 'text', text: 'one' }])
+ expect(pulls).toBe(1)
+ releaseDrain?.()
+ const result = await pending
+ expect(result.outcome).toBe('success')
+ expect(frames).toEqual([
+ { type: 'text', text: 'one' },
+ { type: 'text', text: 'two' },
+ ])
+ })
+
+ it('does not redeem when the client aborted before the attempt was dispatched', async () => {
+ const redeem = vi.fn(async () => redeemSuccess())
+ const finalize = vi.fn(async () => ({
+ providerAttemptId: 'att-pre-abort',
+ outcome: 'canceled' as const,
+ duplicate: false,
+ }))
+ const fetchFn = vi.fn(async (_url: FetchInput, _init?: RequestInit) =>
+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])
+ )
+ const abort = new AbortController()
+ abort.abort()
+ const result = await streamCodexCompletion({
+ executionTicket: 'ticket-pre-abort',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-pre-abort',
+ hostRef: 'research-host',
+ model: REQUEST.model,
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-pre-abort',
+ },
+ signal: abort.signal,
+ redeem,
+ finalize,
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ expect(result.outcome).toBe('canceled')
+ expect(redeem).not.toHaveBeenCalled()
+ expect(fetchFn).not.toHaveBeenCalled()
+ expect(finalize).not.toHaveBeenCalled()
+ })
+
it('preserves real MCP optional schemas with explicit non-strict upstream tools', async () => {
const request = {
...REQUEST,
diff --cc codex-llm-proxy/test/server.security.test.ts
index 7ae05d5f2,f052b12c3..e060c651f
--- a/codex-llm-proxy/test/server.security.test.ts
+++ b/codex-llm-proxy/test/server.security.test.ts
@@@ -1,10 -1,15 +1,15 @@@
- import { describe, expect, it } from 'vitest'
- import jwt from 'jsonwebtoken'
import { generateKeyPairSync } from 'node:crypto'
+ import jwt from 'jsonwebtoken'
import request from 'supertest'
++import { describe, expect, it } from 'vitest'
+ import {
+ hashCodexCompletionRequestV1,
+ parseCodexCompletionRequestV1,
+ } from '@clerum/llm-provider-attempt-contract'
-import { describe, expect, it } from 'vitest'
import { verifyAdminPermit } from '../src/auth/adminPermitVerifier.js'
import { verifyExecutionTicket } from '../src/auth/executionTicketVerifier.js'
-import { loadConfig, type CodexLlmProxyConfig } from '../src/config.js'
+import { type CodexLlmProxyConfig, loadConfig } from '../src/config.js'
+ import { ControlApiClient, ControlApiClientError } from '../src/controlApiClient.js'
import { createProxyApps } from '../src/server.js'
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
@@@ -351,21 -286,163 +356,186 @@@ describe('codex-llm-proxy security surf
})
).toThrow(/bounded positive integer/)
})
+
+ it('keeps visual rollout disabled by default and refuses an incompatible envelope budget', () => {
- expect(loadConfig({ CODEX_LLM_PROXY_JWT_PUBLIC_KEY: publicKey }).imageInputModels).toEqual([])
++ const required = {
++ CODEX_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,
++ CODEX_LLM_PROXY_CONTROL_API_URL:
++ 'http://control-api-rpc-gateway.control-plane.svc.cluster.local:8090/api/v1',
++ CODEX_LLM_PROXY_CONTROL_API_TOKEN: 'dev-codex-llm-proxy-token',
++ }
++ expect(loadConfig(required).imageInputModels).toEqual([])
+ expect(() =>
+ loadConfig({
- CODEX_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,
++ ...required,
+ CODEX_IMAGE_INPUT_MODELS: 'gpt-5.1',
+ CODEX_LLM_PROXY_MAX_VISUAL_BODY_BYTES: '1024',
+ })
+ ).toThrow(/shared envelope byte budget/)
+ expect(
+ loadConfig({
- CODEX_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,
++ ...required,
+ CODEX_IMAGE_INPUT_MODELS: ' gpt-5.1, gpt-5.3-codex ',
+ }).imageInputModels
+ ).toEqual(['gpt-5.1', 'gpt-5.3-codex'])
+ })
})
+
+ describe('codex-llm-proxy execution kill switch', () => {
+ const lookup = async () => [{ address: '1.2.3.4', family: 4 }]
+
+ function validCompletionBody(): Record<string, unknown> {
+ const raw = {
+ schemaVersion: 'codex-completion-request.v1',
+ requestId: 'req-kill-switch',
+ idempotencyKey: 'idem-kill-switch',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ messages: [{ role: 'user', content: 'hello' }],
+ }
+ const parsed = parseCodexCompletionRequestV1(raw)
+ if (!parsed.ok) throw new Error(parsed.message)
+ const requestHash = hashCodexCompletionRequestV1(parsed.value)
+ const executionTicket = sign(
+ {
+ jti: '33333333-3333-4333-8333-333333333333',
+ typ: 'codex-execution-ticket',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash,
+ providerAttemptId: 'att-kill-switch',
+ },
+ 'codex-llm-proxy'
+ )
+ return { executionTicket, requestHash, request: raw }
+ }
+
+ function recordingClient(): { client: ControlApiClient; redeems: unknown[] } {
+ const redeems: unknown[] = []
+ const client = {
+ async redeem(input: unknown) {
+ redeems.push(input)
+ throw new ControlApiClientError('no_grant', 'no grant in kill-switch test')
+ },
+ async finalize() {
+ throw new Error('finalize must not run in kill-switch test')
+ },
+ } as unknown as ControlApiClient
+ return { client, redeems }
+ }
+
+ it('returns 404 disabled for a fully valid runtime JWT + ticket when execution is disabled', async () => {
+ const body = validCompletionBody()
+
+ // Liveness witness: the identical request reaches redeem when enabled.
+ const enabled = recordingClient()
+ const live = createProxyApps(config({ executionEnabled: true, maxBodyBytes: 65_536 }), {
+ controlApiClient: enabled.client,
+ lookup,
+ })
+ const reached = await request(live.runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken()}`)
+ .send(body)
+ expect(reached.status).toBe(403)
+ expect(JSON.parse(reached.text)).toEqual({ error: 'no_grant' })
+ expect(enabled.redeems).toHaveLength(1)
+
+ const disabled = recordingClient()
+ const off = createProxyApps(config({ executionEnabled: false, maxBodyBytes: 65_536 }), {
+ controlApiClient: disabled.client,
+ lookup,
+ })
+ const res = await request(off.runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken()}`)
+ .send(body)
+ expect(res.status).toBe(404)
+ expect(res.body).toEqual({ error: 'disabled' })
+ expect(disabled.redeems).toHaveLength(0)
+ })
+
+ it('returns 404 disabled for a valid admin permit when execution is disabled', async () => {
+ const upstream = () =>
+ new Response(JSON.stringify({ data: [{ id: 'gpt-5.1' }] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+
+ // Liveness witness: the identical admin call reaches the catalog upstream when enabled.
+ let enabledCalls = 0
+ const live = createProxyApps(config({ executionEnabled: true, maxBodyBytes: 65_536 }), {
+ fetchFn: (async () => {
+ enabledCalls += 1
+ return upstream()
+ }) as typeof fetch,
+ lookup,
+ })
+ const reached = await request(live.adminApp)
+ .post('/internal/admin/v1/codex/models')
+ .set('Authorization', `Bearer ${adminPermit()}`)
+ .send({ accessToken: 'tok' })
+ expect(reached.status).toBe(200)
+ expect(reached.body.outcome).toBe('ready')
+ expect(enabledCalls).toBe(1)
+
+ let disabledCalls = 0
+ const off = createProxyApps(config({ executionEnabled: false, maxBodyBytes: 65_536 }), {
+ fetchFn: (async () => {
+ disabledCalls += 1
+ return upstream()
+ }) as typeof fetch,
+ lookup,
+ })
+ const res = await request(off.adminApp)
+ .post('/internal/admin/v1/codex/models')
+ .set('Authorization', `Bearer ${adminPermit()}`)
+ .send({ accessToken: 'tok' })
+ expect(res.status).toBe(404)
+ expect(res.body).toEqual({ error: 'disabled' })
+ expect(disabledCalls).toBe(0)
+ })
+ })
+
+ describe('codex-llm-proxy startup config', () => {
+ const base = {
+ CODEX_LLM_PROXY_JWT_PUBLIC_KEY: publicKey,
+ CODEX_LLM_PROXY_CONTROL_API_URL:
+ 'http://control-api-rpc-gateway.control-plane.svc.cluster.local:8090/api/v1',
+ CODEX_LLM_PROXY_CONTROL_API_TOKEN: 'dev-codex-llm-proxy-token',
+ }
+
+ it('loads a complete environment', () => {
+ const loaded = loadConfig(base)
+ expect(loaded.controlApiBaseUrl).toBe(base.CODEX_LLM_PROXY_CONTROL_API_URL)
+ expect(loaded.controlApiServiceToken).toBe('dev-codex-llm-proxy-token')
+ expect(loaded.controlApiServiceName).toBe('codex-llm-proxy')
+ })
+
+ it.each([undefined, '', ' '])(
+ 'fails at startup when the control-api URL is %j',
+ value => {
+ expect(() => loadConfig({ ...base, CODEX_LLM_PROXY_CONTROL_API_URL: value })).toThrow(
+ /CODEX_LLM_PROXY_CONTROL_API_URL/
+ )
+ }
+ )
+
+ it.each(['not a url', 'ftp://control-api/api/v1', 'file:///etc/passwd'])(
+ 'fails at startup when the control-api URL %j is not http(s)',
+ value => {
+ expect(() => loadConfig({ ...base, CODEX_LLM_PROXY_CONTROL_API_URL: value })).toThrow(
+ /CODEX_LLM_PROXY_CONTROL_API_URL/
+ )
+ }
+ )
+
+ it.each([undefined, '', ' '])(
+ 'fails at startup when the control-api service token is %j',
+ value => {
+ expect(() => loadConfig({ ...base, CODEX_LLM_PROXY_CONTROL_API_TOKEN: value })).toThrow(
+ /CODEX_LLM_PROXY_CONTROL_API_TOKEN/
+ )
+ }
+ )
+ })
diff --cc control-api/src/services/llmProviderAttemptAuthorizer.ts
index 46ff0fe7e,e428f1a88..c0fc4a71b
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@@ -1,12 -1,14 +1,18 @@@
+ import {
+ LIMITS as GROK_LIMITS,
+ computeGrokPolicyHash,
+ hashGrokCompletionRequestV1,
+ parseGrokCompletionRequestV1,
+ } from '@clerum/grok-provider-attempt-contract'
import {
LIMITS,
+ buildCodexProxyEnvelope,
computeCodexPolicyHash,
- hashCodexCompletionRequestV1,
- parseCodexCompletionRequestV1,
+ hashCodexCompletionRequest,
+ isBoundedId,
+ measureNonImageAuthorizeBytes,
+ parseCodexCompletionRequest,
+ requestBodyLimitBytes,
} from '@clerum/llm-provider-attempt-contract'
import { config } from '../config.js'
import { type DbClient, pool, withTransaction } from '../db.js'
@@@ -194,19 -610,11 +615,17 @@@ export async function authorizeLlmProvi
'mcp-host JWT lacks the llm:codex:execute scope'
)
}
- if (!isPlainObject(body)) {
- throw new LlmProviderAttemptAuthorizeError('invalid_request', 'body must be an object')
- }
+ assertBodyNestingWithinLimit(body)
const serialized = JSON.stringify(body)
- if (Buffer.byteLength(serialized, 'utf8') > LIMITS.maxRequestBodyBytes) {
+ if (Buffer.byteLength(serialized, 'utf8') > requestBodyLimitBytes(body.request)) {
throw new LlmProviderAttemptAuthorizeError('invalid_request', 'request body exceeds the limit')
}
+ if (measureNonImageAuthorizeBytes(body) > LIMITS.maxRequestBodyBytes) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'invalid_request',
+ 'authorize wrapper exceeds the non-image limit'
+ )
+ }
const unknown = firstUnknownKey(body)
if (unknown) {
throw new LlmProviderAttemptAuthorizeError('unknown_field', `unknown field '${unknown}'`)
diff --cc control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
index dd8c0f452,43fc9bd22..40ce0887f
--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
@@@ -120,18 -119,38 +120,48 @@@ describe('POST /api/v1/mcp-host/llm/pro
.send({ request: {} })
expect(unassigned.status).toBe(403)
expect(unassigned.body).toEqual({ error: 'unassigned_connection' })
+
+ vi.mocked(authorizer.authorizeLlmProviderAttempt).mockRejectedValueOnce(
+ new LlmProviderAttemptAuthorizeError('payload_too_large', 'proxy envelope exceeds limit')
+ )
+ const oversized = await request(app)
+ .post('/api/v1/mcp-host/llm/provider-attempts/authorize')
+ .set('Authorization', `Bearer ${token()}`)
+ .send({ request: {} })
+ expect(oversized.status).toBe(413)
+ expect(oversized.body).toEqual({ error: 'payload_too_large' })
})
+ it('injects resolveAssignment from the live Host instead of the empty default', async () => {
+ const getResource = vi.fn().mockResolvedValue({
+ spec: {
+ model: { provider: 'codex-subscription', name: 'gpt-5.1', connectionRef: 'team-plus' },
+ },
+ })
+ const app = express()
+ app.use(express.json({ limit: '1mb' }))
+ const api = express.Router()
+ api.use(createMcpHostLlmProviderAttemptRoutes({ getResource } as never))
+ app.use('/api/v1', api)
+ vi.mocked(authorizer.authorizeLlmProviderAttempt).mockResolvedValueOnce({
+ providerAttemptId: '33333333-3333-4333-8333-333333333333',
+ requestHash: 'a'.repeat(64),
+ executionTicket: 'ticket.jwt',
+ expiresAt: '2026-08-20T12:00:00.000Z',
+ })
+ await request(app)
+ .post('/api/v1/mcp-host/llm/provider-attempts/authorize')
+ .set('Authorization', `Bearer ${token()}`)
+ .send({ request: { schemaVersion: 'codex-completion-request.v1' } })
+ expect(authorizer.authorizeLlmProviderAttempt).toHaveBeenCalled()
+ const injected = vi.mocked(authorizer.authorizeLlmProviderAttempt).mock.calls[0]?.[2]
+ expect(injected?.resolveAssignment).toEqual(expect.any(Function))
+ await expect(injected!.resolveAssignment!('research-host')).resolves.toEqual({
+ liveBrokerProviders: ['codex-subscription'],
+ liveConnectionRef: 'team-plus',
+ })
+ })
+
it('returns the authorize contract without leaking tokens', async () => {
const app = buildApp()
vi.mocked(authorizer.authorizeLlmProviderAttempt).mockResolvedValueOnce({
@@@ -153,60 -172,66 +183,87 @@@
})
expect(JSON.stringify(res.body)).not.toMatch(/refresh|access_token|Authorization/i)
})
+
+ it('admits a V2 authorize body larger than 1 MiB', async () => {
+ const app = buildApp()
+ vi.mocked(authorizer.authorizeLlmProviderAttempt).mockResolvedValueOnce({
+ providerAttemptId: '33333333-3333-4333-8333-333333333333',
+ requestHash: 'a'.repeat(64),
+ executionTicket: 'ticket.jwt',
+ expiresAt: '2026-08-20T12:00:00.000Z',
+ })
+ const res = await request(app)
+ .post('/api/v1/mcp-host/llm/provider-attempts/authorize')
+ .set('Authorization', `Bearer ${token()}`)
+ .send({
+ request: {
+ schemaVersion: 'codex-completion-request.v2',
+ pad: 'x'.repeat(2 * 1024 * 1024),
+ },
+ })
+ expect(res.status).toBe(200)
+ expect(authorizer.authorizeLlmProviderAttempt).toHaveBeenCalledOnce()
+ })
})
- describe('resolveHostAssignedConnectionKey', () => {
- it('reads the Host connectionRef and treats a missing field as unassigned', async () => {
+ describe('resolveHostAssignedAssignment', () => {
+ it('reads connectionRef from a static primary with a Codex fallback', async () => {
const gateway = {
getResource: vi.fn().mockResolvedValue({
- spec: { model: { provider: 'codex-subscription', connectionRef: 'team-plus' } },
+ spec: {
+ model: { provider: 'openai', name: 'gpt-5.1', connectionRef: 'team-plus' },
+ secretRef: 'llm',
+ llmPolicy: { fallbacks: [{ provider: 'codex-subscription', name: 'gpt-5.3-codex' }] },
+ },
}),
}
- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-a')).resolves.toBe('team-plus')
+ await expect(resolveHostAssignedAssignment(gateway, 'agent-a')).resolves.toEqual({
+ liveBrokerProviders: ['codex-subscription'],
+ liveConnectionRef: 'team-plus',
+ })
+ })
- gateway.getResource.mockResolvedValueOnce({
- spec: { model: { provider: 'codex-subscription' } },
+ it('reads connectionRef from a Grok Host', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({
+ spec: {
+ model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: 'team-grok' },
+ },
+ }),
+ }
+ await expect(resolveHostAssignedAssignment(gateway, 'agent-g')).resolves.toEqual({
+ liveBrokerProviders: ['grok-subscription'],
+ liveConnectionRef: 'team-grok',
})
- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-b')).resolves.toBe('unassigned')
+ })
- gateway.getResource.mockResolvedValueOnce({
- spec: { model: { provider: 'codex-subscription', connectionRef: 'unassigned' } },
+ it('reads the Host connectionRef and treats a missing field as unassigned', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({
+ spec: { model: { provider: 'codex-subscription', connectionRef: 'team-plus' } },
+ }),
+ }
+ await expect(resolveHostAssignedAssignment(gateway, 'agent-a')).resolves.toMatchObject({
+ liveConnectionRef: 'team-plus',
})
- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-c')).resolves.toBe('unassigned')
gateway.getResource.mockResolvedValueOnce({
- spec: { model: { provider: 'codex-subscription', connectionRef: 'deployment-default' } },
+ spec: { model: { provider: 'codex-subscription' } },
+ })
+ await expect(resolveHostAssignedAssignment(gateway, 'agent-b')).resolves.toMatchObject({
+ liveConnectionRef: 'unassigned',
})
- await expect(resolveHostAssignedConnectionKey(gateway, 'agent-d')).resolves.toBe(
- 'deployment-default'
- )
})
- it('attests a recipe caller from the codex-connection-ref annotation', async () => {
+ it('returns recipe broker targets and raw annotations for the authorizer to attest', async () => {
+ const annotations = {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'clerum.io/subscription-connection-ref': 'other-key',
+ }
const gateway = {
getResource: vi.fn().mockResolvedValue({
- metadata: { annotations: { 'clerum.io/codex-connection-ref': 'team-plus' } },
+ metadata: { annotations },
+ spec: { agent: { provider: 'codex-subscription' } },
}),
}
await expect(
diff --cc mcp-host/src/config.ts
index 0ee7afafe,2f66223df..1a68627d5
--- a/mcp-host/src/config.ts
+++ b/mcp-host/src/config.ts
@@@ -67,10 -67,12 +67,14 @@@ export interface Config
// Default OFF. Codex provider construction stays dark until the operator
// sets MCP_HOST_CODEX_SUBSCRIPTION_ENABLED=true.
codexSubscriptionEnabled: boolean
+ /** Models explicitly cleared for visual rollout; empty until interoperability is verified. */
+ codexImageInputModels: string[]
// Server-owned Codex proxy URL. Callers cannot override this per request.
codexProxyRuntimeBaseUrl: string
+ grokSubscriptionEnabled: boolean
+ grokProxyRuntimeBaseUrl: string
+ grokPolicyRevision: number
+ grokPolicyHash: string
// Explicit authorize override for tests/dev. Host chat ignores an empty hash
// and binds policyRevision/policyHash from the allowlist ConfigMap instead.
codexPolicyRevision: number
diff --cc mcp-host/src/llm/codexSubscription.ts
index 66355e0ad,20d85c5f1..ace8e5542
--- a/mcp-host/src/llm/codexSubscription.ts
+++ b/mcp-host/src/llm/codexSubscription.ts
@@@ -1,9 -1,8 +1,8 @@@
import { randomUUID } from 'node:crypto'
import {
- type CodexCompletionRequestV1,
+ type CodexCompletionRequest,
LIMITS,
- hashCodexCompletionRequest,
- parseCodexCompletionRequest,
+ hashCanonicalCodexRequest,
} from '@clerum/llm-provider-attempt-contract'
import { LlmErrorCode } from '../core/errors'
import {
@@@ -317,20 -253,16 +324,20 @@@ export class CodexSubscriptionProvider
if (options?.signal?.aborted) {
throw new CodexProxyError('canceled', 'aborted before authorize', false)
}
- const request = this.buildRequest(messages, tools, options)
- // Validate the projection before anything is authorized or hashed: the
- // ticket, the proxy and control-api must all bind the same canonical
- // request, and an unusable visual payload must fail here as a known,
- // non-retryable error instead of being dropped on the way out.
- const parsed = parseCodexCompletionRequest(request)
- if (!parsed.ok) {
+ // Hash and send the validated wire projection — exactly what control-api
+ // authorize and the proxy re-derive. Hashing the locally built object let
+ // shapes the parser normalizes away (an empty `generation` from a
+ // tool-name tool_choice, empty tools/hints) fail authorize with a
+ // 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,
- `codex completion request rejected: ${parsed.message}`
++ `codex completion request rejected: ${canonical.message}`
+ )
}
- const wireRequest = parsed.value
- const requestHash = hashCodexCompletionRequest(wireRequest)
- const { request, requestHash } = canonical.value
++ const wireRequest = canonical.value.request
++ const requestHash = canonical.value.requestHash
const context = this.deps.attemptContext({ model: this.model })
if (
!Number.isInteger(context.policyRevision) ||
diff --cc mcp-host/src/llm/index.ts
index 9ab1079de,d6c54c35b..0c727f00e
--- a/mcp-host/src/llm/index.ts
+++ b/mcp-host/src/llm/index.ts
@@@ -23,10 -25,41 +26,42 @@@ export type { ClassifiedError, SingleTu
const DEFAULT_CODEX_AUTHORIZE_GATEWAY =
'http://nginx-workflow-approval-gateway.control-plane.svc.cluster.local:8092'
+ function createGrokRuntimeDeps(captured?: GrokAttemptContext) {
+ const gateway = (config.mcpHostGatewayUrl ?? '').trim() || DEFAULT_CODEX_AUTHORIZE_GATEWAY
+ return {
+ authorizer: new ProviderAttemptAuthorizer({
+ authorizeUrl: resolveCodexAuthorizeUrl(gateway),
+ readPlatformJwt: readCodexPlatformJwt,
+ refreshOnUnauthorized: refreshCodexPlatformJwt,
+ }),
+ proxy: new GrokLlmProxyClient({
+ runtimeUrl: resolveGrokProxyRuntimeUrl(config.grokProxyRuntimeBaseUrl),
+ readPlatformJwt: readCodexPlatformJwt,
+ refreshOnUnauthorized: refreshCodexPlatformJwt,
+ }),
+ attemptContext: ({ model }: { model: string }): GrokAttemptContext => {
+ if (captured) return captured
+ const resolved = resolveGrokAttemptPolicy({
+ model,
+ envRevision: config.grokPolicyRevision,
+ envHash: config.grokPolicyHash,
+ binding: readLiveGrokPolicyBinding(),
+ })
+ if (!resolved) {
+ return { policyRevision: 0, policyHash: '' }
+ }
+ return {
+ ...resolved,
+ hostRef: config.hostName,
+ }
+ },
+ }
+ }
+
-function createCodexRuntimeDeps(captured?: CodexAttemptContext) {
+function createCodexRuntimeDeps(model: string | undefined, captured?: CodexAttemptContext) {
const gateway = (config.mcpHostGatewayUrl ?? '').trim() || DEFAULT_CODEX_AUTHORIZE_GATEWAY
return {
+ imageInputEnabled: Boolean(model && config.codexImageInputModels.includes(model)),
authorizer: new ProviderAttemptAuthorizer({
authorizeUrl: resolveCodexAuthorizeUrl(gateway),
readPlatformJwt: readCodexPlatformJwt,
@@@ -100,11 -134,13 +136,13 @@@ export function createLLMProvider
credentials,
modelName,
provider === 'codex-subscription'
- ? { codex: createCodexRuntimeDeps(options?.capturedCodexAttemptContext) }
+ ? { codex: createCodexRuntimeDeps(modelName, options?.capturedCodexAttemptContext) }
- : undefined
+ : provider === 'grok-subscription'
+ ? { grok: createGrokRuntimeDeps(options?.capturedGrokAttemptContext) }
+ : undefined
)
} catch (err) {
- console.error('[LLM] failed to construct provider')
+ logger.error({}, 'Failed to construct LLM provider')
return null
}
}
diff --cc mcp-host/src/llm/registryCore.ts
index 643948fe2,1dc3972a6..3c178e772
--- a/mcp-host/src/llm/registryCore.ts
+++ b/mcp-host/src/llm/registryCore.ts
@@@ -203,7 -200,8 +203,8 @@@ const RUNTIME_FIELDS: Record<LlmProvide
// defaultModel is the Azure DEPLOYMENT name the operator expects by default.
azure: { defaultModel: 'gpt-4.1', tokenizer: 'openai' },
// Broker: explicit model required later; no Secret slot and no default.
- 'codex-subscription': { tokenizer: 'fallback' },
+ 'codex-subscription': { tokenizer: 'fallback', requiresImageSourceIdentity: true },
+ 'grok-subscription': { tokenizer: 'fallback' },
}
// Order = dev auto-detection priority (first present key wins), inherited from
diff --cc packages/llm-provider-attempt-contract/index.cjs
index 9e73ae67e,884c5e951..8d2d5fa1c
--- a/packages/llm-provider-attempt-contract/index.cjs
+++ b/packages/llm-provider-attempt-contract/index.cjs
@@@ -441,34 -365,20 +497,43 @@@ function parseTransportHints(raw)
return ok({ promptCacheKey: raw.promptCacheKey })
}
-function parseCodexCompletionRequestV1(input) {
+/**
+ * One root parser for every request version: the same closed root field set,
+ * the same ordered checks and the same projection. Only the schema version
+ * literal and the message field set differ, so a new version cannot become a
+ * looser root by accident.
+ *
+ * Two size gates run first, before any key, id or payload work:
+ * 1. the whole body against this version's ceiling (24 MiB for V2, 1 MiB
+ * otherwise), then
+ * 2. for V2 only, the body with every image payload blanked against the V1
+ * ceiling — the images, not the text, are what the larger budget buys.
+ * Both are pure measurements, so the projected value and its hash are
+ * unaffected by them.
+ */
+function parseCodexCompletionRequestRoot(input, schemaVersion, messageKeys) {
if (!isPlainObject(input)) return fail('invalid', 'request must be an object')
+ // Runs before JSON.stringify: a deeply nested body would otherwise throw a
+ // RangeError out of the parser instead of failing closed.
+ const structure = checkStructure(input, MAX_REQUEST_DEPTH)
+ if (structure) return structure
+ const visualSchema = schemaVersion === SCHEMA_VERSION_V2
- const encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ let encoded
+ try {
+ encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ } catch {
+ return fail('invalid', 'request is not JSON-serializable')
+ }
- if (encoded > LIMITS.maxRequestBodyBytes) {
- return fail('limit', 'request exceeds maxRequestBodyBytes')
+ if (encoded > schemaRequestBodyLimit(schemaVersion)) {
+ return fail(
+ 'limit',
+ visualSchema
+ ? 'request exceeds maxVisualRequestBodyBytes'
+ : 'request exceeds maxRequestBodyBytes'
+ )
+ }
+ if (visualSchema && measureNonImageRequestBytes(input) > LIMITS.maxRequestBodyBytes) {
+ return fail('limit', 'request exceeds maxRequestBodyBytes outside image data')
}
const extra = rejectUnknown(input, ROOT_KEYS, 'request')
if (extra) return extra
@@@ -527,182 -433,31 +592,209 @@@ function hashCodexCompletionRequestV1(r
return createHash('sha256').update(stableStringify(request)).digest('hex')
}
+/**
+ * Minimal image provenance for V2. Closed union: an attachment that arrived
+ * with a user message, or one produced by a tool call. It is hashed with the
+ * rest of the part and never becomes model text.
+ *
+ * Identifier shape reuses the existing bounded ID pattern. Evidence from the
+ * current producers: attachment ids are `att_<epoch>_<rand>`
+ * (mcp-host/src/core/tools/desktop/screenshotUtil.ts), channel message ids are
+ * values such as `telegram:tg-chat-1:42` or `1700000001.000001`
+ * (mcp-host/src/workflow/providerWorkflowCallerContextClient.test.ts), and
+ * tool-call ids come from the assistant tool call. All fit
+ * `[A-Za-z0-9._:/-]{1,128}`; no producer needs a different alphabet.
+ */
+function parseImageSource(raw, label) {
+ if (!isPlainObject(raw)) return fail('invalid', `${label} must be an object`)
+ if (raw.kind !== 'attachment' && raw.kind !== 'tool') {
+ return fail('invalid', `${label}.kind is not allowed`)
+ }
+ const fromAttachment = raw.kind === 'attachment'
+ const extra = rejectUnknown(
+ raw,
+ fromAttachment ? IMAGE_SOURCE_ATTACHMENT_KEYS : IMAGE_SOURCE_TOOL_KEYS,
+ label
+ )
+ if (extra) return extra
+ if (!isBoundedId(raw.attachmentId)) return fail('invalid', `${label}.attachmentId is invalid`)
+ const ownerKey = fromAttachment ? 'messageId' : 'toolCallId'
+ if (!isBoundedId(raw[ownerKey])) return fail('invalid', `${label}.${ownerKey} is invalid`)
+ if (fromAttachment) {
+ return ok({ kind: 'attachment', attachmentId: raw.attachmentId, messageId: raw.messageId })
+ }
+ return ok({ kind: 'tool', attachmentId: raw.attachmentId, toolCallId: raw.toolCallId })
+}
+
+/**
+ * Ordered content parts. Order is significant and preserved verbatim; nothing
+ * is merged, reordered or dropped. Text parts must agree with the message
+ * `content` string, so the textual projection and the part projection cannot
+ * contradict each other. Parts are optional and may be text-only (a compacted
+ * message that no longer carries an image is valid); images are bounded by
+ * count, per-image bytes, total bytes, dimension and pixel budgets.
+ */
+function parseContentParts(raw, label, visualBudget) {
+ if (!Array.isArray(raw) || raw.length === 0) {
+ return fail('invalid', `${label} must be a non-empty array`)
+ }
+ const parts = []
+ const textBits = []
+ for (let i = 0; i < raw.length; i++) {
+ const part = raw[i]
+ const partLabel = `${label}[${i}]`
+ if (!isPlainObject(part)) return fail('invalid', `${partLabel} must be an object`)
+ if (part.type === 'text') {
+ const extra = rejectUnknown(part, CONTENT_PART_TEXT_KEYS, partLabel)
+ if (extra) return extra
+ if (typeof part.text !== 'string') {
+ return fail('invalid', `${partLabel}.text must be a string`)
+ }
+ parts.push({ type: 'text', text: part.text })
+ textBits.push(part.text)
+ continue
+ }
+ if (part.type === 'image') {
+ const extra = rejectUnknown(part, CONTENT_PART_IMAGE_KEYS, partLabel)
+ if (extra) return extra
+ if (part.mimeType !== 'image/jpeg' && part.mimeType !== 'image/png') {
+ return fail('invalid', `${partLabel}.mimeType is not allowed`)
+ }
+ const source = parseImageSource(part.source, `${partLabel}.source`)
+ if (!source.ok) return source
+ const image = inspectVisualImage({ mimeType: part.mimeType, data: part.data })
+ if (!image.ok) return fail(image.code, `${partLabel}: ${image.message}`)
+ // Request-scoped budgets: history can carry more messages than one, so a
+ // per-message counter would let a request exceed the declared limits.
+ visualBudget.images += 1
+ if (visualBudget.images > VISUAL_LIMITS.maxImages) {
+ return fail('limit', `request exceeds ${VISUAL_LIMITS.maxImages} images`)
+ }
+ visualBudget.totalBytes += image.value.bytes
+ if (visualBudget.totalBytes > VISUAL_LIMITS.maxTotalImageBytes) {
+ return fail(
+ 'limit',
+ `request exceeds ${VISUAL_LIMITS.maxTotalImageBytes} total image bytes`
+ )
+ }
+ parts.push({
+ type: 'image',
+ mimeType: part.mimeType,
+ data: part.data,
+ source: source.value,
+ })
+ continue
+ }
+ return fail('invalid', `${partLabel}.type is not allowed`)
+ }
+ return ok({ parts, text: textBits.join('\n') })
+}
+
+/**
+ * V2 root: the shared root parser with the V2 schema version and the message
+ * field set that additionally allows `contentParts`.
+ */
+function parseCodexCompletionRequestV2(input) {
+ return parseCodexCompletionRequestRoot(input, SCHEMA_VERSION_V2, MESSAGE_KEYS_V2)
+}
+
+/**
+ * Single dispatcher for every supported version. It only selects the version
+ * and defers all validation to that version's parser, so an unknown or missing
+ * schemaVersion fails closed instead of falling through to a loose path.
+ */
+function parseCodexCompletionRequest(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'request must be an object')
+ if (input.schemaVersion === SCHEMA_VERSION) return parseCodexCompletionRequestV1(input)
+ if (input.schemaVersion === SCHEMA_VERSION_V2) return parseCodexCompletionRequestV2(input)
+ return fail(
+ 'invalid',
+ 'schemaVersion must be codex-completion-request.v1 or codex-completion-request.v2'
+ )
+}
+
+function hashCodexCompletionRequest(request) {
+ return createHash('sha256').update(stableStringify(request)).digest('hex')
+}
+
+/**
+ * Exact proxy request envelope shared by the authorizer and the proxy.
+ *
+ * The outer `deadlineMs` is never emitted: a V2 request carries its deadline in
+ * `request.deadlineMs`, already bound by the request hash, and a caller must
+ * not be able to add an independent deadline after the envelope was measured.
+ *
+ * The returned envelope is re-parsed and re-hashed here, so it cannot carry a
+ * request the contract rejects or a hash that disagrees with the request it
+ * carries. Its exact UTF-8 byte length (JSON.stringify minus whitespace, the
+ * same serialization the transport sends) must fit the ceiling of the schema it
+ * carries — `requestBodyLimitBytes(request)`, i.e. 24 MiB for V2 and 1 MiB
+ * otherwise — which is the number the proxy enforces through
+ * CODEX_LLM_PROXY_MAX_BODY_BYTES. A deployment that lowers that proxy limit
+ * below the contract limit is not covered by this measurement.
+ *
+ * The request inside the envelope already passed the V2 non-image budget, so
+ * the V2 headroom here can only be spent by the ticket and the digest the
+ * authorizer produced; a caller cannot reach this ceiling with text.
+ */
+function buildCodexProxyEnvelope(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'proxy envelope must be an object')
+ const extra = rejectUnknown(input, ENVELOPE_KEYS, 'proxy envelope')
+ if (extra) return extra
+ const ticket = input.executionTicket
+ if (typeof ticket !== 'string' || ticket.length < 8 || /[\p{Cc}\p{Cs}]/u.test(ticket)) {
+ return fail('invalid', 'executionTicket is invalid')
+ }
+ if (typeof input.requestHash !== 'string' || !SHA256_HEX.test(input.requestHash)) {
+ return fail('invalid', 'requestHash must be a SHA-256 hex digest')
+ }
+ const parsed = parseCodexCompletionRequest(input.request)
+ if (!parsed.ok) return parsed
+ const requestHash = hashCodexCompletionRequest(parsed.value)
+ if (requestHash !== input.requestHash) {
+ return fail('request_hash_mismatch', 'requestHash does not match the request')
+ }
+ const envelope = { executionTicket: ticket, requestHash, request: parsed.value }
+ const visualSchema = parsed.value.schemaVersion === SCHEMA_VERSION_V2
+ const encoded = Buffer.byteLength(JSON.stringify(envelope), 'utf8')
+ if (encoded > requestBodyLimitBytes(parsed.value)) {
+ return fail(
+ 'limit',
+ visualSchema
+ ? 'proxy envelope exceeds maxVisualRequestBodyBytes'
+ : 'proxy envelope exceeds maxRequestBodyBytes'
+ )
+ }
+ return ok(Object.freeze(envelope))
+}
+
+ /**
+ * Client-side canonical hashing. Serializes `raw` exactly as a JSON peer
- * receives it, parses that wire form with parseCodexCompletionRequestV1, and
- * hashes the validated projection — the same steps control-api authorize and
- * codex-llm-proxy perform. Callers send `value.request` with
++ * receives it, parses that wire form with parseCodexCompletionRequest (v1 or
++ * v2), and hashes the validated projection — the same steps control-api
++ * authorize and the proxy perform. Callers send `value.request` with
+ * `value.requestHash`, so shapes the parser normalizes away (empty
+ * generation/tools/transportHints, undefined leaves) cannot make the two ends
+ * disagree. For an already well-formed request the digest is identical to
- * hashCodexCompletionRequestV1(request). Never throws; invalid input fails closed.
++ * hashCodexCompletionRequest(request). Never throws; invalid input fails closed.
+ */
+ function hashCanonicalCodexRequest(raw) {
+ if (!isPlainObject(raw)) return fail('invalid', 'request must be an object')
+ const structure = checkStructure(raw, MAX_REQUEST_DEPTH)
+ if (structure) return structure
+ let wire
+ try {
+ wire = JSON.parse(JSON.stringify(raw))
+ } catch {
+ return fail('invalid', 'request is not JSON-serializable')
+ }
- const parsed = parseCodexCompletionRequestV1(wire)
++ const parsed = parseCodexCompletionRequest(wire)
+ if (!parsed.ok) return parsed
- return ok(Object.freeze({ request: parsed.value, requestHash: hashCodexCompletionRequestV1(parsed.value) }))
++ return ok(
++ Object.freeze({ request: parsed.value, requestHash: hashCodexCompletionRequest(parsed.value) })
++ )
+ }
+
/**
* Grant-binding digest for a Codex authorize attempt. Must match
* control-api's expected hash: SHA-256 of lexicographic stableStringify of
@@@ -870,17 -611,10 +962,18 @@@ module.exports =
PROVIDER_ID,
TICKET_TYP,
LIMITS,
+ VISUAL_LIMITS,
+ requestBodyLimitBytes,
+ measureNonImageAuthorizeBytes,
+ isBoundedId,
stableStringify,
parseCodexCompletionRequestV1,
+ parseCodexCompletionRequestV2,
+ parseCodexCompletionRequest,
hashCodexCompletionRequestV1,
+ hashCodexCompletionRequest,
+ hashCanonicalCodexRequest,
+ buildCodexProxyEnvelope,
computeCodexPolicyHash,
parseCodexExecutionTicketClaims,
parseAuthorizeAttemptResponse,
diff --cc packages/llm-provider-attempt-contract/index.d.ts
index 4bff40ce3,c87ee6092..be35cb396
--- a/packages/llm-provider-attempt-contract/index.d.ts
+++ b/packages/llm-provider-attempt-contract/index.d.ts
@@@ -36,26 -20,9 +36,27 @@@ export declare const LIMITS:
readonly maxOutputTokens: 16384
readonly maxDeadlineMs: 300000
readonly maxIdLength: 128
+ readonly maxNestingDepth: 64
}
+/**
+ * Conservative local safety/product budgets for V2 image parts. These are
+ * deliberately not upstream facts: the frozen ChatGPT endpoint is not
+ * certified by these numbers. `typical*` is the usual 2048 JPEG/PNG target;
+ * `max*` is the hard ceiling so one poorly compressed 2048 PNG may exceed
+ * 10 MiB. Model vision capability is owned by issue #654 / PR #669.
+ */
+export declare const VISUAL_LIMITS: {
+ readonly maxImages: 3
+ readonly typicalImageBytes: 5242880
+ readonly typicalTotalImageBytes: 9437184
+ readonly typicalEnvelopeBytes: 14680064
+ readonly maxImageBytes: 16777216
+ readonly maxTotalImageBytes: 16777216
+ readonly maxImageDimension: 2048
+ readonly maxImagePixels: 4194304
+}
+
export type ContractResult<T> =
| { ok: true; value: T }
| { ok: false; code: string; message: string }
@@@ -251,19 -136,18 +252,29 @@@ export declare function isBoundedId(val
export declare function parseCodexCompletionRequestV1(
input: unknown
): ContractResult<CodexCompletionRequestV1>
-export declare function hashCodexCompletionRequestV1(
- request: CodexCompletionRequestV1
-): string
+export declare function parseCodexCompletionRequestV2(
+ input: unknown
+): ContractResult<CodexCompletionRequestV2>
+export declare function parseCodexCompletionRequest(
+ input: unknown
+): ContractResult<CodexCompletionRequest>
+export declare function hashCodexCompletionRequestV1(request: CodexCompletionRequestV1): string
+export declare function hashCodexCompletionRequest(request: CodexCompletionRequest): string
+ /**
- * Canonical client hash: JSON wire round-trip, parseCodexCompletionRequestV1,
- * then hashCodexCompletionRequestV1 of the projection. Send `request` together
- * with `requestHash`. Never throws; invalid input returns `{ ok: false }`.
++ * Canonical client hash: JSON wire round-trip, parseCodexCompletionRequest
++ * (v1 or v2), then hashCodexCompletionRequest of the projection. Send
++ * `request` together with `requestHash`. Never throws; invalid input returns
++ * `{ ok: false }`.
+ */
+ export declare function hashCanonicalCodexRequest(raw: unknown): ContractResult<{
- request: CodexCompletionRequestV1
++ request: CodexCompletionRequest
+ requestHash: string
+ }>
+export declare function buildCodexProxyEnvelope(input: {
+ executionTicket: string
+ requestHash: string
+ request: CodexCompletionRequest
+}): ContractResult<CodexProxyEnvelope>
export declare function computeCodexPolicyHash(input: {
model: string
catalogRevision: number
diff --cc packages/llm-provider-attempt-contract/index.test.cjs
index 5ad6d7a0c,f19287964..cefb61667
--- a/packages/llm-provider-attempt-contract/index.test.cjs
+++ b/packages/llm-provider-attempt-contract/index.test.cjs
@@@ -432,918 -368,235 +432,1151 @@@ test('opaque canonical names remain bou
})
})
+// --- V2 (codex-completion-request.v2) -------------------------------------
+
+const V2_REQUEST_KEYS = { schemaVersion: contract.SCHEMA_VERSION_V2 }
+const IMAGE_DATA = {
+ png: VISUAL_FIXTURE.png.messages[0].contentParts.find(part => part.type === 'image').data,
+ jpeg: VISUAL_FIXTURE.jpeg.messages[0].contentParts.find(part => part.type === 'image').data,
+}
+const MAX_ENCODED_IMAGE_CHARS = 4 * Math.ceil(contract.VISUAL_LIMITS.maxImageBytes / 3)
+
+/**
+ * Fixture image parts carry `dataRef` (resolved from visual-requests.json) so
+ * the frozen hash corpus stays readable, and `mutate` for documented
+ * truncations. Resolution returns a deep copy: a loaded fixture is never
+ * mutated in place.
+ */
+function resolveFixtureImages(value) {
+ if (Array.isArray(value)) return value.map(resolveFixtureImages)
+ if (value && typeof value === 'object') {
+ if (typeof value.dataRef === 'string') {
+ const source = IMAGE_DATA[value.dataRef]
+ assert.ok(source, `unknown image ref ${value.dataRef}`)
+ const bytes = Buffer.from(source, 'base64')
+ let data = source
+ if (value.mutate === 'strip-eoi')
+ data = bytes.subarray(0, bytes.length - 2).toString('base64')
+ else if (value.mutate === 'truncate-after-ihdr')
+ data = bytes.subarray(0, 33).toString('base64')
+ else assert.equal(value.mutate, undefined, `unknown mutate ${value.mutate}`)
+ const clone = { ...value, data }
+ delete clone.dataRef
+ delete clone.mutate
+ return clone
+ }
+ const out = {}
+ for (const [key, inner] of Object.entries(value)) out[key] = resolveFixtureImages(inner)
+ return out
+ }
+ return value
+}
+
+function pngChunks(bytes) {
+ const chunks = []
+ let pos = 8
+ while (pos < bytes.length) {
+ const length = bytes.readUInt32BE(pos)
+ chunks.push({
+ type: bytes.toString('latin1', pos + 4, pos + 8),
+ data: bytes.subarray(pos + 8, pos + 8 + length),
+ crc: bytes.readUInt32BE(pos + 8 + length),
+ crcInput: bytes.subarray(pos + 4, pos + 8 + length),
+ })
+ pos += 12 + length
+ }
+ return chunks
+}
+
+const MIB = 1024 * 1024
+// The per-image ceiling this suite replaced. Kept as a literal so the tests
+// prove the raise rather than restating the current constant.
+const FORMER_IMAGE_CEILING = 524288
+
+function imagePart(data, mimeType = 'image/png') {
+ return {
+ type: 'image',
+ mimeType,
+ data,
+ source: { kind: 'tool', attachmentId: 'att_1700000000001_ff00aa11', toolCallId: 'call_abc123' },
+ }
+}
+
+function v2WithMessages(messages) {
+ return { ...BASE, ...V2_REQUEST_KEYS, messages }
+}
+
+function v2WithParts(parts, content = '') {
+ return v2WithMessages([{ role: 'user', content, contentParts: parts }])
+}
+
+function v2TextRequest(content) {
+ return v2WithMessages([{ role: 'user', content }])
+}
+
+test('v2 fixture corpus: valid cases match frozen digests and distinct payloads differ', () => {
+ for (const fixture of FIXTURE_V2.cases) {
+ const request = resolveFixtureImages(fixture.request)
+ const parsed = contract.parseCodexCompletionRequest(request)
+ assert.equal(parsed.ok, true, fixture.name)
+ const direct = contract.parseCodexCompletionRequestV2(request)
+ assert.equal(direct.ok, true, fixture.name)
+ assert.deepEqual(parsed, direct, `${fixture.name} dispatcher parity`)
+ const digest = contract.hashCodexCompletionRequest(parsed.value)
+ assert.equal(digest, fixture.sha256, fixture.name)
+ assert.equal(
+ contract.hashCodexCompletionRequest(direct.value),
+ digest,
+ `${fixture.name} hash parity`
+ )
+ if (fixture.distinctRequest) {
+ const other = contract.parseCodexCompletionRequest(
+ resolveFixtureImages(fixture.distinctRequest)
+ )
+ assert.equal(other.ok, true, `${fixture.name} distinct`)
+ assert.notEqual(contract.hashCodexCompletionRequest(other.value), digest, fixture.name)
+ }
+ }
+})
+
+test('v2 fixture corpus: rejected payloads fail closed with the frozen code and message', () => {
+ for (const fixture of FIXTURE_V2.rejects) {
+ const parsed = contract.parseCodexCompletionRequest(resolveFixtureImages(fixture.request))
+ assert.equal(parsed.ok, false, fixture.name)
+ assert.equal(parsed.code, fixture.reason, fixture.name)
+ assert.equal(parsed.message, fixture.message, fixture.name)
+ }
+})
+
+test('v2 visual fixtures: inline png/jpeg requests parse and pin the exact octets', () => {
+ for (const key of ['png', 'jpeg', 'pngImageOnly']) {
+ const request = VISUAL_FIXTURE[key]
+ assert.equal(request.schemaVersion, contract.SCHEMA_VERSION_V2, key)
+ const imageParts = request.messages[0].contentParts.filter(part => part.type === 'image')
+ assert.equal(imageParts.length, 1, key)
+ const bytes = Buffer.from(imageParts[0].data, 'base64')
+ const pinned = VISUAL_FIXTURE.imageSha256[imageParts[0].mimeType.replace('image/', '')]
+ assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'), pinned, key)
+ const parsed = contract.parseCodexCompletionRequest(request)
+ assert.equal(parsed.ok, true, `${key}: ${parsed.message}`)
+ assert.deepEqual(
+ parsed.value.messages[0].contentParts,
+ request.messages[0].contentParts,
+ `${key} projection`
+ )
+ }
+
+ const png = Buffer.from(IMAGE_DATA.png, 'base64')
+ assert.deepEqual(
+ [png.readUInt32BE(16), png.readUInt32BE(20)],
+ [VISUAL_FIXTURE.expectedDimensions.png.width, VISUAL_FIXTURE.expectedDimensions.png.height]
+ )
+ const jpeg = Buffer.from(IMAGE_DATA.jpeg, 'base64')
+ assert.deepEqual([jpeg[0], jpeg[1]], [0xff, 0xd8])
+ assert.deepEqual([jpeg[jpeg.length - 2], jpeg[jpeg.length - 1]], [0xff, 0xd9])
+ assert.ok(jpeg.includes(Buffer.from([0xff, 0xda])), 'jpeg carries a start-of-scan segment')
+})
+
+test('v2 fixture png is a real image: real CRCs and an inflatable scanline stream', () => {
+ const bytes = Buffer.from(IMAGE_DATA.png, 'base64')
+ const chunks = pngChunks(bytes)
+ assert.deepEqual(
+ chunks.map(chunk => chunk.type),
+ ['IHDR', 'IDAT', 'IEND']
+ )
+ for (const chunk of chunks) {
+ assert.equal(chunk.crc, zlib.crc32(chunk.crcInput) >>> 0, chunk.type)
+ }
+ const { width, height } = VISUAL_FIXTURE.expectedDimensions.png
+ const raw = zlib.inflateSync(chunks[1].data)
+ assert.equal(raw.length, height * (1 + width * 3))
+ for (let row = 0; row < height; row++) {
+ assert.equal(raw[row * (1 + width * 3)], 0, `scanline ${row} filter byte`)
+ }
+})
+
+test('dispatcher: v1 rejects contentParts, unknown versions fail closed, one hash serves both', () => {
+ const v1WithParts = { ...VISUAL_FIXTURE.png, schemaVersion: contract.SCHEMA_VERSION }
+ const rejected = contract.parseCodexCompletionRequestV1(v1WithParts)
+ assert.equal(rejected.ok, false)
+ assert.equal(rejected.code, 'unknown-field')
+ assert.match(rejected.message, /contentParts/)
+ assert.equal(contract.parseCodexCompletionRequest(v1WithParts).ok, false)
+
+ for (const schemaVersion of ['codex-completion-request.v3', undefined, null, 2]) {
+ const parsed = contract.parseCodexCompletionRequest({ ...BASE, schemaVersion })
+ assert.equal(parsed.ok, false, String(schemaVersion))
+ assert.equal(parsed.code, 'invalid', String(schemaVersion))
+ }
+ assert.equal(contract.parseCodexCompletionRequest('not an object').ok, false)
+
+ const v1 = contract.parseCodexCompletionRequest(BASE)
+ const v2 = contract.parseCodexCompletionRequest(v2TextRequest('hello'))
+ assert.equal(v1.ok, true)
+ assert.equal(v2.ok, true)
+ assert.equal(
+ contract.hashCodexCompletionRequest(v1.value),
+ contract.hashCodexCompletionRequestV1(v1.value)
+ )
+ const withoutVersion = ({ schemaVersion, ...rest }) => rest
+ assert.deepEqual(
+ withoutVersion(v2.value),
+ withoutVersion(v1.value),
+ 'text-only v2 keeps v1 semantics'
+ )
+ assert.notEqual(
+ contract.hashCodexCompletionRequest(v2.value),
+ contract.hashCodexCompletionRequest(v1.value)
+ )
+})
+
+test('dispatcher: v2 keeps every v1 root check instead of bypassing it', () => {
+ for (const fixture of FIXTURE.rejects) {
+ const asV1 = contract.parseCodexCompletionRequest(fixture.request)
+ const asV2 = contract.parseCodexCompletionRequest({
+ ...fixture.request,
+ schemaVersion: contract.SCHEMA_VERSION_V2,
+ })
+ assert.equal(asV1.ok, false, fixture.name)
+ assert.equal(asV2.ok, false, `${fixture.name} v2`)
+ assert.equal(asV2.code, asV1.code, `${fixture.name} code`)
+ }
+
+ const roots = [
+ { name: 'requestId', patch: { requestId: 'bad id' } },
+ { name: 'idempotencyKey', patch: { idempotencyKey: 'é' } },
+ { name: 'provider', patch: { provider: 'openai-api' } },
+ { name: 'model', patch: { model: 'bad model' } },
+ { name: 'deadline-low', patch: { deadlineMs: 0 }, code: 'limit' },
+ {
+ name: 'deadline-high',
+ patch: { deadlineMs: contract.LIMITS.maxDeadlineMs + 1 },
+ code: 'limit',
+ },
+ { name: 'deadline-fraction', patch: { deadlineMs: 1.5 }, code: 'non-finite' },
+ {
+ name: 'deadline-nonfinite',
+ patch: { deadlineMs: Number.POSITIVE_INFINITY },
+ code: 'non-finite',
+ },
+ { name: 'generation-unknown', patch: { generation: { topK: 5 } } },
+ { name: 'generation-temperature', patch: { generation: { temperature: 3 } } },
+ { name: 'transport-hints-unknown', patch: { transportHints: { cacheKey: 'x' } } },
+ { name: 'messages-empty', patch: { messages: [] } },
+ { name: 'message-role', patch: { messages: [{ role: 'human', content: 'x' }] } },
+ { name: 'message-content-type', patch: { messages: [{ role: 'user', content: 5 }] } },
+ {
+ name: 'message-tool-calls-on-user',
+ patch: {
+ messages: [
+ { role: 'user', content: 'x', toolCalls: [{ id: 'a', name: 'b', arguments: {} }] },
+ ],
+ },
+ },
+ { name: 'tool-description', patch: { tools: [{ name: 'a', description: 1, parameters: {} }] } },
+ {
+ name: 'tool-name-control',
+ patch: { tools: [{ name: 'a\u0000b', description: 'x', parameters: {} }] },
+ },
+ {
+ name: 'text-part-text-type',
+ patch: {
+ messages: [{ role: 'user', content: 'x', contentParts: [{ type: 'text', text: 5 }] }],
+ },
+ },
+ ]
+ for (const entry of roots) {
+ const parsed = contract.parseCodexCompletionRequest({
+ ...BASE,
+ ...V2_REQUEST_KEYS,
+ ...entry.patch,
+ })
+ assert.equal(parsed.ok, false, entry.name)
+ if (entry.code) assert.equal(parsed.code, entry.code, entry.name)
+ }
+})
+
+test('v2 projection preserves part order, source identity and the text projection verbatim', () => {
+ const multi = resolveFixtureImages(
+ FIXTURE_V2.cases.find(item => item.name === 'multi-image-order-significant').request
+ )
+ const parsed = contract.parseCodexCompletionRequest(multi)
+ assert.equal(parsed.ok, true)
+ assert.equal(Object.isFrozen(parsed.value), true)
+ assert.deepEqual(parsed.value.messages[0].contentParts, multi.messages[0].contentParts)
+ assert.deepEqual(
+ parsed.value.messages[0].contentParts.map(part => part.type),
+ ['text', 'image', 'image']
+ )
+
+ const compacted = resolveFixtureImages(
+ FIXTURE_V2.cases.find(item => item.name === 'text-only-parts-after-compaction').request
+ )
+ const parsedCompacted = contract.parseCodexCompletionRequest(compacted)
+ assert.equal(parsedCompacted.ok, true)
+ const parts = parsedCompacted.value.messages[0].contentParts
+ assert.ok(
+ parts.every(part => part.type === 'text'),
+ 'text-only parts survive without an image'
+ )
+ assert.equal(parsedCompacted.value.messages[0].content, parts.map(part => part.text).join('\n'))
+
+ const imageOnly = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.pngImageOnly)
+ assert.equal(imageOnly.ok, true)
+ assert.equal(imageOnly.value.messages[0].content, '', 'an image-only message has empty text')
+})
+
+test('v2 limits: image count, encoder bound, per-image bytes, total bytes, dimensions and pixels', () => {
+ const png = IMAGE_DATA.png
+ const three = [imagePart(png), imagePart(png), imagePart(png)]
+ assert.equal(
+ contract.parseCodexCompletionRequest(v2WithParts(three)).ok,
+ true,
+ 'three images fit'
+ )
+ const four = contract.parseCodexCompletionRequest(v2WithParts([...three, imagePart(png)]))
+ assert.equal(four.ok, false)
+ assert.equal(four.code, 'limit')
+ assert.match(four.message, /3 images/)
+
+ const encoded = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart('A'.repeat(MAX_ENCODED_IMAGE_CHARS + 4))])
+ )
+ assert.equal(encoded.code, 'limit', 'encoded length is bounded before decoding')
+ const decoded = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(Buffer.alloc(contract.VISUAL_LIMITS.maxImageBytes + 1).toString('base64')),
+ ])
+ )
+ assert.equal(decoded.code, 'limit')
+
+ // Above the ceiling this suite replaced, in both accepted containers.
+ const pngOverFormerCeiling = declaredHeaderPngOfSize(FORMER_IMAGE_CEILING + 1)
+ assert.equal(pngOverFormerCeiling.length, FORMER_IMAGE_CEILING + 1)
+ const acceptedPng = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(pngOverFormerCeiling.toString('base64'))])
+ )
+ assert.equal(acceptedPng.ok, true, acceptedPng.message)
+ const acceptedJpeg = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(jpegOfSize(FORMER_IMAGE_CEILING + 1).toString('base64'), 'image/jpeg')])
+ )
+ assert.equal(acceptedJpeg.ok, true, acceptedJpeg.message)
+ const acceptedFiveMiBJpeg = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(jpegOfSize(5 * MIB).toString('base64'), 'image/jpeg')])
+ )
+ assert.equal(acceptedFiveMiBJpeg.ok, true, acceptedFiveMiBJpeg.message)
+
+ // 3 MiB, and exactly the per-image ceiling, are inside the budget.
+ const acceptedThreeMiB = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(declaredHeaderPngOfSize(3 * MIB).toString('base64'))])
+ )
+ assert.equal(acceptedThreeMiB.ok, true, acceptedThreeMiB.message)
+ const acceptedCeiling = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(declaredHeaderPngOfSize(contract.VISUAL_LIMITS.maxImageBytes).toString('base64')),
+ ])
+ )
+ assert.equal(acceptedCeiling.ok, true, acceptedCeiling.message)
+
+ // One byte over the per-image ceiling, as a container that is otherwise valid.
+ const overCeiling = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(
+ declaredHeaderPngOfSize(contract.VISUAL_LIMITS.maxImageBytes + 1).toString('base64')
+ ),
+ ])
+ )
+ assert.equal(overCeiling.ok, false)
+ assert.equal(overCeiling.code, 'limit')
+ assert.match(overCeiling.message, /image exceeds/)
+ assert.match(overCeiling.message, new RegExp(String(contract.VISUAL_LIMITS.maxImageBytes)))
+
+ // Exceptional >10 MiB is allowed; the hard per-image ceiling is 16 MiB.
+ const twelveMiB = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(declaredHeaderPngOfSize(12 * MIB).toString('base64'))])
+ )
+ assert.equal(twelveMiB.ok, true, twelveMiB.message)
+
+ // A larger individual image does not increase the aggregate resource budget.
+ const tenMiB = declaredHeaderPngOfSize(10 * MIB).toString('base64')
+ const fiveMiB = declaredHeaderPngOfSize(5 * MIB).toString('base64')
+ const combined = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(tenMiB), imagePart(fiveMiB)])
+ )
+ assert.equal(combined.ok, true, combined.message)
+ const combinedWithJpeg = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(tenMiB), imagePart(jpegOfSize(5 * MIB).toString('base64'), 'image/jpeg')])
+ )
+ assert.equal(combinedWithJpeg.ok, true, combinedWithJpeg.message)
+ const atAggregate = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(tenMiB), imagePart(declaredHeaderPngOfSize(6 * MIB).toString('base64'))])
+ )
+ assert.equal(atAggregate.ok, true, atAggregate.message)
+ const overAggregate = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(tenMiB),
+ imagePart(declaredHeaderPngOfSize(6 * MIB + 1).toString('base64')),
+ ])
+ )
+ assert.equal(overAggregate.ok, false)
+ assert.equal(overAggregate.code, 'limit')
+ assert.match(overAggregate.message, /total image bytes/)
+
+ const atDimension = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(realPng(contract.VISUAL_LIMITS.maxImageDimension, 1, 9).toString('base64')),
+ ])
+ )
+ assert.equal(atDimension.ok, true, atDimension.message)
+ const overDimension = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(realPng(contract.VISUAL_LIMITS.maxImageDimension + 1, 1, 11).toString('base64')),
+ ])
+ )
+ assert.equal(overDimension.code, 'limit')
+ assert.match(overDimension.message, /dimension/)
+
+ // Phone-sized frames are a Codex pixel problem, not a byte problem.
+ const phoneShape = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(declaredHeaderPng(8064, 6048).toString('base64'))])
+ )
+ assert.equal(phoneShape.ok, false)
+ assert.equal(phoneShape.code, 'limit')
+ assert.match(phoneShape.message, /dimension/)
+
+ // 2048×2048 is both the dimension and the pixel ceiling.
+ assert.equal(
+ contract.VISUAL_LIMITS.maxImageDimension * contract.VISUAL_LIMITS.maxImageDimension,
+ contract.VISUAL_LIMITS.maxImagePixels
+ )
+ const atPixels = contract.parseCodexCompletionRequest(
+ v2WithParts([
+ imagePart(
+ declaredHeaderPng(
+ contract.VISUAL_LIMITS.maxImageDimension,
+ contract.VISUAL_LIMITS.maxImageDimension
+ ).toString('base64')
+ ),
+ ])
+ )
+ assert.equal(atPixels.ok, true, atPixels.message)
+
+ const wrongMime = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(png, 'image/jpeg')])
+ )
+ assert.equal(wrongMime.ok, false, 'mime and container signature must agree')
+ const jpegAsPng = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(IMAGE_DATA.jpeg, 'image/png')])
+ )
+ assert.equal(jpegAsPng.ok, false)
+})
+
+test('v2 visual budgets are request-scoped across messages: three 5 MiB images fit, four do not', () => {
+ const png = IMAGE_DATA.png
+ const userWithImages = count => ({
+ role: 'user',
+ content: '',
+ contentParts: Array.from({ length: count }, () => imagePart(png)),
+ })
+
+ // 2 + 2 images: every message is inside maxImages on its own, the request is not.
+ const twoEach = contract.parseCodexCompletionRequest(
+ v2WithMessages([userWithImages(2), userWithImages(2)])
+ )
+ assert.equal(twoEach.ok, false)
+ assert.equal(twoEach.code, 'limit')
+ assert.match(twoEach.message, /3 images/)
+
+ // Boundary: exactly maxImages spread over three messages is accepted.
+ const oneEach = contract.parseCodexCompletionRequest(
+ v2WithMessages([userWithImages(1), userWithImages(1), userWithImages(1)])
+ )
+ assert.equal(oneEach.ok, true, oneEach.message)
+
+ // Three 5 MiB images across messages fill the unchanged aggregate budget.
+ const atCeiling = declaredHeaderPngOfSize(5 * MIB).toString('base64')
+ const messageWith = encoded => ({
+ role: 'user',
+ content: '',
+ contentParts: [imagePart(encoded)],
+ })
+ const oneEachAtCeiling = contract.parseCodexCompletionRequest(
+ v2WithMessages([messageWith(atCeiling), messageWith(atCeiling), messageWith(atCeiling)])
+ )
+ assert.equal(oneEachAtCeiling.ok, true, oneEachAtCeiling.message)
+ // Three ceiling images are the exact aggregate boundary, and the encoded body
+ // is larger than the V1 ceiling — this is the request that needs the V2 budget.
+ const ceilingBody = Buffer.byteLength(
+ JSON.stringify(
+ v2WithMessages([messageWith(atCeiling), messageWith(atCeiling), messageWith(atCeiling)])
+ ),
+ 'utf8'
+ )
+ assert.ok(ceilingBody > contract.LIMITS.maxRequestBodyBytes)
+ assert.ok(ceilingBody <= contract.LIMITS.maxVisualRequestBodyBytes)
+
+ // A fourth ceiling image is refused before the count gate is reached: four
+ // 5 MiB payloads encode to more than the 24 MiB body ceiling. The count rule
+ // is exercised with small images above; this asserts which gate fires first
+ // for maximum-size payloads.
+ const fourMessages = contract.parseCodexCompletionRequest(
+ v2WithMessages([
+ messageWith(atCeiling),
+ messageWith(atCeiling),
+ messageWith(atCeiling),
+ messageWith(atCeiling),
+ ])
+ )
+ assert.equal(fourMessages.ok, false)
+ assert.equal(fourMessages.code, 'limit')
+ assert.equal(fourMessages.message, 'request exceeds maxVisualRequestBodyBytes')
+})
+
+/**
+ * The request with every image payload replaced by an empty string — the
+ * non-image share the V2 budget is defined on. Used to find an exact boundary;
+ * the assertions below always check the contract's verdict, not this helper.
+ */
+function nonImageBytes(request) {
+ return Buffer.byteLength(
+ JSON.stringify({
+ ...request,
+ messages: request.messages.map(message =>
+ Array.isArray(message.contentParts)
+ ? {
+ ...message,
+ contentParts: message.contentParts.map(part =>
+ part.type === 'image' ? { ...part, data: '' } : part
+ ),
+ }
+ : message
+ ),
+ }),
+ 'utf8'
+ )
+}
+
+test('requestBodyLimitBytes: V2 declares 24 MiB; every other body keeps the 1 MiB ceiling', () => {
+ assert.equal(contract.LIMITS.maxRequestBodyBytes, 1048576)
+ assert.equal(contract.LIMITS.maxVisualRequestBodyBytes, 25165824)
+ assert.equal(contract.VISUAL_LIMITS.maxImages, 3)
+ assert.equal(contract.VISUAL_LIMITS.typicalImageBytes, 5 * MIB)
+ assert.equal(contract.VISUAL_LIMITS.typicalTotalImageBytes, 9 * MIB)
+ assert.equal(contract.VISUAL_LIMITS.typicalEnvelopeBytes, 14 * MIB)
+ assert.equal(contract.VISUAL_LIMITS.maxImageBytes, 16 * MIB)
+ assert.equal(contract.VISUAL_LIMITS.maxTotalImageBytes, 16 * MIB)
+ assert.equal(contract.VISUAL_LIMITS.maxImageDimension, 2048)
+ assert.equal(contract.VISUAL_LIMITS.maxImagePixels, 2048 * 2048)
+
+ for (const v2 of [VISUAL_FIXTURE.png, VISUAL_FIXTURE.jpeg, VISUAL_FIXTURE.pngImageOnly]) {
+ assert.equal(v2.schemaVersion, contract.SCHEMA_VERSION_V2)
+ assert.equal(contract.requestBodyLimitBytes(v2), 25165824)
+ }
+ // A declaration is not a payload: unknown, missing and non-object bodies keep
+ // the smaller ceiling so a caller cannot ask for the larger budget it has not
+ // satisfied.
+ for (const other of [
+ BASE,
+ { ...BASE, schemaVersion: 'codex-completion-request.v3' },
+ { ...BASE, schemaVersion: undefined },
+ {},
+ null,
+ undefined,
+ 'x',
+ 7,
+ [],
+ ]) {
+ assert.equal(contract.requestBodyLimitBytes(other), 1048576, String(other))
+ }
+})
+
+test('v2 preserves the non-image budget: text and tools stay on the 1 MiB ceiling', () => {
+ const { maxRequestBodyBytes, maxVisualRequestBodyBytes } = contract.LIMITS
+ const image = imagePart(IMAGE_DATA.png)
+ const overflow = 'request exceeds maxRequestBodyBytes outside image data'
+ const longText = 'x'.repeat(2 * MIB)
+
+ // Images do not buy text: 2 MiB of content-class payload is refused far below
+ // the 24 MiB ceiling the same body is allowed to use for image data.
+ const textHeavy = contract.parseCodexCompletionRequest(
+ v2WithParts([image, { type: 'text', text: longText }], longText)
+ )
+ assert.equal(textHeavy.ok, false)
+ assert.equal(textHeavy.code, 'limit')
+ assert.equal(textHeavy.message, overflow)
+
+ // A text-only V2 body is not a 24 MiB allowance either.
+ assert.deepEqual(contract.parseCodexCompletionRequest(v2TextRequest(longText)), {
+ ok: false,
+ code: 'limit',
+ message: overflow,
+ })
+
+ // Tool definitions are on the same caller-controlled budget.
+ const toolHeavy = contract.parseCodexCompletionRequest({
+ ...v2WithParts([image]),
+ tools: [{ name: 'read', description: 'y'.repeat(2 * MIB), parameters: {} }],
+ })
+ assert.equal(toolHeavy.ok, false)
+ assert.equal(toolHeavy.code, 'limit')
+ assert.equal(toolHeavy.message, overflow)
+
+ // Exact boundary. The image is blanked out of the measurement, so the largest
+ // accepted text still leaves the body far under the V2 ceiling, and one byte
+ // more is refused by the non-image rule.
+ const withImageAndText = length =>
+ v2WithParts([image, { type: 'text', text: 'z'.repeat(length) }], 'z'.repeat(length))
+ const base = nonImageBytes(withImageAndText(0))
+ const growth = (nonImageBytes(withImageAndText(10)) - base) / 10
+ assert.equal(growth, 2, 'content and its text part both carry the payload')
+ const exactLength = Math.floor((maxRequestBodyBytes - base) / growth)
+ const boundary = nonImageBytes(withImageAndText(exactLength))
+ assert.ok(
+ boundary <= maxRequestBodyBytes && boundary > maxRequestBodyBytes - growth,
+ `non-image boundary landed at ${boundary}`
+ )
+ const bodyAtBoundary = Buffer.byteLength(JSON.stringify(withImageAndText(exactLength)), 'utf8')
+ assert.ok(
+ bodyAtBoundary < maxVisualRequestBodyBytes,
+ 'the non-image boundary is decided well below the V2 ceiling'
+ )
+ const atLimit = contract.parseCodexCompletionRequest(withImageAndText(exactLength))
+ assert.equal(atLimit.ok, true, atLimit.message)
+ const overLimit = contract.parseCodexCompletionRequest(withImageAndText(exactLength + 1))
+ assert.equal(overLimit.ok, false)
+ assert.equal(overLimit.code, 'limit')
+ assert.equal(overLimit.message, overflow)
+ assert.ok(
+ nonImageBytes(withImageAndText(exactLength + 1)) > maxRequestBodyBytes,
+ 'the rejection is the non-image budget, not another gate'
+ )
+})
+
+test('v2 total budget: the raw body is capped at 24 MiB and the three budgets stay consistent', () => {
+ const { maxVisualRequestBodyBytes, maxRequestBodyBytes } = contract.LIMITS
+ // The V2 ceiling must cover the largest legal image set (3 x 5 MiB decoded, so
+ // ~21 MiB of canonical base64) plus the whole non-image share. Asserted so a
+ // future change to any of the three image numbers is caught here.
+ const aggregateEncoded = 4 * Math.ceil(contract.VISUAL_LIMITS.maxTotalImageBytes / 3) + 8
+ assert.ok(aggregateEncoded + maxRequestBodyBytes < maxVisualRequestBodyBytes)
+
+ // Over the ceiling is refused by the size gate, before any payload work.
+ const oversized = v2WithParts([imagePart('A'.repeat(maxVisualRequestBodyBytes))])
+ assert.ok(Buffer.byteLength(JSON.stringify(oversized), 'utf8') > maxVisualRequestBodyBytes)
+ const refused = contract.parseCodexCompletionRequest(oversized)
+ assert.equal(refused.ok, false)
+ assert.equal(refused.code, 'limit')
+ assert.equal(refused.message, 'request exceeds maxVisualRequestBodyBytes')
+
+ // The same shape parsed as V1 keeps the V1 ceiling and its V1 message: the
+ // larger budget is a property of the version, not of the payload.
+ const asV1 = contract.parseCodexCompletionRequestV1({
+ ...oversized,
+ schemaVersion: contract.SCHEMA_VERSION,
+ })
+ assert.equal(asV1.ok, false)
+ assert.equal(asV1.code, 'limit')
+ assert.equal(asV1.message, 'request exceeds maxRequestBodyBytes')
+})
+
+test('large real PNG: CRCs and inflatable scanlines at 3 MiB and at 10 MiB', () => {
+ const cases = [
+ ['3 MiB', 3 * MIB, 512, 512, 21],
+ ['10 MiB', 10 * MIB, 1150, 1150, 31],
+ ]
+ for (const [label, target, width, height, seed] of cases) {
+ const png = realPngOfSize(target, width, height, seed)
+ assert.equal(png.length, target, label)
+ const chunks = pngChunks(png)
+ assert.deepEqual(
+ chunks.map(chunk => chunk.type),
+ ['IHDR', 'IDAT', 'tEXt', 'IEND'],
+ label
+ )
+ for (const chunk of chunks) {
+ assert.equal(chunk.crc, zlib.crc32(chunk.crcInput) >>> 0, `${label} ${chunk.type} crc`)
+ }
+ const raw = zlib.inflateSync(chunks[1].data)
+ assert.equal(raw.length, height * (1 + width * 3), label)
+ const parsed = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(png.toString('base64'))])
+ )
+ assert.equal(parsed.ok, true, `${label}: ${parsed.message}`)
+ }
+})
+
+test('shared pads keep a real fixture JPEG/PNG contract-valid at 5 MiB', () => {
+ const jpeg = padJpegToSize(Buffer.from(IMAGE_DATA.jpeg, 'base64'), 5 * MIB)
+ const png = padPngToSize(Buffer.from(IMAGE_DATA.png, 'base64'), 5 * MIB)
+ assert.equal(jpeg.length, 5 * MIB)
+ assert.equal(png.length, 5 * MIB)
+ const jpegParsed = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(jpeg.toString('base64'), 'image/jpeg')])
+ )
+ const pngParsed = contract.parseCodexCompletionRequest(
+ v2WithParts([imagePart(png.toString('base64'))])
+ )
+ assert.equal(jpegParsed.ok, true, jpegParsed.message)
+ assert.equal(pngParsed.ok, true, pngParsed.message)
+})
+
+test('buildCodexProxyEnvelope: exact shape, no outer deadline, exact size boundary', () => {
+ const ticket = 'header.payload.signature'.repeat(3)
+ const parsed = contract.parseCodexCompletionRequest({
+ ...BASE,
+ ...V2_REQUEST_KEYS,
+ deadlineMs: 15000,
+ })
+ assert.equal(parsed.ok, true)
+ const requestHash = contract.hashCodexCompletionRequest(parsed.value)
+ const envelope = contract.buildCodexProxyEnvelope({
+ executionTicket: ticket,
+ requestHash,
+ request: parsed.value,
+ })
+ assert.equal(envelope.ok, true, envelope.message)
+ assert.deepEqual(Object.keys(envelope.value), ['executionTicket', 'requestHash', 'request'])
+ assert.equal('deadlineMs' in envelope.value, false, 'outer deadline is never emitted')
+ assert.equal(
+ envelope.value.request.deadlineMs,
+ 15000,
+ 'deadline travels inside the hashed request'
+ )
+ assert.equal(Object.isFrozen(envelope.value), true)
+ assert.equal(
+ Buffer.byteLength(JSON.stringify(envelope.value), 'utf8') <=
+ contract.requestBodyLimitBytes(envelope.value.request),
+ true
+ )
+
+ const shifted = contract.parseCodexCompletionRequest({
+ ...BASE,
+ ...V2_REQUEST_KEYS,
+ deadlineMs: 15001,
+ })
+ assert.notEqual(
+ contract.hashCodexCompletionRequest(shifted.value),
+ requestHash,
+ 'the deadline is bound by the request hash'
+ )
+
+ // V2 exact boundary. The request's own share is bounded (images at ~21 MiB
+ // encoded, everything else at 1 MiB), so padding its text can no longer reach
+ // the envelope ceiling — the ticket is the field that moves it, and the ticket
+ // is what the authorizer really adds.
+ const envelopeForTicket = ticketBytes => {
+ const request = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.png)
+ assert.equal(request.ok, true, request.message)
+ const hash = contract.hashCodexCompletionRequest(request.value)
+ const executionTicket = 't'.repeat(ticketBytes)
+ return {
+ executionTicket,
+ hash,
+ request,
+ size: Buffer.byteLength(
+ JSON.stringify({ executionTicket, requestHash: hash, request: request.value }),
+ 'utf8'
+ ),
+ }
+ }
+ const limit = contract.requestBodyLimitBytes(parsed.value)
+ assert.equal(limit, contract.LIMITS.maxVisualRequestBodyBytes)
+ const probe = envelopeForTicket(8)
+ const exactTicket = 8 + (limit - probe.size)
+ const exact = envelopeForTicket(exactTicket)
+ assert.equal(exact.size, limit)
+ const atLimit = contract.buildCodexProxyEnvelope({
+ executionTicket: exact.executionTicket,
+ requestHash: exact.hash,
+ request: exact.request.value,
+ })
+ assert.equal(atLimit.ok, true, atLimit.message)
+ assert.equal(Buffer.byteLength(JSON.stringify(atLimit.value), 'utf8'), limit)
+
+ const over = envelopeForTicket(exactTicket + 1)
+ assert.equal(over.size, limit + 1)
+ const refused = contract.buildCodexProxyEnvelope({
+ executionTicket: over.executionTicket,
+ requestHash: over.hash,
+ request: over.request.value,
+ })
+ assert.equal(refused.ok, false)
+ assert.equal(refused.code, 'limit')
+ assert.equal(refused.message, 'proxy envelope exceeds maxVisualRequestBodyBytes')
+
+ // V1 keeps the 1 MiB envelope ceiling: same construction, exact boundary, and
+ // the V1 failure message.
+ const v1Request = contract.parseCodexCompletionRequest({ ...BASE, deadlineMs: 5000 })
+ assert.equal(v1Request.ok, true)
+ const v1Hash = contract.hashCodexCompletionRequest(v1Request.value)
+ const v1Size = ticketBytes =>
+ Buffer.byteLength(
+ JSON.stringify({
+ executionTicket: 't'.repeat(ticketBytes),
+ requestHash: v1Hash,
+ request: v1Request.value,
+ }),
+ 'utf8'
+ )
+ const v1Ticket = 8 + (contract.LIMITS.maxRequestBodyBytes - v1Size(8))
+ const v1Exact = contract.buildCodexProxyEnvelope({
+ executionTicket: 't'.repeat(v1Ticket),
+ requestHash: v1Hash,
+ request: v1Request.value,
+ })
+ assert.equal(v1Exact.ok, true, v1Exact.message)
+ assert.equal(Buffer.byteLength(JSON.stringify(v1Exact.value), 'utf8'), v1Size(v1Ticket))
+ assert.equal(
+ Buffer.byteLength(JSON.stringify(v1Exact.value), 'utf8'),
+ contract.LIMITS.maxRequestBodyBytes
+ )
+ const v1Over = contract.buildCodexProxyEnvelope({
+ executionTicket: 't'.repeat(v1Ticket + 1),
+ requestHash: v1Hash,
+ request: v1Request.value,
+ })
+ assert.equal(v1Over.ok, false)
+ assert.equal(v1Over.code, 'limit')
+ assert.equal(v1Over.message, 'proxy envelope exceeds maxRequestBodyBytes')
+})
+
+test('buildCodexProxyEnvelope: fails closed on hash mismatch, bad input and invalid requests', () => {
+ const ticket = 'header.payload.signature'
+ const parsed = contract.parseCodexCompletionRequest(VISUAL_FIXTURE.png)
+ assert.equal(parsed.ok, true)
+ const requestHash = contract.hashCodexCompletionRequest(parsed.value)
+ const cases = [
+ {
+ name: 'hash-mismatch',
+ input: { executionTicket: ticket, requestHash: 'a'.repeat(64), request: parsed.value },
+ code: 'request_hash_mismatch',
+ },
+ {
+ name: 'hash-shape',
+ input: { executionTicket: ticket, requestHash: 'not-a-digest', request: parsed.value },
+ code: 'invalid',
+ },
+ {
+ name: 'unknown-envelope-field',
+ input: { executionTicket: ticket, requestHash, request: parsed.value, deadlineMs: 1000 },
+ code: 'unknown-field',
+ },
+ {
+ name: 'short-ticket',
+ input: { executionTicket: 'short', requestHash, request: parsed.value },
+ code: 'invalid',
+ },
+ {
+ name: 'ticket-control-character',
+ input: { executionTicket: 'ticket\u0000value', requestHash, request: parsed.value },
+ code: 'invalid',
+ },
+ {
+ name: 'request-unknown-root-field',
+ input: {
+ executionTicket: ticket,
+ requestHash,
+ request: { ...VISUAL_FIXTURE.png, headers: { Authorization: 'Bearer x' } },
+ },
+ code: 'unknown-field',
+ },
+ {
+ name: 'request-contradictory-parts',
+ input: {
+ executionTicket: ticket,
+ requestHash,
+ request: v2WithParts([{ type: 'text', text: 'actual' }], 'different'),
+ },
+ code: 'invalid',
+ },
+ ]
+ for (const entry of cases) {
+ const built = contract.buildCodexProxyEnvelope(entry.input)
+ assert.equal(built.ok, false, entry.name)
+ assert.equal(built.code, entry.code, entry.name)
+ }
+ assert.equal(contract.buildCodexProxyEnvelope(null).code, 'invalid')
+
+ const v1 = contract.parseCodexCompletionRequest({ ...BASE, deadlineMs: 5000 })
+ assert.equal(v1.ok, true)
+ const v1Envelope = contract.buildCodexProxyEnvelope({
+ executionTicket: ticket,
+ requestHash: contract.hashCodexCompletionRequest(v1.value),
+ request: v1.value,
+ })
+ assert.equal(v1Envelope.ok, true, v1Envelope.message)
+ assert.deepEqual(Object.keys(v1Envelope.value), ['executionTicket', 'requestHash', 'request'])
+ assert.equal('deadlineMs' in v1Envelope.value, false)
+})
+
+test('isBoundedId rejects empty, oversized, and non-id characters', () => {
+ assert.equal(contract.isBoundedId('invocation-1'), true)
+ assert.equal(contract.isBoundedId('ns/name:slot'), true)
+ assert.equal(contract.isBoundedId(''), false)
+ assert.equal(contract.isBoundedId('x'.repeat(129)), false)
+ assert.equal(contract.isBoundedId('has space'), false)
+ assert.equal(contract.isBoundedId(1), false)
+})
+
+test('measureNonImageAuthorizeBytes keeps wrapper fields on the 1 MiB budget', () => {
+ const image = imagePart(IMAGE_DATA.png)
+ const request = {
+ ...BASE,
+ schemaVersion: contract.SCHEMA_VERSION_V2,
+ messages: [
+ {
+ role: 'user',
+ content: 'look',
+ contentParts: [{ type: 'text', text: 'look' }, image],
+ },
+ ],
+ }
+ const wrapper = {
+ request,
+ invocationId: 'invocation-1',
+ attemptGeneration: 1,
+ targetRef: 'codex-primary',
+ }
+ const whole = Buffer.byteLength(JSON.stringify(wrapper), 'utf8')
+ const nonImage = contract.measureNonImageAuthorizeBytes(wrapper)
+ assert.ok(whole > nonImage)
+ assert.ok(nonImage < contract.LIMITS.maxRequestBodyBytes)
+ assert.equal(contract.requestBodyLimitBytes(wrapper.request), 25165824)
+
+ const stuffed = { ...wrapper, invocationId: 'x'.repeat(2 * 1024 * 1024) }
+ assert.ok(contract.measureNonImageAuthorizeBytes(stuffed) > contract.LIMITS.maxRequestBodyBytes)
+ assert.equal(contract.requestBodyLimitBytes(stuffed.request), 25165824)
+})
++
+ // ---------------------------------------------------------------------------
+ // Canonical hashing shared by mcp-host (client) and control-api/codex-llm-proxy
+ // (server), plus the structural depth cap.
+ // ---------------------------------------------------------------------------
+
+ const GOLDEN = JSON.parse(
+ fs.readFileSync(path.join(__dirname, 'fixtures/golden-request-hashes.json'), 'utf8')
+ )
+
+ function nest(depth, key, leaf = {}) {
+ let value = leaf
+ for (let i = 1; i < depth; i++) value = { [key]: value }
+ return value
+ }
+
+ function nestArrays(depth) {
+ let value = []
+ for (let i = 1; i < depth; i++) value = [value]
+ return value
+ }
+
+ /** What a JSON peer (control-api authorize, codex-llm-proxy) computes. */
+ function serverHash(wireRequest) {
+ const onWire = JSON.parse(JSON.stringify({ request: wireRequest })).request
+ const parsed = contract.parseCodexCompletionRequestV1(onWire)
+ assert.equal(parsed.ok, true, parsed.message)
+ return contract.hashCodexCompletionRequestV1(parsed.value)
+ }
+
+ test('golden digests: well-formed requests keep their pre-change hashes on every path', () => {
+ const golden = [
+ ...GOLDEN.cases,
+ {
+ name: 'parameters-at-max-depth-64',
+ request: {
+ ...BASE,
+ requestId: 'req-golden',
+ idempotencyKey: 'idem-golden',
+ messages: [{ role: 'user', content: 'deep' }],
+ tools: [{ name: 'deep', description: 'deep schema', parameters: nest(64, 'n') }],
+ },
+ sha256: GOLDEN.depthBoundaryDigests['parameters-at-max-depth-64'],
+ },
+ {
+ name: 'arguments-at-max-depth-64',
+ request: {
+ ...BASE,
+ requestId: 'req-golden',
+ idempotencyKey: 'idem-golden',
+ messages: [
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'call-deep', name: 'deep', arguments: nest(64, 'a') }],
+ },
+ ],
+ },
+ sha256: GOLDEN.depthBoundaryDigests['arguments-at-max-depth-64'],
+ },
+ ]
+ assert.equal(golden.length, 6)
+ for (const entry of golden) {
+ const parsed = contract.parseCodexCompletionRequestV1(entry.request)
+ assert.equal(parsed.ok, true, `${entry.name}: ${parsed.message}`)
+ assert.equal(contract.hashCodexCompletionRequestV1(parsed.value), entry.sha256, entry.name)
+ const canonical = contract.hashCanonicalCodexRequest(entry.request)
+ assert.equal(canonical.ok, true, entry.name)
+ assert.equal(canonical.value.requestHash, entry.sha256, entry.name)
+ assert.equal(serverHash(canonical.value.request), entry.sha256, entry.name)
+ }
+ })
+
+ const DIVERGENT_SHAPES = [
+ ['empty generation from a non-enum tool_choice', { generation: {} }],
+ ['empty tools array', { tools: [] }],
+ ['empty transportHints', { transportHints: {} }],
+ ['transportHints with an undefined cache key', { transportHints: { promptCacheKey: undefined } }],
+ [
+ 'undefined optional message fields',
+ { messages: [{ role: 'user', content: 'x', name: undefined, toolCallId: undefined }] },
+ ],
+ [
+ 'undefined leaves in assistant tool-call arguments',
+ {
+ messages: [
+ { role: 'user', content: 'x' },
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'c1', name: 't', arguments: { a: undefined, b: [undefined] } }],
+ },
+ ],
+ },
+ ],
+ [
+ 'a Date inside tool parameters (serialized by toJSON on the wire)',
+ {
+ tools: [{ name: 't', description: 'd', parameters: { type: 'object', since: new Date(0) } }],
+ },
+ ],
+ ]
+
+ for (const [label, overrides] of DIVERGENT_SHAPES) {
+ test(`hashCanonicalCodexRequest matches the server hash for ${label}`, () => {
+ const raw = { ...BASE, ...overrides }
+ const canonical = contract.hashCanonicalCodexRequest(raw)
+ assert.equal(canonical.ok, true, canonical.message)
+ assert.match(canonical.value.requestHash, /^[a-f0-9]{64}$/)
+ // mcp-host sends the canonical request; a caller that still sent the raw
+ // request must land on the same digest.
+ assert.equal(serverHash(canonical.value.request), canonical.value.requestHash)
+ assert.equal(serverHash(raw), canonical.value.requestHash)
+ })
+ }
+
+ test('hashCanonicalCodexRequest drops empty optional containers from the canonical request', () => {
+ const canonical = contract.hashCanonicalCodexRequest({
+ ...BASE,
+ generation: {},
+ tools: [],
+ transportHints: {},
+ })
+ assert.equal(canonical.ok, true)
+ assert.deepEqual(Object.keys(canonical.value.request).sort(), Object.keys(BASE).sort())
+ })
+
+ test('hashCanonicalCodexRequest fails closed without throwing on invalid input', () => {
+ const cases = [
+ [{ ...BASE, generation: { temperature: 3 } }, 'invalid'],
+ [{ ...BASE, provider: 'grok-subscription' }, 'invalid'],
+ [{ ...BASE, headers: { authorization: 'x' } }, 'unknown-field'],
+ [{ ...BASE, deadlineMs: 10n }, 'invalid'],
+ ['not-an-object', 'invalid'],
+ ]
+ for (const [raw, code] of cases) {
+ const result = contract.hashCanonicalCodexRequest(raw)
+ assert.equal(result.ok, false)
+ assert.equal(result.code, code)
+ }
+ const cyclic = { ...BASE, tools: [{ name: 't', description: 'd', parameters: {} }] }
+ cyclic.tools[0].parameters.self = cyclic.tools[0].parameters
+ const cyclicResult = contract.hashCanonicalCodexRequest(cyclic)
+ assert.equal(cyclicResult.ok, false)
+ assert.equal(cyclicResult.code, 'limit')
+ })
+
+ test('LIMITS publishes the nesting depth cap', () => {
+ assert.equal(contract.LIMITS.maxNestingDepth, 64)
+ })
+
+ test('tool parameters accept depth 64 and reject depth 65 with a limit failure', () => {
+ const at = contract.parseCodexCompletionRequestV1({
+ ...BASE,
+ tools: [{ name: 'deep', description: 'd', parameters: nest(64, 'n') }],
+ })
+ assert.equal(at.ok, true, at.message)
+ const over = contract.parseCodexCompletionRequestV1({
+ ...BASE,
+ tools: [{ name: 'deep', description: 'd', parameters: nest(65, 'n') }],
+ })
+ assert.equal(over.ok, false)
+ assert.equal(over.code, 'limit')
+ assert.match(over.message, /nesting depth/)
+ })
+
+ test('assistant tool-call arguments accept depth 64 and reject depth 65', () => {
+ const request = depth => ({
+ ...BASE,
+ messages: [
+ {
+ role: 'assistant',
+ content: '',
+ toolCalls: [{ id: 'c1', name: 'deep', arguments: nest(depth, 'a') }],
+ },
+ ],
+ })
+ const at = contract.parseCodexCompletionRequestV1(request(64))
+ assert.equal(at.ok, true, at.message)
+ const over = contract.parseCodexCompletionRequestV1(request(65))
+ assert.equal(over.ok, false)
+ assert.equal(over.code, 'limit')
+ })
+
+ for (const depth of [5000, 150000]) {
+ test(`a ${depth}-deep body returns a limit failure instead of a RangeError`, () => {
+ const viaObjects = {
+ ...BASE,
+ tools: [{ name: 't', description: 'd', parameters: nest(depth, 'n') }],
+ }
+ const viaArrays = {
+ ...BASE,
+ tools: [{ name: 't', description: 'd', parameters: { x: nestArrays(depth) } }],
+ }
+ for (const raw of [viaObjects, viaArrays]) {
+ const parsed = contract.parseCodexCompletionRequestV1(raw)
+ assert.equal(parsed.ok, false)
+ assert.equal(parsed.code, 'limit')
+ const canonical = contract.hashCanonicalCodexRequest(raw)
+ assert.equal(canonical.ok, false)
+ assert.equal(canonical.code, 'limit')
+ }
+ })
+ }
+
+ test('stableStringify rejects over-deep values with a limit error, not a stack overflow', () => {
+ for (const value of [nest(5000, 'n'), nestArrays(150000)]) {
+ assert.throws(
+ () => contract.stableStringify(value),
+ err => err.code === 'limit' && !(err instanceof RangeError)
+ )
+ }
+ // Any request the parser accepts stays serializable.
+ assert.doesNotThrow(() =>
+ contract.stableStringify({
+ tools: [{ parameters: nest(64, 'n') }],
+ m: [[{ a: nest(64, 'a') }]],
+ })
+ )
+ })
+
+ test('frozen Codex fixture corpus hashes identically through hashCanonicalCodexRequest', () => {
+ for (const fixture of FIXTURE.cases) {
+ for (const request of [fixture.request, fixture.equivalentRequest].filter(Boolean)) {
+ const canonical = contract.hashCanonicalCodexRequest(request)
+ assert.equal(canonical.ok, true, fixture.name)
+ assert.equal(canonical.value.requestHash, fixture.sha256, fixture.name)
+ }
+ }
+ for (const fixture of FIXTURE.rejects) {
+ assert.equal(contract.hashCanonicalCodexRequest(fixture.request).ok, false, fixture.name)
+ }
+ })
diff --cc scripts/tests/test-codex-subscription-t0.sh
index 19a1b6d10,2a2db3224..6e9a48793
--- a/scripts/tests/test-codex-subscription-t0.sh
+++ b/scripts/tests/test-codex-subscription-t0.sh
@@@ -245,10 -252,11 +252,12 @@@ run_group "codex-llm-proxy" "codex-llm-
"test/controlApiClient.test.ts" \
"test/originPolicy.test.ts" \
"test/redaction.test.ts" \
- "test/server.security.test.ts"
+ "test/requestLimits.test.ts" \
+ "test/server.security.test.ts" \
+ "test/sseBackpressure.test.ts"
run_group "mcp-host" "mcp-host" \
+ "src/__tests__/bodylimits.test.ts" \
"src/capabilities/toolCatalogTools.test.ts" \
"src/core/orchestration/__tests__/approvedToolsLifecycle.integration.test.ts" \
"src/core/orchestration/__tests__/toolUseLoop.spillover.test.ts" \
@@@ -258,15 -266,10 +267,16 @@@
"src/core/orchestration/__tests__/deferrableToolController.test.ts" \
"src/core/orchestration/__tests__/toolCallBridge.test.ts" \
"src/core/orchestration/__tests__/toolUseLoop.test.ts" \
+ "src/core/orchestration/__tests__/toolUseLoopMessages.test.ts" \
+ "src/core/extensions/__tests__/prePrune.test.ts" \
+ "src/core/adapters/__tests__/llmImageCompatibility.test.ts" \
+ "src/core/adapters/__tests__/llmPortAdapterDiagnostics.test.ts" \
"src/agent/__tests__/taskExecutor.test.ts" \
+ "src/llm/__tests__/openai.singleTurn.test.ts" \
+ "src/llm/__tests__/claude.singleTurn.test.ts" \
"src/llm/__tests__/codexSubscription.test.ts" \
"src/llm/__tests__/codexLlmProxyClient.test.ts" \
+ "src/llm/__tests__/subscriptionRequestHash.test.ts" \
"src/llm/__tests__/providerAttemptAuthorizer.test.ts" \
"src/llm/hostLlmBinding.test.ts" \
"src/config/configStore.test.ts" \
diff --cc tests/e2e/fixtures/package-lock.json
index ed3798c84,294dde8e7..0d1f39505
--- 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.82",
- "version": "1.0.81",
++ "version": "1.0.83",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.82",
- "version": "1.0.81",
++ "version": "1.0.83",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --cc tests/e2e/fixtures/package.json
index 4a7bd3ce9,2e65862dc..e99436a70
--- 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.82",
- "version": "1.0.81",
++ "version": "1.0.83",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",