Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs-site/src/content/docs/guides/codex-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,22 @@ encodes that declaration and its history as an upstream function tool, then rest
function-call lifecycle to `custom_tool_call` before Codex sees it. Native OpenAI forward routing
and the supported `apply_patch` custom tool stay unchanged.

For an xAI/Grok destination, a writable Code Mode turn uses a provider-native catalog instead of
asking Grok to author JavaScript for Codex's freeform `exec` tool. OpenCodex exposes the
collision-free request-local subset of `read_file`, `grep`, `list_dir`, `search_replace`, `write`,
and `run_terminal_command` upstream; same-name caller-owned tools remain unchanged. It translates
file edits into the caller's existing `apply_patch` helper, translates reads and commands into the
existing `exec_command` helper, and restores the original `exec` call shape, ids, and stream events
before Codex sees the response. Supported calls in prior history are reconstructed into the same
Grok-native vocabulary for continuation turns.

This bridge is automatic and has no configuration switch. It activates only when the destination
is xAI, Codex supplied a visible freeform `exec` declaration with `apply_patch`, and the turn allows
mutation. Plan/no-mutation turns and non-xAI providers keep their existing tool catalog. OpenCodex
only translates declarations and calls; it never executes the filesystem or shell operation.
Codex remains responsible for sandboxing and approval prompts, including escalation requested for
git mutations.
Comment thread
goodwilliam0126 marked this conversation as resolved.

Comment thread
goodwilliam0126 marked this conversation as resolved.
The selected provider must support function/tool calling. A text-only provider without tool-call
support cannot use `exec`, Browser, or Computer Use. Native OpenAI rows keep their upstream tool
mode unchanged.
Expand Down
13 changes: 13 additions & 0 deletions docs-site/src/content/docs/ja/guides/codex-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,19 @@ Codex の `exec` custom-tool grammar を受け付けない key-auth Responses pr
`custom_tool_call` へ復元します。ネイティブ OpenAI の forward routing と、対応済みの `apply_patch` custom tool は
変更されません。

xAI/Grok 宛てでは、変更可能な Code Mode ターンで Grok に Codex の freeform `exec` 用 JavaScript を直接
書かせる代わりに、provider-native catalog を使用します。OpenCodex は上流に `read_file`、`grep`、`list_dir`、
`search_replace`、`write`、`run_terminal_command` を公開します。ファイル編集は呼び出し元が用意した
`apply_patch` helper に、読み取りとコマンドは既存の `exec_command` helper に変換されます。応答が Codex に
届く前に元の `exec` call shape、ID、stream event を復元し、対応している過去の history call も継続ターン用に
同じ Grok-native vocabulary へ再構成します。

この bridge は設定なしで自動的に動作します。宛先が xAI で、Codex が `apply_patch` を含む可視の freeform
`exec` 宣言を送り、そのターンで変更が許可されている場合にのみ有効になります。Plan/no-mutation ターンと
xAI 以外の provider は従来の tool catalog を維持し、同名の caller-owned tool も変換されません。OpenCodex は
宣言と call のみを変換し、filesystem や shell 操作を実行しません。git mutation の権限昇格要求を含め、
sandbox と承認 prompt の責任は引き続き Codex にあります。

