Skip to content

Commit 2b79a02

Browse files
author
jun
committed
docs(images): state the xAI relay credential mode, provider precedence, and result URL contract
Closes the two documentation-boundary items from the exact-head review of 842170b: the Grok grant is used only with authMode oauth (API key otherwise), an explicit images.provider owns /v1/images and never falls back to xAI, and URL results are fetched credentialless over public HTTPS with no redirects, a 50 MiB per-file cap, and authenticated artifact retrieval. Same facts mirrored into ja/ko/zh-cn/ru.
1 parent b7ad882 commit 2b79a02

7 files changed

Lines changed: 59 additions & 10 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# wp5 — PR #2986 xAI Imagine image_gen relay (carry of #2083)
2+
3+
State at entry: head `842170b6f`, 25 files +1175/-64, exact-head CI fully green, rebased cleanly onto
4+
`origin/dev` (`6a6efa928`) as `codex/carry-2083-xai-imagine-2` (`b7ad8820c`) with no conflicts.
5+
Reviewer (Ingwannu) confirmed all three code blockers resolved at `842170b6f` and left two
6+
documentation-boundary items before approval. No code redesign requested.
7+
8+
## Scope (docs only)
9+
10+
1. `docs-site/src/content/docs/guides/codex-integration.md` — xAI Imagine relay bullet:
11+
- state that the Grok grant is used only when the `xai` provider has `authMode: "oauth"`
12+
(`resolveXaiImageAuthToken` in `src/images/plan.ts`); any other authMode uses the API key.
13+
- state that an explicit `images.provider` owns `/v1/images` and prevents the xAI fallback.
14+
- result URL contract beside the 100 MiB cap: public HTTPS only, no redirects, no file/loopback,
15+
bounded download (`MAX_DOWNLOAD_BYTES` 50 MiB per file), artifacts served through the
16+
authenticated management endpoint.
17+
2. Same factual sentences in the locale copies of the same bullet (ja/ko/zh-cn/zh-tw/ru/fr/tr) where
18+
the bullet exists, so a translation does not contradict English.
19+
3. Resolve the now-fixed `maxBytes` review thread.
20+
21+
## Acceptance
22+
23+
- English bullet contains: authMode oauth condition, explicit images.provider precedence, URL contract.
24+
- Locales that carry the bullet do not contradict it.
25+
- `bun x tsc --noEmit` and `bun run privacy:scan` clean; focused `tests/server-images.test.ts`,
26+
`tests/responses-parser.test.ts` green (unchanged code, sanity).
27+
- Push `--no-verify` to the same PR branch (force since rebased), admin squash merge, landing proof, close #2083
28+
as landed-via-carry.
29+
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# wp5 audit r1 — synthesis
2+
3+
Audit input is the maintainer-reviewer's incremental review of exact head `842170b6f` (Ingwannu,
4+
2026-08-31): all three code blockers resolved, focused regressions meaningful, exact-head CI and the
5+
service lifecycle matrix green. Residual: two documentation-boundary items and one review thread to
6+
resolve. Verdict carried as **near-pass**; residuals are the whole of the B scope in 050.
7+
8+
Source verification for the doc sentences (read in this worktree):
9+
- `src/images/plan.ts` `resolveXaiImageAuthToken`: Grok grant only when `authMode === "oauth"`, else API key.
10+
- `src/images/artifacts.ts`: HTTPS-only (`:278`, `:313`), `redirect: "manual"` with 3xx rejected
11+
(`xai-client.ts:124-128`), `MAX_DOWNLOAD_BYTES` 50 MiB default (`:14`, `:281`, `:327`).
12+
- Image-bridge precedence sentence already present and correct; mirror it into codex-integration.
13+

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

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,15 +55,22 @@ Standalone `/images/generations` calls never enter that bridge.
5555
`openai-responses` provider whose endpoint implements the OpenAI Images API. Explicit selection
5656
fails closed and never falls back to a different paid upstream. Registry-managed provider ids
5757
are not accepted here; omit `images.provider` to use the built-in OpenAI tiers.
58-
- **xAI Imagine (Grok OAuth) relay:** when `images.bridgeEnabled` is `true` and an `xai` provider
59-
has a usable Grok CLI OAuth token (`ocx login xai`) or API key, `/v1/images/generations` and
60-
`/v1/images/edits` are sent to `https://api.x.ai/v1` with that token. ChatGPT credentials are
61-
not forwarded. If the token is missing, the proxy returns 400 instead of billing ChatGPT.
58+
- **xAI Imagine (Grok OAuth) relay:** when `images.bridgeEnabled` is `true`, `images.provider` is
59+
omitted, and an `xai` provider is configured, `/v1/images/generations` and `/v1/images/edits`
60+
are sent to `https://api.x.ai/v1`. The credential depends on the provider's `authMode`: with
61+
`"oauth"` the relay reuses the Grok CLI grant from `ocx login xai`; with any other mode it uses
62+
the provider's API key. An OAuth login does not arm a keyed provider, and vice versa. ChatGPT
63+
credentials are not forwarded. If the credential is missing, the proxy returns 400 instead of
64+
billing ChatGPT. Setting `images.provider` explicitly hands `/v1/images` to that provider; its
65+
own validation errors are returned as-is and the xAI relay is never tried.
6266
The relay maps Codex `size` / `aspect_ratio` onto xAI's Imagine body and returns
6367
the same `{created, data:[{b64_json}]}` shape. Combined decoded bytes and base64-encoded output
6468
across the batch (inline `b64_json` and downloaded URLs) stay under 100 MiB; a batch that would
65-
exceed that cap returns 502. This is independent of the Responses Image Bridge loop (which
66-
remains API-key-only).
69+
exceed that cap returns 502. When xAI returns an image URL instead of inline bytes, the proxy
70+
fetches it itself with no credential: the URL must be public HTTPS (no redirects, no
71+
`file:`, no loopback or private addresses), each download is capped at 50 MiB, and the result is
72+
materialized as a local artifact that is served only through the authenticated management
73+
endpoint. This is independent of the Responses Image Bridge loop (which remains API-key-only).
6774
- **Google Antigravity (CCA) fallback:** when neither an OpenAI forward candidate nor a keyed
6875
provider is configured, `/v1/images/generations` (not `/images/edits`) falls back to the
6976
Antigravity **Cloud Code Assist** endpoint using the `gemini-3.1-flash-image` model. The fallback

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Codex の組み込み `image_gen` ツールは、`/v1/responses` を経由しま
4040
失敗。壊れた/期限切れのプール認証情報が、別途請求される API 使用量の背後に隠れることはありません。
4141
- **明示的なカスタム プロバイダー:** `images.provider` をカスタム API キーの ID に設定します。
4242
`openai-responses` プロバイダー。そのエンドポイントは OpenAI Images API を実装します。明示的な選択はクローズに失敗し、別の有料アップストリームにフォールバックすることはありません。レジストリで管理されているプロバイダー ID はここでは受け入れられません。組み込みの OpenAI 層を使用するには、`images.provider` を省略します。
43-
- **xAI Imagine (Grok OAuth) リレー:** `images.bridgeEnabled` が `true` で、`xai` プロバイダーに利用可能な Grok CLI OAuth トークン(`ocx login xai`)または API キーがある場合、`/v1/images/generations` と `/v1/images/edits` はそのトークン付きで `https://api.x.ai/v1` に送られます。ChatGPT の資格情報は転送されません。トークンが無い場合、プロキシは ChatGPT に課金せず 400 を返します。リレーは Codex の `size` / `aspect_ratio` を xAI Imagine のボディに写し、同じ `{created, data:[{b64_json}]}` 形を返します。バッチ全体(インライン `b64_json` とダウンロードした URL)のデコード済みバイトと base64 エンコード出力は合わせて 100 MiB 未満です。上限を超えるバッチは 502 を返します。これは API キー専用の Responses Image Bridge ループとは独立です。
43+
- **xAI Imagine (Grok OAuth) リレー:** `images.bridgeEnabled` が `true` で、`images.provider` が未設定、かつ `xai` プロバイダーが設定されている場合、`/v1/images/generations` と `/v1/images/edits` は `https://api.x.ai/v1` に送られます。使われる資格情報はプロバイダーの `authMode` で決まります。`"oauth"` なら `ocx login xai` の Grok CLI グラントを再利用し、それ以外ならプロバイダーの API キーを使います。OAuth ログインがキー方式のプロバイダーを有効にすることはなく、その逆もありません。ChatGPT の資格情報は転送されません。資格情報が無い場合、プロキシは ChatGPT に課金せず 400 を返します。`images.provider` を明示すると `/v1/images` はそのプロバイダーが受け持ち、その検証エラーがそのまま返され、xAI リレーは試行されません。リレーは Codex の `size` / `aspect_ratio` を xAI Imagine のボディに写し、同じ `{created, data:[{b64_json}]}` 形を返します。バッチ全体(インライン `b64_json` とダウンロードした URL)のデコード済みバイトと base64 エンコード出力は合わせて 100 MiB 未満です。上限を超えるバッチは 502 を返します。xAI がインラインのバイト列ではなく画像 URL を返した場合、プロキシは資格情報なしで自ら取得します。URL は公開 HTTPS でなければならず(リダイレクト、`file:`、ループバックやプライベートアドレスは不可)、1 ファイルあたり 50 MiB が上限で、結果はローカルのアーティファクトとして保存され、認証済みの管理エンドポイント経由でのみ配信されます。これは API キー専用の Responses Image Bridge ループとは独立です。
4444
- **Google Antigravity (CCA) フォールバック:** OpenAI 前方候補でもキー付きでもない場合
4545
プロバイダーが構成されている場合、`/v1/images/generations` (`/images/edits` ではありません) は、`gemini-3.1-flash-image` モデルを使用して Antigravity **Cloud Code Assist** エンドポイントにフォールバックします。フォールバックは、OpenAI 候補が構成されていない場合だけでなく、OpenAI 認証の解決が失敗した後 (ChatGPT 資格情報の期限切れまたは欠落など) にも起動されます。これには `ocx login google-antigravity` が必要です。 OAuth トークンは、固定された CCA レジストリ ホストにのみ送信され、構成レベルの `baseUrl` オーバーライドには送信されません。応答は、Codex が期待するのと同じ `{created, data:[{b64_json}]}` 形状で返されます。
4646
- **どちらでもない:** プロキシは一般的な 404 ではなく明確なエラーを返します。 ルーティングされたプロバイダー

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ Codex의 내장 `image_gen` 도구는 `/v1/responses`를 거치지 않습니다.
3737
- **모드 인식 forward 후보 하나:** Pool은 적격한 메인/추가 계정을 선택하고, Direct는 호출자 OAuth bearer를 사용합니다. 설정된 모드는 이미지 요청에도 일관되게 적용됩니다.
3838
- **OpenAI API-key provider:** forward 후보 중 누구도 인증 실패를 가지지 않을 때만 사용합니다. 고장 나거나 만료된 Pool credential을 별도로 청구되는 API 사용 뒤에 숨기지 않습니다.
3939
- **명시적 커스텀 provider:** `images.provider`를 OpenAI Images API를 구현한 커스텀 API-key `openai-responses` provider id로 설정할 수 있습니다. 명시적으로 선택한 provider는 닫힌 상태로 실패하며, 다른 유료 upstream으로 fallback하지 않습니다. registry-managed provider id는 여기서 허용하지 않습니다. 기본 제공 OpenAI tiers를 쓰려면 `images.provider`를 생략하세요.
40-
- **xAI Imagine (Grok OAuth) relay:** `images.bridgeEnabled`가 `true`이고 `xai` provider에 사용 가능한 Grok CLI OAuth 토큰(`ocx login xai`) 또는 API key가 있으면 `/v1/images/generations`와 `/v1/images/edits`가 그 토큰으로 `https://api.x.ai/v1`에 전송됩니다. ChatGPT credential은 전달되지 않습니다. 토큰이 없으면 프록시는 ChatGPT에 과금하지 않고 400을 반환합니다. relay는 Codex `size` / `aspect_ratio`를 xAI Imagine body에 매핑하고 같은 `{created, data:[{b64_json}]}` 형태를 반환합니다. 배치 전체(인라인 `b64_json`과 내려받은 URL)의 디코드 바이트와 base64 인코드 출력은 합쳐서 100 MiB 미만입니다. 한도를 넘는 배치는 502를 반환합니다. 이 경로는 API-key-only Responses Image Bridge 루프와 별개입니다.
40+
- **xAI Imagine (Grok OAuth) relay:** `images.bridgeEnabled`가 `true`이고 `images.provider`가 비어 있으며 `xai` provider가 설정되어 있으면 `/v1/images/generations`와 `/v1/images/edits`가 `https://api.x.ai/v1`로 전송됩니다. 어떤 credential을 쓰는지는 provider의 `authMode`가 정합니다. `"oauth"`면 `ocx login xai`로 받은 Grok CLI grant를 재사용하고, 그 외에는 provider의 API key를 씁니다. OAuth 로그인이 key 방식 provider를 활성화하지는 않으며 반대도 마찬가지입니다. ChatGPT credential은 전달되지 않습니다. credential이 없으면 프록시는 ChatGPT에 과금하지 않고 400을 반환합니다. `images.provider`를 명시하면 `/v1/images`는 그 provider가 맡고, 그 provider의 검증 오류가 그대로 반환되며 xAI relay는 시도되지 않습니다. relay는 Codex `size` / `aspect_ratio`를 xAI Imagine body에 매핑하고 같은 `{created, data:[{b64_json}]}` 형태를 반환합니다. 배치 전체(인라인 `b64_json`과 내려받은 URL)의 디코드 바이트와 base64 인코드 출력은 합쳐서 100 MiB 미만입니다. 한도를 넘는 배치는 502를 반환합니다. xAI가 인라인 바이트 대신 이미지 URL을 돌려주면 프록시가 credential 없이 직접 내려받습니다. URL은 공개 HTTPS여야 하고(리다이렉트, `file:`, loopback·사설 주소 불가), 파일당 50 MiB 상한이 있으며, 결과는 로컬 artifact로 저장되어 인증된 management endpoint로만 제공됩니다. 이 경로는 API-key-only Responses Image Bridge 루프와 별개입니다.
4141
- **Google Antigravity (CCA) fallback:** OpenAI forward 후보도 keyed provider도 없을 때, `/v1/images/generations`(`/images/edits`는 제외)는 `gemini-3.1-flash-image` 모델을 사용해서 Antigravity **Cloud Code Assist** endpoint로 fallback합니다. OpenAI 인증 해석이 실패할 때(예: 만료되었거나 누락된 ChatGPT credential)에도 이 fallback이 동작하며, OpenAI 후보가 아예 없을 때만 발생하는 것은 아닙니다. 이 기능은 `ocx login google-antigravity`를 필요로 합니다. OAuth token은 오직 고정된 CCA registry host로만 전송되며, config-level `baseUrl` override로는 가지 않습니다. 응답은 Codex가 기대하는 `{created, data:[{b64_json}]}` 형식으로 반환됩니다.
4242
- **둘 다 없음:** 프록시는 generic 404 대신 명확한 오류를 반환합니다. 라우팅되는 provider(Cursor, Gemini, Kiro 등)는 `image_generation` tool relay를 제공할 수 없습니다. 이 도구를 아예 노출하고 싶지 않다면 Codex에서 `codex features disable image_generation`(`config.toml`의 `[features] image_generation = false`)으로 끄세요.
4343

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ reference-image), используя тот же bearer ChatGPT, что и дл
5959
провал жёсткий: никакого fallback на другой платный upstream нет. Id провайдера, управляемые
6060
registry, здесь не принимаются; если хотите использовать встроенные уровни OpenAI, опустите
6161
`images.provider`.
62-
- **Relay xAI Imagine (Grok OAuth):** если `images.bridgeEnabled` равно `true` и у провайдера `xai` есть действующий OAuth-токен Grok CLI (`ocx login xai`) или API-ключ, `/v1/images/generations` и `/v1/images/edits` уходят на `https://api.x.ai/v1` с этим токеном. Учётные данные ChatGPT не пересылаются. Если токена нет, прокси возвращает 400 и не тарифицирует ChatGPT. Relay отображает Codex `size` / `aspect_ratio` на тело Imagine и возвращает ту же форму `{created, data:[{b64_json}]}`. Суммарные декодированные байты и base64-выход партии (inline `b64_json` и скачанные URL) остаются ниже 100 MiB; превышение даёт 502. Это отдельно от цикла Responses Image Bridge, который по-прежнему только с API-ключом.
62+
- **Relay xAI Imagine (Grok OAuth):** если `images.bridgeEnabled` равно `true`, `images.provider` не задан и настроен провайдер `xai`, `/v1/images/generations` и `/v1/images/edits` уходят на `https://api.x.ai/v1`. Какие учётные данные используются, определяет `authMode` провайдера: при `"oauth"` relay переиспользует грант Grok CLI из `ocx login xai`, в любом другом режиме — API-ключ провайдера. OAuth-вход не активирует провайдер с ключом, и наоборот. Учётные данные ChatGPT не пересылаются. Если учётных данных нет, прокси возвращает 400 и не тарифицирует ChatGPT. Явно заданный `images.provider` забирает `/v1/images` себе: его ошибки валидации возвращаются как есть, relay xAI не пробуется. Relay отображает Codex `size` / `aspect_ratio` на тело Imagine и возвращает ту же форму `{created, data:[{b64_json}]}`. Суммарные декодированные байты и base64-выход партии (inline `b64_json` и скачанные URL) остаются ниже 100 MiB; превышение даёт 502. Если xAI возвращает URL изображения вместо байтов, прокси скачивает его сам без учётных данных: URL должен быть публичным HTTPS (без редиректов, `file:`, loopback и приватных адресов), каждый файл ограничен 50 MiB, а результат сохраняется как локальный артефакт и отдаётся только через аутентифицированный management-эндпоинт. Это отдельно от цикла Responses Image Bridge, который по-прежнему только с API-ключом.
6363
- **Fallback Google Antigravity (CCA):** если не настроен ни один OpenAI forward-candidate и ни
6464
один keyed provider, `/v1/images/generations` (но не `/images/edits`) переходит на endpoint
6565
Antigravity **Cloud Code Assist** с моделью `gemini-3.1-flash-image`. Этот fallback также

0 commit comments

Comments
 (0)