Skip to content

Commit b29edeb

Browse files
authored
feat(web-search): live xai executor with opt-in x_search (lidge-jun#2188 L7) (lidge-jun#2242)
* feat(web-search): xai executor with opt-in x_search (lidge-jun#2188 L7) runXaiWebSearch POSTs the pinned api.x.ai Responses endpoint with the stored Grok OAuth credential, hosted web_search (+ opt-in x_search with doc-validated handle/date limits), and reduces the SSE stream to text + deduped sources from url_citation annotations unioned with web_search_call action.sources. custom_tool_call items and skeleton action are tolerated per live captures. planWebSearch's xai arm goes live fail-closed; the loop dispatches it without touching forward headers; the registry activates the backend on OAuth presence; PUT validates the xSearch block before persisting. * fix(web-search): pin the xai origin exactly, fail the loop arm closed, round-trip xSearch Origin pinning by prefix admitted https://api.x.ai.evil — parse and compare url.origin, falling back to the canonical endpoint (Critical). A missing xaiSidecar on the xai loop arm now yields an error outcome instead of falling through to the forward-header OpenAI executor (High). GET and the PUT response now carry the persisted xSearch block so a dashboard reload cannot lose visible configuration (High). Tests: lookalike-origin bearer containment, xSearch 400/round-trip/clear. * test(web-search): loop-level regression for the xai fail-closed arm * fix(web-search): close xai executor review blockers Attach abort-driven body cancellation immediately after the xAI fetch, cancel oversized SSE readers upstream, and cover transport release. Stage and validate complete web-search management candidates before commit; reject malformed xSearch types without partial mutation or broadened searches. Document the live Grok OAuth/x_search backend across canonical docs, locales, type comments, and structure sources. Evidence: 47 focused tests pass; bun x tsc --noEmit; docs Astro build 393 pages. * fix(web-search): reject unknown xSearch fields * fix(web-search): unify WebSearchBackend with the five-value union after rebase Cross-layer reconciliation: lidge-jun#2209 introduced the (backend, model) pair contract typed as openai|anthropic; lidge-jun#2238 widened the configured union to five backends. The options module now re-exports WebSearchBackendId and passes config into isActive, so inert arms simply never produce rows. tsc clean; 48/0 across the three web-search suites.
1 parent c9feb6f commit b29edeb

29 files changed

Lines changed: 869 additions & 106 deletions

File tree

‎docs-site/src/content/docs/fr/guides/sidecars.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ description: Dotez les modèles routés d’une véritable recherche web et donn
55

66
Tous les modèles routés ne proposent pas une **recherche web** hébergée ni une **entrée d’image** native. opencodex complète
77
ces capacités au moyen de deux services auxiliaires. Chacun peut s’appuyer sur un fournisseur connecté à ChatGPT (`forward`) ou sur un
8-
fournisseur Anthropic OAuth enregistré. Les erreurs des services auxiliaires sont converties en résultats d’outil limités ou en marqueurs d’image,
8+
fournisseur Anthropic OAuth enregistré ; la recherche web peut aussi utiliser un OAuth Grok enregistré via le moteur `xai` explicite. Les erreurs des services auxiliaires sont converties en résultats d’outil limités ou en marqueurs d’image,
99
au lieu de faire échouer l’intégralité du tour.
1010

1111
:::note[Sélection automatique du moteur]
12-
Une valeur `backend` explicite est prioritaire. Lorsqu'elle est omise, opencodex utilise `anthropic` si un fournisseur OAuth Anthropic actif
13-
possède un compte actif qui n'est pas marqué `needsReauth` ; sinon, il utilise `openai`. Une sélection explicite de
14-
`anthropic` sans ces identifiants échoue de manière sûre. `openai` exige à la fois une connexion ChatGPT et un
12+
Une valeur `backend` explicite est prioritaire. Sans valeur, la recherche web utilise toujours `openai` ; Vision utilise
13+
`anthropic` si un compte OAuth Anthropic utilisable existe, sinon `openai`. Une sélection explicite de
14+
`anthropic` ou `xai` sans identifiants utilisables échoue sans repli. `openai` exige à la fois une connexion ChatGPT et un
1515
fournisseur `forward` actif.
1616
:::
1717

@@ -24,7 +24,8 @@ Lorsque Codex demande un hébergement `web_search` pour un modèle routé sans p
2424
2. Exécute le modèle routé dans une petite **boucle d'agent**. Lorsqu'il appelle `web_search`, opencodex utilise le
2525
moteur du service auxiliaire sélectionné : OpenAI exécute l'outil hébergé `web_search` avec `gpt-5.6-luna` par défaut ;
2626
Anthropic exécute `web_search_20250305` avec `claude-sonnet-5` par défaut. La réponse en streaming et
27-
les citations deviennent le résultat d’un outil.
27+
les citations deviennent le résultat d’un outil. xAI exécute `web_search` avec `grok-4.6` par défaut et ajoute
28+
`x_search` à la même requête lorsque `xSearch.enabled` vaut true.
2829
3. **Répète la boucle** jusqu'à ce que le modèle réponde ou que le nombre total de recherches réelles atteigne `maxSearchesPerTurn`
2930
(par défaut 3), supprime ensuite l'outil de recherche et force une réponse finale. De vrais outils clients tels que
3031
`apply_patch` ou le shell mettent fin au tour afin que ces appels parviennent à Codex.

‎docs-site/src/content/docs/fr/reference/configuration/server.md‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,8 +209,10 @@ l'API Images d'OpenAI et la forme de réponse attendue par Codex.
209209
| Champ | Type | Par défaut | Signification |
210210
| --- | --- | --- | --- |
211211
| `enabled?` | `boolean` | activé lorsqu'il est utilisable | Interrupteur principal. |
212-
| `backend?` | `"openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"` | `openai` | Une valeur explicite est prioritaire ; sans valeur, `openai` est toujours utilisé. `xai`, `gemini` et `exa` ne s'activent que s'ils sont configurés explicitement. |
213-
| `model?` | `string` | dépendant du backend | `gpt-5.6-luna` pour OpenAI ou `claude-sonnet-5` pour Anthropic. L'héritage explicite `gpt-5.4-mini` migre au démarrage. |
212+
| `backend?` | `"openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"` | `openai` | Une valeur explicite est prioritaire ; l'absence de valeur sélectionne toujours `openai`. `anthropic` et `xai` ne s'exécutent que s'ils sont configurés explicitement ; `gemini` et `exa` restent réservés jusqu'à la livraison de leur executor. |
213+
| `model?` | `string` | dépendant du backend | `gpt-5.6-luna` pour OpenAI, `claude-sonnet-5` pour Anthropic ou `grok-4.6` pour xAI. L'héritage explicite `gpt-5.4-mini` migre au démarrage. |
214+
| `exaApiKey?` | `string` | aucun | Clé opérateur pour le backend `exa`. Écriture seule : les lectures de gestion ne renvoient jamais la valeur stockée. |
215+
| `xSearch?` | `object` | omis | Activation facultative de `x_search` hébergé, propre à xAI : `enabled`, tableaux mutuellement exclusifs `allowedXHandles` / `excludedXHandles` (20 au maximum), et dates ISO `fromDate` / `toDate` (`YYYY-MM-DD`). |
214216
| `reasoning?` | `string` | `low` | Effort secondaire. `minimal` est rejeté lors de la recherche sur le Web. |
215217
| `maxSearchesPerTurn?` | `number` | `3` | Recherches réelles autorisées par tour de modèle principal. |
216218
| `routedModelStallTimeoutMs?` | `number` | `200000` | Date limite d'inactivité du corps brut du modèle routé uniquement pour les fichiers de configuration. Entier 1–2147483647 ; chaque morceau non vide le réinitialise. |
@@ -220,7 +222,11 @@ Le moteur OpenAI nécessite une connexion à ChatGPT et un fournisseur ChatGPT `
220222
entrantes depuis Claude injectent l'authentification ChatGPT principale dans la requête interne. Le moteur Anthropic utilise les
221223
identifiants actifs stockés auprès d'un fournisseur Anthropic OAuth activé. Si le moteur Anthropic est sélectionné explicitement
222224
mais qu'aucun compte n'est utilisable, l'opération échoue de manière sûre au lieu de se rabattre sur un autre moteur. L'exécuteur Anthropic utilise son
223-
outil `web_search_20250305` natif.
225+
outil `web_search_20250305` natif. Le backend xAI nécessite un compte OAuth Grok stocké et utilisable, emploie
226+
`web_search` hébergé et ajoute `x_search` hébergé lorsque `xSearch.enabled` vaut true. Une entrée de gestion
227+
`xSearch` mal formée renvoie `400` ; un bloc persistant mal formé échoue de manière sûre pendant la planification.
228+
Les voies `gemini` et `exa` ne s'activent jamais par découverte d'identifiants ni par fallback ; l'opérateur doit
229+
les sélectionner explicitement. `exaApiKey` est accepté en écriture mais omis des réponses de gestion.
224230

225231
Quatre horloges régissent la recherche : base `stallTimeoutSec`, `connectTimeoutMs`, inactivité du modèle routé et
226232
délai d'expiration de la recherche hébergée. Le chien de garde efficace du pont est le maximum plus 30 secondes. Le décrochage routé est

‎docs-site/src/content/docs/guides/sidecars.md‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,18 @@ description: Give routed models real web search and text-only models image under
44
---
55

66
Routed models do not all expose hosted **web search** or native **image input**. opencodex backfills
7-
those capabilities with two sidecars. Each can run through a ChatGPT-login (`forward`) provider or a
8-
stored Anthropic OAuth provider. Sidecar errors become bounded tool results or image markers instead
9-
of failing the whole turn.
7+
those capabilities with two sidecars. Both support a ChatGPT-login (`forward`) provider or stored
8+
Anthropic OAuth provider; web search can additionally use stored Grok OAuth through the explicit
9+
`xai` backend. Sidecar errors become bounded tool results or image markers instead of failing the
10+
whole turn.
1011

1112
:::note[Automatic backend selection]
1213
Explicit `backend` config wins. The two sidecars default differently when `backend` is unset:
1314
**web search** always defaults to `openai` — `anthropic` runs only when explicitly configured.
1415
**Vision** defaults to `anthropic` if an enabled Anthropic OAuth provider has an active account not
1516
marked `needsReauth`, otherwise `openai`. Explicit `anthropic` without that credential fails
16-
closed. `openai` requires both ChatGPT login auth and an enabled `forward` provider.
17+
closed. Explicit `xai` requires a usable stored Grok OAuth account and does not fall back. `openai`
18+
requires both ChatGPT login auth and an enabled `forward` provider.
1719
:::
1820

1921
## Web-search sidecar
@@ -25,7 +27,8 @@ When Codex requests hosted `web_search` for a non-passthrough routed model, open
2527
2. Runs the routed model in a small **agentic loop**. When it calls `web_search`, opencodex uses the
2628
selected sidecar backend: OpenAI runs hosted `web_search` with `gpt-5.6-luna` by default;
2729
Anthropic runs `web_search_20250305` with `claude-sonnet-5` by default. The streamed answer and
28-
citations become a tool result.
30+
citations become a tool result. xAI runs Grok hosted `web_search` with `grok-4.6` by default and,
31+
when enabled, adds hosted `x_search` to the same request.
2932
3. **Loops** until the model answers or the total real-query budget reaches `maxSearchesPerTurn`
3033
(default 3), then removes the search tool and forces a final answer. Real client tools such as
3134
`apply_patch` or shell finalize the turn so those calls reach Codex.
@@ -70,6 +73,28 @@ relevant images in words and include their source URLs.
7073
}
7174
```
7275

76+
The explicit xAI backend uses the stored credential created by `ocx login xai`. Its optional
77+
`xSearch` block enables X search and may restrict it to one handle list and an ISO date range:
78+
79+
```json
80+
{
81+
"webSearchSidecar": {
82+
"backend": "xai",
83+
"model": "grok-4.6",
84+
"xSearch": {
85+
"enabled": true,
86+
"allowedXHandles": ["xai"],
87+
"fromDate": "2026-08-01",
88+
"toDate": "2026-08-21"
89+
}
90+
}
91+
}
92+
```
93+
94+
`allowedXHandles` and `excludedXHandles` are mutually exclusive and each accepts at most 20
95+
strings. Dates use `YYYY-MM-DD`. Malformed management writes return `400`; persisted malformed
96+
blocks fail closed at planning time instead of silently broadening the search.
97+
7398
`minimal` reasoning is not used because the hosted backend rejects tools at that effort. A failed
7499
search is returned to the routed model as a bounded error result, allowing it to answer from the
75100
context it already has.

‎docs-site/src/content/docs/ja/guides/sidecars.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ description: ネイティブ ChatGPT サイドカー経由でルーティング
55

66
ルーティングモデルごとにホスト型**ウェブ検索**やネイティブ**画像入力**のサポート範囲が異なります。opencodex は
77
ChatGPT ログイン(`forward`)プロバイダーまたは保存された Anthropic OAuth プロバイダーを使う 2 つの
8-
サイドカーで不足機能を補います。サイドカーエラーはターン全体を失敗させず、長さ制限付きのツール
8+
サイドカーで不足機能を補い、ウェブ検索は明示的な `xai` バックエンドで保存済み Grok OAuth も利用できます。サイドカーエラーはターン全体を失敗させず、長さ制限付きのツール
99
結果や画像案内文に差し替わります。
1010

1111
:::note[バックエンド自動選択]
12-
`backend` を明示するとその値が優先します。省略するとアクティブアカウントが `needsReauth` 状態でない Anthropic
13-
OAuth プロバイダーがあるとき `anthropic`、ないとき `openai` を使います。使える認証情報なしに
14-
`anthropic` を明示すると失敗後停止します。`openai` は ChatGPT ログインと有効化された `forward`
12+
`backend` を明示するとその値が優先します。ウェブ検索は省略時に常に `openai`、Vision は利用可能な
13+
Anthropic OAuth アカウントがあれば `anthropic`、なければ `openai` を使います。利用可能な認証情報なしに
14+
`anthropic` または `xai` を明示するとフォールバックせず失敗します。`openai` は ChatGPT ログインと有効化された `forward`
1515
プロバイダーが両方必要です。
1616
:::
1717

@@ -24,8 +24,9 @@ Codex がパススルーでないルーティングモデルにホスト型 `web
2424
公開します。元のホスト型ツールのオプションはサイドカー呼び出しにそのまま使います。
2525
2. ルーティングモデルを小さな**エージェントループ**で実行します。モデルが `web_search` を呼ぶと選んだ
2626
バックエンドを使います。OpenAI はデフォルト `gpt-5.6-luna` でホスト型 `web_search` を実行し、
27-
Anthropic はデフォルト `claude-sonnet-5` で `web_search_20250305` を実行します。ストリーミング回答と
28-
引用をパースした結果をツール結果として返します。
27+
Anthropic はデフォルト `claude-sonnet-5` で `web_search_20250305` を実行します。xAI はデフォルト
28+
`grok-4.6` で hosted `web_search` を実行し、`xSearch.enabled` が true の場合は同じリクエストに
29+
`x_search` を追加します。ストリーミング回答と引用をパースした結果をツール結果として返します。
2930
3. モデルが答えるか実際の検索クエリの総数が `maxSearchesPerTurn`(デフォルト 3)に達するまで
3031
**反復**します。限度に達すると検索ツールを削除し最終回答を強制します。`apply_patch` や shell
3132
のような実際のクライアントツールが出たらターンを終了し該当呼び出しが Codex に渡るようにします。

‎docs-site/src/content/docs/ja/reference/configuration/server.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,14 +133,16 @@ Codex は、タイトルやコミット メッセージなどのタスクに小
133133
|フィールド |タイプ |デフォルト |意味 |
134134
| --- | --- | --- | --- |
135135
| `enabled?` | `boolean` |使用可能な場合はオン |マスタースイッチ。 |
136-
| `backend?` | `"openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"` | `openai` |明示指定が優先され、未指定時は常に `openai` です。`xai`、`gemini`、`exa` は明示的に設定した場合のみ有効になります。 |
137-
| `model?` | `string` |バックエンド依存 | OpenAI の場合は `gpt-5.6-luna`、Anthropic の場合は `claude-sonnet-5`。従来の明示的な `gpt-5.4-mini` は開始時に移行されます。 |
136+
| `backend?` | `"openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"` | `openai` | 明示設定が優先され、未設定なら常に `openai` です。`anthropic` と `xai` は明示設定時のみ実行され、`gemini` と `exa` は executor が提供されるまで予約値です。 |
137+
| `model?` | `string` |バックエンド依存 | OpenAI は `gpt-5.6-luna`、Anthropic は `claude-sonnet-5`、xAI は `grok-4.6`。従来の明示的な `gpt-5.4-mini` は開始時に移行されます。 |
138+
| `exaApiKey?` | `string` | なし | `exa` バックエンドのオペレーターキー。書き込み専用で、管理 API の読み取りでは保存値を返しません。 |
139+
| `xSearch?` | `object` | 省略 | xAI 専用の hosted `x_search` opt-in。`enabled`、相互排他的な `allowedXHandles` / `excludedXHandles` 配列(最大 20 件)、ISO の `fromDate` / `toDate`(`YYYY-MM-DD`)を指定します。 |
138140
| `reasoning?` | `string` | `low` |サイドカーの取り組み。 `minimal` は Web 検索で拒否されます。 |
139141
| `maxSearchesPerTurn?` | `number` | `3` |メインモデルのターンごとに許可される実際の検索。 |
140142
| `routedModelStallTimeoutMs?` | `number` | `200000` |設定ファイルのみのルーテッド モデルの raw ボディの非アクティブ期限。整数 1 ~ 2147483647。空でないすべてのチャンクがリセットされます。 |
141143
| `timeoutMs?` | `number` | `60000` | 1 つのホストされた検索の期限。 |
142144

143-
OpenAI バックエンドには、ChatGPT ログインと有効な ChatGPT `forward` プロバイダーが必要です。クロードインバウンドのルーティングされたリプレイは、メインの ChatGPT 認証を内部リクエストに挿入します。 Anthropic バックエンドは、有効な Anthropic OAuth プロバイダーからのアクティブに保存された資格情報を使用します。使用可能なアカウントがない、明示的に選択された Anthropic バックエンドは、フォールバックせずに失敗して閉じられます。 Anthropic executor は、ネイティブの `web_search_20250305` ツールを使用します。
145+
OpenAI バックエンドには、ChatGPT ログインと有効な ChatGPT `forward` プロバイダーが必要です。クロードインバウンドのルーティングされたリプレイは、メインの ChatGPT 認証を内部リクエストに挿入します。 Anthropic バックエンドは、有効な Anthropic OAuth プロバイダーからのアクティブに保存された資格情報を使用します。使用可能なアカウントがない、明示的に選択された Anthropic バックエンドは、フォールバックせずに失敗して閉じられます。 Anthropic executor は、ネイティブの `web_search_20250305` ツールを使用します。xAI バックエンドには使用可能な保存済み Grok OAuth アカウントが必要で、hosted `web_search` を使用し、`xSearch.enabled` が true の場合は hosted `x_search` を追加します。不正な `xSearch` 管理入力は `400` を返し、不正な永続化ブロックは計画時に fail closed します。`gemini` と `exa` は資格情報の検出やフォールバックからは決して有効にならず、オペレーターが明示的に選択する必要があります。`exaApiKey` は書き込み時に受け付けますが、管理レスポンスからは省略されます。
144146

145147
検索は 4 つのクロック (ベース `stallTimeoutSec`、`connectTimeoutMs`、ルーテッド モデルの非アクティビティ、ホスト型検索のタイムアウト) によって制御されます。有効なブリッジ ウォッチドッグは、最大プラス 30 秒です。ルート ストールは非アクティブ ガードであり、総生成期限ではありません。
146148

‎docs-site/src/content/docs/ko/guides/sidecars.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@ description: 네이티브 ChatGPT 사이드카를 통해 라우팅 모델에 실
55

66
라우팅 모델마다 호스팅 **웹 검색**이나 네이티브 **이미지 입력** 지원 범위가 다릅니다. opencodex는
77
ChatGPT 로그인(`forward`) 프로바이더나 저장된 Anthropic OAuth 프로바이더를 사용하는 두
8-
사이드카로 부족한 기능을 보완합니다. 사이드카 오류는 턴 전체를 실패시키지 않고 길이가 제한된 도구
8+
사이드카로 부족한 기능을 보완하며, 웹 검색은 명시적인 `xai` 백엔드로 저장된 Grok OAuth도 사용할 수
9+
있습니다. 사이드카 오류는 턴 전체를 실패시키지 않고 길이가 제한된 도구
910
결과나 이미지 안내문으로 바뀝니다.
1011

1112
:::note[백엔드 자동 선택]
12-
`backend`를 명시하면 그 값이 우선합니다. 생략하면 활성 계정이 `needsReauth` 상태가 아닌 Anthropic
13-
OAuth 프로바이더가 있을 때 `anthropic`, 없을 때 `openai`를 사용합니다. 쓸 수 있는 자격 증명 없이
14-
`anthropic`을 명시하면 실패 후 중단합니다. `openai`는 ChatGPT 로그인과 활성화된 `forward`
13+
`backend`를 명시하면 그 값이 우선합니다. 웹 검색은 생략 시 항상 `openai`를 사용하고, 비전은 사용
14+
가능한 Anthropic OAuth 계정이 있으면 `anthropic`, 없으면 `openai`를 사용합니다. 쓸 수 있는 자격
15+
증명 없이 `anthropic` 또는 `xai`를 명시하면 폴백 없이 실패합니다. `openai`는 ChatGPT 로그인과 활성화된 `forward`
1516
프로바이더가 모두 필요합니다.
1617
:::
1718

@@ -24,8 +25,9 @@ Codex가 패스스루가 아닌 라우팅 모델에 호스팅 `web_search`를
2425
노출합니다. 원래 호스팅 도구의 옵션은 사이드카 호출에 그대로 사용합니다.
2526
2. 라우팅 모델을 작은 **에이전트 루프**에서 실행합니다. 모델이 `web_search`를 호출하면 선택한
2627
백엔드를 사용합니다. OpenAI는 기본 `gpt-5.6-luna`로 호스팅 `web_search`를 실행하고,
27-
Anthropic은 기본 `claude-sonnet-5`로 `web_search_20250305`를 실행합니다. 스트리밍 답변과
28-
인용을 파싱한 결과는 도구 결과로 돌려줍니다.
28+
Anthropic은 기본 `claude-sonnet-5`로 `web_search_20250305`를 실행합니다. xAI는 기본
29+
`grok-4.6`으로 호스팅 `web_search`를 실행하고, `xSearch.enabled`가 true이면 같은 요청에
30+
`x_search`를 추가합니다. 스트리밍 답변과 인용을 파싱한 결과는 도구 결과로 돌려줍니다.
2931
3. 모델이 답하거나 실제 검색 쿼리의 총합이 `maxSearchesPerTurn`(기본값 3)에 도달할 때까지
3032
**반복**합니다. 한도에 닿으면 검색 도구를 제거하고 최종 답변을 강제합니다. `apply_patch`나 shell
3133
같은 실제 클라이언트 도구가 나오면 턴을 끝내 해당 호출이 Codex에 전달되게 합니다.

0 commit comments

Comments
 (0)