選択した provider は function/tool calling をサポートしている必要があります。tool call に対応しない text-only
provider では `exec`、Browser、Computer Use は使用できません。ネイティブ OpenAI の項目は上流の tool mode を
そのまま維持します。
Expand Down
12 changes: 12 additions & 0 deletions docs-site/src/content/docs/ja/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@ interface ProviderAdapter {
`xhigh`、`max` tier をそのまま保持し、`delta.reasoning_content` または `delta.reasoning` を
reasoning delta として扱い、`stream_options.include_usage` でストリーム usage を要求し、非ストリームのレスポンス envelope からも usage を読み取ります。

## xAI/Grok Code Mode bridge

`openai-chat` と `openai-responses` は、変更可能な xAI Code Mode ターンに同じ bridge を適用します。
Codex が `apply_patch` を含む可視の freeform `exec` 宣言を送ると、adapter は `read_file`、`grep`、
`list_dir`、`search_replace`、`write`、`run_terminal_command` のうち、caller-owned tool と衝突しない
request-local な名前だけを公開します。Plan/no-mutation ターン、xAI 以外の宛先、同名の caller-owned tool は
変更されません。

live call と対応済みの history は、呼び出し元の既存 `apply_patch` / `exec_command` helper を介して変換され、
応答の名前、ID、JSON/SSE event lifecycle は Codex に届く前に復元されます。proxy は filesystem や shell 操作を
実行しません。git mutation の権限昇格 prompt を含め、sandbox と承認の責任は Codex に残ります。

## `openai-responses`

**対象:** OpenAI **Responses API**。**`passthrough: true`** — 通常は元のリクエストとレスポンスをそのまま渡し、ルーティング先ゲートウェイに必要な限定的な互換変換だけを適用します。
Expand Down
13 changes: 13 additions & 0 deletions docs-site/src/content/docs/ko/guides/codex-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,19 @@ history를 업스트림 function tool로 인코딩한 다음 스트리밍된 fun
`custom_tool_call`로 복원합니다. 네이티브 OpenAI forward routing과 지원되는 `apply_patch` custom tool은 변경되지
않습니다.

xAI/Grok 대상에서는 파일 수정이 허용된 Code Mode 턴에 Grok이 Codex의 freeform `exec`용 JavaScript를 직접
작성하도록 요구하는 대신 provider-native catalog를 사용합니다. OpenCodex는 upstream에 `read_file`, `grep`,
`list_dir`, `search_replace`, `write`, `run_terminal_command`를 노출합니다. 파일 편집은 호출자가 원래 제공한
`apply_patch` helper로, 읽기와 명령은 기존 `exec_command` helper로 변환하며, 응답이 Codex에 도달하기 전에 원래
`exec` call shape, id, stream event를 복원합니다. 지원되는 이전 history call도 continuation 턴에서 같은
Grok-native vocabulary로 재구성합니다.

이 bridge는 별도 설정 없이 자동으로 동작합니다. 대상이 xAI이고, Codex가 `apply_patch`를 포함한 visible
freeform `exec` 선언을 보냈으며, 해당 턴이 수정을 허용할 때만 활성화됩니다. Plan/no-mutation 턴과 xAI가 아닌
provider는 기존 tool catalog를 유지합니다. OpenCodex는 선언과 호출만 변환하며 filesystem 또는 shell 작업을
직접 실행하지 않습니다. git mutation에 필요한 권한 상승 요청을 포함해 sandbox와 승인 prompt는 계속 Codex가
담당합니다.

선택한 provider는 function/tool calling을 지원해야 합니다. tool call을 지원하지 않는 text-only provider에서는
`exec`, Browser 또는 Computer Use를 사용할 수 없습니다. 네이티브 OpenAI 항목은 업스트림 tool mode를 그대로
유지합니다.
Expand Down
13 changes: 13 additions & 0 deletions docs-site/src/content/docs/ko/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ interface ProviderAdapter {
유지하고, `delta.reasoning_content` 또는 `delta.reasoning`을 reasoning delta로 처리하며,
`stream_options.include_usage`로 스트림 usage를 요청하고 비스트림 응답 envelope에서도 usage를 읽습니다.

## xAI/Grok Code Mode bridge

`openai-chat`과 `openai-responses` 경로는 수정 가능한 xAI Code Mode 턴에 같은 bridge를 적용합니다.
Codex가 `apply_patch`를 포함한 visible freeform `exec` 선언을 보내면 adapter는 `read_file`, `grep`,
`list_dir`, `search_replace`, `write`, `run_terminal_command` 중 caller-owned tool과 충돌하지 않는
request-local 이름만 노출합니다. Plan/no-mutation 턴, xAI가 아닌 대상, 같은 이름의 caller-owned tool은
변경하지 않습니다.

실시간 호출과 지원되는 history는 호출자의 기존 `apply_patch` 및 `exec_command` helper를 통해 변환되며,
응답 이름, ID, JSON/SSE event lifecycle은 Codex에 도달하기 전에 복원됩니다. proxy는 filesystem 또는 shell
작업을 실행하지 않습니다. git mutation의 권한 상승 prompt를 포함해 sandbox와 승인 권한은 계속 Codex가
담당합니다.

## `openai-responses`

**대상:** OpenAI **Responses API**. **`passthrough: true`** — 일반적으로 원본 요청과 응답을
Expand Down
13 changes: 13 additions & 0 deletions docs-site/src/content/docs/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ provider — xAI, Kimi, DeepSeek, GLM, Groq, OpenRouter, Ollama (local & cloud),
tiers, accepts reasoning deltas from either `delta.reasoning_content` or `delta.reasoning`, requests
streamed usage with `stream_options.include_usage`, and reads usage from non-stream response envelopes.

## xAI/Grok Code Mode bridge

The `openai-chat` and `openai-responses` paths apply the same bridge to writable xAI Code Mode
turns. When Codex supplies a visible freeform `exec` declaration containing `apply_patch`, the
adapter projects the collision-free request-local subset of `read_file`, `grep`, `list_dir`,
`search_replace`, `write`, and `run_terminal_command`. Plan/no-mutation turns, non-xAI destinations,
and caller-owned tools with the same names remain unchanged.

Live calls and supported history are translated through the caller's existing `apply_patch` and
`exec_command` helpers; response names, IDs, and JSON/SSE event lifecycles are restored before they
reach Codex. The proxy never executes the filesystem or shell operation. Codex remains the sandbox
and approval authority, including escalation prompts for git mutations.

## `openai-responses`

**Targets:** the OpenAI **Responses API**. **`passthrough: true`** — normally forwards the raw request
Expand Down
15 changes: 15 additions & 0 deletions docs-site/src/content/docs/ru/guides/codex-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,21 @@ opencodex кодирует объявление и историю как functio
потоковый lifecycle function call в `custom_tool_call` до передачи в Codex. Нативная forward-
маршрутизация OpenAI и поддерживаемый custom tool `apply_patch` остаются без изменений.

Для назначения xAI/Grok изменяемый turn Code Mode использует provider-native catalog вместо того,
чтобы Grok напрямую писал JavaScript для freeform-инструмента `exec` в Codex. OpenCodex показывает
upstream-инструменты `read_file`, `grep`, `list_dir`, `search_replace`, `write` и
`run_terminal_command`. Изменения файлов преобразуются в существующий helper `apply_patch`
вызывающей стороны, а чтение и команды — в существующий helper `exec_command`. До передачи ответа
в Codex восстанавливаются исходные shape вызова `exec`, ID и stream events; поддерживаемые вызовы
из предыдущей history также реконструируются в тот же Grok-native vocabulary для продолжения.

Bridge работает автоматически и не требует настройки. Он включается только для назначения xAI,
когда Codex передал видимое freeform-объявление `exec` с `apply_patch` и turn разрешает изменения.
Plan/no-mutation turns и provider'ы не-xAI сохраняют прежний tool catalog; одноимённые caller-owned
tools также не преобразуются. OpenCodex меняет только объявления и вызовы, но не выполняет операции
filesystem или shell. Sandboxing и approval prompts, включая запрос повышения прав для git
mutations, остаются ответственностью Codex.

Выбранный provider должен поддерживать function/tool calling. Text-only provider без tool calls
не может использовать `exec`, Browser или Computer Use. Нативные записи OpenAI сохраняют свой
upstream tool mode без изменений.
Expand Down
18 changes: 16 additions & 2 deletions docs-site/src/content/docs/ru/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,24 @@ interface ProviderAdapter {
`delta.reasoning_content` или `delta.reasoning`, запрашивает usage потока через
`stream_options.include_usage` и читает usage из envelope нестримингового ответа.

## Bridge xAI/Grok Code Mode

Пути `openai-chat` и `openai-responses` применяют один bridge к изменяемым turns xAI Code Mode.
Когда Codex передаёт видимое freeform-объявление `exec` с `apply_patch`, adapter показывает только
не конфликтующее с caller-owned tools request-local подмножество `read_file`, `grep`, `list_dir`,
`search_replace`, `write` и `run_terminal_command`. Plan/no-mutation turns, назначения не-xAI и
одноимённые caller-owned tools остаются без изменений.

Live calls и поддерживаемая history преобразуются через существующие helpers `apply_patch` и
`exec_command` вызывающей стороны; имена ответов, ID и lifecycle событий JSON/SSE восстанавливаются
до передачи в Codex. Proxy не выполняет операции filesystem или shell. Codex остаётся владельцем
sandbox и approval prompts, включая повышение прав для git mutations.

Comment thread
coderabbitai[bot] marked this conversation as resolved.
## `openai-responses`

**Назначение:** OpenAI **Responses API**. **`passthrough: true`** — пересылает исходное тело
запроса и стримит ответ обратно **без преобразования**.
**Назначение:** OpenAI **Responses API**. **`passthrough: true`** — обычно пересылает исходное тело
запроса и ответ обратно, применяя только узкие compatibility rewrites для маршрутизируемых шлюзов,
включая bridge xAI/Grok Code Mode.
**Аутентификация:** `forward` (ретрансляция заголовков вызывающей стороны) или `key`.

При `key`-аутентификации [`retryOn429`](/ru/reference/configuration/) действует и здесь: 429 до
Expand Down
11 changes: 11 additions & 0 deletions docs-site/src/content/docs/zh-cn/guides/codex-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,17 @@ Codex 显示的模型来自一个磁盘上的 catalog(默认是 `$CODEX_HOME/o
历史记录编码成上游 function tool,再在 Codex 收到结果前,把流式 function-call lifecycle 还原成
`custom_tool_call`。原生 OpenAI forward routing 和已支持的 `apply_patch` custom tool 保持不变。

对于 xAI/Grok 目标,可写的 Code Mode 回合会使用 provider-native catalog,而不是要求 Grok 直接为 Codex 的
freeform `exec` 工具编写 JavaScript。OpenCodex 会向上游公开 `read_file`、`grep`、`list_dir`、
`search_replace`、`write` 和 `run_terminal_command`。文件编辑会转换为调用方已有的 `apply_patch` helper,
读取和命令会转换为现有的 `exec_command` helper;在响应到达 Codex 前,还会恢复原始 `exec` 调用形状、ID 和
流式事件。历史记录中受支持的调用也会重建为同一套 Grok-native vocabulary,以供后续回合继续使用。

该 bridge 无需配置,会自动工作。它只在目标为 xAI、Codex 提供了一个包含 `apply_patch` 的可见 freeform
`exec` 声明,并且当前回合允许修改时启用。Plan/no-mutation 回合和非 xAI provider 会保留原有 tool catalog;
调用方拥有的同名工具也不会被转换。OpenCodex 只转换声明和调用,绝不会执行 filesystem 或 shell 操作。
包括 git mutation 权限提升请求在内的 sandbox 和审批提示仍由 Codex 负责。

所选 provider 必须支持 function/tool calling。不支持 tool call 的 text-only provider 无法使用 `exec`、
Browser 或 Computer Use。原生 OpenAI 条目会保持其上游 tool mode 不变。

Expand Down
11 changes: 11 additions & 0 deletions docs-site/src/content/docs/zh-cn/reference/adapters.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ interface ProviderAdapter {
`medium`、`high`、`xhigh` 或 `max` 档位,把 `delta.reasoning_content` 或 `delta.reasoning`
作为 reasoning delta,通过 `stream_options.include_usage` 请求流式 usage,并从非流式响应 envelope 中读取 usage。

## xAI/Grok Code Mode bridge

`openai-chat` 和 `openai-responses` 路径会对可写的 xAI Code Mode 回合应用同一个 bridge。
当 Codex 提供包含 `apply_patch` 的可见 freeform `exec` 声明时,adapter 只会公开 `read_file`、`grep`、
`list_dir`、`search_replace`、`write` 和 `run_terminal_command` 中不与 caller-owned tool 冲突的
request-local 子集。Plan/no-mutation 回合、非 xAI 目标和调用方拥有的同名工具保持不变。

实时调用和受支持的历史记录会通过调用方现有的 `apply_patch` 与 `exec_command` helper 转换;响应名称、ID
以及 JSON/SSE 事件生命周期会在到达 Codex 前恢复。proxy 不会执行 filesystem 或 shell 操作。包括 git
mutation 权限提升提示在内的 sandbox 和审批权仍由 Codex 负责。

## `openai-responses`

**目标:** OpenAI **Responses API**。**`passthrough: true`** —— 通常原样转发请求与响应,仅对
Expand Down
3 changes: 2 additions & 1 deletion src/adapters/anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { stripResponsesOnlyEncryptedMarker } from "./responses-tool-schema";
import { identifyRoutedModel } from "./identity";
import { redactSecretString } from "../lib/redact";
import { CLAUDE_CODE_HEADERS, claudeCodeSessionId } from "./client-fingerprint";
import { buildNonOpenAIToolCatalogNudgeForTools } from "./tool-catalog-nudge";
import { buildNonOpenAIToolCatalogNudgeForTools, effectiveInstructionText } from "./tool-catalog-nudge";
import { decodeServerSentEvents } from "../lib/sse-decoder";
import { isTranslatorBudgetExceededError, retainTranslatedEventBatch, type TranslatorBudget } from "../lib/translator-budget";

Expand Down Expand Up @@ -672,6 +672,7 @@ function messagesToAnthropicFormat(
parsed.context.tools,
parsed.options.toolChoice,
tool => toolNames.toWire(namespacedToolName(tool.namespace, tool.name)),
effectiveInstructionText(parsed.context.messages, parsed.context.systemPrompt),
);
const systemParts = [...(parsed.context.systemPrompt ?? []), ...(toolCatalogNudge ? [toolCatalogNudge] : [])];
const system = systemParts.length
Expand Down
4 changes: 4 additions & 0 deletions src/adapters/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ export interface AdapterRequest {
convertedRoutedToolSearchNames?: ReadonlySet<string>;
/** Upstream-only aliases for namespace tools flattened in this request. */
convertedRoutedNamespaceToolAliases?: ReadonlyMap<string, { namespace: string; name: string }>;
/** Native Grok tool names introduced while replacing Codex code-mode exec. */
convertedGrokNativeToolNames?: ReadonlySet<string>;
/** Caller-facing custom exec name that receives converted native Grok calls. */
grokStructuredEditExecSinkName?: string;
/** Releases observation of a serialized request body after its final fetch attempt settles. */
releaseBodyObservation?: () => void;
/** Exact reasoning parameter emitted by the adapter, for request-log diagnostics only. */
Expand Down
Loading
Loading