Skip to content
Merged
Prev Previous commit
Next Next commit
feat(codex): implement OpenAI Responses API to fix Codex startup
New Codex removed wire_api="chat" (codex#7782) and requires "responses",
which makes it POST {base_url}/responses — an endpoint we didn't serve,
so Codex failed to start. Add POST /openai/responses with a full
Responses translator (item-centric request → canonical, canonical →
response object, and a stateful SSE emitter carrying sequence_number and
the response.created → output_item.added → content_part.added →
output_text.delta → … → response.completed sequence). Flip the Codex
config to wire_api="responses" (base_url stays …/openai; Codex appends
/responses, no /v1).

Verified live against real Copilot: non-stream returns a completed
response object; stream begins response.created and ends
response.completed.

Co-Authored-By: Claude <noreply@anthropic.com>
  • Loading branch information
wangcansunking and claude committed Jun 26, 2026
commit b2fbd9adefd80c80297263eec745a9dea73692c2
11 changes: 11 additions & 0 deletions e2e/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@
Latest run of the end-to-end suite. Regenerate after every code change with `npm run test:e2e`
and update this file (paste the summary).

- **2026-06-26 (Codex /responses)** — Fixed Codex startup: new Codex removed `wire_api = "chat"`
(codex#7782) and requires `"responses"`, which makes it POST `{base_url}/responses`. Implemented the
OpenAI Responses API at `POST /openai/responses` (new `src/core/responses-inbound.ts`: item-centric
request → canonical, canonical → response object, and a stateful SSE emitter with `sequence_number`
and the `response.created → output_item.added → content_part.added → output_text.delta → … →
response.completed` event sequence). Codex config now writes `wire_api = "responses"` (base_url
stays `…/openai`; Codex appends `/responses`). Verified live end-to-end against real Copilot:
non-stream returns a completed `response` object with an `output_text` item; stream begins
`response.created` and ends `response.completed` with `output_text.delta` in between. Full suite
green: `npm test` → **294 passed** (52 files), `npm run test:e2e` → **31 passed**, tsc build clean.

- **2026-06-26** — Restored web_search / web_fetch for Claude Code through the gateway. The inbound
translator now converts Anthropic's server-side web tools to function tools (instead of dropping
them); a capped agentic loop in the Anthropic endpoint runs those tools internally against
Expand Down
146 changes: 146 additions & 0 deletions src/core/responses-inbound.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import type { CanonicalRequest, CanonicalResponse, CanonicalMessage, ContentBlock } from "./canonical.js";
import { joinText } from "./canonical.js";

// OpenAI Responses API translation. Codex (post codex#7782) speaks ONLY this API — it POSTs to
// {base_url}/responses. Like agent-maestro's implementation we are STATELESS: previous_response_id /
// conversation / item_reference are unsupported (the client sends full history in `input` each turn),
// and only function tools are honored. Mirrors the chat-completions translator in openai-inbound.ts.

interface ResponsesContentPart { type?: string; text?: string; image_url?: string | { url?: string } }
interface ResponsesInputItem {
type?: string; role?: string;
content?: string | ResponsesContentPart[]; // message
call_id?: string; name?: string; arguments?: string; // function_call
output?: string; // function_call_output
}
interface ResponsesTool { type: string; name?: string; description?: string; parameters?: Record<string, unknown> }
export interface ResponsesRequest {
model: string; input: string | ResponsesInputItem[]; instructions?: string;
stream?: boolean; temperature?: number; max_output_tokens?: number; tools?: ResponsesTool[];
}

function partsText(content: string | ResponsesContentPart[] | undefined): string {
if (content == null) return "";
if (typeof content === "string") return content;
return content.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("");
}
function partsImages(content: string | ResponsesContentPart[] | undefined): ContentBlock[] {
if (!Array.isArray(content)) return [];
const urlOf = (p: ResponsesContentPart): string | undefined => typeof p.image_url === "string" ? p.image_url : p.image_url?.url;
return content.filter((p) => p?.type === "input_image" && urlOf(p)).map((p) => ({ type: "image", dataUrl: urlOf(p)! }));
}
function safeJson(s: string | undefined): unknown { try { return s ? JSON.parse(s) : {}; } catch { return {}; } }

function itemToMessage(it: ResponsesInputItem): CanonicalMessage | null {
if (it.type === "function_call" && it.call_id) {
return { role: "assistant", content: [{ type: "tool_use", id: it.call_id, name: it.name ?? "", input: safeJson(it.arguments) }] };
}
if (it.type === "function_call_output" && it.call_id) {
return { role: "tool", content: [{ type: "tool_result", toolUseId: it.call_id, content: it.output ?? "" }] };
}
// default: a message item
const role = (["system", "user", "assistant"].includes(it.role ?? "") ? it.role : "user") as CanonicalMessage["role"];
const content: ContentBlock[] = [];
const text = partsText(it.content);
if (text) content.push({ type: "text", text });
content.push(...partsImages(it.content));
return content.length ? { role, content } : null;
}

export function responsesRequestToCanonical(req: ResponsesRequest): CanonicalRequest {
const messages: CanonicalMessage[] = [];
if (req.instructions) messages.push({ role: "system", content: [{ type: "text", text: req.instructions }] });
if (typeof req.input === "string") {
messages.push({ role: "user", content: [{ type: "text", text: req.input }] });
} else {
for (const it of req.input) { const m = itemToMessage(it); if (m) messages.push(m); }
}
return {
model: req.model, stream: Boolean(req.stream), temperature: req.temperature, maxTokens: req.max_output_tokens,
tools: req.tools?.filter((t) => t.type === "function" && t.name).map((t) => ({ name: t.name!, description: t.description, parameters: t.parameters ?? {} })),
messages,
};
}

// Build the non-stream Responses object: text -> an output_text message item, tool_use -> function_call items.
export function canonicalToResponsesResponse(r: CanonicalResponse) {
const output: unknown[] = [];
const text = joinText(r.content);
if (text) output.push({ type: "message", id: `msg_${r.id}`, role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] });
for (const b of r.content) {
if (b.type === "tool_use") output.push({ type: "function_call", id: `fc_${b.id}`, call_id: b.id, name: b.name, arguments: JSON.stringify(b.input ?? {}), status: "completed" });
}
return {
id: r.id, object: "response" as const, status: "completed" as const, model: r.model,
output, output_text: text,
usage: { input_tokens: r.usage.promptTokens, output_tokens: r.usage.completionTokens, total_tokens: r.usage.promptTokens + r.usage.completionTokens },
};
}

