Skip to content

Commit 659c9e4

Browse files
committed
fix(responses): address streaming review edge cases
1 parent b091233 commit 659c9e4

10 files changed

Lines changed: 162 additions & 9 deletions

File tree

‎docs-site/src/content/docs/guides/codex-integration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ max | ultra` ladder; unsupported values are mapped or clamped before the upstrea
195195

196196
### Routed local tools
197197

198-
Non-OpenAI catalog rows use `tool_mode: "code_mode_only"`. This lets Codex expose its official
198+
Non-native routed catalog rows use `tool_mode: "code_mode_only"`. This lets Codex expose its official
199199
`exec` entrypoint and nested MCP tools, including Browser and Computer Use, while opencodex routes
200200
only the model's ordinary function call. Tool execution, permissions, and confirmations remain
201201
local to Codex; opencodex does not implement a second browser or desktop-control executor.

‎docs-site/src/content/docs/ja/guides/codex-integration.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,25 @@ Codex には、ディスク上のカタログ (デフォルトでは `$CODEX_HOM
134134
プロバイダーとモデルメタデータに応じて Codex の `low | medium | high | xhigh | max | ultra` 段階を使い、
135135
上流がサポートしない値はリクエスト送信前にマッピングまたはサポート範囲に下げます。
136136

137+
### ルーティングされたローカルツール
138+
139+
ネイティブではないルーティング済みカタログ項目は `tool_mode: "code_mode_only"` を使用します。これにより、
140+
Codex は公式の `exec` エントリポイントと、Browser や Computer Use を含むネストされた MCP ツールを公開できます。
141+
opencodex がルーティングするのはモデルの通常の function call だけです。ツールの実行、権限、確認は Codex 内に
142+
残り、opencodex が別のブラウザーやデスクトップ操作 executor を実装することはありません。
143+
144+
Codex の `exec` custom-tool grammar を受け付けない key-auth Responses provider に対しては、opencodex が宣言と
145+
履歴を上流向けの function tool にエンコードし、ストリーミングされた function-call lifecycle を Codex に返す前に
146+
`custom_tool_call` へ復元します。ネイティブ OpenAI の forward routing と、対応済みの `apply_patch` custom tool は
147+
変更されません。
148+
149+
選択した provider は function/tool calling をサポートしている必要があります。tool call に対応しない text-only
150+
provider では `exec`、Browser、Computer Use は使用できません。ネイティブ OpenAI の項目は上流の tool mode を
151+
そのまま維持します。
152+
153+
`ocx sync` でこの metadata を変更した後は Codex App を再起動し、新しいタスクを開いてください。既存の
154+
app-server process とタスクは、起動時に読み込んだ catalog と tool plan を保持している場合があります。
155+
137156
### カスタムモデルの表示名
138157

139158
カスタム モデルは、モデルのルーティング方法を何も変更することなく、Codex がモデル ピッカーに表示するラベルをオーバーライドする人間が判読できる **表示名** を付けることができます。表示名はカタログ エントリの `display_name` フィールドのみにマップされます。ルーティング スラグ (`<provider>/<model>`)、エイリアスの衝突順序、プロバイダー、およびネイティブ OpenAI マーケティング名はすべて変更されません。

