Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(codex): preserve canonical tool names through transport aliases
Alfredo Lopez299762dac09e
diff --git a/codex-llm-proxy/src/codexTransport.ts b/codex-llm-proxy/src/codexTransport.tsindex b8a90566d..b3427c370 100644--- a/codex-llm-proxy/src/codexTransport.ts+++ b/codex-llm-proxy/src/codexTransport.ts@@ -16,6 +16,7 @@ import {fetchFrozenOrigin,} from './originPolicy.js'import { assertBoundedDeadline } from './requestLimits.js'+import { ToolNameMap } from './toolNameMap.js'import { type SafeUsage, parseSafeUsage } from './usage.js'export type StreamFrame =@@ -205,6 +206,12 @@ async function readUpstreamStream(input: {'Codex access token is missing ChatGPT account id')}+ const names = new ToolNameMap([+ ...(input.request.tools ?? []).map(tool => tool.name),+ ...input.request.messages.flatMap(message =>+ message.role === 'assistant' ? (message.toolCalls ?? []).map(call => call.name) : []+ ),+ ])const response = await fetchFrozenOrigin({url,fetchFn: input.fetchFn,@@ -213,7 +220,7 @@ async function readUpstreamStream(input: {method: 'POST',signal,headers,- body: JSON.stringify(toUpstreamPayload(input.request)),+ body: JSON.stringify(toUpstreamPayload(input.request, names)),},})if (!response.ok || !response.body) {@@ -237,10 +244,13 @@ async function readUpstreamStream(input: {}throw new CodexTransportError('provider_unavailable', 'upstream completion failed')}- return consumeSse(response.body, input.onFrame, signal)+ return consumeSse(response.body, input.onFrame, signal, names)}-function toUpstreamPayload(request: CodexCompletionRequestV1): Record<string, unknown> {+function toUpstreamPayload(+ request: CodexCompletionRequestV1,+ names: ToolNameMap+): Record<string, unknown> {const instructions = request.messages.filter(message => message.role === 'system' && message.content.trim()).map(message => message.content)@@ -264,7 +274,7 @@ function toUpstreamPayload(request: CodexCompletionRequestV1): Record<string, uninput.push({type: 'function_call',call_id: call.id,- name: call.name,+ name: names.toWire(call.name),arguments: JSON.stringify(call.arguments ?? {}),})}@@ -282,7 +292,7 @@ function toUpstreamPayload(request: CodexCompletionRequestV1): Record<string, unif (request.tools && request.tools.length > 0) {payload.tools = request.tools.map(tool => ({type: 'function',- name: tool.name,+ name: names.toWire(tool.name),description: tool.description,parameters: tool.parameters,}))@@ -306,7 +316,8 @@ function toUpstreamPayload(request: CodexCompletionRequestV1): Record<string, unasync function consumeSse(body: ReadableStream<Uint8Array>,onFrame: ((frame: StreamFrame) => void) | undefined,- signal: AbortSignal+ signal: AbortSignal,+ names: ToolNameMap): Promise<StreamCodexCompletionResult> {const reader = body.getReader()const decoder = new TextDecoder()@@ -328,7 +339,14 @@ async function consumeSse(`tool calls exceed ${LIMITS.maxToolCalls}`)}- toolFrames.push(frame)+ const canonicalName = names.fromWire(frame.name)+ if (canonicalName === undefined) {+ throw new CodexTransportError(+ 'provider_unavailable',+ 'upstream returned an unknown tool name'+ )+ }+ toolFrames.push({ ...frame, name: canonicalName })} else if (frame) onFrame?.(frame)}let buffer = ''diff --git a/codex-llm-proxy/src/toolNameMap.ts b/codex-llm-proxy/src/toolNameMap.tsnew file mode 100644index 000000000..620f2f6c0--- /dev/null+++ b/codex-llm-proxy/src/toolNameMap.ts@@ -0,0 +1,50 @@+import { createHash } from 'node:crypto'++// Conservative standard OpenAI function-name envelope. This is not evidence+// that the ChatGPT /codex/responses endpoint rejects wider canonical MCP names.+const wireNamePattern = /^[A-Za-z0-9_-]{1,64}$/++export class ToolNameMap {+ private readonly outbound = new Map<string, string>()+ private readonly inbound = new Map<string, string>()++ constructor(names: Iterable<string>) {+ const canonicalNames = [...new Set(names)].sort()+ // Reserve compliant canonical names before allocating any aliases, including+ // legitimate tool names that happen to look like our generated aliases.+ const occupied = new Set(canonicalNames.filter(name => wireNamePattern.test(name)))+ for (const name of canonicalNames) {+ let wireName = name+ if (!wireNamePattern.test(name)) {+ const base = `__codex_tool_${createHash('sha256').update(name).digest('hex').slice(0, 40)}`+ wireName = base+ // At most N occupied names exist. N + 1 distinct candidates guarantee+ // allocation without assuming that truncated hashes never collide.+ for (let suffix = 0; occupied.has(wireName) && suffix < canonicalNames.length; suffix++) {+ wireName = `${base}_${suffix.toString(36)}`+ }+ if (occupied.has(wireName) || !wireNamePattern.test(wireName)) {+ throw new Error('Unable to allocate a unique transport tool name')+ }+ }+ occupied.add(wireName)+ this.outbound.set(name, wireName)+ this.inbound.set(wireName, name)+ }+ }++ toWire(name: string): string {+ const mapped = this.outbound.get(name)+ if (mapped === undefined) throw new Error('Unknown canonical tool name')+ return mapped+ }++ fromWire(name: string): string | undefined {+ const canonical = this.inbound.get(name)+ if (canonical !== undefined) return canonical+ // Ordinary unknown names still reach the Host registry for rejection.+ // Never infer a target from an unregistered alias or unsafe name.+ if (wireNamePattern.test(name) && !name.startsWith('__codex_tool_')) return name+ return undefined+ }+}diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.tsindex b9782d8df..c16cc3ce7 100644--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts@@ -673,6 +673,82 @@ describe('streamCodexCompletion', () => {expect(body).not.toHaveProperty('temperature')})+ it.each(['service.with.dots__read', `generated_server_${'x'.repeat(70)}__read`])(+ 'roundtrips the canonical tool name %s without changing authorization identity',+ async name => {+ const request = {+ ...REQUEST,+ tools: [{ name, description: 'Read one record', parameters: { type: 'object' } }],+ messages: [+ ...REQUEST.messages,+ {+ role: 'assistant' as const,+ content: '',+ toolCalls: [{ id: 'previous', name, arguments: {} }],+ },+ { role: 'tool' as const, content: 'previous result', toolCallId: 'previous', name },+ ],+ }+ const requestHash = hashCodexCompletionRequestV1(request)+ const original = structuredClone(request)+ const emitted: unknown[] = []+ const fetchFn = vi.fn(async (_url: unknown, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body))+ const wireName = body.tools[0].name+ expect(wireName).toMatch(/^[A-Za-z0-9_-]{1,64}$/)+ expect(wireName).not.toBe(name)+ expect(+ body.input.find((item: { type?: string }) => item.type === 'function_call').name+ ).toBe(wireName)+ expect(+ body.input.find((item: { type?: string }) => item.type === 'function_call_output')+ ).toEqual({+ type: 'function_call_output',+ call_id: 'previous',+ output: 'previous result',+ })+ return sseResponse([+ `data: ${JSON.stringify({+ type: 'response.output_item.done',+ item: {+ type: 'function_call',+ id: 'item-new',+ call_id: 'new-call',+ name: wireName,+ arguments: '{}',+ },+ })}\n\n`,+ 'data: {"type":"response.completed","response":{"usage":{}}}\n\n',+ ])+ })+ const result = await streamCodexCompletion({+ executionTicket: 'ticket-name-map',+ requestHash,+ request,+ ticket: {+ jti: 'name-map',+ hostRef: 'research-host',+ model: request.model,+ requestHash,+ providerAttemptId: 'att-name-map',+ },+ redeem: async () => redeemSuccess(),+ finalize: async () => ({+ providerAttemptId: 'att-name-map',+ outcome: 'success' as const,+ duplicate: false,+ }),+ fetchFn,+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],+ onFrame: frame => emitted.push(frame),+ })+ expect(result.outcome).toBe('success')+ expect(emitted).toContainEqual({ type: 'tool_call', id: 'new-call', name, arguments: {} })+ expect(request).toEqual(original)+ expect(hashCodexCompletionRequestV1(request)).toBe(requestHash)+ }+ )+it('omits Notify-like generation fields on the Responses wire', async () => {const fetchFn = vi.fn(async () =>sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])diff --git a/codex-llm-proxy/test/toolNameMap.test.ts b/codex-llm-proxy/test/toolNameMap.test.tsnew file mode 100644index 000000000..114c5c2b0--- /dev/null+++ b/codex-llm-proxy/test/toolNameMap.test.ts@@ -0,0 +1,57 @@+import { createHash } from 'node:crypto'+import { describe, expect, it, vi } from 'vitest'+import { ToolNameMap } from '../src/toolNameMap.js'++vi.mock('node:crypto', async importOriginal => {+ const actual = await importOriginal<typeof import('node:crypto')>()+ return { ...actual, createHash: vi.fn(actual.createHash) }+})++describe('ToolNameMap', () => {+ it('preserves compliant names and reverses punctuation and 128-character names', () => {+ const names = ['tool_A-2', 'x'.repeat(64), 'files.read', 'mcp:lookup', 'x'.repeat(128)]+ const map = new ToolNameMap(names)+ for (const name of names) {+ expect(map.toWire(name)).toMatch(/^[A-Za-z0-9_-]{1,64}$/)+ expect(map.fromWire(map.toWire(name))).toBe(name)+ }+ expect(map.toWire(names[0])).toBe(names[0])+ expect(map.toWire(names[1])).toBe(names[1])+ expect(new Set(names.map(name => map.toWire(name))).size).toBe(names.length)+ })+ it('is stable across order, duplicate history, and unrelated inventory additions', () => {+ const names = ['files.read', 'history:removed', 'safe']+ const first = new ToolNameMap(names)+ const next = new ToolNameMap(['other:new', ...names.toReversed(), ...names])+ for (const name of names) expect(next.toWire(name)).toBe(first.toWire(name))+ })+ it('reserves legitimate alias-shaped canonical names and occupied suffixes', () => {+ const canonical = 'files.read'+ const base = new ToolNameMap([canonical]).toWire(canonical)+ const names = [canonical, base, `${base}_0`, `${base}_1`]+ const first = new ToolNameMap(names)+ const reversed = new ToolNameMap(names.toReversed())+ expect(first.toWire(canonical)).toBe(`${base}_2`)+ for (const name of names) {+ expect(first.fromWire(first.toWire(name))).toBe(name)+ expect(reversed.toWire(name)).toBe(first.toWire(name))+ }+ expect(first.toWire(base)).toBe(base)+ })+ it('resolves hash collisions with distinct bounded candidates', () => {+ const hash = { update: () => hash, digest: () => 'a'.repeat(64) }+ vi.mocked(createHash).mockReturnValueOnce(hash as unknown as ReturnType<typeof createHash>)+ vi.mocked(createHash).mockReturnValueOnce(hash as unknown as ReturnType<typeof createHash>)+ const map = new ToolNameMap(['a.b', 'a:b'])+ expect(map.toWire('a:b')).toBe(`${map.toWire('a.b')}_0`)+ expect(map.fromWire(map.toWire('a.b'))).toBe('a.b')+ expect(map.fromWire(map.toWire('a:b'))).toBe('a:b')+ })+ it('does not manufacture canonical targets from unknown aliases or unsafe names', () => {+ const map = new ToolNameMap(['files.read'])+ expect(map.fromWire('__codex_tool_unknown')).toBeUndefined()+ expect(map.fromWire('files.read')).toBeUndefined()+ expect(map.fromWire('ordinary_unknown')).toBe('ordinary_unknown')+ expect(() => map.toWire('missing')).toThrow('Unknown canonical tool name')+ })+})diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.mdindex 4b8c650a2..55207c945 100644--- a/docs/architecture/codex-subscription-transport-contract.md+++ b/docs/architecture/codex-subscription-transport-contract.md@@ -97,6 +97,24 @@ only the sender is insufficient. For rollback, restore the old sender first,drain outstanding incompatible attempts, then restore older validators. An oldsender reintroduces the known connector exclusion and is not a correction.+### Transport tool names++Canonical Evenfire tool names remain unchanged in authorization, request hashes,+Host dispatch and stored history. At the proxy boundary, names outside+`[A-Za-z0-9_-]{1,64}` receive deterministic, reversible aliases. Compliant names+are reserved first; bounded collision handling also covers legitimate names+that resemble generated aliases. The map includes active definitions and+historical assistant calls, and restores canonical names before emitting calls+to the Host. Call IDs and function-call outputs remain unchanged.++This uses the conservative function-name envelope documented by the+[official OpenAI SDK](https://github.com/openai/openai-python/blob/main/src/openai/types/shared_params/function_definition.py).+It is not evidence of a measured rejection by the ChatGPT Codex endpoint.+The transformation preserves all tools; no name is truncated or omitted.+If an inventory change introduces an alias collision, the request remaps its+entire history consistently. Unknown generated aliases fail explicitly;+ordinary unknown names retain the Host registry's authorization checks.+### Selected MCP argument validationThe Host validates selected MCP arguments before approval and rechecks the live