// Stateful SSE emitter for the Responses stream. Each event carries a monotonically increasing
// sequence_number (Codex/agent-maestro require it). Text streams as one output_text message item;
// each tool call is its own function_call output item. Indices are allocated sequentially.
const frame = (event: unknown): string => `data: ${JSON.stringify(event)}\n\n`;
export class ResponsesSSE {
private seq = 0;
private nextIndex = 0;
private textIndex?: number;
private textItemId?: string;
private toolIndex = new Map<number, { outputIndex: number; itemId: string }>();
constructor(private responseId: string, private model: string) {}

private ev(type: string, extra: Record<string, unknown>): string {
return frame({ type, sequence_number: this.seq++, ...extra });
}
private envelope(status: string) {
return { id: this.responseId, object: "response", status, model: this.model };
}

start(): string {
return this.ev("response.created", { response: { ...this.envelope("in_progress"), output: [] } });
}

text(delta: string): string[] {
const out: string[] = [];
if (this.textIndex === undefined) {
this.textIndex = this.nextIndex++;
this.textItemId = `msg_${this.responseId}`;
out.push(this.ev("response.output_item.added", { output_index: this.textIndex, item: { type: "message", id: this.textItemId, role: "assistant", status: "in_progress", content: [] } }));
out.push(this.ev("response.content_part.added", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text: "", annotations: [] } }));
}
out.push(this.ev("response.output_text.delta", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, delta }));
return out;
}

