Skip to content

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

TypeScript

fix(codex-llm-proxy): report tool_call_limit_exceeded as 422 with attempt telemetry

Alfredo Lopez1a457fb54171
diff --git a/codex-llm-proxy/src/codexTransport.ts b/codex-llm-proxy/src/codexTransport.ts
index 5fca274bb..8364d87ea 100644
--- a/codex-llm-proxy/src/codexTransport.ts
+++ b/codex-llm-proxy/src/codexTransport.ts
@@ -41,7 +41,8 @@ export type TransportTicket = {
export class CodexTransportError extends Error {
constructor(
readonly code: string,
- message: string
+ message: string,
+ readonly details?: Readonly<Record<string, number | string>>
) {
super(message)
this.name = 'CodexTransportError'
@@ -343,15 +344,17 @@ async function consumeSse(
const acceptFrame = async (frame?: StreamFrame): Promise<void> => {
if (pending.size > LIMITS.maxToolCalls) {
throw new CodexTransportError(
- 'provider_unavailable',
- `tool calls exceed ${LIMITS.maxToolCalls}`
+ 'tool_call_limit_exceeded',
+ `tool calls exceed ${LIMITS.maxToolCalls}`,
+ { limit: LIMITS.maxToolCalls, observed: pending.size }
)
}
if (frame?.type === 'tool_call') {
if (toolFrames.length >= LIMITS.maxToolCalls) {
throw new CodexTransportError(
- 'provider_unavailable',
- `tool calls exceed ${LIMITS.maxToolCalls}`
+ 'tool_call_limit_exceeded',
+ `tool calls exceed ${LIMITS.maxToolCalls}`,
+ { limit: LIMITS.maxToolCalls, observed: toolFrames.length + 1 }
)
}
const canonicalName = names.fromWire(frame.name)
diff --git a/codex-llm-proxy/src/metrics.ts b/codex-llm-proxy/src/metrics.ts
index ce5b8a67c..4c71f426f 100644
--- a/codex-llm-proxy/src/metrics.ts
+++ b/codex-llm-proxy/src/metrics.ts
@@ -13,10 +13,19 @@ export function createProxyMetrics(register: Registry) {
buckets: [0.1, 0.5, 1, 2, 5, 15, 30, 60, 120, 300],
registers: [register],
})
+ const attemptFailures = new Counter({
+ name: 'codex_proxy_attempt_failures_total',
+ help: 'Codex completion attempts that failed, by provider error code',
+ labelNames: ['code'],
+ registers: [register],
+ })
return {
observeAttempt(outcome: string, operation: string) {
outcomes.inc({ outcome, operation })
},
+ observeAttemptFailure(code: string) {
+ attemptFailures.inc({ code })
+ },
observeStream(durationMs: number) {
streamSeconds.observe(durationMs / 1000)
},
diff --git a/codex-llm-proxy/src/server.ts b/codex-llm-proxy/src/server.ts
index 6d6448cfe..2af941235 100644
--- a/codex-llm-proxy/src/server.ts
+++ b/codex-llm-proxy/src/server.ts
@@ -161,6 +161,17 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeD
// to req 'close' aborts the ChatGPT hop on every call (3–12ms canceled).
// Abort only when the client drops the response before we finish writing.
abortWhenClientDisconnects(req, res, abort)
+ // One `codex_proxy_attempt_finished` line per attempt. Identifiers and
+ // counts only: never the body, ticket, frames, tool names or arguments.
+ const attempt = {
+ providerAttemptId: ticket.providerAttemptId,
+ hostRef: ticket.hostRef,
+ model: ticket.model,
+ requestHash: ticket.requestHash,
+ }
+ const attemptStarted = Date.now()
+ let toolCalls = 0
+ let textChunks = 0
try {
release = await streamGate.acquire(abort.signal)
res.status(200)
@@ -185,23 +196,58 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeD
finalize: input => client.finalize(input),
fetchFn,
lookup,
- onFrame: frame => writeSseChunk(res, `data: ${JSON.stringify(frame)}\n\n`, abort.signal),
+ onFrame: frame => {
+ if (frame.type === 'tool_call') toolCalls += 1
+ else textChunks += 1
+ return writeSseChunk(res, `data: ${JSON.stringify(frame)}\n\n`, abort.signal)
+ },
})
res.write(
`data: ${JSON.stringify({ type: 'done', outcome: result.outcome, ...(result.usage ? { usage: result.usage } : {}) })}\n\n`
)
metrics.observeAttempt(result.outcome, 'completion_stream')
metrics.observeStream(Date.now() - started)
+ const finished = {
+ event: 'codex_proxy_attempt_finished',
+ ...attempt,
+ outcome: result.outcome,
+ deliveredAs: 'sse_done',
+ toolCalls,
+ textChunks,
+ durationMs: Date.now() - attemptStarted,
+ ...(result.usage ? { usage: result.usage } : {}),
+ }
+ if (result.outcome === 'success') logger.info(finished, 'codex attempt finished')
+ else logger.warn(finished, 'codex attempt finished')
res.end()
} catch (err) {
const mapped = mapError(err)
metrics.observeAttempt('error', 'completion_stream')
- if (res.headersSent) {
+ metrics.observeAttemptFailure(mapped.code)
+ const deliveredAs = res.headersSent ? 'sse_error' : 'http_status'
+ logger.warn(
+ {
+ event: 'codex_proxy_attempt_finished',
+ ...attempt,
+ outcome: 'failed',
+ code: mapped.code,
+ ...(err instanceof CodexTransportError
+ ? { reason: err.message, ...(err.details ? { details: err.details } : {}) }
+ : {}),
+ deliveredAs,
+ ...(deliveredAs === 'http_status' ? { httpStatus: mapped.status } : {}),
+ toolCalls,
+ textChunks,
+ durationMs: Date.now() - attemptStarted,
+ },
+ 'codex attempt finished'
+ )
+ if (deliveredAs === 'sse_error') {
res.write(`data: ${JSON.stringify({ type: 'error', code: mapped.code })}\n\n`)
res.end()
return
}
- reject(res, mapped.status, mapped.code)
+ res.status(mapped.status).json({ error: mapped.code })
} finally {
release?.()
}
@@ -327,6 +373,7 @@ function mapError(err: unknown): { status: number; code: string } {
insufficient_scope: 403,
disabled: 404,
ticket_replayed: 409,
+ tool_call_limit_exceeded: 422,
connection_unavailable: 503,
provider_unavailable: 503,
}
diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.ts
index 7a02f7ca4..945609cad 100644
--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts
+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts
@@ -336,7 +336,7 @@ describe('streamCodexCompletion', () => {
expect(emitted).toEqual([])
}
)
- it.each([32, 33])(
+ it.each([64, 65])(
'validates the complete %s-call response before emitting executable calls',
async count => {
const emitted: Array<{ type: string }> = []
@@ -373,11 +373,16 @@ describe('streamCodexCompletion', () => {
emitted.push(frame)
},
})
- if (count === 32) {
+ if (count === 64) {
expect((await pending).outcome).toBe('success')
- expect(emitted.filter(frame => frame.type === 'tool_call')).toHaveLength(32)
+ expect(emitted.filter(frame => frame.type === 'tool_call')).toHaveLength(64)
} else {
- await expect(pending).rejects.toThrow(/tool calls exceed 32/)
+ await expect(pending).rejects.toMatchObject({
+ name: 'CodexTransportError',
+ code: 'tool_call_limit_exceeded',
+ message: 'tool calls exceed 64',
+ details: { limit: 64, observed: 65 },
+ })
expect(emitted.filter(frame => frame.type === 'tool_call')).toHaveLength(0)
expect(finalize).toHaveBeenCalledWith(
expect.objectContaining({ receipt: expect.objectContaining({ outcome: 'error' }) })
diff --git a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
index 413ab4d95..a002134be 100644
--- a/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
+++ b/codex-llm-proxy/test/runtimePath.hermetic.e2e.test.ts
@@ -222,6 +222,55 @@ let upstream: ChildProcess | undefined
let workdir: string
let servers: ProxyServers | undefined
let fixtureCa: Buffer | undefined
+let tlsPaths: { certPath: string; keyPath: string } | undefined
+
+/**
+ * Spawn the fixture upstream on `port` with the run-generated certificate.
+ * The fixture reads its canned reply from the environment at startup, so a
+ * case that needs a different reply spawns its own process.
+ */
+async function spawnFixtureUpstream(
+ port: number,
+ extraEnv: Record<string, string>
+): Promise<ChildProcess> {
+ if (!tlsPaths) throw new Error('fixture TLS material is not ready')
+ const child = spawn(process.execPath, [FIXTURE_UPSTREAM], {
+ env: {
+ ...process.env,
+ CODEX_TEST_UPSTREAM_PORT: String(port),
+ CODEX_TEST_UPSTREAM_CERT_PATH: tlsPaths.certPath,
+ CODEX_TEST_UPSTREAM_KEY_PATH: tlsPaths.keyPath,
+ CODEX_TEST_UPSTREAM_TOOL_CALL: JSON.stringify({
+ name: eventaskUpdateTool.name,
+ arguments: OPTIONAL_CALL_ARGUMENTS,
+ }),
+ ...extraEnv,
+ },
+ stdio: ['ignore', 'pipe', 'inherit'],
+ })
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('fixture upstream did not start')), 15_000)
+ child.stdout?.on('data', (chunk: Buffer) => {
+ if (chunk.toString('utf8').includes('listening')) {
+ clearTimeout(timer)
+ resolve()
+ }
+ })
+ child.on('exit', code => {
+ clearTimeout(timer)
+ reject(new Error(`fixture upstream exited early (code ${code})`))
+ })
+ })
+ return child
+}
+
+async function stopFixtureUpstream(child: ChildProcess): Promise<void> {
+ if (child.exitCode !== null || child.signalCode !== null) return
+ await new Promise<void>(resolve => {
+ child.once('exit', () => resolve())
+ child.kill('SIGTERM')
+ })
+}
function trustedLoopbackFetch(url: string | URL, init?: RequestInit): Promise<Response> {
if (!fixtureCa) {
@@ -303,32 +352,8 @@ beforeAll(async () => {
{ stdio: 'ignore' }
)
fixtureCa = readFileSync(certPath)
- upstream = spawn(process.execPath, [FIXTURE_UPSTREAM], {
- env: {
- ...process.env,
- CODEX_TEST_UPSTREAM_PORT: String(UPSTREAM_PORT),
- CODEX_TEST_UPSTREAM_CERT_PATH: certPath,
- CODEX_TEST_UPSTREAM_KEY_PATH: keyPath,
- CODEX_TEST_UPSTREAM_TOOL_CALL: JSON.stringify({
- name: eventaskUpdateTool.name,
- arguments: OPTIONAL_CALL_ARGUMENTS,
- }),
- },
- stdio: ['ignore', 'pipe', 'inherit'],
- })
- await new Promise<void>((resolve, reject) => {
- const timer = setTimeout(() => reject(new Error('fixture upstream did not start')), 15_000)
- upstream?.stdout?.on('data', (chunk: Buffer) => {
- if (chunk.toString('utf8').includes('listening')) {
- clearTimeout(timer)
- resolve()
- }
- })
- upstream?.on('exit', code => {
- clearTimeout(timer)
- reject(new Error(`fixture upstream exited early (code ${code})`))
- })
- })
+ tlsPaths = { certPath, keyPath }
+ upstream = await spawnFixtureUpstream(UPSTREAM_PORT, {})
}, 30_000)
afterAll(async () => {
@@ -480,3 +505,130 @@ describe('hermetic authorize → proxy → fixture upstream → finalize', () =>
servers = undefined
})
})
+
+describe('hermetic per-response tool-call limit', () => {
+ // Each case owns an upstream on its own port: the fixture reads the repeat
+ // count at startup, so the shared upstream above cannot serve these replies.
+ const LIMIT_UPSTREAM_PORT = UPSTREAM_PORT + 1
+
+ async function runWithToolCallCount(
+ count: number,
+ providerAttemptId: string,
+ options: { omitText: boolean }
+ ) {
+ const limitUpstream = await spawnFixtureUpstream(LIMIT_UPSTREAM_PORT, {
+ CODEX_TEST_UPSTREAM_TOOL_CALL_COUNT: String(count),
+ ...(options.omitText ? { CODEX_TEST_UPSTREAM_OMIT_TEXT: '1' } : {}),
+ })
+ const base = `https://127.0.0.1:${LIMIT_UPSTREAM_PORT}`
+ const { client, redeems, finalizes } = makeControlApiMock()
+ const proxy = createProxyApps(config(), {
+ controlApiClient: client,
+ fetchFn: (url, init) => {
+ const parsed = new URL(String(url))
+ expect(parsed.origin).toBe('https://chatgpt.com')
+ return trustedLoopbackFetch(new URL(parsed.pathname + parsed.search, base), init)
+ },
+ lookup: async () => [{ address: '104.18.32.47', family: 4 }],
+ })
+ try {
+ // The request presents the fixture's tool name, so the upstream serves
+ // the stream instead of refusing with fixture_tool_not_declared.
+ const raw = { ...completionRequest('gpt-5.3-codex'), tools: structuredClone(optionalMcpTools) }
+ const parsed = parseCodexCompletionRequestV1(raw)
+ if (!parsed.ok) throw new Error(parsed.message)
+ const requestHash = hashCodexCompletionRequestV1(parsed.value)
+ const res = await request(proxy.runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken(RECIPE_HOST_REF)}`)
+ .send({
+ executionTicket: executionTicket({
+ hostRef: RECIPE_HOST_REF,
+ model: 'gpt-5.3-codex',
+ requestHash,
+ providerAttemptId,
+ }),
+ requestHash,
+ request: raw,
+ })
+ const counters = (await (
+ await trustedLoopbackFetch(`${base}/internal/counters`)
+ ).json()) as Record<string, number>
+ return { res, redeems, finalizes, counters }
+ } finally {
+ await proxy.close()
+ await stopFixtureUpstream(limitUpstream)
+ }
+ }
+
+ it('rejects 65 calls before any text with 422 tool_call_limit_exceeded', async () => {
+ const { res, redeems, finalizes, counters } = await runWithToolCallCount(
+ 65,
+ 'att-hermetic-limit-65',
+ { omitText: true }
+ )
+
+ // Liveness witness: the upstream really served the 65-call stream.
+ expect(counters.streams).toBe(1)
+ // One assertion so a regression reports both the status and the code.
+ expect({ status: res.status, body: JSON.parse(res.text) }).toEqual({
+ status: 422,
+ body: { error: 'tool_call_limit_exceeded' },
+ })
+ expect(res.text).not.toContain('"type":"tool_call"')
+ expect(redeems).toHaveLength(1)
+ expect(finalizes).toHaveLength(1)
+ expect(finalizes[0]?.receipt).toMatchObject({
+ providerAttemptId: 'att-hermetic-limit-65',
+ outcome: 'error',
+ })
+ })
+
+ it('rejects 65 calls after streamed text with an SSE tool_call_limit_exceeded frame', async () => {
+ const { res, redeems, finalizes, counters } = await runWithToolCallCount(
+ 65,
+ 'att-hermetic-limit-65-text',
+ { omitText: false }
+ )
+
+ expect(counters.streams).toBe(1)
+ // The text delta already reached the client, so the status is committed.
+ expect(res.status).toBe(200)
+ const frames = sseFrames(res.text)
+ // Liveness witness: the stream was live before the limit tripped.
+ expect(frames[0]).toEqual({ type: 'text', text: 'hello' })
+ expect(frames.filter(frame => frame.type === 'tool_call')).toHaveLength(0)
+ expect(frames.filter(frame => frame.type === 'done')).toHaveLength(0)
+ expect(frames[frames.length - 1]).toMatchObject({ type: 'error', code: 'tool_call_limit_exceeded' })
+ expect(redeems).toHaveLength(1)
+ expect(finalizes).toHaveLength(1)
+ expect(finalizes[0]?.receipt).toMatchObject({
+ providerAttemptId: 'att-hermetic-limit-65-text',
+ outcome: 'error',
+ })
+ })
+
+ it('delivers exactly 64 calls in one response', async () => {
+ const { res, redeems, finalizes, counters } = await runWithToolCallCount(
+ 64,
+ 'att-hermetic-limit-64',
+ { omitText: true }
+ )
+
+ expect(counters.streams).toBe(1)
+ expect(res.status).toBe(200)
+ const frames = sseFrames(res.text)
+ const toolCalls = frames.filter(frame => frame.type === 'tool_call')
+ expect(toolCalls).toHaveLength(64)
+ expect(toolCalls.map(frame => frame.id)).toEqual(
+ Array.from({ length: 64 }, (_, index) => `call-hermetic-${index}`)
+ )
+ expect(frames.find(frame => frame.type === 'done')?.outcome).toBe('success')
+ expect(redeems).toHaveLength(1)
+ expect(finalizes).toHaveLength(1)
+ expect(finalizes[0]?.receipt).toMatchObject({
+ providerAttemptId: 'att-hermetic-limit-64',
+ outcome: 'success',
+ })
+ })
+})
diff --git a/codex-llm-proxy/test/server.security.test.ts b/codex-llm-proxy/test/server.security.test.ts
index f052b12c3..dbd237242 100644
--- a/codex-llm-proxy/test/server.security.test.ts
+++ b/codex-llm-proxy/test/server.security.test.ts
@@ -5,11 +5,18 @@ import {
hashCodexCompletionRequestV1,
parseCodexCompletionRequestV1,
} from '@clerum/llm-provider-attempt-contract'
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } 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 { ControlApiClient, ControlApiClientError } from '../src/controlApiClient.js'
+import {
+ ControlApiClient,
+ ControlApiClientError,
+ type FinalizeAttemptSuccess,
+ type RedeemAttemptSuccess,
+} from '../src/controlApiClient.js'
+import { logger } from '../src/logger.js'
+import { CODEX_COMPLETIONS_ORIGIN } from '../src/originPolicy.js'
import { createProxyApps } from '../src/server.js'
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
@@ -446,3 +453,187 @@ describe('codex-llm-proxy startup config', () => {
}
)
})
+
+describe('codex-llm-proxy attempt telemetry', () => {
+ const lookup = async () => [{ address: '1.2.3.4', family: 4 }]
+ const FORBIDDEN_LOG_KEYS = ['body', 'request', 'executionTicket', 'arguments']
+
+ function completionBody(providerAttemptId: string): Record<string, unknown> {
+ const raw = {
+ schemaVersion: 'codex-completion-request.v1',
+ requestId: `req-${providerAttemptId}`,
+ idempotencyKey: `idem-${providerAttemptId}`,
+ 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: '44444444-4444-4444-8444-444444444444',
+ typ: 'codex-execution-ticket',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash,
+ providerAttemptId,
+ },
+ 'codex-llm-proxy'
+ )
+ return { executionTicket, requestHash, request: raw }
+ }
+
+ function grantingClient(): { client: ControlApiClient; receipts: unknown[] } {
+ const receipts: unknown[] = []
+ const claims = Buffer.from(
+ JSON.stringify({
+ sub: 'telemetry',
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'acct_live_1' },
+ })
+ ).toString('base64url')
+ const client = {
+ async redeem(): Promise<RedeemAttemptSuccess> {
+ return {
+ accessToken: `hdr.${claims}.sig`,
+ transport: {
+ protocolVersion: 'codex-subscription-transport.v1',
+ completionsOrigin: CODEX_COMPLETIONS_ORIGIN,
+ catalogOrigin: 'https://chatgpt.com/backend-api/codex/models?client_version=1.0.0',
+ operation: 'completion_stream',
+ servedModel: 'gpt-5.1',
+ maxStreamDurationMs: 300_000,
+ },
+ expiryClass: 'short_lived',
+ attemptReceipt: 'a'.repeat(64),
+ }
+ },
+ async finalize(input: {
+ receipt: { outcome: FinalizeAttemptSuccess['outcome'] }
+ }): Promise<FinalizeAttemptSuccess> {
+ receipts.push(input.receipt)
+ return { providerAttemptId: 'att', outcome: input.receipt.outcome, duplicate: false }
+ },
+ } as unknown as ControlApiClient
+ return { client, receipts }
+ }
+
+ function upstream(textDeltas: number, calls: number): typeof fetch {
+ const frames: string[] = []
+ for (let index = 0; index < textDeltas; index += 1) {
+ frames.push(
+ `data: ${JSON.stringify({ type: 'response.output_text.delta', delta: `t${index}` })}\n\n`
+ )
+ }
+ for (let index = 0; index < calls; index += 1) {
+ frames.push(
+ `data: ${JSON.stringify({
+ type: 'response.output_item.done',
+ item: { type: 'function_call', id: `call-${index}`, name: 'lookup', arguments: '{}' },
+ })}\n\n`
+ )
+ }
+ frames.push('data: {"type":"response.completed"}\n\n')
+ return (async () =>
+ new Response(frames.join(''), {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ })) as typeof fetch
+ }
+
+ function failureCount(metricsText: string, code: string): number {
+ const line = metricsText
+ .split('\n')
+ .find(row => row.startsWith(`codex_proxy_attempt_failures_total{code="${code}"}`))
+ return line ? Number(line.split(' ').pop()) : 0
+ }
+
+ async function run(providerAttemptId: string, textDeltas: number, calls: number) {
+ const info = vi.spyOn(logger, 'info')
+ const warn = vi.spyOn(logger, 'warn')
+ const { client, receipts } = grantingClient()
+ const apps = createProxyApps(config({ maxBodyBytes: 65_536 }), {
+ controlApiClient: client,
+ fetchFn: upstream(textDeltas, calls),
+ lookup,
+ })
+ try {
+ const res = await request(apps.runtimeApp)
+ .post('/internal/runtime/v1/codex/completions')
+ .set('Authorization', `Bearer ${platformToken()}`)
+ .send(completionBody(providerAttemptId))
+ const metricsText = (await request(apps.probeApp).get('/metrics')).text
+ const lines = [...info.mock.calls, ...warn.mock.calls]
+ .map(call => call[0] as unknown as Record<string, unknown>)
+ .filter(entry => entry?.event === 'codex_proxy_attempt_finished')
+ return { res, receipts, lines, metricsText }
+ } finally {
+ info.mockRestore()
+ warn.mockRestore()
+ }
+ }
+
+ function expectNoForbiddenKeys(line: Record<string, unknown>): void {
+ for (const key of FORBIDDEN_LOG_KEYS) expect(key in line).toBe(false)
+ }
+
+ it('(a) answers 422 and logs one attempt line when 65 calls arrive before any text', async () => {
+ const { res, receipts, lines, metricsText } = await run('att-limit-http', 0, 65)
+ expect(res.status).toBe(422)
+ // The SSE content-type is set before streaming starts, so parse the text.
+ expect(JSON.parse(res.text)).toEqual({ error: 'tool_call_limit_exceeded' })
+ expect(receipts).toEqual([expect.objectContaining({ outcome: 'error' })])
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).toMatchObject({
+ providerAttemptId: 'att-limit-http',
+ outcome: 'failed',
+ code: 'tool_call_limit_exceeded',
+ reason: 'tool calls exceed 64',
+ details: { limit: 64, observed: 65 },
+ deliveredAs: 'http_status',
+ httpStatus: 422,
+ toolCalls: 0,
+ textChunks: 0,
+ })
+ expectNoForbiddenKeys(lines[0]!)
+ expect(failureCount(metricsText, 'tool_call_limit_exceeded')).toBe(1)
+ })
+
+ it('(b) sends an SSE error frame when text was already streamed', async () => {
+ const { res, lines } = await run('att-limit-sse', 1, 65)
+ expect(res.status).toBe(200)
+ expect(res.text).toContain('data: {"type":"text","text":"t0"}')
+ expect(res.text).toContain('data: {"type":"error","code":"tool_call_limit_exceeded"}')
+ expect(res.text).not.toContain('"type":"tool_call"')
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).toMatchObject({
+ outcome: 'failed',
+ code: 'tool_call_limit_exceeded',
+ deliveredAs: 'sse_error',
+ textChunks: 1,
+ toolCalls: 0,
+ })
+ expect('httpStatus' in lines[0]!).toBe(false)
+ expectNoForbiddenKeys(lines[0]!)
+ })
+
+ it('(c) logs the counted frames of a successful attempt', async () => {
+ const { res, lines, metricsText } = await run('att-success', 0, 3)
+ expect(res.status).toBe(200)
+ expect(res.text).toContain('"type":"done","outcome":"success"')
+ expect(lines).toHaveLength(1)
+ expect(lines[0]).toMatchObject({
+ providerAttemptId: 'att-success',
+ outcome: 'success',
+ deliveredAs: 'sse_done',
+ toolCalls: 3,
+ textChunks: 0,
+ })
+ expectNoForbiddenKeys(lines[0]!)
+ // Witness: the attempt was counted, so the absent failure sample is meaningful.
+ expect(metricsText).toMatch(
+ /codex_llm_proxy_attempts_total\{outcome="success",operation="completion_stream"\} 1/
+ )
+ expect(failureCount(metricsText, 'tool_call_limit_exceeded')).toBe(0)
+ })
+})
diff --git a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
index 6289c4ca4..d6f693c50 100755
--- a/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
+++ b/tests/e2e/fixtures/codex-subscription/test-upstream/server.mjs
@@ -16,6 +16,27 @@ const key = readFileSync(process.env.CODEX_TEST_UPSTREAM_KEY_PATH, 'utf8')
const fixtureToolCall = process.env.CODEX_TEST_UPSTREAM_TOOL_CALL
? JSON.parse(process.env.CODEX_TEST_UPSTREAM_TOOL_CALL)
: undefined
+// Optional repeat count for the canned call, used by the per-response
+// tool-call limit tests. Unset keeps the single `call-hermetic-optional` reply.
+const rawToolCallCount = process.env.CODEX_TEST_UPSTREAM_TOOL_CALL_COUNT
+const fixtureToolCallCount = rawToolCallCount === undefined ? undefined : Number(rawToolCallCount)
+if (
+ fixtureToolCallCount !== undefined &&
+ (!Number.isInteger(fixtureToolCallCount) || fixtureToolCallCount < 1 || !fixtureToolCall)
+) {
+ throw new Error(
+ 'CODEX_TEST_UPSTREAM_TOOL_CALL_COUNT must be an integer >= 1 and requires CODEX_TEST_UPSTREAM_TOOL_CALL'
+ )
+}
+// Optional: drop the leading text delta so a limit failure happens before the
+// proxy sends any SSE byte (HTTP status path instead of an SSE error frame).
+const rawOmitText = process.env.CODEX_TEST_UPSTREAM_OMIT_TEXT
+if (rawOmitText !== undefined && (rawOmitText !== '1' || fixtureToolCallCount === undefined)) {
+ throw new Error(
+ 'CODEX_TEST_UPSTREAM_OMIT_TEXT must be "1" and requires CODEX_TEST_UPSTREAM_TOOL_CALL_COUNT'
+ )
+}
+const fixtureOmitText = rawOmitText === '1'
const counters = {
consent: 0,
@@ -127,25 +148,33 @@ const server = createServer({ cert, key }, async (request, response) => {
// the `type` field INSIDE the data payload, exactly like the live
// ChatGPT backend. `event:` lines alone are ignored, so frames without
// an embedded type would leave the stream outcome `unknown`.
- response.write(
- `event: response.output_text.delta\ndata: ${JSON.stringify({
- type: 'response.output_text.delta',
- delta: 'hello',
- })}\n\n`
- )
- if (fixtureToolCall) {
+ if (!fixtureOmitText) {
response.write(
- `data: ${JSON.stringify({
- type: 'response.output_item.done',
- item: {
- type: 'function_call',
- call_id: 'call-hermetic-optional',
- name: fixtureToolCall.name,
- arguments: JSON.stringify(fixtureToolCall.arguments),
- },
+ `event: response.output_text.delta\ndata: ${JSON.stringify({
+ type: 'response.output_text.delta',
+ delta: 'hello',
})}\n\n`
)
}
+ if (fixtureToolCall) {
+ const callIds =
+ fixtureToolCallCount === undefined
+ ? ['call-hermetic-optional']
+ : Array.from({ length: fixtureToolCallCount }, (_, index) => `call-hermetic-${index}`)
+ for (const callId of callIds) {
+ response.write(
+ `data: ${JSON.stringify({
+ type: 'response.output_item.done',
+ item: {
+ type: 'function_call',
+ call_id: callId,
+ name: fixtureToolCall.name,
+ arguments: JSON.stringify(fixtureToolCall.arguments),
+ },
+ })}\n\n`
+ )
+ }
+ }
response.write(
`event: response.completed\ndata: ${JSON.stringify({
type: 'response.completed',
diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.json
index 294dde8e7..ed3798c84 100644
--- a/tests/e2e/fixtures/package-lock.json
+++ b/tests/e2e/fixtures/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.81",
+ "version": "1.0.82",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.81",
+ "version": "1.0.82",
"dependencies": {
"@kubernetes/client-node": "^1.0.0"
},
diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.json
index 2e65862dc..4a7bd3ce9 100644
--- a/tests/e2e/fixtures/package.json
+++ b/tests/e2e/fixtures/package.json
@@ -1,6 +1,6 @@
{
"name": "@clerum/e2e-test-fixtures",
- "version": "1.0.81",
+ "version": "1.0.82",
"description": "E2E test fixtures and utilities for Clerum testing",
"type": "module",
"main": "index.ts",