‎docs-site/src/content/docs/ko/guides/codex-integration.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,25 @@ Codex는 디스크의 카탈로그(`$CODEX_HOME/opencodex-catalog.json`이 기
124124
프로바이더와 모델 메타데이터에 따라 Codex의 `low | medium | high | xhigh | max | ultra` 단계를 사용하며,
125125
업스트림이 지원하지 않는 값은 요청을 보내기 전에 매핑하거나 지원 범위로 낮춥니다.
126126

127+
### 라우팅된 로컬 도구
128+
129+
네이티브가 아닌 라우팅 catalog 항목은 `tool_mode: "code_mode_only"`를 사용합니다. 이를 통해 Codex는 공식
130+
`exec` 진입점과 Browser 및 Computer Use를 포함한 중첩 MCP 도구를 노출할 수 있으며, opencodex는 모델의 일반
131+
function call만 라우팅합니다. 도구 실행, 권한, 확인은 Codex에 그대로 남고 opencodex가 별도의 browser 또는
132+
desktop-control executor를 구현하지는 않습니다.
133+
134+
Codex의 `exec` custom-tool grammar를 허용하지 않는 key-auth Responses provider의 경우, opencodex는 해당 선언과
135+
history를 업스트림 function tool로 인코딩한 다음 스트리밍된 function-call lifecycle을 Codex에 전달하기 전에
136+
`custom_tool_call`로 복원합니다. 네이티브 OpenAI forward routing과 지원되는 `apply_patch` custom tool은 변경되지
137+
않습니다.
138+
139+
선택한 provider는 function/tool calling을 지원해야 합니다. tool call을 지원하지 않는 text-only provider에서는
140+
`exec`, Browser 또는 Computer Use를 사용할 수 없습니다. 네이티브 OpenAI 항목은 업스트림 tool mode를 그대로
141+
유지합니다.
142+
143+
`ocx sync`가 이 metadata를 변경한 뒤에는 Codex App을 다시 시작하고 새 task를 여세요. 기존 app-server process와
144+
task는 시작할 때 불러온 catalog와 tool plan을 계속 유지할 수 있습니다.
145+
127146
### 사용자 지정 모델 표시 이름
128147

129148
사용자 지정 모델은 사람이 읽을 수 있는 **표시 이름**을 가질 수 있습니다. 이 이름은 Codex의 model picker에 보이는 label만 바꾸고, 모델이 라우팅되는 방식은 바꾸지 않습니다. 표시 이름은 catalog entry의 `display_name` 필드에만 매핑되며, routing slug(`<provider>/<model>`), alias collision order, provider, native OpenAI marketing name은 모두 그대로 둡니다.

‎docs-site/src/content/docs/ru/guides/codex-integration.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,27 @@ Codex показывает модели из каталога на диске (`
204204
по шкале Codex `low | medium | high | xhigh | max | ultra`; неподдерживаемые значения
205205
сопоставляются или ограничиваются перед запросом к вышестоящему провайдеру.
206206

207+
### Локальные инструменты для маршрутизируемых моделей
208+
209+
Маршрутизируемые записи, которые не являются нативными, используют
210+
`tool_mode: "code_mode_only"`. Благодаря этому Codex предоставляет официальный entrypoint `exec`
211+
и вложенные MCP-инструменты, включая Browser и Computer Use, а opencodex маршрутизирует только
212+
обычный function call модели. Выполнение инструментов, разрешения и подтверждения остаются в
213+
Codex; opencodex не реализует второй executor для браузера или управления рабочим столом.
214+
215+
Для key-auth Responses provider'ов, которые не принимают custom-tool grammar `exec` от Codex,
216+
opencodex кодирует объявление и историю как function tool для upstream, а затем восстанавливает
217+
потоковый lifecycle function call в `custom_tool_call` до передачи в Codex. Нативная forward-
218+
маршрутизация OpenAI и поддерживаемый custom tool `apply_patch` остаются без изменений.
219+
220+
Выбранный provider должен поддерживать function/tool calling. Text-only provider без tool calls
221+
не может использовать `exec`, Browser или Computer Use. Нативные записи OpenAI сохраняют свой
222+
upstream tool mode без изменений.
223+
224+
После того как `ocx sync` изменит эти metadata, перезапустите Codex App и откройте новую задачу.
225+
Существующие процессы app-server и задачи могут сохранять catalog и tool plan, загруженные при
226+
запуске.
227+
207228
### Пользовательские display-name моделей
208229

209230
У custom-модели может быть человекочитаемый **display name**, который переопределяет метку в

‎docs-site/src/content/docs/zh-cn/guides/codex-integration.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,21 @@ Codex 显示的模型来自一个磁盘上的 catalog(默认是 `$CODEX_HOME/o
181181
使用 Codex 的 `low | medium | high | xhigh | max | ultra` 档位;上游不支持的值会在发送请求前完成
182182
映射或下调。
183183

184+
### 路由模型的本地工具
185+
186+
非原生的路由 catalog 条目使用 `tool_mode: "code_mode_only"`。这样 Codex 可以公开其官方 `exec` 入口以及
187+
嵌套的 MCP 工具,包括 Browser 和 Computer Use;opencodex 只负责路由模型发起的普通 function call。
188+
工具执行、权限和确认仍由 Codex 在本地处理;opencodex 不会实现另一套浏览器或桌面控制 executor。
189+
190+
对于不接受 Codex `exec` custom-tool grammar 的 key-auth Responses provider,opencodex 会把该工具声明及其
191+
历史记录编码成上游 function tool,再在 Codex 收到结果前,把流式 function-call lifecycle 还原成
192+
`custom_tool_call`。原生 OpenAI forward routing 和已支持的 `apply_patch` custom tool 保持不变。
193+
194+
所选 provider 必须支持 function/tool calling。不支持 tool call 的 text-only provider 无法使用 `exec`、
195+
Browser 或 Computer Use。原生 OpenAI 条目会保持其上游 tool mode 不变。
196+
197+
`ocx sync` 修改这些 metadata 后,请重启 Codex App 并打开一个新任务。现有 app-server process 和任务可能仍会
198+
保留它们在启动时加载的 catalog 和 tool plan。
184199

185200
### 自定义模型显示名
186201

‎src/providers/registry.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2399,8 +2399,9 @@ export function providerModelResponsesTerminalRepair(
23992399
const entry = getProviderRegistryEntry(id);
24002400
if (!entry?.modelResponsesTerminalRepair || !providerMatchesRegistryTransport(id, provider)) return undefined;
24012401
const policy = entry.modelResponsesTerminalRepair[modelId.trim().toLowerCase()];
2402-
if (!policy || !Number.isFinite(policy.graceMs) || policy.graceMs <= 0) return undefined;
2403-
return { graceMs: Math.floor(policy.graceMs) };
2402+
const graceMs = Math.floor(policy?.graceMs ?? 0);
2403+
if (!Number.isFinite(graceMs) || graceMs <= 0) return undefined;
2404+
return { graceMs };
24042405
}
24052406

24062407
/**

‎src/server/responses-custom-tool-repair.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ function partialCustomToolInput(argumentsText: string): string {
3333
if (escaped === "n") output += "\n";
3434
else if (escaped === "t") output += "\t";
3535
else if (escaped === "r") output += "\r";
36+
else if (escaped === "b") output += "\b";
37+
else if (escaped === "f") output += "\f";
3638
else if (escaped === "u") {
3739
const hex = body.slice(index + 1, index + 5);
3840
if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) break;

‎tests/deepseek-inbound-wire.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ class ManualTerminalScheduler implements ResponsesTerminalRepairScheduler {
4646
return id;
4747
}
4848
cancel(handle: unknown): void { this.jobs.delete(handle as number); }
49+
pending(): number { return this.jobs.size; }
4950
advance(ms: number): void {
5051
this.current += ms;
5152
for (const [id, job] of [...this.jobs.entries()]) {
@@ -143,6 +144,19 @@ describe("DeepSeek wire selection is scoped to the inbound protocol", () => {
143144
expect(providerModelResponsesTerminalRepair("deepseek", provider, "deepseek-chat")).toBeUndefined();
144145
expect(providerModelResponsesTerminalRepair("custom-deepseek", provider, MODEL)).toBeUndefined();
145146
});
147+
148+
test("terminal repair rejects a fractional grace that normalizes to zero", () => {
149+
const entry = PROVIDER_REGISTRY.find(candidate => candidate.id === "deepseek");
150+
const policy = entry?.modelResponsesTerminalRepair?.[MODEL];
151+
if (!policy) throw new Error("missing DeepSeek terminal-repair fixture");
152+
const originalGraceMs = policy.graceMs;
153+
try {
154+
policy.graceMs = 0.5;
155+
expect(providerModelResponsesTerminalRepair("deepseek", deepseekProvider(), MODEL)).toBeUndefined();
156+
} finally {
157+
policy.graceMs = originalGraceMs;
158+
}
159+
});
146160
});
147161

148162
describe("the inbound scope survives the handleResponses replay", () => {
@@ -269,7 +283,10 @@ describe("the inbound scope survives the handleResponses replay", () => {
269283
sequence_number: 6,
270284
}),
271285
].join(""));
272-
await Bun.sleep(0);
286+
for (let attempts = 0; attempts < 20 && scheduler.pending() === 0; attempts += 1) {
287+
await Bun.sleep(0);
288+
}
289+
expect(scheduler.pending()).toBe(1);
273290
scheduler.advance(5_000);
274291
const remainder = await Promise.race([
275292
drainReader(reader),

‎tests/responses-custom-tool-repair.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,35 @@ describe("routed Responses custom-tool compatibility", () => {
167167
rewrite.dispose?.();
168168
});
169169

170+
test("keeps progressive exec input consistent for escaped control characters", () => {
171+
const rewrite = createRoutedCustomToolRestoreBlockRewrite(new Set(["exec"]));
172+
rewrite(frame("response.output_item.added", {
173+
output_index: 0,
174+
item: { type: "function_call", id: "fc_exec", call_id: "call_exec", name: "exec", arguments: "", status: "in_progress" },
175+
}));
176+
177+
const fragments = ['{"inp', 'ut":"before\\', 'b\\fafter"}'];
178+
let streamedInput = "";
179+
for (const delta of fragments) {
180+
const blocks = rewrite(frame("response.function_call_arguments.delta", {
181+
output_index: 0,
182+
item_id: "fc_exec",
183+
delta,
184+
}));
185+
for (const block of blocks) streamedInput += String(dataPayload(block).delta ?? "");
186+
}
187+
188+
const done = rewrite(frame("response.function_call_arguments.done", {
189+
output_index: 0,
190+
item_id: "fc_exec",
191+
arguments: fragments.join(""),
192+
}));
193+
const doneInput = dataPayload(done[0]!).input;
194+
expect(streamedInput).toBe(doneInput);
195+
expect(streamedInput).toBe("before\b\fafter");
196+
rewrite.dispose?.();
197+
});
198+
170199
test("handleResponses sends an upstream-safe exec function and restores client SSE", async () => {
171200
const savedFetch = globalThis.fetch;
172201
let outboundBody: Record<string, unknown> | undefined;

‎tests/responses-terminal-repair.test.ts‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ class ManualScheduler implements ResponsesTerminalRepairScheduler {
4242
}
4343
}
4444

45+
takeDue(ms: number): () => void {
46+
this.current += ms;
47+
const due = [...this.jobs.entries()]
48+
.filter(([, job]) => job.at <= this.current)
49+
.sort((left, right) => left[1].at - right[1].at)[0];
50+
if (!due) throw new Error("no due scheduler job");
51+
this.jobs.delete(due[0]);
52+
return due[1].callback;
53+
}
54+
4555
pending(): number { return this.jobs.size; }
4656
}
4757

@@ -87,6 +97,19 @@ async function readAll(stream: ReadableStream<Uint8Array>): Promise<string> {
8797
}
8898
}
8999

100+
async function readUntil(
101+
reader: ReadableStreamDefaultReader<Uint8Array>,
102+
pattern: string,
103+
): Promise<string> {
104+
let out = "";
105+
while (!out.includes(pattern)) {
106+
const { done, value } = await reader.read();
107+
if (done) throw new Error(`stream closed before ${pattern}`);
108+
out += decoder.decode(value, { stream: true });
109+
}
110+
return out;
111+
}
112+
90113
async function settle(): Promise<void> {
91114
await Promise.resolve();
92115
await Bun.sleep(0);
@@ -405,9 +428,12 @@ describe("DeepSeek Responses terminal repair", () => {
405428
));
406429
source.push(completedMessageLifecycle());
407430
await settle();
431+
expect(scheduler.pending()).toBe(1);
432+
const dueCallback = scheduler.takeDue(5_000);
408433
source.push(sse({ type: "response.completed", response: { id: "resp_message", status: "completed" }, sequence_number: 3 }));
409434
source.close();
410-
scheduler.advance(5_000);
435+
await settle();
436+
dueCallback();
411437
const output = await outputPromise;
412438
expect(terminalTypes(output)).toEqual(["response.completed"]);
413439
expect(scheduler.pending()).toBe(0);
@@ -447,9 +473,11 @@ describe("DeepSeek Responses terminal repair", () => {
447473
createTestTranslatorBudget(),
448474
cancelScheduler,
449475
);
476+
const cancelReader = cancelled.getReader();
450477
cancelSource.push(completedMessageLifecycle());
451-
await settle();
452-
await cancelled.cancel("client gone");
478+
expect(await readUntil(cancelReader, "response.output_item.done")).toContain("response.output_item.done");
479+
expect(cancelScheduler.pending()).toBe(1);
480+
await cancelReader.cancel("client gone");
453481
cancelScheduler.advance(5_000);
454482
expect(cancelSource.cancelled()).toBe(true);
455483
expect(cancelScheduler.pending()).toBe(0);
@@ -464,13 +492,15 @@ describe("DeepSeek Responses terminal repair", () => {
464492
createTestTranslatorBudget(),
465493
abortScheduler,
466494
);
495+
const abortReader = aborted.getReader();
467496
abortSource.push(completedMessageLifecycle());
468-
await settle();
497+
expect(await readUntil(abortReader, "response.output_item.done")).toContain("response.output_item.done");
498+
expect(abortScheduler.pending()).toBe(1);
469499
abortUpstream.abort("shutdown");
470500
await settle();
471501
expect(abortSource.cancelled()).toBe(true);
472502
expect(abortScheduler.pending()).toBe(0);
473-
await aborted.cancel("test cleanup");
503+
await abortReader.cancel("test cleanup");
474504
});
475505

476506
test("retained-state overflow throws translation_buffer_limit and releases budget", async () => {

0 commit comments

Comments
 (0)