toolStart(copilotIdx: number, callId: string, name: string): string[] {
if (this.toolIndex.has(copilotIdx)) return [];
const outputIndex = this.nextIndex++;
const itemId = `fc_${callId}`;
this.toolIndex.set(copilotIdx, { outputIndex, itemId });
return [this.ev("response.output_item.added", { output_index: outputIndex, item: { type: "function_call", id: itemId, call_id: callId, name, arguments: "", status: "in_progress" } })];
}

toolArgs(copilotIdx: number, deltaArgs: string): string[] {
const t = this.toolIndex.get(copilotIdx);
if (!t) return [];
return [this.ev("response.function_call_arguments.delta", { item_id: t.itemId, output_index: t.outputIndex, delta: deltaArgs })];
}

// Close all open items and complete the response. `argsByIdx` supplies final accumulated tool args.
finish(usage: { promptTokens: number; completionTokens: number } | undefined, _finishReason: string, argsByIdx?: Map<number, string>): string[] {
const out: string[] = [];
if (this.textIndex !== undefined) {
out.push(this.ev("response.output_text.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, text: "" }));
out.push(this.ev("response.content_part.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text: "", annotations: [] } }));
out.push(this.ev("response.output_item.done", { output_index: this.textIndex, item: { type: "message", id: this.textItemId, role: "assistant", status: "completed", content: [] } }));
}
for (const [copilotIdx, t] of this.toolIndex) {
const args = argsByIdx?.get(copilotIdx) ?? "";
out.push(this.ev("response.function_call_arguments.done", { item_id: t.itemId, output_index: t.outputIndex, arguments: args }));
out.push(this.ev("response.output_item.done", { output_index: t.outputIndex, item: { type: "function_call", id: t.itemId, status: "completed" } }));
}
const u = usage ? { input_tokens: usage.promptTokens, output_tokens: usage.completionTokens, total_tokens: usage.promptTokens + usage.completionTokens } : undefined;
out.push(this.ev("response.completed", { response: { ...this.envelope("completed"), ...(u ? { usage: u } : {}) } }));
return out;
}
}
6 changes: 4 additions & 2 deletions src/tui/setup/codex-toml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { join, dirname } from "node:path";

// Codex reads ~/.codex/config.toml. copilot-reverse writes a managed provider block there (model,
// provider, context window) while preserving the user's other top-level keys. Mirrors
// agent-maestro's `configureCodex`, but uses wire_api="chat" since our proxy is chat/completions.
// agent-maestro's `configureCodex`. Codex removed wire_api="chat" (codex#7782), so we write
// "responses" and serve the OpenAI Responses API at /openai/responses (Codex appends /responses to
// base_url verbatim — no /v1 auto-added).
export const PROVIDER_ID = "copilot-reverse";

export function codexTomlPath(home = homedir()): string {
Expand Down Expand Up @@ -43,7 +45,7 @@ export function applyCodexToml(opts: CodexTomlOpts): { path: string; changed: st
`[model_providers.${PROVIDER_ID}]`,
`name = "copilot-reverse"`,
`base_url = "${opts.baseUrl}"`,
`wire_api = "chat"`,
`wire_api = "responses"`,
].join("\n");

const body = (head ? `${head}\n\n` : "") + managed + "\n";
Expand Down
47 changes: 47 additions & 0 deletions src/worker/openai-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
import type { Router } from "./router.js";
import type { MetricSink } from "./server.js";
import { openaiRequestToCanonical, canonicalToOpenAIResponse, canonicalChunkToOpenAISSE } from "../core/openai-inbound.js";
import { responsesRequestToCanonical, canonicalToResponsesResponse, ResponsesSSE } from "../core/responses-inbound.js";
import { errorHint } from "./errors.js";
import { CopilotAuthError } from "../providers/copilot/token.js";

Expand Down Expand Up @@ -47,4 +48,50 @@ export function mountOpenAI(app: Express, router: Router, onMetric: MetricSink):
metric(status, message);
}
});

// OpenAI Responses API — Codex speaks ONLY this after codex#7782 removed wire_api="chat". Codex
// POSTs {base_url}/responses, so with base_url …/openai the route is /openai/responses. Same
// canonical pipeline as chat/completions; the Responses translator handles the item-centric shape.
app.post("/openai/responses", async (req, res) => {
const start = Date.now();
const canon = responsesRequestToCanonical(req.body);
canon.model = router.resolveModel(canon.model);
const provider = router.pick(canon.model);
const metric = (status: number, error?: string) => onMetric({ endpoint: "/openai/responses", model: canon.model, status, latencyMs: Date.now() - start, error });
try {
if (canon.stream) {
res.setHeader("content-type", "text/event-stream");
res.setHeader("cache-control", "no-cache");
const sse = new ResponsesSSE(`resp_${randomUUID().replace(/-/g, "")}`, canon.model);
res.write(sse.start());
const argsByIdx = new Map<number, string>();
let usage: { promptTokens: number; completionTokens: number } | undefined;
let finish = "stop";
for await (const chunk of provider.stream(canon)) {
if (chunk.done) { finish = chunk.finishReason ?? "stop"; usage = chunk.usage; break; }
if (chunk.kind === "text") for (const f of sse.text(chunk.delta)) res.write(f);
else if (chunk.kind === "tool_use_start") for (const f of sse.toolStart(chunk.index, chunk.id, chunk.name)) res.write(f);
else if (chunk.kind === "tool_use_delta") { argsByIdx.set(chunk.index, (argsByIdx.get(chunk.index) ?? "") + chunk.argsDelta); for (const f of sse.toolArgs(chunk.index, chunk.argsDelta)) res.write(f); }
}
for (const f of sse.finish(usage, finish, argsByIdx)) res.write(f);
res.end();
metric(200);
} else {
res.json(canonicalToResponsesResponse(await provider.complete(canon)));
metric(200);
}
} catch (err) {
const raw = err instanceof Error ? err.message : String(err);
const hint = errorHint(raw);
const message = hint ? `${raw}\n${hint}` : raw;
const status = err instanceof CopilotAuthError ? 401 : 502;
if (!res.headersSent) {
res.status(status).json({ error: { type: "error", message } });
} else {
res.write(`data: ${JSON.stringify({ type: "error", message })}\n\n`);
res.end();
}
metric(status, message);
}
});
}
93 changes: 93 additions & 0 deletions tests/core/responses-inbound.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { describe, it, expect } from "vitest";
import { responsesRequestToCanonical, canonicalToResponsesResponse, ResponsesSSE } from "../../src/core/responses-inbound.js";
import type { CanonicalResponse } from "../../src/core/canonical.js";

describe("responsesRequestToCanonical", () => {
it("flattens instructions to a system message and a string input to a user message", () => {
const c = responsesRequestToCanonical({ model: "gpt-5-mini", instructions: "be terse", input: "hello", stream: false });
expect(c.model).toBe("gpt-5-mini");
expect(c.messages[0]).toEqual({ role: "system", content: [{ type: "text", text: "be terse" }] });
expect(c.messages[1]).toEqual({ role: "user", content: [{ type: "text", text: "hello" }] });
});

it("maps input items: message / function_call / function_call_output", () => {
const c = responsesRequestToCanonical({
model: "gpt-5", stream: false,
input: [
{ type: "message", role: "user", content: [{ type: "input_text", text: "what time" }] },
{ type: "function_call", call_id: "fc1", name: "now", arguments: '{"tz":"utc"}' },
{ type: "function_call_output", call_id: "fc1", output: "12:00" },
],
});
expect(c.messages[0]).toEqual({ role: "user", content: [{ type: "text", text: "what time" }] });
expect(c.messages[1].content[0]).toEqual({ type: "tool_use", id: "fc1", name: "now", input: { tz: "utc" } });
expect(c.messages[2]).toEqual({ role: "tool", content: [{ type: "tool_result", toolUseId: "fc1", content: "12:00" }] });
});

it("maps function tools to canonical tools and ignores non-function tools", () => {
const c = responsesRequestToCanonical({
model: "gpt-5", stream: false, input: "hi",
tools: [
{ type: "function", name: "search", description: "d", parameters: { type: "object", properties: {} } },
{ type: "web_search" },
] as any,
});
expect(c.tools).toHaveLength(1);
expect(c.tools![0]).toMatchObject({ name: "search" });
});
});

describe("canonicalToResponsesResponse", () => {
it("wraps text in an output_text message item with usage", () => {
const r: CanonicalResponse = { id: "r1", model: "gpt-5", content: [{ type: "text", text: "hi there" }], finishReason: "stop", usage: { promptTokens: 10, completionTokens: 3 } };
const out = canonicalToResponsesResponse(r);
expect(out.object).toBe("response");
expect(out.status).toBe("completed");
const msg = out.output.find((o: any) => o.type === "message");
expect(msg.content[0]).toMatchObject({ type: "output_text", text: "hi there" });
expect(out.usage).toMatchObject({ input_tokens: 10, output_tokens: 3, total_tokens: 13 });
});

it("emits function_call items for tool_use blocks", () => {
const r: CanonicalResponse = { id: "r1", model: "gpt-5", content: [{ type: "tool_use", id: "fc1", name: "search", input: { q: "x" } }], finishReason: "tool_use", usage: { promptTokens: 1, completionTokens: 1 } };
const out = canonicalToResponsesResponse(r);
const fc = out.output.find((o: any) => o.type === "function_call");
expect(fc).toMatchObject({ type: "function_call", call_id: "fc1", name: "search" });
expect(JSON.parse(fc.arguments)).toEqual({ q: "x" });
});
});

describe("ResponsesSSE emitter", () => {
it("emits the ordered text event sequence with monotonic sequence_number", () => {
const sse = new ResponsesSSE("resp_1", "gpt-5");
const out: string[] = [];
out.push(sse.start());
out.push(...[sse.text("Hel"), sse.text("lo")].flat());
out.push(...sse.finish({ promptTokens: 1, completionTokens: 1 }, "stop"));
const events = out.join("").split("\n\n").filter(Boolean).map((b) => JSON.parse(b.replace(/^data: /, "")));
const types = events.map((e) => e.type);
expect(types[0]).toBe("response.created");
expect(types).toContain("response.output_item.added");
expect(types).toContain("response.content_part.added");
expect(types.filter((t) => t === "response.output_text.delta")).toHaveLength(2);
expect(types).toContain("response.output_text.done");
expect(types.at(-1)).toBe("response.completed");
// sequence_number is present and strictly increasing
const seqs = events.map((e) => e.sequence_number);
expect(seqs.every((n, i) => i === 0 || n > seqs[i - 1])).toBe(true);
});

it("emits function_call argument events for a tool call", () => {
const sse = new ResponsesSSE("resp_2", "gpt-5");
const out: string[] = [];
out.push(sse.start());
out.push(...sse.toolStart(0, "fc1", "search"));
out.push(...sse.toolArgs(0, '{"q":1}'));
out.push(...sse.finish({ promptTokens: 1, completionTokens: 1 }, "tool_use"));
const text = out.join("");
expect(text).toContain("response.output_item.added");
expect(text).toContain("response.function_call_arguments.delta");
expect(text).toContain("response.function_call_arguments.done");
expect(text).toContain("response.completed");
});
});
2 changes: 1 addition & 1 deletion tests/tui/codex-toml.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe("applyCodexToml", () => {
expect(toml).toContain("model_context_window = 1050000");
expect(toml).toContain("[model_providers.copilot-reverse]");
expect(toml).toContain('base_url = "http://127.0.0.1:7891/v1"');
expect(toml).toContain('wire_api = "chat"');
expect(toml).toContain('wire_api = "responses"');
});

it("preserves unrelated existing keys and is idempotent", () => {
Expand Down
Loading
Loading